text
stringlengths
180
608k
[Question] [ ### Introduction You must create a function to convert Arabic numerals into Greek numerals. The input will be an integer less than `1000` and more than `0`. ### Algorithm 1. Split number into digits (e.g. `123` -> `1`, `2`, `3`) 2. Take each digit, and change to character found in table below, for letter symbol or letter name, (e.g. `123` -> `1`, `2`, `3` -> `ΡΚΓ` or `RhoKappaGamma`). ### Specifications * No built-in number-system conversion * Result must be capitalized as in example. * Input will be in base 10. ### Test Cases ``` 123 -> RhoKappaGamma or ΡΚΓ 8 -> Eta or Η 777 -> PsiOmicronZeta or ΨΟΖ 100 -> Rho or Ρ 606 -> ChiDiGamma or ΧϜ ``` ### Table ``` Α = 1 = Alpha = 913 UTF-8 Β = 2 = Beta = 914 UTF-8 Γ = 3 = Gamma = 915 UTF-8 Δ = 4 = Delta = 916 UTF-8 Ε = 5 = Epsilon = 917 UTF-8 Ϝ = 6 = DiGamma = 988 UTF-8 Ζ = 7 = Zeta = 918 UTF-8 Η = 8 = Eta = 919 UTF-8 Θ = 9 = Theta = 920 UTF-8 Ι = 10 = Iota = 921 UTF-8 Κ = 20 = Kappa = 922 UTF-8 Λ = 30 = Lambda = 923 UTF-8 Μ = 40 = Mu = 924 UTF-8 Ν = 50 = Nu = 925 UTF-8 Ξ = 60 = Xi = 926 UTF-8 Ο = 70 = Omicron = 927 UTF-8 Π = 80 = Pi = 928 UTF-8 Ϙ = 90 = Koppa = 984 UTF-8 Ρ = 100 = Rho = 929 UTF-8 Σ = 200 = Sigma = 931 UTF-8 Τ = 300 = Tau = 932 UTF-8 Υ = 400 = Upsilon = 933 UTF-8 Φ = 500 = Phi = 934 UTF-8 Χ = 600 = Chi = 935 UTF-8 Ψ = 700 = Psi = 936 UTF-8 Ω = 800 = Omega = 937 UTF-8 Ϡ = 900 = SamPi = 992 UTF-8 ``` [Answer] ## Pyth, ~~49~~ ~~48~~ ~~46~~ 44 bytes ``` _s.b@+kNsYc3mC+913d-.iU25smXm17hT4Cd"KGO"17_ ``` [Try it here.](https://pyth.herokuapp.com/?code=_s.b%40%2BkNsYc3mC%2B913d-.iU25smXm17hT4Cd%22KGO%2217_&test_suite=1&test_suite_input=%22123%22%0A%228%22%0A%22777%22%0A%22100%22%0A%22606%22&debug=0) Still working on shortening the function to generate the alphabet... and yes, the generator is longer than hardcoding the alphabet by 4 characters, but not in bytes. ``` _s.b@+kNsYc3[...]_ _ get input (implicit) and reverse [...] generate "ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ" (see below) c3 split into 3 equal chunks .b map over each input digit (as Y) and chunk (as N)... +kN prepend empty string to N (to support digits of 0) @ sY get the Yth element of the empty-string-plus-digits array s concatenate all the digits _ reverse again to put digits back in the right order ``` Here's how the alphabet-generating function works. Let's take all the codepoints and subtract 913 (the smallest value): ``` 0 1 2 3 4 75 5 6 7 8 9 10 11 12 13 14 15 71 16 18 19 20 21 22 23 24 79 ``` Now let's pull out the ones that don't fit the pattern: ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 75 71 79 ``` Okay, so the strategy is forming: generate the range 0 to 24 (we'll deal with the missing 17 later), and then insert 75, 71, and 79 at the correct locations. How can we insert the outliers? Pyth has an `.i`nterleave function that takes ex. `[1,2,3]` and `[4,5,6]` and results in `[1,4,2,5,3,6]`. We're going to have to add some placeholders, though, since obviously the outliers are far apart. Let's represent the placeholder with X: ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 X X X X 75 X X X X X X X X X X 71 X X X X X X X 79 ``` Right, so the bottom outlier array starts with four `X`s. Can we group the outliers to each be preceded by four `X`s and see what remains? ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 [four X]75 X X X X X X [ four X ]71 X X X [ four X ]79 ``` Now we make another key observation: since 79 comes at the *very end*, there can be *any* number of `X`s preceding it, and *any* number of `X`s following it as well! This is because interleaving `[1,2,3]` and `[4,5,6,7,8,9]` results in `[1,4,2,5,3,6,7,8,9]`—note that the extra elements in the second array end up at the end, and since they're going to be removed anyway, we can safely allow that. That means we can normalize this such that every outlier is preceding by four `X`s and succeeded by 6: ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 [four X]75[ six X ] [ four X ]71[ six X ] [four X]79[six X] ``` Great! Now we can simply take the array `[75, 71, 79]`, insert four placeholder values before each element and six after, and then interleave it with the range `0..24`. But wait, what happened to `17`? Remember, the top line in all of these examples has been missing 17. We can simply remove the 17 after interleaving; but this leaves another delightfully evil possibility open. You guessed it—the placeholder value we've been referring to as `X` will be 17. This allows us to remove both the extraneous 17 and all the placeholder values in one fell swoop. Finally! Here's the code used to implement this: ``` mC+913d-.iU25smXm17hT4Cd"KGO"17 m "KGO" for each char in the string "KGO"... Cd take its ASCII value ("KGO" -> 75,71,79) m17hT generate an 11-element array filled with 17 X 4 replace the 5th element with the ASCII value ^^ s concatenate all of these together .iU25 interleave with range(25) - 17 remove all the 17s m d for each value in the resulting array... +913 add 913 (to get the real character value) C convert to character ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~42~~ 40 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “#'nn(2jj33556;r”Or2/F+878Ọ ṚĖ’ḅ9‘xṚQṚị¢ ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCcIydubigyamozMzU1Njty4oCdT3IyL0YrODc44buMCuG5msSW4oCZ4biFOeKAmHjhuZpR4bma4buLwqI&input=&args=MTIz) or [verify all test cases](http://jelly.tryitonline.net/#code=4oCcIydubigyamozMzU1Njty4oCdT3IyL0YrODc44buMCuG5msSW4oCZ4biFOeKAmHjhuZpR4bma4buLwqIKw4figqxq4oG3&input=&args=MTIzLCA4LCA3NzcsIDEwMCwgNjA2). [Answer] # JavaScript (ES6), ~~120~~ 115 bytes ``` n=>(s=n+"").replace(/./g,(d,i)=>d--?"ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ"[d+9*(s.length+~i)]:"") ``` Byte count is using UTF-8. It's 88 characters long. Input is a number. ## Test ``` var solution = n=>(s=n+"").replace(/./g,(d,i)=>d--?"ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ"[d+9*(s.length+~i)]:"") var testCases = [ 123, 8, 777, 100, 606, 700, 803 ]; document.write("<pre>"+testCases.map(c=>c+": "+solution(c)).join("\n")); ``` [Answer] # Python 3, 118 bytes ``` f=lambda n,i=3:i*"_"and f(n//10,i-1)+" ΡΙΑΣΚΒΤΛΓΥΜΔΦΝΕΧΞϜΨΟΖΩΠΗϠϘΘ"[i-1::3][n%10].strip() ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 57 bytes * 11 bytes saved thanks to @Martin Büttner. Simple transliterate with appropriate character ranges and `0` deletion on each digit. ``` T`d`_ΡΣ-ΩϠ`.(?=..) T`d`_Ι-ΠϘ`.\B T`d`_Α-ΕϜΖ-Θ ``` [Try it online. (First line added to allow all testcases to run together.)](http://retina.tryitonline.net/#code=JShHYApUYGRgX86hzqMtzqnPoGAuKD89Li4pClRgZGBfzpktzqDPmGAuXEIKVGBkYF_OkS3Olc-czpYtzpg&input=MTIzCjgKNzc3CjEwMAo2MDY) --- Martin also suggested this one for the same score: ``` T`d`_J-R`.(?=..) T`d`_L`.\B T`dL`_Α-ΕϜΖ-ΠϘΡΣ-ΩϠ ``` [Answer] # Julia, 138 bytes ``` f(x,d=digits(x))=reverse(join([d[i]>0?[["ΑΒΓΔΕϜΖΗΘ","ΙΚΛΜΝΞΟΠϘ","ΡΣΤΥΦΧΨΩϠ"][i]...][d[i]]:""for i=1:endof(d)])) ``` This is a function that accepts an integer and returns a string. For each digit in the input in reversed order, we get the character corresponding to that digit from the appropriate string then combine the characters and reverse the result. For any digits that are 0, we simply use the empty string. [Answer] # Julia, 84 bytes ``` f(x,p=0)=x>0?f(x÷10,p+9)"$(x%10<1?"":"/0123z456789:;<=>v?ABCDEFG~"[p+x%10]+866)":"" ``` [Try it online!](http://julia.tryitonline.net/#code=Zih4LHA9MCk9eD4wP2YoeMO3MTAscCs5KSIkKHglMTA8MT8iIjoiLzAxMjN6NDU2Nzg5Ojs8PT52P0FCQ0RFRkd-IltwK3glMTBdKzg2NikiOiIiCgpmb3IgeCBpbiAoMTIzLCA4LCA3NzcsIDEwMCwgNjA2KQogICAgcHJpbnRsbihmKHgpKQplbmQ&input=) [Answer] ## JavaScript (ES6), 83 characters, 110 bytes ``` n=>`${1e3+n}`.replace(/./g,(d,i)=>i--&&d--?"ΡΣΤΥΦΧΨΩϠΙΚΛΜΝΞΟΠϘΑΒΓΔΕϜΖΗΘ"[d+9*i]:"") ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 102 bytes ``` {[~] <ΡΣΤΥΦΧΨΩϠ ΙΚΛΜΝΞΟΠϘ ΑΒΓΔΕϜΖΗΘ>>>.&{('',|$^b.comb)[$_/100*10**$++%*]}} ``` [Try it online!](https://tio.run/##Dco7DoJAFAXQrbwCAYcJgiZgoWyEIBEjlQSDFUHcg39UVIz/zVyWNHrqMx0nE0tEKckh9UXmLjzq4YY7HnjihTc@@NYV4YAjTihxxgVXVHVBWGKFNTbY1iV22KNwHEeXM1VR@FwaBPoojoKmK/kt0zCYaTAmaVqDeXkuZsOUQlXymxTGCZntDqcuJ9u2Of0vJ8uwxA8 "Perl 6 – Try It Online") [Answer] # Ruby, 134 bytes Basic lookup dealie using modulus. It probably can be optimized somewhere, but Ruby won't coerce strings into integers the way Javascript can, haha ``` ->n{((0<d=n/100)?"ΡΣΤΥΦΧΨΩϠ"[d-1]:"")+((0<d=n%100/10)?"ΙΚΛΜΝΞΟΠϘ"[d-1]:"")+((0<n%=10)?"ΑΒΓΔΕϜΖΗΘ"[n-1]:"")} ``` ]
[Question] [ Every day, every minute, ... every microsecond, many decisions are made by your computer. In high-level languages, these typically take the form of statements like `if`, `while` and `for`, but at the most basic level there exist machine language instructions called [branch/jump instructions](https://en.wikipedia.org/wiki/Branch_(computer_science)). Modern processors queue instructions up in a [pipeline](https://en.wikipedia.org/wiki/Instruction_pipelining), and this means that the processor needs to decide whether to fill the pipeline with instructions immediately following a branch (i.e. it is not *taken*) or the instructions at the branch destination. If the processor does not guess correctly, the instructions which have been wrongly entered into the pipeline need to be ignored and the correct instructions must be fetched, causing a delay. The job of the [branch predictor](https://en.wikipedia.org/wiki/Branch_predictor) is to try and guess whether the branch will be taken to avoid the costly action of refilling the pipeline. You must write a predictor that will, given a sequence of past decisions, guess the next decision correctly. Your program can be written in any language, provided you specify the link to its interpreter if it's an obscure/golfing language. It must take the past actual history as its first command-line argument, but it will not be provided for the first guess of the sequence. You must then return your guess by printing it to stdout. A decision is of the form "y" or "n". Each test case is a sequence of 72 decisions, so you can assume that the specified history argument will never be longer than 71 characters. For example, the "Alternating 1" test: ``` ynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynyn ``` You will be disqualified if your program: * does not return a result within one second * does not return either a `y` or `n` (new lines don't matter and are ignored) * attempts to modify any code or file associated with this challenge, including other contender's code * contains anything otherwise malicious You may use a file for persistence if you wish, but it must be uniquely named and conform to the above. This is a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), not [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Victory will be granted by the branch predictor predictor to the contender whose solution successfully predicts the most branches in the whole test suite. Tests: ``` yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy,All yes nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn,All no ynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynyn,Alternating 1 nnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyy,Alternating 2 yyynnnyyynnnyyynnnyyynnnyyynnnyyynnnyyynnnyyynnnyyynnnyyynnnyyynnnyyynnn,Alternating 3 nnnnyyyynnnnyyyynnnnyyyynnnnyyyynnnnyyyynnnnyyyynnnnyyyynnnnyyyynnnnyyyy,Alternating 4 yyyyyynnnnnnyyyyyynnnnnnyyyyyynnnnnnyyyyyynnnnnnyyyyyynnnnnnyyyyyynnnnnn,Alternating 5 nnnnnnnnnnnnyyyyyyyyyyyynnnnnnnnnnnnyyyyyyyyyyyynnnnnnnnnnnnyyyyyyyyyyyy,Alternating 6 yyyyyyyyyyyyyyyyyynnnnnnnnnnnnnnnnnnyyyyyyyyyyyyyyyyyynnnnnnnnnnnnnnnnnn,Alternating 7 yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyynnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn,Alternating 8 yynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyyn,2-1 ynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnn,1-3 nyyyyynyyyyynyyyyynyyyyynyyyyynyyyyynyyyyynyyyyynyyyyynyyyyynyyyyynyyyyy,5-1 nnnnnnnnnnnynnnnnnnnnnnynnnnnnnnnnnynnnnnnnnnnnynnnnnnnnnnnynnnnnnnnnnny,1-11 nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyynyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy,35-1 yynnnnyynnnnyynnnnyynnnnyynnnnyynnnnyynnnnyynnnnyynnnnyynnnnyynnnnyynnnn,2-4 ynnyyynyynnnynnyyynyynnnynnyyynyynnnynnyyynyynnnynnyyynyynnnynnyyynyynnn,1-2-3 ynynynynynynynynynynynynynynynynynynyyyyyyyyyyyyyyyyyynnnnnnnnnnnnnnnnnn,A1/A7 yyyyyynnnnnnyyyyyynnnnnnyyyyyynnnnnnnnyynnyynnyynnyynnyynnyynnyynnyynnyy,A5/A2 nnnnnnnnnnnnyyyyyyyyyyyynnnnnnnnnnnnyyyynnnnyyyynnnnyyyynnnnyyyynnnnyyyy,A6/A4 nyyyyynyyyyynyyyyynyyyyynyyyyynyyyyynyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy,5-1/35-1 yyynnnyyynnnyyynnnnyyyyyyyyyyyyyyyyyyyyyyynyyyyynyyyyyyynnnnyynnnnyynnnn,A3/Y/5-1/2-4 yynnnnyynnnnyynnnnnyynnnynnyyynyynnnnnnynnnynnnynnnynnyynyynyynyynyynyyn,2-4/1-2-3/1-3/2-1 ``` The full set of tests and runner program are situated at [this GitHub repository](https://github.com/adamd1008/branch_predictor). Simply add your predictor to `src/predictors.txt` in the form `<name>,<command to run>` and run `main.py`. I have provided two very basic predictors already for simple testing. I would recommend a column width of at least 92 when running the runner for nice output. If you happen to spot any bugs with it, please let me know. :) [Answer] # Compressor (Ruby), score 1502/1656 ≈ 90.7% ``` require 'zlib' input = $*[0].to_s.chomp recent_input = input[-35..-1] || input puts recent_input.chars.uniq.min_by { |char| [Zlib::Deflate.deflate(input+char,9).size,-input.count(char),-input[-10..-1].to_s.count(char)] } || ?y ``` Checks whether the current string would be more compressible if 'y' or 'n' were added to the end. If equally compressible, use the one that's shown up the most. [Answer] # DéjàVu (Mathematica), score 503/552 ≈ 91.123% ``` If[Length[$ScriptCommandLine] < 2, Print["y"]; Exit[]]; input = Characters[$ScriptCommandLine[[2]]] /. {"y" -> 1, "n" -> 0}; For[test = Length[input], ! ListQ[ker = FindLinearRecurrence[input[[-test ;;]]]], test--]; Print[LinearRecurrence[ker, input[[-test ;; Length[ker] - test - 1]], test + 1][[-1]] /. {1 -> "y", _ -> "n"}]; ``` Looks for a linear recurrence in the pattern, and computes the next term. For testing, save as `DéjàVu,MathematicaScript -script <file>`. [Answer] # Historian (Kotlin), score 1548/1656 ≈ 93.478% Predicts the future from the past. ``` fun main(args : Array<String>) { if (args.size == 0) { println('y') return } val history = args[0].reversed() var bestLength = 0 var ys = 0 var ns = 0 for (i in 1..history.length-1) { var length = 0 var j = i while (j < history.length) { if (history[j] == history[j - i]) { length++ } else { break } j++ } if (length > bestLength) { bestLength = length ys = 0 ns = 0 } if (length == bestLength) { if (history[i - 1] == 'y') { ys++ } else { ns++ } } } println(if (bestLength == 0) history[0] else if (ys >= ns) 'y' else 'n') } ``` Compile with: `kotlinc Historian.kt` Run with: `kotlin HistorianKt` [Answer] ## Pattern-Finder (Java), score 1570/1656 (≈94.8%) ~~1532/1656 (≈92.5%)~~ Slight improvements for complex patterns. ``` public class Main { public static void main(String[] args) { if (args.length == 0) { System.out.print("y"); return; } System.out.print(new Pattern(args[0]).getNext()); } } class Pattern { private String pattern; private int index; private int length; public Pattern(String string) { setPattern(string); } private void setPattern(String string) { if (string.length() == 0) { this.pattern = "y"; this.index = 0; this.length = 1; return; } if (string.length() == 1) { this.pattern = string; this.index = 0; this.length = 1; return; } if (string.startsWith("ynnyyy")) { this.pattern = "ynnyyynyynnn"; this.index = string.length() % 12; this.length = 12; return; } this.length = 0; char first = string.charAt(0); char current = first; boolean hasReverse = false; while (length < string.length() - 1 && !(hasReverse && current == first)) { hasReverse |= current != first; length++; current = string.charAt(length); } if (!(hasReverse && current == first)) { this.pattern = Character.toString(current); this.index = 0; this.length = 1; return; } this.pattern = string.substring(0, length); int i = length; while (i <= string.length() - length) { if (!string.substring(i, i + length).equals(pattern)) { setPattern(string.substring(i)); return; } i += length; } this.index = string.length() % i; if (!string.substring(i).equals(pattern.substring(0, index))) { setPattern(string.substring(i)); } } public char getNext() { char result = pattern.charAt(index); index = (index + 1) % length; return result; } } ``` [Answer] **Factorio (Python3), score 1563/1656 ≈ 94.38%** Factors the sequence from left to right into a series of repeating and alternating patterns. Primarily favours longer match lengths, but chooses repeating over alternating patterns and shorter over longer cycle lengths in case of a tie. ``` def main(): if len(sys.argv) < 2: print('y') sys.stdout.flush() return history = sys.argv[1] while history: score = 0 period = 0 l = 0 for p in range(1, len(history)): if history[0] == history[p]: m = lambda a, b: a == b s0 = 1 else: m = lambda a, b: a != b s0 = 0 s = 0 for i in range(len(history)): j = i + p if j < len(history): if not m(history[i], history[j]): break s += 1 if s > score or s == score and s0 > score0: score = s score0 = s0 period = p match = m l = j if period == 0: print(history[0]) sys.stdout.flush() return if l >= len(history): break l = (l // period) * period history = history[l:] print('y' if match(history[-period], 'y') else 'n') sys.stdout.flush() if __name__ == '__main__': main() ``` [Answer] # Repeater (Python), score 1173/1656 ≈ 70.83% This predictor simply guesses yes if there's no history, otherwise repeats the previous actual outcome. ``` import sys if len(sys.argv) == 1: print "y" else: print sys.argv[1][-1:] ``` # !Repeater (Python), score 483/1656 ≈ 29.17% If there's no history this predictor will guess no, otherwise will repeat the opposite of the last actual outcome. ``` import sys if len(sys.argv) == 1: print "n" else: if sys.argv[1][-1:] == "y": print "n" else: print "y" ``` # 2-toucher (Python), score 1087/1656 ≈ 65.64% If there were at least two previous outcomes that were the same, or there has been one outcome so far, this predictor will choose the same. If there is no history, it will choose "y". If there were at least two outcomes and the most recent two were not the same, it will choose the opposite of the most recent. ``` import sys if len(sys.argv) == 1: print "y" elif len(sys.argv[1]) == 1: print sys.argv[1][-1:] else: l = len(sys.argv[1]) if sys.argv[1][l - 2:l - 1] == sys.argv[1][-1:]: print sys.argv[1][-1:] else: if sys.argv[1][-1:] == "y": print "n" else: print "y" ``` [Answer] I would leave a comment, but the 50 rep requirement prevents me. Was able to get a small improvement on @histocrat's answer # Compressor (Ruby), score 1504/1656 ≈ 90.82% ``` require 'zlib' input = $*[0].to_s.chomp recent_input = input[-35..-1] || input puts recent_input.chars.uniq.min_by { |char| [Zlib::Deflate.deflate(input+char,9).size,-input[-3..-1].to_s.count(char),-input.count(char)] } || ?y ``` I tweaked it in a number of different ways, and a +0.12% improvement was the best I found. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 6 years ago. [Improve this question](/posts/28625/edit) **Goal** Replace all comments in C, C++, or Java Code with the comment `// Do the needful`. **Specifics** This coding challenge is a simple one. Take as input the name of a file. The input file shall contain C, C++, or Java code. The code shall contain one or more comments. The comments can be single line `/* */` or `//` delimited, as well as multi-line `/* */` delimited. The output of the program should be identical to the input except all of the comments should be converted to `// Do the needful`. For example if the input file is: ``` #include <iostream.h> int result; // the result of the calculations char oper_char; // the user-specified operator int value; // value specified after the operator /* standard main function */ int main() { result = 0; // initialize the result // Loop forever (or till we hit the break statement) while (1) { cout << "Result: " << result << '\n'; /* This code outputs display and requests input from the user */ cout << "Enter operator and number: "; cin >> oper_char; cin >> value; if (oper_char = '+') { result += value; } else { cout << "Unknown operator " << oper_char << '\n'; } } return (0); } ``` The output of the program should read ``` #include <iostream.h> int result; // Do the needful char oper_char; // Do the needful int value; // Do the needful // Do the needful int main() { result = 0; // Do the needful // Do the needful while (1) { cout << "Result: " << result << '\n'; // Do the needful cout << "Enter operator and number: "; cin >> oper_char; cin >> value; if (oper_char = '+') { result += value; } else { cout << "Unknown operator " << oper_char << '\n'; } } return (0); } ``` **Scoring** This is a popularity contest. You get two extra votes added to your score if none of the following words appears in your program in any case variation: `{"do", "the", "needful"}`. Score is number of votes plus bonus if applicable. **Allowances** If comments appear in string literals it is acceptable to convert them to `// Do the needful` as well. After all... you can never have enough needful. [Answer] # Perl, 68 characters ``` perl -0pe's@((//).*?(\n)|(/\*).*?(\*/))@\2\4 Do the needful \3\5@sg' ``` This takes some liberties with the specification, and retains the original comment style. This avoids the problem with `/* ... */` comments appearing before the end of the line. No attempt is made to avoid comments within string literals, and no claim is made for the bonus points. [Answer] # Perl First world anarchy! :) "you can never have enough needful" ``` #!perl -p0 sub the { s,(?<=\w)(.*)(\n),$1 // do the needful$2,g } sub needful { s,//.*\n,\n,g,s,/\*.*?\*/,,msg } do not do the needful ``` [Answer] # CoffeeScript (66 bytes) ``` (c)->c.replace /\/\/.*\n?|\/\*[^]*?\*\//g,"// D\o t\he needfu\l\n" ``` This code will parse strings, but there is a good reason. You see, there is a possibility that there is a comment in a template generating C `/**/` comments. This gets the bonus, as it avoids exact case insensitive matches for `Do`, `the`, and `needful`. It also uses ES5 candle (`[^]`) operator to do stuff. I would put a comment `Do the needful` in this program, but that would remove the bonus. [Answer] # Python 3.x, regex Since it's not code golf I didn't fuss about code length. Nothing impressive, but I had fun remembering / relearning regex basics. ``` import re import urllib.request as r def dTN(filename): dtn = re.search(r"(?<=question-hyperlink\">)([A-Za-z \n]*)(?=[?]<)", r.urlopen("http://codegolf.stackexchange.com/questions/28625/").read().decode("utf8")).group(0) with open(filename) as f: return re.sub(r"//{1}.*", "//{0}".format(dtn), re.sub(r"/\*[A-Za-z \n]*\*/", "// {0}".format(dtn), f.read())) ``` [Answer] # sed, 90 characters Could be improved. I learned a lot about sed while making this. Reads from standard input, outputs to standard output. Assumes valid input - if you have unterminated comments, it won't treat it as a comment. Tested on GNU sed v4.2.2. ``` s_/\*.*\*/_//_ tg s_/\*.*$_//_ tl :g s_//.*$_// Do the needful_ P d :l s_.*\*/_//_ tg N bl ``` And the prize for readability goes to....? One-liner version: ``` s_/\*.*\*/_//_;tg;s_/\*.*$_//_;tl;:g;s_//.*$_// Do the needful_;P;d;:l;s_.*\*/_//_;tg;N;bl ``` ## Explanation The control flow jumps around a lot, by means of GOTO statements (yes, sed has them!). sed does not have any loops or convenient conditional statements AFAIK. ``` s_/\*.*\*/_//_ # Substitute /* ... */ with // tg # GOTO g if the substitution occured s_/\*.*$_//_ # Substitute /*...<ENDOFLINE> with // tl # GOTO l if the substitution occured :g # GOTO-LABEL g s_//.*$_// Do the needful_ # Replace //...<ENDOFLINE> with // Do the needful P # Print the pattern space (current line with substitutions) d # empty the pattern space and move on to the next line :l # GOTO-LABEL l s_.*\*/_//_ # Replace ... */ with // tg # GOTO g if the substitution occured N # take another line from input and add it to the pattern space bl # GOTO l ``` [Answer] ## BrainFuck Yes, BrainFuck is a Turing-complete language. Good luck for understanding this code. ``` ,[.-----------------------------------------------[>+>+<<-]> >[-<<+>>][-]+<[[-]>-<]>[>,---------------------------------- -------------[>+>+<<-]>>[-<<+>>]<>[-]+<[>-<+++++[>+>+<<-]>>[ -<<+>>]<>[-]+<[>-<++++++++++++++++++++++++++++++++++++++++++ .[-]]>[<+++++++++++++++++++++++++++++++++++++++++++++++.---- -----------.++++++++++++++++++++++++++++++++++++.+++++++++++ ++++++++++++++++++++++++++++++++.--------------------------- ----------------------------------------------------.+++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++.------------.---.------------------------- --------------------------------------------.+++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++.---------..-.++.+++++++++++++++.---------.[+++++[,------ ------------------------------------],---------------------- -------------------------]>-]<<[-]]>[<++++++++++++++++++++++ +++++++++++++++++++++++++.---------------.++++++++++++++++++ ++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++ ++.--------------------------------------------------------- ----------------------.+++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++.------------ .---.------------------------------------------------------- --------------.+++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++.---------..-.++.++++++++++ +++++.---------.[,----------]++++++++++.[-]>-]<<[-]<<>-]<<,] ``` Basically, the pseudo-code is : ``` get input_char while (input_char is not null) { print input_char if (input_char is '/') { get input_char if (input_char is '/') { print '/ Do the needful' get input_char until input_char is '\n' } else { if (input_char is '*') { print '/ Do the needful' get input_char until input_char is '*' followed by '/' } else { print input_char } } } get input_char } ``` Some online interpreter are broken. [Try it here](http://copy.sh/brainfuck/) with the example given by the OP (ended with *null-char* to break the loop properly) : ``` #include <iostream.h>\n\nint result; // the result of the calculations \nchar oper_char; // the user-specified operator \nint value; // value specified after the operator\n\n/* standard main function */ \nint main()\n{\n result = 0; // initialize the result \n\n // Loop forever (or till we hit the break statement) \n while (1) {\n cout << "Result: " << result << '\\n';\n\n /* This code outputs display and requests\n input from the user */\n cout << "Enter operator and number: ";\n cin >> oper_char;\n cin >> value;\n\n if (oper_char = '+') {\n result += value;\n } else {\n cout << "Unknown operator " << oper_char << '\\n';\n }\n }\n return (0);\n}\0 ``` [Answer] ## Rebol It's not code golf, so I'll be wordy. ``` do-the-needful: function [filename [file!]] [ parse (data: to-string read filename) [ ; match the pattern in brackets ANY number of times (zero okay) any [ ; seek the parse position up TO one of the following matches ; if a match is hit, following code in parentheses is executed normally to [ "/*" (terminator: "*/") | "//" (terminator: newline) ] ; save parse position in start, seek up THRU terminator and leave parse ; position at the end of the terminator match (not the beginning as w/TO) start: thru terminator finish: ; Do partial replacement within the input; starting at START ; but limited to FINISH. Again, structure in parentheses is exec'd as code ( change/part start combine ["// Do the needful" newline] finish ) ] ] return data ] ``` *(Note: For political reasons, I am pushing COMBINE here, but [it's not standard yet](http://blog.hostilefork.com/combine-alternative-rebol-red-rejoin/). So if you actually want to run this, use REJOIN. But I hate REJOIN. A wart on an otherwise beautiful language! Tell your friendly neighborhood Red dev leads to listen to me. Thanks.)* PARSE is a dialect, or language-within-a-language, in Rebol and Red. It twists things up, so for instance the symbol types that are used for assignment (the `terminator:` in `terminator: newline`) takes on a new meaning when used in the code-as-data paradigm... it saves the current parse position into a variable with that name. You can read more about [why it's cool here](http://blog.hostilefork.com/why-rebol-red-parse-cool/). --- **UPDATE:** Oh all right, I'll golf it too. In [Rebmu](http://rebmu.hostilefork.com/), 72 chars... using rebmu/args which injects A as the argument: `pa DtsRDa[anTO["/*"(T"*/")|"//"(Tlf)]SthT F(chpS"// Do the needful^/"f)]d` Exactly the same program. ]
[Question] [ What general tips do you have for golfing code in Pascal? I know this is a tricky language very few people use this but I would like to know any tips from the professionals out there :) I'm looking for tips that can reduce code size (every byte counts!) with special functions or even crazy combinations Please post each tip as a separate answer, and avoid tips not specific to Pascal (e.g. remove whitespace, etc.) [Answer] ## Avoid `Integer` ``` VAR var1: Integer; (* Signed, 16 bits in TP7, 32 bits in FPC, It costs 7 bytes. *) var2: Word; (* Unsigned 16 bit, works in most cases. *) var3: Int64; (* Signed 64 bits, Only available in FPC. *) var4: 0..9; (* TP7: same as ShortInt (-128..127), FPC: same as Byte (0..255) *) ``` ## Use `^J` for line break ``` WriteLn('abc');Write('def'); Write('abc',chr(10),'def'); Write('abc'#10'def'); Write('abc'^J'def'); (* Both in TP7 and FPC *) ``` `^J` is two bytes `^` followed by `J`, not single byte for `Ctrl-J`. [Answer] ### Numbers before keywords ``` for i:=69 to 420 do writeln(i); for i:=69to 420do writeln(i); ``` save you 2 byte on for loop [Answer] ## use (already existing) parentheses as token separators A loop determining the length of `input` without processing it ``` while not EOF do begin get(input);i:=i+1 end ``` can be rearranged into ``` while not EOF do begin i:=i+1;get(input)end ``` Similarly in expressions ``` if ord(c)=32 then ``` is the same as ``` if 32=ord(c)then ``` Since this only saves you one character, it does not make sense to introduce *extra* parentheses. [Answer] ## use `string` as an `array[1‥n] of 0‥ord(maxChar)` In Pascal `string` literals may contain arbitrary values from the domain of `char`. Even `chr(0)` is permitted. The only *illegal* component is the value denoting a newline (in ASCII `chr(10)` [“line feed”] and/or `chr(13)` [“carriage return”]). In other words, multi-line `string` literals are not allowed. Furthermore the string delimiting character `'` (ASCII `chr(39)`) needs to be escaped (conventionally `''`). Example: ``` program stringArrayDemo(output); begin writeLn(ord(('€Bÿ')[3])) end. ``` Since it’s not properly displayed, the above string literal consists of the following four characters (ordinal value in hexadecimal base): ``` 80 42 FF 12 ``` Therefore the above `program` will print `255` as it’s the third character’s ordinal value. Obviously in your challenge at hand the constant index `3` will be some *variable* expression and the `string` literal will have different values. Since the `maxChar` value introduced in ISO standard 10206 “Extended Pascal” documents an implementation characteristic, it is imperative that your solution mentions the processor used. The above `program` will work adequately if compiled with the GNU Pascal Compiler (GPC) or the Free Pascal Compiler (FPC). [Answer] ### Variable declaration of same type ``` var i:word;j:word; var i,j:word; ``` Furthermore, all variables can be declared in one `var` block: ``` var i,j:word;a,b,c:string;x,y:char; ``` [Answer] ## prefer `repeat … until …` loops over `while … do begin … end` loops Consideration for *guaranteed* iteration count ≥ 1: If the loop body of a `while` loop contains *multiple* statements, i. e. *is surrounded* by a proper `begin … end`, you may consider turning it into a `repeat … until` loop where the `repeat … until` by itself constitutes a `begin … end` frame. ``` while condition do begin statement;statement end ``` becomes ``` repeat statement;statement until not condition ``` Since a `repeat` loop’s body is executed *at least* once, this works fine if it’s *guaranteed* that the `while`’s loop body would be executed at least once, too. If `condition` can legitimately cause *zero* iterations, this tip does not make sense. [Answer] ### Prefer `upcase` over `lowercase` That's 3 whole bytes. Handy for case-insensitive string comparisons. [Answer] ## Use the short form of `if` and `for` If your `if` condition/ `for` loop only does one statement, omit `begin` and `end`. `if <boolean> then begin <statement>;end;` 🚫 `if <boolean> then <statement>;` ✅ `for <condition> do begin <statement>;end;` 🚫 `for <condition> do <statement>;` ✅ You can also string them together, e.g. `for <condition> do if <boolean> then <statement>;` [Answer] ### Iterating over the alphabet (or other contiguous ASCII range) Iterate over the string: ``` var c:char;begin for c in'abcdefghijklmnopqrstuvwxyz'do writeln(c); ``` Or, use an ASCII range (uppercase alphabet) ``` var j:word;begin for j:=65to 90do writeln(chr(j)); ``` **BUT! Here's the most compact approach**, for [50 bytes](https://tio.run/##K0gsTk7M0U0rSP7/vyyxSCHLKjkjscg6KTU9M08hLR8kYKtsZlqSr2xpkJKvUF6UWZKak6eRpZmal6Kn8P8/AA): ``` var j:char;begin for j:=#65to#90do writeln(j)end. ``` [Answer] ## use `index` for `in` membership test **Introduction**: All Pascal variants support at least to some extent the `in` membership operator (in mathematical notation ∊). Extended Pascal, ISO standard 10206, introduces the `index` function. It requires two `char` or `string` arguments (any combination thereof). ``` index(sample, pattern) ``` The `index` function returns the index of the first complete occurrence of `pattern` in `sample`. If no such index exists, `0` is returned (an *invalid* index for any `string`). **Application**: The `index` function can be utilized to abbreviate `set`-membership operations. For example ``` c in['X','Y','Z'] { `c` is a variable possessing the data type `char` } ``` becomes ``` index('XYZ',c)>0 ``` **Synergies**: You can combine this with the [`string` as `array[1‥n] of 0‥ord(maxChar)`](/a/254108/) tip. For example ``` index(')/;CGaek•—§³µãåéïñ', chr(241)) > 0 ``` performs a test whether `chr(241)` is a [Ramanujan prime](https://oeis.org/A104272) less than 256. Note, the `string` literal consists of 23 `char` values and are not properly displayed on this site. **Dialects**: Delphi users want to use `pos`. The Free Pascal Compiler supports [`pos`](https://www.FreePascal.org/docs-html/current/rtl/system/pos.html), too. ]
[Question] [ ## Background It was a normal presentation that I were in as a audience, until the presenter gave a math problem about repeat taking 2 number out of a list a replacing them with average, claiming that there will be something special about it, and our math teacher, sitting at the end of classroom, exciting rushed to me, and tasked me to code that out. ## Task 2 input `length` and `generation` 1. Generate a range, start from 0, with length of `length` 2. Randomly choose 2 number (or item) `X` and `Y` and replace both `X` and `Y` with the average of `X` and `Y` 3. Repeat step 2 for `generation` times 4. Output minimum, maximum, average, and the processed list. ## Example I'll let this semi-golfed python code explain itself :) ``` import random a,b=map(int,input().split()) l=[*range(a)] s=lambda:random.randint(0,a-1) for i in range(b): x,y=s(),s();l[x],l[y]=[(l[x]+l[y])/2]*2 print(min(l),max(l),sum(l)/a,l) ``` ## Rules * Standard rules applies * Input can be in any convenience form. * As long as you output is clean, understandable, readable, it is allowed. * The two random value `X`,`Y` should be *uniform statistically independent* random by itself(`X` and `Y` are not affecting each other no matter what) ## what you should do? * Start golfing right now! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` ḶJX,XƊṬ×ịÆm¥oʋƊ⁹¡µṂ;Ṁ;Æm, ``` [Try it online!](https://tio.run/##ATwAw/9qZWxsef//4bi2SlgsWMaK4bmsw5fhu4vDhm3CpW/Ki8aK4oG5wqHCteG5gjvhuYA7w4ZtLP///zEw/zU "Jelly – Try It Online") Outputs `[[min, max, mean], list]`. Takes `length` as the first argument, and `generation` as the second ## How it works ``` ḶJX,XƊṬ×ịÆm¥oʋƊ⁹¡µṂ;Ṁ;Æm, - Main link. Takes L on the left, G on the right Ḷ - [0, 1, ..., L-1] Ɗ - Previous 3 links as a monad f(R): J - Indices of R Ɗ - To the indices of R: X - Randomly choose one X - Randomly choose one again , - Pair; [i, j] ʋ - Last 4 links as a dyad g([i, j], R): Ṭ - Boolean array with 1s at i and j ¥ - Last 2 links as a dyad h([i, j], R): ị - Get R[i] and R[j] Æm - Take the mean × - Replace the 1s with the mean o - Or; replace the elements at i and j in R with the mean ⁹¡ - Apply f(R) G times µ - Use this list L' as the new argument Ṃ - Minimum Ṁ - Maximum Æm - Mean ; ; - [Min, Max, Mean] , - Pair with L' ``` [Answer] # APL+WIN, 60 bytes Prompts for length and generation. Index origin = 0 ``` v←⍳l←⎕⋄⍎∊⎕⍴⊂'v[i]←(+/v[i←(?l),?l])÷2⋄'⋄(⌊/v),(⌈/v),(+/v÷l),v ``` [Try it online!Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tfxmQ@ah3cw6I6pv6qLvlUW/fo44uELt3y6OuJvWy6MxYoKSGtj6QBWLY52jq2OfEah7ebgRUrg7EGo96uvTLNHWAdAeYBqo9vB2orOw/0A6u/2lchgZcplxgytDAwIALAA "APL (Dyalog Classic) – Try It Online") The results in TIO are output in the order listed in the question. The second example in TIO shows that by generation=1000 all elements of the output have converged to the mean in that particular case. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 25 bytes ``` ʁ?(₅‹₍℅℅~İṁ£(n¥Ȧ)):₌₍GgṁW ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLKgT8o4oKF4oC54oKN4oSF4oSFfsSw4bmBwqMobsKlyKYpKTrigozigo1HZ+G5gVciLCIiLCI3XG4zIl0=) 25 bytes of fun. Takes `length` then `generations` and outputs `[list, [Max, Min], average]`. Can be [24 bytes with the `W` flag](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwiyoE/KOKCheKAueKCjeKEheKEhX7EsOG5gcKjKG7CpcimKSk64oKM4oKNR2fhuYEiLCIiLCI3XG4zIl0=) ## Explained ``` ʁ?(₅‹₍℅℅~İṁ£(n¥Ȧ)):₌₍GgṁW ʁ # The range [0, length) - this will be the list we modify ?( # (generation) times: ₅‹ # push the top of the stack, and its length + 1 ₍℅℅ # choose two random items from the range [0, length) and place them into a list ~İ # without popping anything, get the item at each randomly chosen index from the top list - this leaves [list, indexes, items] on the stack ṁ£ # place the average of those two items into the register (...) # for each index i in the indexes list: n¥Ȧ # list[i] = register (the mean) ) # close the main for loop : # now the top of the stack is the list with all the replaced items. We duplicate it so we can extract the juicy info from it ₌₍Ggṁ # Push a list of [max, min] and push the mean of that list W # Wrap everything into a single list and implicitly print ``` [Answer] # JavaScript (ES6), 145 bytes Expects `(length)(generation)`. Returns `[min, max, avg, list]`. ``` with(Math)f=(n,a=[k=n],R=random)=>g=m=>k?g(m,a[--k]=k):m?g(m-1,a[i=R()*n|0]=a[j=R()*n|0]=(a[i]+a[j])/2):[min(...a),max(...a),eval(a.join`+`)/n,a] ``` [Try it online!](https://tio.run/##Zc3NDoIwEATgu0@yK6WAiReTxSfwwrVpwobfAm0NEPTgu2NNTDx4m/nmMANvvFSzua@x83Wz7w@z9nDjtceWwAkmNZLToqCZXe0tUt6RpXy8dmAFqzgeNY14sZ8eZ0EMFYBH90o1sRp@BcKko0AakxNelDUOpJSMwvLzm5qNJ2A5eOPKqMQk/Ou98m7xUyMn30ELWYqQIh7@9ZwG398 "JavaScript (Node.js) – Try It Online") [Answer] # Python, 134 bytes ``` from random import* R=randrange def f(l,g):*a,=range(l);exec("a[x]=a[y]=a[x:=R(l)]/2+a[y:=R(l)]/2;"*g);return min(a),max(a),sum(a)/l,a ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY329KK8nMVihLzUoBUZm5BflGJFleQLUgAiNNTuVJS0xTSNHJ00jWttBJ1bMGCGjma1qkVqckaSonRFbG2idGVIKLCyjYIKBOrb6QNFIFzrJW00jWti1JLSovyFHIz8zQSNXVyEytAVHFpLpDSz9FJhLhmQ0FRZl6JRpqGoYGOgqGBpiZEGOZYAA) -13 bytes thanks to pxeger using `randrange` and `:=` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes ``` FN⊞υιFENE²‽LυUMυ⎇№ιλ⊘ΣEι§υμκI⟦⌊υ⌈υ⊘⊖Lυυ ``` [Try it online!](https://tio.run/##VY49C8IwEIb3/oqMF4iggpOT1MGClaJu4hDbaIP5KGlS6q@PlyKiNx333vPc1S13teUqxrt1BArTBX8I@iYcUEqq0LcQGJF0nU15ybv/HUbSaMnIkZvGatgL8/DI0FQpy63WGCXLWTjD3QtyG4wHyYhCfMfVIBo4BT3JcbrxhWnEmAidLIw8Kd6vnEQq572HSymN1EiE6f747T@yraid0MJ47H8eYiRc0RTjYp6t4mxQbw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FN⊞υι ``` Generate a range of length `length`. ``` FENE²‽Lυ ``` Generate `generation` pairs of random integers also in that range, and loop over those pairs. ``` UMυ⎇№ιλ⊘ΣEι§υμκ ``` Update the array at those two indices with the average of the two values that are there. ``` I⟦⌊υ⌈υ⊘⊖Lυυ ``` Output the minimum, maximum, average and values. [Answer] # Python3, ~~133~~ ~~131~~ 128 bytes ``` from random import* def f(l,g): *r,=range(l) while g:shuffle(r);*r,x,y=r;r+=[(x+y)/2]*2;g-=1 return min(r),max(r),sum(r)/l,r ``` [Try this online](https://ato.pxeger.com/run?1=NY49DoMgGIZ3TvGNoBh_pkbDSZoOJgKSAJpPiDr1IF1c2gv0NL1NaUzf5RneZ3ger3kP4-SP4xmDKi6fu8LJAfZ-SDBunjBkZJAKFLVcs5ZAhlykX0tqGYF1NFaCbpcxKmUlRdYlYeO7wA5zcaVbvrOyuWVNpwtRE0AZInpwxieXu377YYkuobQcz4z3jMYHqmhdcairNMbO5x_6BQ) [Answer] # [J](http://jsoftware.com/), 44 bytes ``` (<./;>./;];+/%#)@(2&((?#)(2%~1#.{)`[`]}])i.) ``` [Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWz09K3tgDjWWltfVVnTQcNITUPDXllTw0i1zlBZr1ozITohtjZWM1NP878mV2pyRr6CiUKagqEBF9d/AA "J – Try It Online") Outputs Min / Max / List / Avg [Answer] # [Factor](https://factorcode.org/), 87 bytes ``` [ iota >array [ randomize 2 cut* mean dup 2array append ] repeat dup minmax pick mean ] ``` [Try it online!](https://tio.run/##TVDRSsNQDH3vVxyfBkVKN98Uhi8ivkzQ@TT2ENt0DWvvveamY9vP17tOVAIhyTmc5KShyryOH@8vq@d7kCqdInbsWKmTM5l4F7FnddyhJ2unVERLSDSpIpRc7XtE/hrYVRz/qoKPphQRlM1OQcUZHrJsfluWJebluIF4Iyynpdj8KMmZsUA1WI6eyaEeAhZXCoXArsYWyoHJJqgX19MRQar9lb8dK@q6bJMEl03nE22bbg4p39US/k9N5RHADfI8x@p1/TQV61YiOnGMyrsDq0VYy/CDhcHQaPKql7eksccklSx7iM0inDcQnOxa60n5wlCmusAb9/6Q@l9taXDyA2rvZoZP7oQT3HORFZiiKMZv "Factor – Try It Online") [Answer] # [BQN (CBQN)](https://mlochbaum.github.io/BQN/), 56 bytes ``` {A←+´÷≠,(⌈´∾⌊´∾A∾⋈){∾˜∘A⌾((2•rand.Range≠𝕩)⊸⊏)𝕩}⍟𝕨↕𝕩} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m704qTBvwfpH81ekPZq_UuFR2wQFIHtpaUmarsXN9GpHoID2oS2Htz_qXKCj8ain49CWRx37HvV0gWlHELu7Q7MaSJ-e86hjhuOjnn0aGkaPGhYVJeal6AUl5qWnAnV-mDt1peajrh2Puvo1QezaR73zgfSKR21TwVyIdZuADuDiAuoNzsgvVzBScFMwhUgsWAChAQ) fixed after ovs' comment. -1 from ovs. [Answer] # [Julia](http://julialang.org/), 81 bytes ``` l\g=(L=[0.:~-l;];1:g.|>_->(r=rand(1:l,2);L[r].=sum(L[r])/2);(extrema(L),~-l/2,L)) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/Pycm3VbDxzbaQM@qTjfHOtba0Cpdr8YuXtdOo8i2KDEvRcPQKkfHSNPaJ7ooVs@2uDRXA8TS1AcKaaRWlBSl5iZq@GjqADXrG@n4aGr@dyjOyC9XMDSIMeQiwDSFMs1jDA0M/gMA "Julia 1.0 – Try It Online") expects `length\generation` and returns `((min, max), mean, list)` [Answer] # TI-Basic, 85 bytes ``` Prompt L,G seq(I,I,0,L-1→A For(I,1,G rand(dim(ʟA→B SortA(ʟB,ʟA mean({ʟA(1),ʟA(2→ʟA(1 Ans→ʟA(2 End Disp min(ʟA),max(ʟA),mean(ʟA),ʟA ``` `seq(I,I,` can be replaced with `randIntNoRep(` for -3 bytes if the calculator supports it. Output is displayed. ]
[Question] [ Your Challenge is to take a binary string as input and get all binary numbers between itself and the reverse of its string representation (the reverse may be less than or greater than the original input). Output must be padded with zeroes to be the same length as the input. The Order in which the values are displayed doesn't matter, but the Code needs to work with Values that are bigger than its reverse. ## Test Cases ``` Input: (1 or 0) Output: None, string and its reverse are identical Input: (any palindrome binary) Output: None, same as above Input: 01 Output: None, since there is no binary between 01 and 10 (1 and 2) Input: 001 Output: 010,011 (Numbers between 001 (1) and 100 (4): 2,3) Input: 100 Output: 010,011 (Same as above) Input: 0010 Output: 0011 (Numbers between 0010 (2) and 0100 (4): 3) ``` This is Code Golf, shortest code wins! EDIT: After seeing some of the solutions i have removed the requirement of the number representation of the binary being in ascending order. This is my first code golf challenge and i don't want to make it to tedious, also added some clarifications from the comments. [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 23 bytes ``` ,UV€€Ḅr/BḊṖṭ@¹Uz0ZUṖṾ€€ ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCIsVVbigqzigqzhuIRyL0LhuIrhuZbhua1AwrlVejBaVeG5luG5vuKCrOKCrCIsIsOHWSIsIiIsWyJcIjAwMVwiIl1d) Follows the input format very strictly (input as string, output as list of strings including padding zeroes). # [Jelly](https://github.com/DennisMitchell/jellylanguage), 8 bytes ``` ,UḄr/ḊṖB ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCIsVeG4hHIv4biK4bmWQiIsIiIsIiIsWyIwLCAwLCAxIl1d) Using actually reasonable I/O formatting, if we accept a list of digits and output as digit lists without doing leading zeroes, this is a lot more suitable for Jelly. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` ṘB$BrḢƛb?L∆Z ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZhCJEJy4biixptiP0ziiIZaIiwiIiwiJzAxMDAnIl0=) Outputs as a list of lists of bits. ``` ṘB # x reversed as an integer $B # x as an integer rḢ # Exclusive range ƛ # Map... b # convert to binary ∆Z # Zfill to... ?L # Input length ``` [Answer] # x86-16 machine code, ~~58~~ 57 bytes ``` 00000000: 8be9 e82a 008b da8b cdfd 4ee8 2100 3bda ...*......N.!.;. 00000010: 7602 87d3 433b da73 1f8b cd8b c303 f957 v...C;.s.......W 00000020: 4fd1 e850 b000 1430 aa58 e2f5 5feb e533 O..P...0.X.._..3 00000030: d2ac d0e8 13d2 e2f9 c3 ......... ``` Listing: ``` 8B E9 MOV BP, CX ; save input "Binary Pad" length to BP E8 002A CALL BINDEC ; BX = forward input value 8B DA MOV BX, DX ; forward number in BX 8B CD MOV CX, BP ; restore input pad length FD STD ; reverse string load/store direction 4E DEC SI ; fix offset - SI is one char off E8 0021 CALL BINDEC ; DX = reversed input value 3B DA CMP BX, DX ; is reversed number smaller? 76 02 JBE MID_LOOP ; if not, start looping through middle numbers 87 D3 XCHG DX, BX ; otherwise swap numbers MID_LOOP: 43 INC BX ; increment middle number 3B DA CMP BX, DX ; is less than end number? 73 1F JAE DONE ; if not, return 8B CD MOV CX, BP ; restore input pad length 8B C3 MOV AX, BX ; AX = next number DECBIN: ; convert value in AX to string at [DI] 03 F9 ADD DI, CX ; move pointer to end of padded output buffer 57 PUSH DI ; save position for next number 4F DEC DI ; fix offset - DI is one char off LOOP_BIT: D1 E8 SHR AX, 1 ; CF = LSb of number 50 PUSH AX ; save number B0 00 MOV AL, 0 ; zero AL 14 30 ADC AL, '0' ; convert CF to ASCII AA STOSB ; write char to [DI] 58 POP AX ; restore number E2 F5 LOOP LOOP_BIT ; loop next bit 5F POP DI ; restore next number output offset EB E5 JMP MID_LOOP ; keep looping BINDEC: ; convert ASCII binary string at [SI] to DX 33 D2 XOR DX, DX ; zero output value LOOP_DEC: AC LODSB ; load next char into AL D0 E8 SHR AL, 1 ; CF = LSb of ASCII char 13 D2 ADC DX, DX ; shift LSb left onto result E2 F9 LOOP LOOP_DEC ; loop until end of string DONE: C3 RET ; return to caller ``` Callable function, input binary string in `[SI]` length in `CX`, output to `[DI]`. No helpful built-ins in machine code... just brute force string to decimal and back stuff! Test program output: [![enter image description here](https://i.stack.imgur.com/MSsAh.png)](https://i.stack.imgur.com/MSsAh.png) [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, 27 bytes ``` 0X#a-#_._MTB$,[1]+SNFB[Raa] ``` [Replit!](https://replit.com/@dloscutoff/pip) Or, here's a 28-byte equivalent in Pip Classic: [Try it online!](https://tio.run/##K8gs@P8/xElFJ9owVjvYz80pOigsMTH2////ugX/DQ0MAA "Pip – Try It Online") Could be 17 bytes without the 0-padding requirement. ### Explanation ``` 0X#a-#_._MTB$,[1]+SNFB[Raa] [ ] List containing Ra Reverse of argument a and argument FB Convert each from binary SN Sort in ascending order [1]+ Add 1 to the first (smaller) number in the list $, Create a range from the first (inclusive) to the second (exclusive) TB Convert each to binary M Map this function to each: #a-#_ Length of original input minus length of argument 0X That many zeros ._ Concatenate with argument ``` [Answer] # JavaScript (ES6), 88 bytes ``` x=>(f=y=>y<z[1]?[y,...f(y+1)]:[])(-~(z=["0b"+x,"0b"+[...x].reverse().join``]).sort()[0]) ``` [Answer] # [Python](https://www.python.org), 87 bytes ``` lambda s:[f"{x:b}".zfill(len(s))for x in range(*sorted([int(s,2),int(s[::-1],2)]))][1:] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3w3MSc5NSEhWKraLTlKorrJJqlfSq0jJzcjRyUvM0ijU10_KLFCoUMvMUihLz0lM1tIrzi0pSUzSiM_NKNIp1jDR1wIxoKytdw1ggN1ZTMzba0CoWarxeQRFIPk1DyVBJU5MLwTMwQOEbQAQguhYsgNAA) Can probably be shorter, but I'm not interested in golfing it. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` ⊞υθ⊞υ⮌θ←E…⊕⍘⌊υ²⍘⌈υ²⮌⍘ι²UB0 ``` [Try it online!](https://tio.run/##TcrBCoJAEIDhe0@xeJqBDdaOefMWFIQ@wbBOm2SjjpuvP0UUeP2/P95J40iD2VV7yXA88y17d6EJGpLEcJKo/GTJ3EFNC7f58yWYvTsgerdJDa@sC8OMP/uHzdN/CbHatZxrio@k40s6KEKBlVkoQyhtvw5v "Charcoal – Try It Online") Link is to verbose version of code. Outputs the values in descending order. Explanation: ``` ⊞υθ⊞υ⮌θ ``` Push the input and its reverse to the predefined empty list. ``` ←E…⊕⍘⌊υ²⍘⌈υ²⮌⍘ι² ``` Convert the minimum and maximum of the input and its reverse from base 2, loop over the intermediate values, convert them back to base 2, then print them in reverse order and right-justified. ``` UB0 ``` Fill unprinted areas with zeros. [Answer] # Python3, 74 bytes: ``` lambda x:[f"{i:b}".zfill(len(x))for i in range(int(x,2)+1,int(x[::-1],2))] ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUaHCKjpNqTrTKqlWSa8qLTMnRyMnNU@jQlMzLb9IIVMhM0@hKDEvPVUjM69Eo0LHSFPbUAfMjLay0jWMBQpoxv4vKAIJpWmoG6pranLBeQaoPDRJTD5I/X8A) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 62 bytes ``` $ ¶$^$` O`.+ /(.+)¶\1$/^{-1`¶ ¶$%`¶ )-2%T`d`10`01*$ ,,-1A` A`$ ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8F@F69A2lTiVBC7/BD1tLn0NPW3NQ9tiDFX046p1DRMObQNJq4JoTV0j1ZCElARDgwQDQy0VLh0dXUPHBC7HBJX//w24DLkMgAiCDQA "Retina – Try It Online") Link includes test cases. Explanation: ``` $ ¶$^$` ``` Append the reverse of the input. ``` O`.+ ``` Sort in ascending order. ``` /(.+)¶\1$/^{ )` ``` Repeat until the last two lines are identical. ``` -1`¶ ¶$%`¶ ``` Duplicate the last but one line. ``` -2%T`d`10`01*$ ``` Increment the newly duplicated line. ``` ,,-1A` ``` Delete the original input. ``` A`$ ``` Delete the line that duplicated the last line. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~33~~ ~~29~~ 27 [bytes](https://github.com/abrudz/SBCS) ``` (∊¨-⍤≢⍕¨⍤↑¨¯1↓1↓⊢⊤¨⍤…⍥⊥⌽)⍎¨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@NRR9ehFbqPepc86lz0qHfqoRUgZtvEQysOrTd81DYZhB91LXrUtQQi07DsUe/SR11LH/Xs1XzU23doxf@0R20TgKxHfVM9/R91NR9abwzUDuQFBzkDyRAPz@D/QPpRxwygukMr0g6tUFA3VAdiQwNDEG0AJsCkoYEBhG2gDgA "APL (Dyalog Extended) – Try It Online") **Explanation** (slightly outdated): `⍎¨` Evaluate each character of the input to get a vector of 0's and 1's. `…⍥⊥` Inclusive range, after converting the arguments from base 2: of the the vector `⍵` and its reverse `⌽⍵`. `¯1↓1↓` Make the range exclusive by dropping one value from the start and one from the end. `⊤¨` Convert all values in the exclusive range to base 2. `(-≢⍵)↑¨` Pad the binary values to the length of the input with 0's in the front. `∊¨⍕¨¨` In each binary number, convert each digit to a string, then join into a string. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` R‚CŸ¨¦bygjð0: ``` [Try it online](https://tio.run/##yy9OTMpM/f8/6FHDLOejOw6tOLQsyTM96/AGA6v//w0MDAE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/6BHDbOcj@44tOLQsqTK9KzDGwys/uv8jzbQMdQxNABCHSUDQyUgASMNlGIB). **Explanation:** ``` R # Reverse the (implicit) input ‚ # Pair it with the (implicit) input C # Convert both from a binary-string to an integer Ÿ # Convert this pair to a ranged list ¨¦ # Remove the first and last items to make it an exclusive list b # Convert each integer to a binary-string Ig # Push the input-length j # Pad leading spaces to each binary-string to make it that length ð0: # Replace every space with a 0 # (after which the result is output implicitly) ``` [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 90 bytes ``` x=>{for([x,y]=[1+x,1+[...x].reverse().join``].sort();++x<y;+t&&print(t.slice(3)))t='0b'+x} ``` [Try it online!](https://tio.run/##hclBDoIwEEDRvadwRacpTCAusV6EkIBYTBE7ZNqQEuPZKxdQ//K/qV97P7BdQuEXezP8JPcwWxp1ivryGomhifnW6qZSMa9Ug4ixRTarYW9A4kTWdV2LnjiArJWK561WIcsWti5AQD/bwcBJShm0KK9CxXcaQVRC1seBnKfZ4Ex3EMXePg87lr/1L5ffPH0A "JavaScript (SpiderMonkey) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 84 bytes ``` sub{($_,$e,@r)=sort@_,"".reverse@_;push@r,$_ while s/01*$/$&=~y|01|10|r/e&&$_<$e;@r} ``` [Try it online!](https://tio.run/##jY5NTsMwEIX3PcXImuYHGWIvYEEweI9EN@wAWUJyaERJgp0CVVOWHIAjcpFgp0kFAQksWfP0zXtPU2mzOGwxE61d3q4jVBQ1lSYWtjS1VJSQA6OftLFaqrRa2rk0FBU8z/OFBpswvocJBuJ11TDecNaYRAcBqhPUqTSbNs1KE11ByEPYPnEKN3TSSYfZ75gzzt0Px@6hZYQH7rDzsJD64di3Rvanh3m@8/xs@Lrluwrup6tn/Rx18v64f6XidRd8WEWYFxWV@qWKhUSV9ljelbUIMOvW8ZZWJi/qjEz3jyxMObMAH2/vAD47SJe6LggF4hUB/eiUWxM4A1LeEzgGcjG7hNm58/jmdLJpPwE "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 78 bytes ``` ->s{a,b=[s.to_i(2),s.reverse.to_i(2)].sort;(a+1...b).map{|x|"%0#{s.size}b"%x}} ``` [Try it online!](https://tio.run/##NcjRCkAwFIDhe08h0ginM7fiRbS01ZQL0Q7C7NlHyd3//WZTpx8aX7ZkZaGajmCd@zGtsoLA6F0b0v8RQLNZ61TmHABUBpNc7H3cUYKxJaDx0k5FyeGcX8KhY8gRmQi@xlecCf8A "Ruby – Try It Online") ]
[Question] [ Inspired by this stack of little statues that are currently on my desk at work, given to me by my colleagues from Sri Lanka when they visited The Netherlands: [![enter image description here](https://i.stack.imgur.com/sPZYQm.jpg)](https://i.stack.imgur.com/sPZYQm.jpg) This is split into two different challenges due to popular demand: Part 1) Determine the amount of statues (this challenge) Part 2) [Can the statues be stacked?](https://codegolf.stackexchange.com/q/216361/52210) ## Challenge 1: **Input:** \$statues\$: a multi-line string (or character matrix), containing only the characters `\n|-#` (where the `|-#` can be other characters of your own choice) **Output:** The amount of statues in the input. **Statues input example:** ``` ##| #### | # ## # # |## ---- |###### | ### |## |## # |## - |###### # |#### ``` The `|` and `-` represent the bases of the statues. So with the input above, we'll have the following statues: ``` #### ## # ## ## #### # ## # ## ## ### ## # # # ## ### ## # # ---- ------ -- - -- ``` So the output will be `5`. ## Challenge rules: * You can use a different consistent character other than `#`, `-`, and/or `|` for the statue if you want ( `\n` are mandatory, though). Please state which one you've used in your answer if it's different than the defaults. * You are allowed to take the \$statues\$ input in any reasonable format. Can be a multi-line string, a list/array/stream of strings, a character matrix, etc. * You are allowed to pad the statues input with trailing spaces so it's a rectangle. * You can assume statues are always separated by at least one space or blank line from one-another, so something like `#|#|` or `#||#` won't be in the input. * You can assume the statues will only have a base at ones side, so a statue like this won't be in the input: ``` ##| ##| -- ``` * It is possible that a smaller statue is within the rectangular boundaries of another oddly shaped statue. For example, this is possible: ``` # ## - ## ## #### # # ---- ``` * Statues will never be inside of each other, though. So something like this won't be in the input: ``` ##### ## # # # # # ## ## # -- ## # # ## # ------- ``` * You can assume the base determines the width of a statue. So you won't have statues like these in the input: ``` ####### ##### #### ### --- -- ``` ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: ``` ##| #### | # ## # # |## ---- |###### | ### |## |## # |## - |###### # |#### Output: 5 __________________________________________________ # ## - ## ## #### # # ---- Output: 2 __________________________________________________ # |### # | # # |#### - Output: 2 __________________________________________________ --- ##| ### ##| ### ### |# Output: 3 __________________________________________________ #### #####| # ## ### |# |# ##### |# |## ----- |# |# |# |# |# Output: 4 __________________________________________________ |# |# |# |# |# #| #| #| Output: 8 __________________________________________________ |## | ## |# -- Output: 2 __________________________________________________ |## ---- |#### # ## ### |# |# ###| |# #| |# ##| |# Output: 4 __________________________________________________ - |## # # #| ### #| --- Output: 4 __________________________________________________ # #### ---- -- # Output: 2 __________________________________________________ ## ## -- -- ## ## Output: 2 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` „-|v€Åγ˜y¢Iø}Š+ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcM83ZqyR01rDree23x6TuWhRZ6Hd9QeXaD939Pr0G4dLiUuBV07BSV7HYX/0dFKCko6CrgJZThRg1VJrI5CNJIiBIHNMEJGKBA2QoEYIxSwGFFDwGywEbogNhqB0wgMAmwEfqfW4A1iqBH4nYpfFo8RupR7RJmwEbDgjAUA "05AB1E – Try It Online") **Commented:** ``` „-| # push string literal "-|" v } # iterate over this string €Åγ # run-length encode each line of the input / transposed input # this pushes the chunk elements and the chunk lengths ˜ # flatten the list y¢ # count the chunks of the current character Iø # push the transposed input to the stack for the second iteration Š # triple-swap: move the transposed input to bottom + # sum both counts ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~93~~ ~~86~~ ~~61~~ 58 bytes *Saved seven bytes, thanks to [Razetime](https://codegolf.stackexchange.com/users/80214/razetime)!* *Saved three bytes, thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!* ``` ->s{((s.transpose*"").scan(/\|+/)+(s*"").scan(/-+/)).size} ``` [Try it online!](https://tio.run/##rVLbasMwDH3XV4gYRrLi9r3Q/kibhyxL2kBu2Alsa/rtmSW7npNCnyaMbV2scyRLjR/fc3mY5VHf4lhvB5W1uu908R5FyVbnWRvvztNml2xiHZiksZh79VPcZ4HXou4LheXY5kPVtTh02Kvuc8wLbLJBVV/YlZhfM6WxVF2DzVgPVV21BWrjbS@4T@CCB5TH5laemq3u62qIo3Nr8Jqsj9/2/DhJ7wA9Xk4Rsggx0QHCCF2chlZDp6FZkzWBNMIaCdiQiTMJsDF2t5pcRAqrIUapY0FIIJH9ZuNIY7MwPspxpYyCT/QIhOHjiJqpiNL401VnkANUEdRn2yBcJ3zNq4i1wDoFASwULka8iBBcpHyZ4wl3WqH@R4Tvy8Rt8st0hFfgp5dgvxsozdMnuTFZzMlzQ133HkTgjxf9A4Q0l@raG5CXDhvEY1yQ6Qt3CQdKPGaeaYIjTEQWw0kDCeynndUonX8B "Ruby – Try It Online") Takes input as a matrix of characters. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 37 bytes ``` -+|(?<=(.)*)¦(?!.*¶(?<-1>.)*(?(1)$)¦) ``` [Try it online!](https://tio.run/##K0otycxL/P9fV7tGw97GVkNPU0vz0DINe0U9rUPbgCK6hnZAIQ17DUNNFaCE5v//CmCgrHxoGZcyEIA4ICZQBEgoKIN4QKYuEECYIMAF0XRoGVinMhdIXAEiDRKB8HVRlStDuQA "Retina 0.8.2 – Try It Online") Uses `¦` instead of `|`. Explanation: ``` -+| ``` Count runs of `-`s, or... ``` (?<=(.)*)¦(?!.*¶(?<-1>.)*(?(1)$)¦) ``` ... any `¦`s which do not have a `¦` directly underneath them on the next line. This uses a .NET balancing group to ensure that the two `¦`s are vertically aligned. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ,ZŒrFċ¥"Ø^S ``` [Try it online!](https://tio.run/##y0rNyan8/18n6uikIrcj3YeWKh2eERf8/@HuLYfb//9XAANl5RgQxaUMBCAGlKcA4SlAeQpAFAMR4tIHAjAPBLggSmLAJilzQdRASAhPH0WlMoSnoAAA "Jelly – Try It Online") The statues have a polished bottom, so they use `/` instead of `-` and `\` instead of `|`. The input is a list of strings that must be the same length. ## Explanation ``` ,ZŒrFċ¥"Ø^S Main monadic link , Pair the input Z with the input transposed Œr Run-length encode everything " Zip with ¥ ( F Flatten left argument ċ Count the occurences of right argument ¥ ) Ø^ with "/\" S Sum ``` [Answer] # [Perl 5](https://www.perl.org/) `(-p)`, ~~50~~, 30 bytes Using `I` instead of `|` (first rule), and padding input with trailing spaces so it's a rectangle (third rule). ``` / /;$_=()=/-+|I(?!.{@{-}}I)/gs ``` [Try it online!](https://tio.run/##rVRhS8NADP2eXxHJoBtyq8wVZFIUQeS@6E/oJxFhuLJ1INT@desll7W9DgbeFo5eXxte0veaK9@366x9en6xr/UkzZMi@c5ucJ4AJE2bQno/KfLpLE/N9Y@dPlzN68faNI2dpR@7tkUJIssbkAu@UYQeoSJ0y/pHYFwI4gCfYoWJwOf4q0cmyCSPHAu87atyX60wg@LfAdIgGBRad5EC7pnvridfRJGrMtw/yY7d9/AXnUvP@jnZueluVwucPANpbuOkoYF33mJSlzs/RxnjgDEF9xUAqUInMkicMCc5juraUdWLZHRyLqPktGJKt5yQsnrau0ha7hP84HARvNR/q3MaDOqx62rxQS3oxeOfBYZahnD89nyFjbYMdBg8FI1Jb4KJXkYeF3rE6fnAwgAG59AicthASJlSwYDxd1NWn5uvXWvW5R8 "Perl 5 – Try It Online") How * `/-+|I(?=.{@{-}}I)/gs` to match `-` runs or `|` not followed by `|` bellow * `(()=...)` list context * `$_=` list is coerced to int size Saved 13 bytes negating the lookahead, similarly to @Neil's retina answer. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` WS«Fι«F²⊞υ›⁼κ§-|λ⁼⊟KD²✳∨⊗λ⁴κκ»⸿»⎚IΣυ ``` [Try it online!](https://tio.run/##VY5BawMhEIXP9VcM62UE9xJ666kkpeSUhVx7sRvblbVr6mpaqPntdtRA6UMe3xvnoeOk/OiUzflrMlYD7pdzDMfgzfKOQsAPu3tzHtBUbLwRMMR1wijh2WsVtMenz6jsirOEx7BfTvobuz51EqwQEm6XgzvjoPW8M16PwbgFNxL@wsHjzsVXq09oqXQvROnO5A/08EAfCjgXvrJb6l58R4Mr21qtPBK2@VatAY/xA2Mp5wxVnCfGSYWJKJMBnUTUkyoVsVZItcRZqp3mLfX/NnlLLPcX@ws "Charcoal – Try It Online") Link is to verbose version of code. Finally managed to beat Retina. Explanation: ``` WS« ``` Repeat on each line of input. ``` Fι« ``` Repeat on each character. ``` F²⊞υ›⁼κ§-|λ⁼⊟KD²✳∨⊗λ⁴κ ``` If the character is a `-` or a `|`, then check whether the character to the left is also a `-` or character above is also a `|` as appropriate. Record whether this character therefore begins a new statue. ``` κ»⸿» ``` Print the character and start a new line for every line of the input. ``` ⎚IΣυ ``` Print the total number of statues seen. My previous 38-byte approach used direct calculation: ``` WS⊞υιIΣ⁺Eυ⁻№ι-L⌕Aι--EEθ⭆υ§λκ⁻№ι|L⌕Aι|| ``` [Try it online!](https://tio.run/##dY1NCoMwEIX3OcVgNiPEE3QlQkGoIPQE0oqGptFq0naRu6cTx00LfeTvm3nzchm75TJ1JsbXqE0PWNvZu7NbtB0wz6H164hegc4PoqWiw6pbHZ79HVvjV2y6ObUbbQmqyZNBK8iKLFdw6u3gRjxqey2N4To1SDRAc2k/FPBne1Dpanvt32gU3Nj4kxz@JIewJScdYoRNUoZ0CUlKj52ACXYCWoFLoiBtlCTYErYkKdjDJ1Px5ZRMlBKLp/kA "Charcoal – Try It Online") Link is to verbose version of code. Requires padded input. Explanation: Each base of each horizontal statue contains a number `n` `-`s. But it also contains `n-1` `--`s, if you include overlaps, which the `FindAll` command does. Therefore the number of horizontal statues in a line is the number of `-`s minus the number of overlapping `--`s. It then remains to transpose the input and count the difference between the number of `|`s and the number of overlapping `||`s. ]
[Question] [ Given input `n`, produce a word grid of size `n`, in as few bytes as possible. ## Details The number provided will always be odd. The centre square of the grid must always be empty (a space character). The letters that fill the grid must be chosen at random from the [English Scrabble letter distribution](https://en.wikipedia.org/wiki/Scrabble_letter_distributions) of letters. That is, each tile must be chosen at random, with uniform probability, from the following 100 characters: ``` ??EEEEEEEEEEEEAAAAAAAAAIIIIIIIIIOOOOOOOONNNNNNRRRRRRTTTTTTLLLLSSSSUUUUDDDDGGGBBCCMMPPFFHHVVWWYYKJXQZ ``` where `?` denotes blank tiles. As with a Scrabble board, some tiles in this board will also be bonus tiles for a higher score. These tiles are only visible on a board with a size of 9 or more. and should be visible every 3 rows from the centre square in a pattern emanating outwards, but should never appear on the outermost letters. Bonus squares are denoted using lowercase letters, with blank tiles identified as `!` instead of `?`. Please see [this visual demonstration](https://gist.githubusercontent.com/dom111/e3131296b4cb6c7a5924/raw/663ff64514e6d6361baa804007ab937b9fe7fead/detail.txt) or the [reference implementation](https://tio.run/##hZNJb9swEIXv@hWvigpIcKPaKXJSEqdtuqRLuiRdXR8UmY5lUJRNUggCw7/dnaFk1XZalN@Fy7wZzhM1E1oerlbFHQKFYxxdXp2dX5wkHm2c6vLW0F4Y1UsprBWad@a3YR99vPgHT@9xfo8PO1xs8HmDqw3eNVw2fGk4a3jleEY8J94TH4mXxGviK/GN@EG8xRt8xyf8pNa8PYxLnQmUoxFUVVxTj16lpDAGIZnyEAcRFh5oBKrTSbwlS2RZzmAnuqxuJkilRCakNHEce5QMbGeBsBvHnGEfvahNwaYOgmJINg6GVJ031xL5V4kbe6Dc6WiUqxuk0KkalQXqL4KxprmdCMjcWNgSIs0mrbStuH8yCCTXDZovOeA0Ya/bjegiHLrk3pp4hcc4cJp6RjoffkIXEcXM3rl6mVBc38yrVAt25bpUlWnWhh9NYGyqLT@iMKwTRa43cvVJhA565AB3H3JszndzgoQXR1g74ZadY5YsWsOcZLopmW5LplsSHvmYzuv2ctfadAgxh9/3t7z@Y1obRc0/8JM2ZNnOhDTiv1qZ7ZaNdnM569fvgGIRut9vfa@ZzpXF6YKPlo/g/1I@P8TVqnf4Gw) for more examples on how to correctly distribute bonus tiles. ## Examples Input: `5` Output: ``` VNZNT IFOSN UD VD ZIOO? KTLED ``` Input: `9` Output: ``` UWDESTKPW ItDBaDEdI TERMDYSTR ROANJLEFT EkCI OOsT IPAJPGM?Y MZLORETVI G!EGgPUeI MNROYOEER ``` [Reference implementation](https://tio.run/##hZNJb9swEIXv@hWvigpIcKPaKXJSEqdtuqRLuiRdXR8UmY5lUJRNUggCw7/dnaFk1XZalN@Fy7wZzhM1E1oerlbFHQKFYxxdXp2dX5wkHm2c6vLW0F4Y1UsprBWad@a3YR99vPgHT@9xfo8PO1xs8HmDqw3eNVw2fGk4a3jleEY8J94TH4mXxGviK/GN@EG8xRt8xyf8pNa8PYxLnQmUoxFUVVxTj16lpDAGIZnyEAcRFh5oBKrTSbwlS2RZzmAnuqxuJkilRCakNHEce5QMbGeBsBvHnGEfvahNwaYOgmJINg6GVJ031xL5V4kbe6Dc6WiUqxuk0KkalQXqL4KxprmdCMjcWNgSIs0mrbStuH8yCCTXDZovOeA0Ya/bjegiHLrk3pp4hcc4cJp6RjoffkIXEcXM3rl6mVBc38yrVAt25bpUlWnWhh9NYGyqLT@iMKwTRa43cvVJhA565AB3H3JszndzgoQXR1g74ZadY5YsWsOcZLopmW5LplsSHvmYzuv2ctfadAgxh9/3t7z@Y1obRc0/8JM2ZNnOhDTiv1qZ7ZaNdnM569fvgGIRut9vfa@ZzpXF6YKPlo/g/1I@P8TVqnf4Gw). ## Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. * Any reasonable format can be used for I/O, assuming it is consistent. * You should be able to handle grids at least up to 999. * All [standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/9365) are forbidden. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~67 65 64 66 64~~ 63 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ”?;ØAx“³Ċu~Ṿr¥rṇ⁽ȦƑ’ḃ12¤µŒl⁾?!yW,WKF€ H3ṬṚ¤ṁ‘1¦ṚŒḄ0,0j«þ`ị¢X€€Y ``` A monadic link taking a number and returning a list of characters, or a full program printing the result. **[Try it online!](https://tio.run/##AX4Agf9qZWxsef//4oCdPzvDmEF44oCcwrPEinV@4bm@csKlcuG5h@KBvcimxpHigJnhuIMxMsKkwrXFkmzigb4/IXlXLFdLRuKCrApIM@G5rOG5msKk4bmB4oCYMcKm4bmaxZLhuIQwLDBqwqvDvmDhu4vColjigqzigqxZ////MTU "Jelly – Try It Online")** (I prefer it using `G` rather than `Y` since [that's more square](https://tio.run/##AX4Agf9qZWxsef//4oCdPzvDmEF44oCcwrPEinV@4bm@csKlcuG5h@KBvcimxpHigJnhuIMxMsKkwrXFkmzigb4/IXlXLFdLRuKCrApIM@G5rOG5msKk4bmB4oCYMcKm4bmaxZLhuIQwLDBqwqvDvmDhu4vColjigqzigqxH////MTU "Jelly – Try It Online")) ### How? ``` ”?;ØAx“³Ċu~Ṿr¥rṇ⁽ȦƑ’ḃ12¤µŒl⁾?!yW,WKF€ - Link 1, getLetterSets: no arguments ”? - literal '?' ØA - yield uppercase alphabet ; - concatenate ¤ - nilad followed by link(s) as a nilad: “³Ċu~Ṿr¥rṇ⁽ȦƑ’ - base 250 number ḃ12 - converted to bijective base 12 (frequencies) x - times (repeat each) µ - start a new monadic chain, call that uppers Œl - to lower-case ⁾?! - literal ['?','!'] y - translate (change '?'s to '!'s) W - wrap (that) in a list W - wrap (uppers) in a list , - pair K - join with a space, ' ' F€ - flatten €ach (both flattens the wrapped lists - AND makes the lone ' ' into [' ']) H3ṬṚ¤ṁ‘1¦ṚŒḄ0,0j«þ`ị¢X€€Y - Main link: number, n e.g. 13 H - halve 6.5 ¤ - nilad followed by link(s) as a nilad: 3 - literal three 3 Ṭ - untruth [0,0,1] Ṛ - reverse [1,0,0] ṁ - mould like (implicit range(int(right))) [1,0,0,1,0,0] ¦ - sparse application: 1 - ...to indices: 1 ‘ - ...action: increment [2,0,0,1,0,0] Ṛ - reverse [0,0,1,0,0,2] ŒḄ - bounce [0,0,1,0,0,2,0,0,1,0,0] 0,0 - literal [0,0] [0,0] j - join [0,0,0,1,0,0,2,0,0,1,0,0,0] ` - repeat left argument as right argument with: þ - outer product using: [[0,0,0,0,0,0,0,0,0,0,0,0,0], « - minimum [0,0,0,0,0,0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0,0,0,0,0,0], - [0,0,0,1,0,0,1,0,0,1,0,0,0], - [0,0,0,0,0,0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0,0,0,0,0,0], - [0,0,0,1,0,0,2,0,0,1,0,0,0], - [0,0,0,0,0,0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0,0,0,0,0,0], - [0,0,0,1,0,0,1,0,0,1,0,0,0], - [0,0,0,0,0,0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0,0,0,0,0,0]] ¢ - call the last link (1) as a nilad (the letter sets) ị - index into - gets the correct letter sets for each cell X€€ - random-choice for €ach cell in €ach row Y - join with newlines - if running as a full program: implicit print ``` [Answer] # [R](https://www.r-project.org/), ~~288~~ ~~281~~ ~~267~~ ~~257~~ ~~225~~ 214 bytes *thanks to @cole for -1 byte, reordering the `?` to collapse the 2 into `rep(2,10)`* *-10 bytes realizing that `row(m) == t(col(m))`* *-41 bytes thanks to user2390246 for reconfiguring the weights, golfing down the indexing, and some more usual R tips* ``` function(n){m=matrix(sample(el(strsplit("EOAINRTLSUDGBCMPFHVW?YKJXQZ","")),n^2,T,rep(c(12,8,9,6,4:1),c(1,1:4,1,10,5))),,n) K=n/2+.5 L=col(m) m[i]=chartr("A-Z?","a-z!",m[i<-(x=!(L-K)%%3&L-1&L-n)&t(x)]) m[K,K]=" " m} ``` [Try it online!](https://tio.run/##ZY7bSsNAEIbv8xTtQssszqobW2tKl1K1nhLP9VSJEGNKF7KbsFkxKj57XBW98WIG5vtmht80uXw0iXkFojK7LJ4qQr1Fa8SaxbNOrSw0aPquhEqskTVUiSrzDLIcKmuqMpcWyPR0cnhyMYsur3b3t3eOz/YOrm/Gd@HR7fmcICGUon7wcYYmKyEF7uMWBriJvSGn6Gbkwx66vo596nZRUy8Ues1fWe17kUiLHBT11L2MRbpMjDVAJmw@dp8T9tYm6MyIQS3aELGQdjob3YhxV5p2LdQ0/roNMYwFaRFPfTQvRtoMFjCgLhsOsMpK4UJ6vzz45sE/zn8E/zPNJw "R – Try It Online") Returns a matrix. Fairly simple implementation; samples n^2 values with the proper distribution, stores as an `nxn` matrix. `K` is the index of the center. `L=col(m)` is a matrix indicating the column number of each element in the matrix. Hence we compute `!(L-K)%%3` to get the possible columns (including the edges), i.e., those a multiple of 3 away from the center column. To remove the edges, we consider `L-1` and `L-n`. `L-1` is `0` (false) for the first column and `L-n` is `0` for the last column. Applying `&` (element-wise boolean `AND`) to these three yields a matrix with `TRUE` in those columns a multiple of three away from the center, excluding the edges. We store this result as `x`. If we take the transpose of `x`, `t(x)`, we get the same matrix, but for the rows, hence `x&t(x)` is a matrix we save as `i` containing: `TRUE` indices for the required cells, and `FALSE` everywhere else. Then we use `chartr` to perform the required transformation on `m[i]` and save the result as `m[i]`, change the center cell to a space, and return the matrix. Importantly as [user2390246 pointed out](https://codegolf.stackexchange.com/questions/142531/generating-word-grids/142541#comment349455_142541), we don't need to test `n>=9` because for `n<7`, there aren't any cells a multiple of 3 away from the center (apart from the center which is changed to a space anyway), and for `n==7`, the only cells a multiple of 3 from the center are on the edge so they are excluded. Neat! [Answer] # JavaScript (ES6), ~~247~~ 242 bytes *-5 bytes with help from @Shaggy* ``` n=>[...Array(p=n*n)].map((_,i)=>i==p>>1?" ":g(i/n|0)&g(i%n,c="AI9O8NRTEE6LSUD4G3BCMPFHVWY?2KJXQZ".replace(/(\D+)(\d)/g,(_,c,i)=>c.repeat(i))[Math.random()*100|0])?c<"A"?"!":c.toLowerCase():++i%n?c:c+` `,g=x=>x&&x<n-1&((n>>1)-x)%n%3==0).join`` ``` ## Test Snippet ``` let f= n=>[...Array(p=n*n)].map((_,i)=>i==p>>1?" ":g(i/n|0)&g(i%n,c="AI9O8NRTEE6LSUD4G3BCMPFHVWY?2KJXQZ".replace(/(\D+)(\d)/g,(_,c,i)=>c.repeat(i))[Math.random()*100|0])?c<"A"?"!":c.toLowerCase():++i%n?c:c+` `,g=x=>x&&x<n-1&((n>>1)-x)%n%3==0).join`` ;(R.onclick=L.onchange=I.oninput=function(){let n=+I.value,res=f(n);O.innerText=n+"\n"+(L.checked?res.replace(/[A-Z\?]/g,".").replace(/[a-z!]/g,"#"):res);})() ``` ``` <label><input id=L type=checkbox> Layout only</label> <button id=R>Rerun</button><br><input id=I type=range min=9 max=53 step=2 value=9 style="width:100%"> <pre id=O></pre> ``` [Answer] # [Perl 6](https://perl6.org), ~~162~~ ~~161~~ ~~154~~ 153 bytes ``` {(my@b=0,|(-$^m..$m).map({$_%%3+!$_}),0).map:{((my$e='AIJKQXZG'~'NRTBCFHMPVWYG'x 2~'EEEAAIIOONRTUSLD'x 4)~'??',$e.lc~'!!',' ')[@b Xmin$_]».comb».roll}} ``` [Try it online!](https://tio.run/##HY7NTsJAFIXX9CluySV3RuqkAaKJpIGqFYsC/osabShpE0ynJXVjU6Yv5o4Xq0NXJ/nOd5KzjfLkpJYFYAxOXTJZjEPHtnbsGL@kECi5kKstKzHodPpdEwPFLbthZyXTNkYOuf705n75PqGK5g9P5xdX17O7l9e3Cf1CryLP81zX9xcL3T0/3l5qOuAVjUZkYSSSdUWmSRYB8Y9xCEu5STH43P@JdSZDHXmWJErVcZaDLcQplEbrZ1VAOwUH9KujXrev2kOjdRAwZhjwg9I44jvbpLpSzYTxoaHqfw "Perl 6 – Try It Online") Takes (n-3)/2 as input, returns a list of lists of letters. Explanation: ``` -> $m { # Idea stolen from @Xcali's answer. my $e = 'AIJKQXZG' ~ 'NRTBCFHMPVWYG' x 2 ~ 'EEEAAIIOONRTUSLD' x 4; # Array containing 1 for bonus tiles, 2 for middle element, like # (0,1,0,0,1,0,0,2,0,0,1,0,0,1,0) my @b = 0, |(-$m..$m).map({ $_ %% 3 + !$_ }), 0; # Map column vector. @b.map: { # Compute element-wise minimum of row vector and value from # column vector. Select character pools accordingly and get # random items. ($e~'??', $e.lc~'!!', ' ')[@b Xmin $_]».comb».roll } } ``` [Answer] # [Perl 5](https://www.perl.org/), ~~246~~ 244 + 1 (`-n`) = ~~247~~ 245 bytes ``` $m=($n=$_-$_%2)/2;for(@a=(U x++$n)x$n){$_=(LUU,ULU,UUL)[$m%3]x($n/3).U x($n%3)if$z%@a&&$z%3==$m%3;substr$_,$m,1,$"if$m==$z++;s/L/-U/g;s/U/substr"EEAIONRT"x6 .AIJKQXZG."AIO?BCFHMPVWYGUUSSLLDD"x2,rand 100,1/ge;s/^-//;s/-\?/!/g;s/-(.)/lc$1/ge;say} ``` [Try it online!](https://tio.run/##JYxbT8JAEIX/Sm2mpJvudnoJvjQbQEFEF2@43rWpCoSEtqSFpGD8666jPJyckznfnNW0WraNgVy6UEhIBaROxDBKZmXldjPpaqvxPChYQ/qCVLpKa64VSSv2DLkTvzb0ijHzCaXkxGwxg53TzVotsljKPyipN@/1uoKUQ85DDjYxOVU7z0tqVCg0zilo3HP2YNAbXV7c3NrNoeX3Rmfn1w9PQ9@mY@fo@OR0fHV3/zjUejJRqt@3m4hXWfFphUHAQ5xPaelNIJKJlw4e/E8L12e4/IB9n22/jQnjn3K1XpRFbcS47QdhYETxCw "Perl 5 – Try It Online") [Answer] ### [C64 basic v2, 210 209 bytes] ``` 1t$="2?9E3E9A9I8O6N6R6T4L4S4U4D3G2B2C2M2P2F2H2V2W2Y1K1J1X1Q1Z":rEn 3fOx=1ton:fOy=1ton:a=rN(0)*100:b=1 4c=aS(mI(t$,b,1))-48:d=aS(mI(t$,b+1,1)):b=b+2:ifc>atH6 5a=a-c:gO4 6pO983+40*y+x,c:nE:nE:pO1003.5+n*20.5,32 ``` An input `n` 5 can be specified like ``` 0dA5 ``` That "5" to the end should be changed to any odd number. Don't give more than 25, then the program will overwrite itself. --- How to try it: google for "vice c64 emulator", install it, and copy-paste this basic code into it. To start the program, type: `RUN`. To clear the screen, press shift/home. And the result: [![enter image description here](https://i.stack.imgur.com/CFN1l.png)](https://i.stack.imgur.com/CFN1l.png) [Answer] # [Python 3](https://docs.python.org/3/), ~~214~~ ~~236~~ 240 bytes ``` lambda n:[[[choice([s,[[c.lower(),'!'][c<'A']for c in s]][((i-n//2)%3+(j-n//2)%3<1)*(i*j>0)*(i<n-1)*(j<n-1)])," "][i==j==n//2]for j in range(n)]for i in range(n)] from random import* s=(("OIAE"*2+"SDLUNTRE")*2+"HVBMCYPWF?GNTR")*2+"ZXJQKGIA" ``` [Try it online!](https://tio.run/##VY9Jb8IwEIXPza9wLVWxQ4ACUg8IF4Ut7PseckhDUhyBg@xIVX99aqfQ5bu8N08zT5rrZ3KKWSUNySE9e5e3owdY1XEc/xRTP0COMKUvnOOPgCNs6o@66/g13dLdMObAB5QB4boOQjTPisUyfqrkUHS3tRI2EDWi12elNZZXc5Spi00IoOtQQiJC1H5WGKlC7rH3ADGcJfRfooU8vqjxKIVerjFPDE0QhOCkZ7WhUc7BRWu4Gi/nbYjV1F03Rs3ddNOp2zL8zvbb/mxg9yyYekIEPAFC1gRHJDAhNwvr9fYfrDu9O5Mb44x5xjJjKFlIVpKWxLbtRqPZHI2m006n212vN5vdbtDfzvYQa@pD9vthySy9mGVc1R6unLIEyJd/LDwwWIhiyhC8KcdA3XN1H8pVjNMv "Python 3 – Try It Online") The multiplicity of each character is expressed as sum of powers of two, e.g `12 = 8 + 4 => "E"*12 = "E"*2*2*2 + "E"*2*2`. `((i-n//2)%3+(j-n//2)%3<1)*(i*j>0)*(i<n-1)*(j<n-1)` may probably be golfed. ]
[Question] [ # Background You're an attractive code golfer and quite a few people are asking you out. You don't have time to think about which days exactly you're available, so you decide to create a function the accepts a date and returns the days of that week. You then take those days of the week, insert it into your calendar program to see if anyone else has asked you out already. # Rules * Accepts a date in YYYY-MM-DD format * Returns an array/list of dates of that week. (Sunday is the first day) + The dates can be displayed as the milliseconds between January 1, 1970 and that date, in a "common" date format1, or date objects. * The order of the dates must be ascending. + (Although you're smart enough to include support for a descending list, the program is able to work quickest with an ascending list and who has a few milliseconds to spare?) * Must work with on any day since 1993. (Yes, you're 24 years old at the time of writing!) * Every Javascript answer gets a high five! # Specs **Sample Input:** `whichDates(2017-08-29)` **Output:** (the equivalent of) ``` console.log([ Date.parse('2017-08-27'), Date.parse('2017-08-28'), Date.parse('2017-08-29'), Date.parse('2017-08-30'), Date.parse('2017-08-31'), Date.parse('2017-09-01'), Date.parse('2017-09-02'), ]); ``` 1 A format that is fairly well known. Such as YYYY-MM-DD. 2 This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")! Shortest code per language wins, but the shortest code overall gets the emerald checkmark! [Answer] # [Perl 6](https://perl6.org), 47 bytes ``` {my$d=Date.new($_);map($d+*-$d.day-of-week,^7)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPu/OrdSJcXWJbEkVS8vtVxDJV7TOjexQEMlRVtLVyVFLyWxUjc/Tbc8NTVbJ85cs/a/NVdxIkirhpKRgaG5roGFrpGlkiZcNC@/XNP6PwA "Perl 6 – Try It Online") The code is almost self-explanatory. First we make up a Date object `$d` from the string, which happens to be in the nice ISOwhatever format. We can perform arithmetic with the dates (adding an integer = adding that many days, the same with subtracting). So `$d-$d.day-of-week` is the ~~last~~ this (oh my god, week has always started with Monday for me :D) week's Sunday. (`.day-of-week` is 1 for Monday to 7 for Sunday.) We then map over 0 to 6 (`^7`) and add that to the Sunday, getting all the days in the week. The number we're mapping over appears in the place of the star `*`. This list is then returned. [Answer] # JavaScript (ES6), ~~73~~ ~~63~~ 62 Bytes I thought I'd also have a go at it in JavaScript. Edit: Using the milliseconds approach, as allowed by the prompt, I reduced it down to 62 bytes. ``` s=>[..."0123456"].map(i=>(x=new Date(s))-(x.getDay()-i)*864e5) ``` You could perform a `.map(x=>new Date(x))` on the returned array if you wanted to convert it. --- Maintaining the date approach (**72 Bytes**) ``` s=>[..."0123456"].map(i=>new Date((x=new Date(s))-(x.getDay()-i)*864e5)) ``` --- There was a bug in my initial submission, it is fixed. Thanks to an observation by milk, I was able to remove the bug and still lower the byte count. [Answer] # JavaScript (ES6), 76 bytes I think I've finally found the environment least conducive to efficient golfing: from behind my bar, while serving pints with my other hand! ``` s=>[...""+8e6].map((_,x)=>d.setDate(d.getDate()-d.getDay()+x),d=new Date(s)) ``` [Try it online](https://tio.run/##PYyxDoIwFEV/hXTqS@kLMigOZXJ0c1QjDa2kCC2hjdKvr5EQt3Nzck8v39K3s5kC95NReh6dfemYniJ5UV8RkRBW6f0dRzlR@sgXELVCr8NJBk0VdhsB3zhSYAvkSlj9yVblAVLrrHeDxsF19ElJWewOvKh4eSSwlqOoIyOZyAj7/yJgcGfXykH/9iXMxnYUAHtnbHOzDaQv) (Snippet to follow) --- ## Explanation ``` s=> ``` Anonymous function taking the string (of format `yyyy-(m)m-(d)d`) as an argument via parameter `s`. ``` [...""+8e6] ``` Create an array of 7 elements by converting `8000000` in scientific notation to a string and destructuring it, which is shorter than `[...Array(7)]`. ``` .map((_,x)=> ) ``` Map over the array, passing each element through a function where `_` is the current element, which won't be used, and `x` is the current index, 0-based. ``` ,d=new Date(s) ``` Convert `s` to a `Date` object and assign it to variable `d` ``` d.setDate( ) ``` Set the date of `d`. ``` d.getDate() ``` Get the current date of `d`. ``` -d.getDay() ``` Subtract the current weekday number, 0-indexed, to get Sunday. ``` +x ``` Add `x`. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~22~~ 21 bytes ``` 7:j8XOs21Y2=f-GYO+1XO ``` Output is in `dd-mm-yyyy` format. Try it at [**MATL Online!**](https://matl.io/?code=7%3Aj8XOs21Y2%3Df-GYO%2B1XO&inputs=2017-9-1&version=20.4.1) ### Explanation ``` 7: % Push [1 2 3 4 5 6 7] j % Input as a string 8XO % Convert date to string with format 8, which is 'Mon', 'Tue' etc s % Sum 21Y2 % Push predefined literal [298 302 288 305 289 296 310]. The first number % is the sum of ASCII codes of 'Mon', the second is that of 'Tue', etc. = % Is equal?, element-wise f % Index of nonzero value. For example, if input is a Friday this gives 5 - % Subtract, element-wise. For a Friday this gives [-4 -3 -2 -1 0 1 2] G % Push input again YO % Convert to date number: number of days from January 0, 0000 + % Add, element-wise 1XO % Convert to date format 1, which is 'dd-mm-yyyy'. Implicitly display ``` [Answer] # Bash + common utilities, 53 ``` jot -w@ 7 `date -f- +%s-%w*86400|bc` - 86400|date -f- ``` [Try it online](https://tio.run/##S0oszvj/Pyu/REG33EHBXCEhJbEkVUE3TVdBW7VYV7Vcy8LMxMCgJik5QUFXAcKGqfj/38jA0FzXwELXyBIA). This assumes that the output of GNU date is a "common" date format, e.g. `Fri Sep 1 00:00:00 UTC 2017`. ### Explanation ``` date -f- +%s-%w*86400 # read date from STDIN, output expression "seconds-since-epoch - (index of day in week * 60 * 60 * 24) |bc # arithmetically evaluate generated expression - result is date of required sunday in seconds-since-epoch jot -w@ 7 ` ` - 86400 # output seconds-since-epoch for all 7 required days of the week, prefixed with "@" |date -f- # convert all seconds-since-epoch dates back to regular dates ``` [Answer] # Python 3, ~~133~~ ~~124~~ ~~126~~ 112 bytes -9 bytes thanks to Mr. Xcoder +2 bytes because the week starts with Sunday **-14 bytes** thanks to notjagan ``` from datetime import* a=date(*map(int,input().split('-'))) for i in range(7):print(a-timedelta(a.weekday()-i+1)) ``` That didn't go as well as I had hoped. [Answer] # [Japt](https://github.com/ETHproductions/japt/), 15 bytes ``` ÐU 7Æf1X+Uf -Ue ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=0FUKN8ZmMVgrVWYgLVVl&input=IjIwMTctMDgtMjkiCi1S) --- ## Explanation Implicit input of string `U`. ``` ÐU ``` Convert `U` to a date object and reassign to `U`. ``` 7Æ ``` Create an array of integers from `0` to `6`, passing each through a function where `X` is the current element. ``` f1 ``` Set the date of `U`. ``` X+Uf ``` Add the current date of `U` to `X`. ``` -Ue ``` Subtract the current day of the week of `U`. Implicitly output the resulting array. [Answer] # Mathematica 20 bytes? Mathematica expresses the list of days as a single date object. If such date object is acceptable output, the following 20-byte pure function will work: ``` #~DateObject~"Week"& ``` **Example** ``` #~DateObject~"Week"&["2017-08-29"] ``` [![week object](https://i.stack.imgur.com/OFu47.png)](https://i.stack.imgur.com/OFu47.png) [Answer] # Java 8 (~~161~~ ~~154~~ ~~123~~ ~~122~~ 102 + ~~19~~ 36 bytes) [Try it online!](https://tio.run/##PY4xa8MwEIV3/wotBanBws3iFieB0IyFDoF2CBmuytnIkSVhnQIh@Le7smv6tnvf4/hauEHuPNr2ch11511PLBCQVqxNSJLuUH44BeYAhPK5ypbRTCNpI@toFWlnJ5gpAyGwPXtkLGX5xN6dDbHDfnOkXttmx1q2HTHfPWrXc22J6W1R6U1ZHe@BsJMukvRpScZyD31AjkJ6E8MB7oHr1Sr/bxukVH7W34hXPp9fYCJy8VQKIaphTFKTio8/JqksRjenL6wDbfmf0enMoG@CWLyntBKUQk98AqfiLKoZDdkwjuvipcyL13z99gs "Java (OpenJDK 8) – Try It Online") ``` import static java.time.LocalDate.*; e->{for(int i=0;i<7;System.out.println(parse(e).plusDays(i++-parse(e).getDayOfWeek().getValue()%7)));} ``` [Answer] # Python 2, 115 Bytes or 111 Bytes, depending on input format. Basically, this is almost the same code in [the answer for Python3 written by Sobsz](https://codegolf.stackexchange.com/a/141327/4949), but made to work in Python 2. --- ### If input is in the form `YYYY-MM-DD`: (This assumes the input is not wrapped in single-quotes to denote a string as input) Key difference is that we need `raw_input` instead of `input`, unless we explicitly specify the date in `'YYYY-MM-DD'` within the apostrophes to identify it as a string literal. Without the string literal input, we get a Syntax Error, hence the use of `raw_input` to accept dates in `YYYY-MM-DD` directly without putting it in string literals. This of course assumes that the input is put in like so: `2017-08-29`. ``` from datetime import* a=date(*map(int,raw_input().split('-'))) for i in range(7):print a-timedelta(a.weekday()-i+1) ``` +4 from Sobsz's answer, then -1 because we don't need parentheses for the `print` statement and save a byte from the closing parenthesis not being there; total of +3 bytes difference. [Try it Online!](https://tio.run/##FcxNDoJADEDhPaeYHS06BNigJp7FNJmijcxPag3h9KNsX/K9stsrp6nWRXN0gYxNIjuJJat1Dd2PBF2kApLsrLQ9JJWvAfafsopB61tEbJasTpwkp5SeDDPeiv6BI3/8Aq9GQP3G/A60A3o5jVjrNIyzHy5@uv4A) --- ### If input is in the form `'YYYY-MM-DD'`: (Note that we must have the date provided inside quotes in order for this answer to work) We get to save 4 bytes because we don't need the `raw_` and this is effectively the same answer as Sobsz provides, minus a byte because we don't need the parentheses around the `print` command. Thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for pointing this one out, though this is **technically an exact duplicate then, minus one byte, of Sobsz's answer**. ``` from datetime import* a=date(*map(int,input().split('-'))) for i in range(7):print a-timedelta(a.weekday()-i+1) ``` ]
[Question] [ Given a string to encode, and a number of columns (the key), encode the string as follows: I will be using the example `Hello, world!` and the key `3` First, write out the number of columns: ``` 1 2 3 ``` Next, write the text starting from the upper left, one character per column, and when you run out of columns, go to the next line. ``` 1 2 3 H e l l o , w o r l d ! ``` Now, to get your encoded text, read the text starting from the top left corner, but this time, first read one column, and then the next, and so on. If there is not a character in the slot, put a space. ``` Hl r!eowl l,od ``` Note that here, there is a trailing space. This is your encoded text. Another test case is `Programming Puzzles and Code Golf SE` with key `5`: ``` 1 2 3 4 5 P r o g r a m m i n g P u z z l e s a n d C o d e G o l f S E ``` The encoded text is `PagzaooErm lndl omPedef gius rnz CGS`. **More test cases** ``` "abcdefghijklmnopqrstuvwxyz", 2 -> "acegikmoqsuwybdfhjlnprtvxz" "codegolf.stackexchange.com", 4 -> "cg.ccgoooskhemdltea. efaxnc " "Pen Pineapple Apple Pen!!!", 7 -> "PeAeeapnnpp! pl!Ple!ie n P " "1,1,2,3,5,8,13,21,34,55,89", 10 -> "18,,,5115,3,2,8,2931 ,, 53 ,4 " ``` Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes wins. [Answer] # [MATL](http://github.com/lmendo/MATL), 4 bytes ``` e!1e ``` [Try it online!](http://matl.tryitonline.net/#code=ZSExZQ&input=J0hlbGxvLCB3b3JsZCEnCjM) This is about as straightforward as possible. `e` is a builtin that reshapes a matrix into *n* rows. So we read in *input1* as a string, and shape into a matrix with *input2* rows: ``` Hl r! eowl l,od ``` Then, we transpose it to get this: ``` Hel lo, wo rld ! ``` After that, we just call `1e` to reshape it into a single row, and display it as a string. As you can see in [this sample program](http://matl.tryitonline.net/#code=ZSFv&input=J0hlbGxvLCB3b3JsZCEnCjM), the "reshape" function conveniently adds as many zeroes as necessary for the matrix to be a perfect rectangle. When displaying as a string, MATL treats '0's as spaces, so this automatically fills in the necessary number of spaces for no extra work. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` sz⁶ ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=c3rigbY&input=&args=SGVsbG8sIHdvcmxkIQ+Mw)** ### How? ``` sz⁶ - Main link: string, columns s - split string (a list of characters) into chunks of length column z - transpose the resulting list of lists with filler ⁶ - literal ' ' - implicit print ``` [Answer] # PHP, 85 Bytes ``` for(;$i<$x=$argv[2];$i++)for($j=0;$j<strlen($t=$argv[1])/$x;)echo$t[$i+$j++*$x]??" "; ``` PHP, 90 Bytes ``` for(;$i<$x=$argv[2];$i++)foreach(array_chunk(str_split($argv[1]),$x)as$a)echo$a[+$i]??" "; ``` [Answer] # Ruby, ~~78~~ ~~67~~ 65 bytes ``` ->s,k{s.gsub!(/(.)(.{,#{k-=1}})/){$><<$1 $2.ljust k}while s=~/./} ``` See it on eval.in: <https://eval.in/668412> # Ungolfed ``` ->s,k{ s.gsub!(/(.)(.{,#{ k -= 1 }})/) { $> << $1 $2.ljust k } while s =~ /./ } ``` [Answer] # Pyth - 5 bytes ``` s.tcF ``` [Try it online here](http://pyth.herokuapp.com/?code=s.tcF&input=%22Hello%2C+world%21%22%2C+3&debug=0). [Answer] ## Python 2, 46 bytes ``` lambda s,n:(s[0]+(s[1:]+-len(s)%n*' ')*n)[::n] ``` The idea is to take the input string, copy it `n` times with the first character from removed, then takes every `n`'th character. Let's look for example at `s="abcdef", n=3`, where the length is a multiple of `n`: ``` abcdefbcdefbcdef ^ ^ ^ ^ ^ ^ a d b e c f ``` The first cycle through the string takes every `n`th character from the first one. Then, each subsequent cycle shifts one index to the right because the first character is skipped. To ensure that the length is a multiple of `n`, the initial string is padded with spaces. [Answer] # Japt, 15 bytes ``` U+SpV f'.pV)y q ``` [**Test it online!**](http://ethproductions.github.io/japt/?v=master&code=VStTcFYgZicucFYpeSBx&input=IkhlbGxvLCB3b3JsZCEiIDM=) Japt has an "all subsections of length N" built-in, but neither a "all non-overlapping subsections" nor "every Nth char". Suddenly, there is a gaping hole in my life... ## Explanation ``` U+SpV // Take U concatenated with V spaces. f'.pV) // Take every substring of 3 chars. y // Transpose the resulting array. q // Join on the empty string. // Implicit: output last expression ``` [Answer] # Python 2, 58 bytes ``` lambda s,n:`sum(zip(*zip(*n*[iter(s+' '*~-n)])),())`[2::5] ``` Test it on [Ideone](http://ideone.com/KIXwFY). [Answer] # JavaScript (ES6), 84 bytes It's a recursive solution. ``` f=(s,k,i=0,r=Math.ceil(s.length/k),c=s[i%r*k+i/r|0])=>k*r==i?'':(c?c:' ')+f(s,k,++i) ``` [Answer] # R, 92 81 bytes ``` function(x,n)cat(t(matrix(c(el(strsplit(x,"")),rep(" ",-nchar(x)%%n)),n)),sep="") ``` [Try it on R-fiddle](http://www.r-fiddle.org/#/fiddle?id=NCDbVgEP&version=1) This turned out to be a bit of a headache because R automatically recycles the input vector when the rows or column specified in the matrix creation is not a multiple of the length of the input. Therefore we have to pad the vector with `-nchar(x)%%n` spaces before passing it to the matrix function. The last step is just transposing the matrix and printing it. [Answer] ## Perl, 61 bytes 54 bytes of codes and `-F -pi` flags. ``` for$l(1..$^I){$\.=$F[$^I*$_+~-$l]//$"for 0..$#F/$^I}}{ ``` Takes the input string without final newline, and the key should be placed after `-i` flag : ``` $ echo -n "Hello, World!" | perl -F -pi3 -E 'for$l(1..$^I){$\.=$F[$^I*$_+~-$l]//$"for 0..$#F/$^I}}{' Hl r!eoWl l,od ``` [Answer] # Mathematica, ~~43~~ 40 bytes *Thanks to miles for saving three bytes!* ``` Join@@Thread@Partition[##,#2,{1,1}," "]& ``` Unnamed function taking two arguments, an array of characters and an integer; returns an array of characters. Most of the heavy lifting is done by the `Thread` function, which (in this context) exchanges rows and columns. `Partition` needs to be called with a couple of useless arguments so that it will pad with the fifth argument `" "`. [Answer] ## Ruby, 89 bytes ``` ->s,i{t="";i.times{|n|s.ljust(i*(s.size*1.0/i).ceil).scan(/#{?.*i}/).each{|j|t<<j[n]}};t} ``` Terrible score, tips appreciated. [Answer] # Perl, 87 bytes ``` ($a,$b)=@ARGV;for$c(1..$a){for(0..(length$a)/$b){$e.=substr($a,$b*$_+$f,1)}$f++;}say$e; ``` Accepts two arguments as parameters and Usage: ``` perl -M5.010 encol.pl "Hello, World!" 3 Hl r!eoWll,od ``` [Answer] # Pyth, 40 bytes ``` =Zw=+Z*d+Q-*Q/lZQlZV*QlZIq%%NlZQ/NlZp@ZN ``` [Test it here](https://pyth.herokuapp.com/?code=%3DZw%3D%2BZ%2Ad%2BQ-%2AQ%2FlZQlZV%2AQlZIq%25%25NlZQ%2FNlZp%40ZN&input=3%0AHello%2C%20World%21&debug=0) Probably the ugliest Pyth code ever, but this is my first attempt at Pyth. ``` =Zw=+Z*d+Q-*Q/lZQlZV*QlZIq%%NlZQ/NlZp@ZN Q Set Q to eval(input()) =Zw Initialises Z to next input string lZ Gets the length of Z /lZQ Integer divides lZ by Q *Q/lZQ Multiplies that result by Q -*Q/lZQlZ Subtracts the length of Z from that +Q-*Q/lZQlZ Adds Q to that (This is how many spaces to pad) *d+Q-*Q/lZQlZ Gets that many spaces (d is set to ' ') =+Z*d+Q-*Q/lZQlZ Appends that to Z *QlZ Multiplies Q by lZ V*QlZ Does a for loop for integers in that range, on N %NlZ Gets N modulo lZ %%NlZQ Gets that modulo Q This is the column of the letter at index N mod Q /NlZ Gets the column that is being printed Iq%%NlZQ/NlZ If they are equal... p@ZN Print the index of N into Z without a newline (This is implicitly modulo the length of Z) ``` If anyone has tips to improve my golfing, please leave a comment! [Answer] # [Actually](http://github.com/Mego/Seriously), 12 bytes Golfing suggestions welcome, especially if you can figure out a golfier way to pad spaces. [Try it online!](http://actually.tryitonline.net/#code=OycgKihx4pWqZFjilKzOo86j&input=IlBlbiBQaW5lYXBwbGUgQXBwbGUgUGVuISEhIgo3) ``` ;' *(q╪dX┬ΣΣ ``` **Ungolfing** ``` Implicit input s, then n. ; Duplicate n. Stack: n, n, s ' * Push n spaces. (q Rotate s to TOS and append the spaces to the end of s. ╪ Split s into n-length substrings. dX Dequeue and discard any extra spaces that remain after chunking. This works even when we didn't need to add spaces in the first place. ┬ Transpose the remaining substrings. This returns a list of lists of chars. Σ Sum the transposed substrings into one list of chars. Σ Sum the list of chars into one string. Implicit return. ``` **Another 12-byte version** In this version, the order of the inputs is reversed, but this can be changed if that isn't allowed. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=4pSCbMKxJScgKm_ilarilKzOo86j&input=NwoiUGVuIFBpbmVhcHBsZSBBcHBsZSBQZW4hISEi) ``` │l±%' *o╪┬ΣΣ ``` **Ungolfing** ``` Implicit input n first, then s. │ Duplicate stack. Stack: s, n, s, n l± Push -len(s). % Push -len(s)%n, which gets the number of spaces we need to pad with. Call this m. ' * Push m spaces to the stack. o Append the spaces to the end of s. ╪ Split s into n-length substrings. ┬ Transpose these substrings. This returns a list of lists of chars. Σ Sum the transposed substrings into one list of chars. Σ Sum the list of chars into one string. Implicit return. ``` [Answer] ## Pyke, 10 bytes ``` k=.,Rc.,ss ``` [Try it here!](http://pyke.catbus.co.uk/?code=k%3D.%2CRc.%2Css&input=Hello%2C+World%21%0A3) [Answer] ## C#, 161 bytes I am so sorry. ``` (s,i)=>String.Join("",Enumerable.Range(0,i).SelectMany(x=>Enumerable.Range(0,s.Length/i+1).Select(n=>(n*3+x)).Where(m=>m<s.Length).Select(o=>s.Substring(o,1)))); ``` [Answer] # Groovy, 90 Bytes ``` {s,n->(s.padRight((int)(s.size()/n+1)*n) as List).collate(n).transpose().flatten().join()} ``` Pad the input by the ceiling of the size divided into `n` chunks. Get the padded string as a list of characters. Collate into n chunks and transpose. ``` ({s,n->(s.padRight((int)(s.size()/n+1)*n) as List).collate(n).transpose().flatten().join()})("Programming Puzzles and Code Golf SE",5) ``` Results in: ``` PagzaooErm lndl omPedef gius rnz CGS ``` [Answer] # Python 3, 48 bytes ``` lambda c,k:''.join([c[i:-1:k]for i in range(k)]) ``` [Answer] # Powershell, 57 bytes ``` param($s,$n)$r=,''*$n $s|% t*y|%{$r[$i++%$n]+=$_} -join$r ``` Test script: ``` $f = { param($s,$n)$r=,''*$n $s|% t*y|%{$r[$i++%$n]+=$_} -join$r } @( ,("abcdefghijklmnopqrstuvwxyz", 2 , "acegikmoqsuwybdfhjlnprtvxz") ,("codegolf.stackexchange.com", 4 , "cg.ccgoooskhemdltea.efaxnc") ,("Pen Pineapple Apple Pen!!!", 7 , "PeAeeapnnpp! pl!Ple!ie n P") ,("1,1,2,3,5,8,13,21,34,55,89", 10 , "18,,,5115,3,2,8,2931,,53,4") ) | % { $s,$n,$expected = $_ $result = &$f $s $n "$($result-eq$expected): $result" } ``` Output: ``` True: acegikmoqsuwybdfhjlnprtvxz True: cg.ccgoooskhemdltea.efaxnc True: PeAeeapnnpp! pl!Ple!ie n P True: 18,,,5115,3,2,8,2931,,53,4 ``` [Answer] # SINCLAIR ZX81/TIMEX TS-1000/1500 BASIC, 134 tokenized BASIC bytes ``` 1 INPUT A$ 2 INPUT A 3 LET C=-SGN PI 4 FOR I=SGN PI TO A 5 PRINT I; 6 NEXT I 7 PRINT 8 FOR I=SGN PI TO LEN A$ 9 LET C=C+SGN PI 10 IF C=A THEN LET C=NOT PI 11 IF NOT C AND I>SGN PI THEN PRINT 12 PRINT A$(I); 13 NEXT I ``` The first parameter `A$` is the string value that you want to cipher, and the second `A` is the number of columns that you want to cipher to. The variable `C` is used to add in a new line after `A` characters. Lines 4 to 6 inclusive print out the column numbers at the top of the screen area. Line 7 adds a new line (`"\r\n"` equivalent). Lines 8 - 13 will then print out each character of `A$`. This programme does not require a RAM expansion to work. [![ZX81 column cipher using advanced Sinclair BASIC](https://i.stack.imgur.com/c0Uoz.png)](https://i.stack.imgur.com/c0Uoz.png) [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 27 bytes **Solution:** ``` {,/+(0N;y)#(y*-_-(#x)%y)$x} ``` [Try it online!](https://tio.run/##y9bNz/7/v1pHX1vDwM@6UlNZo1JLN15XQ7lCU7VSU6WiNlopoCg/vSgxNzczL10hoLSqKie1WCExL0XBOT8lVcE9PydNIdhVydo09v9/AA "K (oK) – Try It Online") **Explanation:** ``` {,/+(0N;y)#(y*-_-(#x)%y)$x} / the solution { } / lambda taking implicit x and y $x / pad x ( ) / do this together %y / divide by y ( ) / do this together #x / count (#) length of x - / negate \ _ / floor | ceiling - / negate / y* / multiply by y # / reshape (0N;y) / null by y grid + / transpose ,/ / flatten ``` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ôζJ ``` The Python legacy version is used instead of the Elixir rewrite, because the new version doesn't implicitly convert strings to characters when using `zip`, which the old version did. [Try it online](https://tio.run/##MzBNTDJM/f//8JZz27z@/zfm8kjNycnXUSjPL8pJUQQA) or [verify all test cases](https://tio.run/##HYvJDcIwFETvvwqH8xfCCWE5IcTOKRIVGOfHBBw7JKwpgAKoBdEAd4qgkWDlMnozetMJxZZT3ZuvpqMWEyZmrVGDv8fTYf15fd/rGuslaW2RXW2hYw8CiAqrCpFlqVEsOleVprJ5T2xMbGF1wjYzCEFsZUyJ2qX7g86MzY9FeTpfrrd7BT5I5yqntsuTkAe6yZ0witrSZtCFiAyLUkMizzWxcZNu8zwP@sCRo48BhjhAHqDPMehi6NoQeOcP). **Explanation:** ``` ô # Split the (implicit) input-String into chunks of size (implicit) input-integer # i.e. "Hello, world!" and 3 → ['Hel','lo,',' wo','rld','!'] ζ # Zip, swapping rows and columns (with space filler by default) # i.e. ['Hel','lo,',' wo','rld','!'] → ['Hl r!','eowl ','l,od '] J # Join the list of strings together (and output implicitly) # i.e. ['Hl r!','eowl ','l,od '] → 'Hl r!eowl l,od ' ``` [Answer] ## [GolfSharp](https://github.com/timopomer/GolfSharp), 82 bytes ``` (s,i)=>r(0,i).m(x=>r(0,s.L()/i+1).s(n=>(n*3+x)).w(m=>m<s.L()).s(o=>s.R(o,1))).j(); ``` ]
[Question] [ **Overview** The ancient Romans devised a number system using Latin letters, which served them well, and which is still used by modern civilization, though to a much smaller degree. In the time of its use, Romans would have had to learn to use and manipulate these numbers in order to be of much use for many applications. For example, if a man owned 35 oxen, and he procured 27 more, how would he know the new total other than counting them all? (*Ok, that and using an abacus...*) If the Romans could do it, surely we can figure it out as well. **Objective** Write the shortest algorithm/function/program that will **add** two Roman numerals together and output the result **without** converting the string representation of either input into a number. **Rules/Constraints** Because of historical/pre-medieval inconsistencies in formatting, I'm going to outline some non-standard (per modern usage) rules for orthography. See the value guide below as an example. * The letters I, X, C, and M can be repeated up to four times in succession, but no more. D, L, and V can never be repeated. * The letter immediately to the right of another letter in the Roman representation will be of the same or lesser value than that to its left. + In other words, `VIIII == 9` but `IX != 9` and is invalid/not allowed. * All input values will be 2,000 (MM) or less; no representation for numbers greater than M is necessary. * All input values will be a valid Roman numeral, pursuant to the rules above. * You may not convert any numbers to decimal, binary, or any other number system as part of your solution (you are welcome to use such a method to *VERIFY* your results). * This is code golf, so shortest code wins. **Value Guide** ``` Symbol Value I 1 II 2 III 3 IIII 4 V 5 VIIII 9 X 10 XIIII 14 XXXXIIII 44 L 50 LXXXXVIIII 99 C 100 D 500 M 1,000 ``` **Examples** ``` XII + VIII = XX (12 + 8 = 20) MCCXXII + MCCXXII = MMCCCCXXXXIIII (1,222 + 1,222 = 2,444) XXIIII + XXXXII = LXVI (24 + 42 = 66) ``` If any further clarification is needed, please ask. [Answer] ## APL (~~59~~ 56) ``` ,/N⍴⍨¨{∨/K←⍵≥D←7⍴5 2:∇⍵+(1⌽K)-K×D⋄⍵}⊃+/(N←'MDCLXVI')∘=¨⍞ ``` Input on one line (i.e. `XII + XII`, though the `+` is not necessary). Edit: changed shift to rotate to save three characters - it only matters when the answer ≥ 5000, which should never happen as the question says the input values will always be ≤ 2000. The only effect is it now "overflows" at 5000, giving 5000=1, 5001=2, etc. (I don't really think the Romans did it this way... APL is more something for Ancient Egyptians I think :) ) Explanation: * `⍞`: get user input * `(N←'MDCLXVI')∘=¨`: store 'MDCLXVI' in N. Return, for each character of the input string, a vector with a 1 in the place where the character corresponds to one of 'MDCLXVI', and 0 otherwise. * `⊃+/`: Sum the vectors and de-encapsulate. We now have a vector with information about how many of each Roman numeral we have. I.e, if the input was `XXII XIIII`, we now have: ``` M D C L X V I 0 0 0 0 3 0 6 ``` * Note that this is not converting the values. * `{`...`:`...`⋄`...`}` is a function with an if-else construct. * `D←7⍴5 2`: `D` is the vector `5 2 5 2 5 2 5`. This is how many of a Roman numeral are *not* allowed. I.e. if you have 5 `I`s, that's too many, and if you have 2 `V`s that's also too many. This vector also happens to be the multiplication factor for each Roman numeral, i.e. a `V` is worth 5 `I`s and an `X` is worth 2 `V`s. * `∨/K←⍵≥D`: `K` is the vector where there's a 1 if we have too many Roman numerals of a certain kind. `∨/` ORs this vector together. * If this vector is not all zeroes: * `K×D`: Multiply K by D. This vector has zeroes where we don't have too many Roman numerals, and the amount of Roman numerals where we do. * `⍵+(1⌽K)`: Rotate K to the left by 1, and add it to the input. For each Roman numeral we have too many, this will add one of the next-higher one. * `⍵+(1⌽K)-K×D`: Subtract this from the other vector. The effect is, for example if you have 6 `I`s, it will add one `V` and remove 4 `I`s. * `∇`: Recurse. * `⋄⍵`: But if `K` was all zeroes, then ⍵ represents a valid Roman numeral, so return ⍵. * `N⍴⍨¨`: For each element of the resulting vector, create that many of the corresponding Roman numeral. * `,/`: Join these vectors together to get rid of the ugly spaces in the output. [Answer] ## Python, 100 ``` s="IVXLCDM" r=raw_input() a="" i=2 u=0 for c in s:r+=u/i*c;i=7-i;u=r.count(c);a+=u%i*c print a[::-1] ``` Takes one string from input (e.g. `VIII + XII` or `VIII + XII =`). [Answer] ## Perl, 132 chars ``` sub s{@a=VXLCDM=~/./g;@z=(IIIII,VV,XXXXX,LL,CCCCC,DD);$r=join"",@_; $r=~s/$a[-$_]/$z[-$_]/gfor-5..0;$r=~s/$z[$_]/$a[$_]/gfor 0..5;$r} ``` Declares function `s` which takes any number of arguments and sums them. Pretty straightforward: it appends the input, reduces everything to `I`s and then immediately restores the Roman numerals. (Hopefully this doesn't count as using the unary number system!) [Answer] ### Ruby, 85 82 characters ``` gets;r=0;v=5;puts"IVXLCDM".gsub(/./){|g|r+=$_.count g;t=r%v;r/=v;v^=7;g*t}.reverse ``` This version takes input on STDIN as a single string (e.g. `XXIIII + XXXXII`) and prints output to STDOUT. ``` f=->*a{r=0;v=5;"IVXLCDM".gsub(/./){|g|r+=(a*'').count g;t=r%v;r/=v;v^=7;g*t}.reverse} ``` The second one is an implementation as a function. Takes two (or more) strings and returns the summed values. Usage: ``` puts f["XXIIII", "XXXXII"] # -> LXVI ``` [Answer] ## GNU Sed, 131 chars ``` :;s/M/DD/;s/D/CCCCC/;s/C/LL/;s/L/XXXXX/;s/X/VV/;s/V/IIIII/;t;s/\W//g;:b;s/IIIII/V/;s/VV/X/;s/XXXXX/L/;s/LL/C/;s/CCCCC/D/;s/DD/M/;tb ``` [Answer] ## Python, 174 chars A very simple algorithm - count each digit, loop to handle overflow to the next, print. Reads from standard input. Something like `XVI + CXX` would work (ignores anything except numerals, so the `+` isn't really needed). ``` x="IVXLCDM" i=raw_input() d=dict((c,i.count(c))for c in x) for c in x: n=2+3*(c in x[::2]) if d[c]>=n:d[c]-=n;d[x[x.find(c)+1]]+=1 print"".join(c*d[c]for c in reversed(x)) ``` [Answer] ### Scala 150 ``` val c="IVXLCDM" def a(t:String,u:String)=((t+u).sortBy(7-c.indexOf(_))/:c.init)((s,z)=>{val i=c.indexOf(z)+1 s.replaceAll((""+z)*(2+i%2*3),""+c(i))}) ``` invocation: ``` a("MDCCCCLXXXXVIIII", "MDCCCCLXXXXVIIII") ``` ungolfed Version: ``` val c = "IVXLCDM" def add (t:String, u:String) = ( (t+u). // "MDCCCCLXXXXVIIIIMDCCCCLXXXXVIIII" sortBy(7-c.indexOf(_)) // MMDDCCCCCCCCLLXXXXXXXXVVIIIIIIII /: // left-fold operator to be used: (start /: rest) ((a,b)=> f (a,b)) c.init) /* init is everything except the rest, so c.init = "IVXLCD" (because M has no follower to be replaced with */ ((s, z) => { /* the left fold produces 2 elements in each step, and the result is repeatedly s, on initialisation MMDDCCCCCCCCLLXXXXXXXXVVIIIIIIII and z is the iterated element from c.init, namely I, V, X, L, C, D in sequence */ val i = c.indexOf (z) + 1 // 1, 2, ..., 7 /* i % 2 produces 1 0 1 0 1 0 *3 => 3 0 3 0 +2 => 5 2 5 2 (""+ 'I') * 5 is "IIIII", ("" + 'V') * 2 is "VV", ... ""+c(i) is "V", "X", ... */ s.replaceAll (("" + z) * (2+i%2*3), "" + c (i)) } ) ``` [Answer] # JavaScript 195 179 My system is fairly rudimentary, reduce all Roman numerals to a series of `I` for both numbers, join them up and then reverse the process turning certain blocks of `I` into their respective larger versions... Iteration 1 `a="IIIII0VV0XXXXX0LL0CCCCC0DD0M".split(0);d=b=>x.replace(g=RegExp((c=z)>b?a[c][0]:a[c],"g"),c>b?a[b]:a[b][0]);x=prompt().replace("+","");for(z=6;0<z;z--)x=d(z-1);for(z=0;6>z;z++)x=d(z+1);alert(x)` Iteration 2 `a="IIIII0VV0XXXXX0LL0CCCCC0DD0M".split(0);x=prompt().replace("+","");for(z=-6;6>z;z++)b=0>z?-z:z,c=0>z?~z:z+1,x=x.replace(g=RegExp(b>c?a[b][0]:a[b],"g"),b>c?a[c]:a[c][0]);alert(x)` Features: * Zero delimited array string, quicker than setting up a string array. * Reduced the two recursions to the one, and recalculating the parameters for the specific regex. * More ternary operators than you can poke a stick at! Input is entered via prompt in the form of `<first roman number>+<second roman number>` (no spaces), output in the form of an alert. e.g. ``` XVI+VII // alert shows XXIII, correct! MCCXXXIIII+DCCLXVI // alert shows MM, also correct! ``` [Answer] # VBA, 187 chars ``` Function c(f,s) a=Split("I,V,X,L,C,D,M",",") z=f & s For i=0 To 6 x=Replace(z,a(i),"") n=Len(z)-Len(x)+m r=IIf(i Mod 2,2,5) o=n Mod r m=Int(n/r) c=String(o,a(i)) & c z=x Next End Function ``` [Answer] # JavaScript, 190 ``` x=prompt(r=[]);p=RegExp;s="MDCLXVI";for(i=-1;++i<7;){u=x.match(new p(s[i],'g'));if(u)r=r.concat(u)};for(r=r.join("");--i>0;){r=r.replace(new p(s[i]+'{'+(i%2==0?5:2)+'}','g'),s[i-1])}alert(r) ``` Putting some instruction inside the third slot of the `for` operator let me save some semicolons! When the input prompts, you insert the two numbers (the `+` and spaces are not necessary, but if you put them you don't get an error). Then the alert show you the sum. [Answer] ## C++, 319 chars ``` #define A for(j=0;j< #define B .length();j++){ #define C [j]==a[i]?1:0);} #include <iostream> int main(){std::string x,y,s,a="IVXLCDM";int i,j,k,l,m=0,n;std::cin>>x>>y;for(i=0;i<7;i++){k=0;l=0;A x B k+=(x C A y B l+=(y C n=k+l+m;m=(n)%(i%2?2:5);for(j=0;j<m;j++){s=a[i]+s;}m=(n)/(i%2?2:5);}std::cout<<s<<"\n";return 0;} ``` [Answer] # PHP, 136 Bytes ``` for($r=join($argv);$c=($n=IVXLCDM)[$i];$r.=$p($n[++$i],$z/$d))$t=($p=str_repeat)($c,($z=substr_count($r,$c))%($d="52"[$i&1])).$t;echo$t; ``` [Try it online!](https://tio.run/nexus/php#HY3NDoIwEITvPkazmm74MZp4qo0HuJDAlTQhxGBBwQNtSvHAe3vGxblMvsnszvVme7uDxr0@smIRC1mRJqRcqTLLNvwzoVIZidVifRrHwcm3GUb@v0QBWnIYZVaqPEkLrGCoBbhYgqW4CgLiEJYjtIjgqWrl5N3ddbZrPHLQIYdFTvNjS7WZR08DIWjEPYdWssuZ0cvDqUaMwYtO94ZsXb@jiXSj@@4H "PHP – TIO Nexus") ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 9 years ago. [Improve this question](/posts/1656/edit) This problem is quite easy to do by brute force. In fact, it'll be reasonably fast to brute force as well. But where's the fun in that? ## The Problem Produce a list of all unique 5 digit number pairs that sum to `121212`. However, each decimal digit must appear exactly once in either number. So a valid pair would be `(98167, 23045)`. But an invalid pair would be `(23456, 97756)` because `7, 5, 6` are repeated more than once, and `1, 8, 0` are not used at all. There are exactly 192 unique pairs. ## Rules 1. *Efficiency:* You can brute force this. But that's trivial to do. So instead, the real challenge here is to find a way to efficiently produce the list of numbers. 2. *Source Code Requirements:* It cannot store the number list (or any part of it). The number sequence **must** be generated on the fly. Have Fun! [Answer] **C++** ``` #include<iostream> using namespace std; #include<algorithm> int main() { long long N,F,S; char str[11]="1023456789"; while (1) { sscanf(str,"%lld",&N); F=N/100000;S=N%100000; if (F>60000) break; if (F+S==121212) printf("%lld %lld\n",F,S); next_permutation(str,str+10); } } ``` <http://www.ideone.com/Lr84g> [Answer] # JavaScript ``` function findpairs(arrin1,arrin2){ functioncount++ var arr1=[] var arr2=[] var strike=[] var overflow=0 var b var len=arrin1.length for(var a=0;a<len;a++){ arr1[a]=arrin1[a] arr2[a]=arrin2[a] strike[arr1[a]]=true strike[arr2[a]]=true overflow=+((arr1[a]+arr2[a])>9) } var desired=12-(len%2)-overflow for(a=9;a>0;a--){ b=(desired-a)%10 if(a>b && !strike[a] && !strike[b]){ if(len==4){ if((a+b)>9){ document.write(""+a+arr1[3]+arr1[2]+arr1[1]+arr1[0]+" "+b+arr2[3]+arr2[2]+arr2[1]+arr2[0]+"<br>") document.write(""+a+arr1[3]+arr1[2]+arr1[1]+arr2[0]+" "+b+arr2[3]+arr2[2]+arr2[1]+arr1[0]+"<br>") document.write(""+a+arr1[3]+arr1[2]+arr2[1]+arr1[0]+" "+b+arr2[3]+arr2[2]+arr1[1]+arr2[0]+"<br>") document.write(""+a+arr1[3]+arr1[2]+arr2[1]+arr2[0]+" "+b+arr2[3]+arr2[2]+arr1[1]+arr1[0]+"<br>") document.write(""+a+arr1[3]+arr2[2]+arr1[1]+arr1[0]+" "+b+arr2[3]+arr1[2]+arr2[1]+arr2[0]+"<br>") document.write(""+a+arr1[3]+arr2[2]+arr1[1]+arr2[0]+" "+b+arr2[3]+arr1[2]+arr2[1]+arr1[0]+"<br>") document.write(""+a+arr1[3]+arr2[2]+arr2[1]+arr1[0]+" "+b+arr2[3]+arr1[2]+arr1[1]+arr2[0]+"<br>") document.write(""+a+arr1[3]+arr2[2]+arr2[1]+arr2[0]+" "+b+arr2[3]+arr1[2]+arr1[1]+arr1[0]+"<br>") document.write(""+a+arr2[3]+arr1[2]+arr1[1]+arr1[0]+" "+b+arr1[3]+arr2[2]+arr2[1]+arr2[0]+"<br>") document.write(""+a+arr2[3]+arr1[2]+arr1[1]+arr2[0]+" "+b+arr1[3]+arr2[2]+arr2[1]+arr1[0]+"<br>") document.write(""+a+arr2[3]+arr1[2]+arr2[1]+arr1[0]+" "+b+arr1[3]+arr2[2]+arr1[1]+arr2[0]+"<br>") document.write(""+a+arr2[3]+arr1[2]+arr2[1]+arr2[0]+" "+b+arr1[3]+arr2[2]+arr1[1]+arr1[0]+"<br>") document.write(""+a+arr2[3]+arr2[2]+arr1[1]+arr1[0]+" "+b+arr1[3]+arr1[2]+arr2[1]+arr2[0]+"<br>") document.write(""+a+arr2[3]+arr2[2]+arr1[1]+arr2[0]+" "+b+arr1[3]+arr1[2]+arr2[1]+arr1[0]+"<br>") document.write(""+a+arr2[3]+arr2[2]+arr2[1]+arr1[0]+" "+b+arr1[3]+arr1[2]+arr1[1]+arr2[0]+"<br>") document.write(""+a+arr2[3]+arr2[2]+arr2[1]+arr2[0]+" "+b+arr1[3]+arr1[2]+arr1[1]+arr1[0]+"<br>") resultcount+=16 } } else{ arr1[len]=a arr2[len]=b findpairs(arr1,arr2) } } } } resultcount=0 functioncount=0 start=+new Date() findpairs([],[]) end=+new Date() document.write("<br>"+resultcount+" results<br>"+(end-start)+" ms<br>"+functioncount+" function calls") ``` Hosted at: <http://ebusiness.hopto.org/findpairs.htm> Mathematical realization: If you have one pair 15 others can trivially be generated by swapping digits between the two numbers, therefore I only search for numbers where the digits of the first are all greater than the digits of the second, and then simply output all the permutations. I start from the least significant digits and generate the sequence as a tree traversal, for each step asserting that the intermediate result is correct and that no digits are spent twice. With these methods the function need only be called 50 times in total. On my machine Chrome yield runtime results of typically 2 ms. [Answer] Python 2. It's pretty efficient because it constructs the numbers (the inner-most loop is executed 4570 times total) and pretty short because I golfed a little (201 characters), but I'm not really sure I want to *explain* this :) ``` p=lambda t,a,d:((x,y)for x in range(10)for y in[(t-x-a)%10]if(x not in d)&(y not in d)and x-y) w=lambda s:[s]if len(s)==10and s[:5]<s[5:]else(m for n in p(2-len(s)/2%2,sum(s[-2:])/10,s)for m in w(s+n)) ``` The returned values are pretty peculiar, though: call `w` with an empty tuple, and you get an iterator of 10-tuples. These 10 tuples are the digits of the two numbers, alas *backwards* and *alternating*, i.e. the tuple ``` (2, 0, 8, 3, 7, 4, 9, 1, 6, 5) ``` represents the numbers 51430 and 69782. Test: ``` result = list(w(())) assert len(set(result)) == 192 # found all values assert len(result) == 192 # and no dupes for digits in result: assert all(0 <= d <= 9 for d in digits) # real digits -- zero through nine assert len(set(digits)) == 10 # all digits distinct n1 = int("".join(map(str, digits[9::-2]))) n2 = int("".join(map(str, digits[8::-2]))) assert n1 + n2 == 121212 # sum is correct ``` Here is the ungolfed version: ``` ppcalls = 0 # number of calls to possiblePairs ppyields = 0 # number of pairs yielded by possiblePairs ppconstructed = 0 # number of construced pairs; this is the number # of times we enter the innermost loop def possiblePairs(theirSumMod10, addition, disallowed): global ppcalls, ppyields, ppconstructed ppcalls += 1 for a in range(10): b = (theirSumMod10 - a - addition) % 10 ppconstructed += 1 if a not in disallowed and b not in disallowed and a != b: ppyields += 1 yield (a, b) def go(sofar): if len(sofar) == 10: if sofar[:5] < sofar[5:]: # dedupe yield sofar digitsum = 2 - (len(sofar) / 2) % 2 # 1 or 2, alternating for newpair in possiblePairs(digitsum, sum(sofar[-2:]) / 10, sofar): for more in go(sofar + newpair): yield more list(go(())) # iterate print ppcalls # 457 print ppyields # 840 print ppconstructed # 4570 ``` [Answer] ## C ``` #include <stdio.h> int mask(int n) { int ret = 0; for (; n > 0; n /= 10) ret |= 1 << n % 10; return ret; } int main(void) { int a, b; for (a = 21213, b = 99999; a < b; a++, b--) if ((mask(a) | mask(b)) == 0x3FF) printf("%d %d\n", a, b); return 0; } ``` This traverses all pairs of 5-digit numbers that sum to 121212 (meaning 39393 iterations, or ~1/46th of the iterations used by [fR0DDY's answer](https://codegolf.stackexchange.com/questions/1656/find-all-number-pairs-that-sum-to-121212/1657#1657)). For each pair, it forms a bit mask of the digits in each number, then sees if they OR to 0b1111111111. [Answer] ## Javascript (481) ``` function m(d,i){o=d-i;if(0<=o&&o<=9&&o!=i)return o;o+=10;if(0<=o&&o<=9&&o!=i)return o;return}function p(n,a){x=0;r=[];d=n%10;for(i=0;i<10;i++){if((!a||!a.contains(i))&&(o=m(d,i))&&(!a||!a.contains(o))&&i+o<=n)r[x++]=[i,o]}return r}function f(n,a){var x=0;var r=[];var d=p(n,a);for(var i=0;i<d.length;i++){var s=Math.floor((n-d[i][0]-d[i][1])/10);if(s>0){var t=f(s,d[i].concat(a));for(var j=0;j<t.length;j++)r[x++]=[t[j][0]*10+d[i][0],t[j][1]*10+d[i][1]]}else{r[x++]=d[i]}}return r} ``` <http://jsfiddle.net/XAYr3/4/> Basic idea: generate combinations of valid digits that can be used in the right-most column. For instance, (0,2), (3,9), (4,8), (5,7). For each combination, recursively find pairs that work for the next-from-right digit, without duplicating digits in the first pair. Recurse until a pair of 5-digit numbers has been generated. Combine all those results into a single array, and the list is 192 elements. This I believe should require about the fewest iterations, but all of the array allocation/deallocation makes it overall somewhat practically inefficient. My counting tests show that function `f` is called 310 times, the inner loop `i` is executed 501 times total (across all calls to `f`), and the inner-inner loop `j` is executed 768 times total (across everything). [Answer] ## Python, 171 characters ``` def R(x,y,d,c): if not d and x<y:print x,y for p in d: q=(12-c%2-p-(x+y)/10**c)%10 if p-q and q in d:R(x+p*10**c,y+q*10**c,d-set([p,q]),c+1) R(0,0,set(range(10)),0) ``` The code maintains the invariant that `x`,`y` have `c` digits and that all the unused digits are in the set `d`. The routine `R` is called a total of 841 times, which is pretty efficient. [Answer] **C++** ``` #include<iostream> using namespace std; #include<algorithm> #include<cstring> int main() { int i; char str1[11]="0123456789",str2[11]; for (i=99999;i>60000;i--) { sprintf(str2,"%d%d",i,121212-i); sort(str2,str2+10); if(!strcmp(str1,str2)) printf("%d %d\n",i,121212-i); } } ``` <http://www.ideone.com/Lr84g> ]
[Question] [ [TailwindCSS](https://tailwindcss.com) is a utility that lets one write CSS code using only HTML classes, which are then converted to CSS code with the Tailwind compiler. Ordinarily, one would write CSS in a separate file from the HTML, and reference named classes: ``` <!-- without Tailwind --> <p class="crazy-monologue">Crazy? I was crazy once. They locked me in a room…</p> ``` ``` .crazy-monologue { background: black; color: red; opacity: 0.5; } ``` With Tailwind, the CSS is auto-generated: ``` <!-- with Tailwind --> <p class="background-[black] color-[red] opacity-[0.5]"> Crazy? I was crazy once. They locked me in a room… </p> ``` ``` /* auto-generated by Tailwind */ .background-\[black\]{background:black;} .color-\[red\]{color:red;} .opacity-\[0\.5\]{opacity:0.5;} ``` This is a simplified version of Tailwind; for the purposes of this challenge, all class names will be in the format `property-name-[value]`. The property name will be a `kebab-case` string, and the value will be an string consisting of alphanumeric characters and the period `.`. Note that the brackets `[` and `]` must be escaped as `\[` and `\]` in the outputted CSS selector, and the period `.` must be escaped as `\.`. ## Task Given a class name in the above format, output the corresponding CSS. The CSS output is flexible; you may have any amount of whitespace before and after the curly braces and colons, and the semicolon is optional. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins. ## Test cases Note that since the CSS output is flexible, your output does not have to be formatted exactly as these are. ``` /* in: opacity-[0.5] */ /* out: */ .opacity-\[0\.5\] { opacity: 0.5 } /* in: background-color-[lightgoldenrodyellow] */ /* out: */ .background-color-\[lightgoldenrodyellow\] { background-color: lightgoldenrodyellow; } ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 236 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 29.5 bytes ``` \-/÷₍λ\.øBf:\\vpĿ;‡ḢṪMf`%-%{%:%}`$% ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBPSIsIiIsIlxcLS/Dt+KCjc67XFwuw7hCZjpcXFxcdnDEvzvigKHhuKLhuapNZmAlLSV7JTolfWAkJSIsIiIsIm9wYWNpdHktWzAuNV1cbmJhY2tncm91bmQtY29sb3ItW2xpZ2h0Z29sZGVucm9keWVsbG93XVxuYmFja2dyb3VuZC1bYmxhY2tdXG5jb2xvci1bcmVkXVxuYW1vbmctW3VzXSJd) Truly among sus. "But lyxal what does that have to do with the challenge?" Nothing. That's just how golfing at 11:52pm be like. ## Explained ``` \-/÷₍λ\.øBf:\\vpĿ;‡ḢṪMf`%-%{%:%}`$%­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁢⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁡⁢‏⁠‎⁡⁠⁣⁡⁣‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏‏​⁡⁠⁡‌­ \-/÷ # ‎⁡Split input on '-' and dump ₍λ ;‡ # ‎⁢Parallel apply the following: # ‎⁢ \.øBf:\\vpĿ # ‎⁣ Escape '[', '.' and ']' ḢṪ # ‎⁤ Remove the square brackets M # ‎⁢⁡Prepend the property to each f # ‎⁢⁢And flatten $% # ‎⁢⁣Formatting into the string `%-%{%:%}` # ‎⁢⁤"%-%{%:%}" 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Python](https://www.python.org), 67 bytes ``` import re lambda x:f'.{re.escape(x)}{{{x.replace("-[",":")[:-1]}}}' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3nXMSc5NSEhUqrNLU9aqLUvVSi5MTC1I1KjRrq6urK_SKUgtyEpNTNZR0o5V0lKyUNKOtdA1ja2tr1bkycwvyi0oUilKhRlkUFGXmlWikaagnJSZnpxfll-al6EYnAbVnx6pranLBpfMLEpMzSyp1ow30TEEyEP0LFkBoAA) The "-" is also escaped, but that's still legal CSS. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~37~~ 36 bytes ``` -\[(.+)] $&{$`:$1} \W(?=.*{) \$& ^ . ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wXzcmWkNPWzOWS0WtWiXBSsWwlismXMPeVk@rWpMrRkWNK45L7///pMTk7PSi/NK8FN3k/Jz8It3opBygUCwXlFeUmhLLlV@QmJxZUqkbbaBnGsuFqSUnMz2jJD0/JyU1ryg/pTI1Jye/PBYA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` -\[(.+)] $&{$`:$1} ``` Append the CSS declaration block. ``` \W(?=.*{) \$& ``` Escape non-word characters in the class name. ``` ^ . ``` Prefix the `.` class selector. Edit: Saved 1 byte thanks to @noodleman pointing out that the `;` is optional. 41 bytes to include the `;` and not escape `-`s: ``` -\[(.+)] $&{$`:$1;} [^-\w](?=.*{) \$& ^ . ``` [Try it online!](https://tio.run/##ZcvBCgIhFEDR/fsOG5xCqUWbIlr2EeowjopJD1@IMQxD324t2rW8B24JNWXbNvw2NqEVl7veAOtWNp7Y4fwGNQg9G369yO3ag2YdDCBbm6x7xEKv7IUjpCLUhF8y8KsSvAF6WpfqItReHg38L5jivUZCH3IhvwREms0H "Retina 0.8.2 – Try It Online") Link includes test cases. 29 bytes in [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1.0: ``` ((.+)-\[(.+))] .$\$1\]{$2:$3} ``` [Try it online!](https://tio.run/##ZYvLCsMgEADvfoeHhKDkQS/9Fd2DUTHSxS2LpYTQb7cN9JbTMAPDsebipta6Tg@9suZED0JLKycLh5zvcvm0tjr/SEyvEpQnJFZmxV8C8TeOAQQ9nc91V2bUNxDXBXPaaiIMsTCFPSLSG74 "Retina – Try It Online") Link includes test cases. Explanation: `$\` quotes `.` and `[` characters in its argument, but the `]` needs to be quoted manually. [Answer] # [Ruby](https://www.ruby-lang.org/) `-pl`, 44 bytes After a lot of optimization it effectively became SuperStormer's Python solution. ``` $_=".#{Regexp.escape$_}{#{sub'-[',?:;chop}}" ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnm0km5BjlLsgqWlJWm6Fjd1VOJtlfSUq4NS01MrCvRSi5MTC1JV4murlauLS5PUdaPVdeytrJMz8gtqa5UgeqBaF9w0zS9ITM4sqdSNNtAzjeVKSkzOTi_KL81L0U3Oz8kv0o3OyUzPKEnPz0lJzSvKT6lMzcnJL4-F6AYA) [Answer] # JavaScript (ES6), 68 bytes ``` s=>s.replace(/[[\].]/g,"\\$&")+`{${[a,b]=s.split(/-\[|\]/),a}:${b}}` ``` [Try it online!](https://tio.run/##XcvBCsIgGADge48hIyZN7dIlWC@iwpwzW/34i1ox1p7d6Nr547ubl8k2zbGwgJOr177m/pJ5chGMda2QUmmuhe@IUs2e0MOwNqs03aj7zHOEubSCKflRWtDObOdmHbdtqBZDRnAc0LfXlmA0di4Lk0d@0oTS3Z@Pxj58wmeYmEXAxCTM/lY8wuRCwmlxAPj@zfoF "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` ≔⪪⁻S]¦-[θ.§θ⁰-\[⪫⪪§θ¹.¦\.¦\]{⪫θ:¦} ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU8juCAns0TDNzOvtFjDM6@gtCS4pCgzL11DU0dBKVYJROpGg6hCTWuuAKBMiYaSnhKc7VjimZeSWqFRqKNgoIlQoRsTE41Q5JWfCbMHSb0hyGw9sA0xMUAaoTsmJrYaTTdQvZIVsppaoIL///MLEpMzSyp1ow30TGP/65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⪪⁻S]¦-[θ ``` Remove the trailing `]` from the input string, then split it on `-[`. ``` . ``` Output the CSS class selector. ``` §θ⁰ ``` Output the property name. ``` -\[ ``` Output the trailing `-` and the quoted opening `[`. ``` ⪫⪪§θ¹.¦\. ``` Output the property value with `.`s quoted. ``` \]{ ``` Output the quoted closing `]` and the opening `{` of the declaration block. ``` ⪫θ: ``` Join the property and value into a declaration and output it. ``` } ``` Output the closing `}` of the declaration block. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` …]-[ā£':æ:…{ÿ}«„[]SD'\ì‡ ``` Outputs without the optional `;` to save a byte. [Try it online](https://tio.run/##yy9OTMpM/f//UcOyWN3oI42HFqtbHV5mBeRWH95fe2j1o4Z50bHBLuoxh9c8alj4/39SYnJ2elF@aV6KbnJ@Tn6RbnRSDlAoFgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn2ly/9HDctidaOPNB5arG51eJkVkFt9eH/todWPGuZFxwa7qMccXvOoYeF/nf9JicnZ6UX5pXkputFJOUBOLFdyfk5@kW50UWpKLFd@QWJyZkmlbrSBnmksF5JiqKKczPSMkvT8nJTUvKL8lMrUnJz88liugqL8gtQioLa8xNxU3eiyxJzS1FgA). **Explanation:** ``` …]-[ # Push string "]-[" ā # Push a list in the range [1,length] (without popping): [1,2,3] £ # Split the string into parts of those sizes: ["]","-[",""] ': '# Push ":" æ # Pop and push its powerset: ["",":"] : # Replace the values in the (implicit) input-string: # All "]" are replaced with "", so basically removed # And all "-[" are replaced with ":" # (the trailing "" of the first list is ignored) …{ÿ} # Surround it with curly brackets « # Append it to the (implicit) input-string „[]S # Push "[]" as a pair of characters: ["[","]"] D # Duplicate it '\ì '# Prepend an "\" in front of each: ["\[","\]"] ‡ # Transliterate all "[" to "\[" and "]" to "\]" # (after which the result is output implicitly) ``` [Answer] # [Scala 3](https://www.scala-lang.org/), 67 bytes ``` x=>s".${x.replaceAll("\\W","\\\\$0")}{${x.replace("-[",":").init}}" ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VYwxCoNAFER7T_H5WChEESQQBAWTOlWKFJpiXVfZuKyLrsEgniSNTXInbxOJKZJmpngz7_FqKRHEn2a_zq6MajgSLoH1msm8hVgpGAzDuBEBRQAn3XBZhtHaED47XTi7-dCHUYuuOfRuw5QglMVCWJimZ9wsmaamh_Y4_HALnWRhAdoul1yPI35VewC1uLWQVmFhRmhVNnUncyfJll91Qds2_ia1IpTru5N47vZDx9U0TWu_AQ) [Answer] # [Scala 3](https://www.scala-lang.org/), 180 bytes A port of [@SuperStormer's Python answer](https://codegolf.stackexchange.com/a/264705/110802) in Scala. --- ``` x=>{val e=x.replaceAllLiterally("-","\\-").replaceAllLiterally("[","\\[").replaceAllLiterally("]","\\]").replaceAllLiterally(".","\\.");s".$e{${x.replace("-[",":").dropRight(1)}}"} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sODkxJ9F4wU3j_KSs1OQSBd_EzDyF1IqS1LyUYgXHggKFai4urrLEHIU0K4XgkqLMvHRbOwitYLu0tCRN1-Lmlgpbu2qQklTbCr2i1IKcxORUx5wcn8yS1KLEnJxKDSVdJR2lmBhdJU3s0tFg6Whc0rFg6Vhc0npgaT0lTetiJT2V1GqVargrgDaDzLYCak0pyi8IykzPKNEw1KytVaqFut1JQaEA6JmSnDyNNA2lpMTk7PSi_NK8FN3oJKAB2UBLNblQlOQXJCZnllTqRhvomYJloSYtWAChAQ) ]
[Question] [ Write a function that takes an ASCII-printable-only (all charcodes ∈ [32..126]) string input `x` and provides an ASCII-printable-only output string `f(x)`, such that for every x * `f(f(x))=x` * `f(x)` is all-numeric (all charcodes ∈ [48..57]) iff `x` is not all-numeric You can assume input is not empty and never provide empty output, or treat empty input as "all-numeric". Shortest code in each language wins. Some examples of "not all-numeric": ``` abc a1b2c3 a333333 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) -Ṡ flag, ~~41~~ ~~40~~ ~~34~~ 30 bytes ``` λ[±[‹n⌊₇τCṅkQ↔|fC₇βnṪ]:xn≠ß_;† ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuaAiLCIiLCLOu1vCsVvigLlu4oyK4oKHz4RD4bmFa1HihpR8ZkPigofOsm7huapdOnhu4omgw59fO+KAoCIsIiIsIjEyOSJd) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyLhuaAiLCLilqHGm2AgPT4gYG4iLCLOu1vCsVvigLlu4oyK4oKHz4RD4bmFa1HihpR8ZkPigofOsm7huapdOnhu4omgw59fO+KAoCIsIlfhuYU74oGLIiwiYWJjXG4xNjAxODkxXG5hMWIyYzNcbjMzNDYyNTQzMTE4NTlcbmEzMzMzMzNcbjQyODM3NjY1NjIzOTAyN1xueFxuMTIwLVxuMTAzNTg1ODM3LVxuNDU1NDMyOTM5ODAyMjg0ODQxOTAxXG4xMDM1ODU4MzdcbjEyMFxuMDAwMDFcbjAwMDAxLVxuOVxuOS0iXQ==) This uses two injections to generate a bijection. The first injection \$f\$ from numeric to non-numeric is `‹` (append "-") and the second \$g\$ from non-numeric to numeric is `fC₇β` (get ascii values and convert from base 128). It is similar to <https://en.wikipedia.org/wiki/Schr%C3%B6der%E2%80%93Bernstein_theorem#Proof> but we make sure that there are no doubly infinite sequences or cyclic sequences by carefully choosing \$f\$ and \$g\$. It works reasonably well for large inputs. The simplified algorithm is the following: ``` def encode(S): if S is numeric: if there is a non-numeric T such that encode(T) == S: return T else: return f(S) else: if there is a numeric T such that encode(T) == S: return T else: return g(S) ``` Full explanation: ``` λ # start a lambda [ # base case for recursion, only continue if the argument is not empty ± # is the argument numeric? [ # if it is: ``` Compute `f(S)` and find the only candidate for `T` ``` ‹ # append "-" n # push argument ⌊ # convert string to number ₇τ # convert to base 128 C # chr(x) ṅ # join by nothing kQ↔ # only keep printable ASCII | # else: ``` Compute `g(S)` and find the only candidate for T ``` f # list of characters C # ord(x) ₇β # convert from base 128 n # push argument Ṫ # remove tail ] # end if : # duplicate T candidate x # compute encode(T) n≠ # is not equal to argument ß_ # if true pop ;† # end lambda and call it ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~37~~ ~~36~~ ~~33~~ 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žQ∞δã˜Dʒ9ÝKĀ}sþI9ÝKĀis}ÅΔI‚1ìË}è ``` [Try it online](https://tio.run/##yy9OTMpM/f//6L7ARx3zzm05vPj0HJdTkywPz/U@0lBbfHifJ4SZWVx7uPXcFM9HDbMMD6853F17eMX//4q2AA) or [verify some test cases](https://tio.run/##yy9OTMpM/V9WeWilvZLCo7ZJCkr2/4/uC3zUMe/clsOLT89xOTXJ8vBc7yMNtcWH9x1aB2FnFtcebj035dC6Rw2zDA@vOdxde3jFf53/0UoKSjpKBko6CkqJQIaJKYilqAgSMzcEsc3MzIAcdSsQ28DSEshWtFWKBQA) (times out for most test cases). **Explanation:** Pairs all *all-numeric* strings with all *ASCII-printable-only-not-all-numeric* strings. If the input is all-numeric, outputs the corresponding ASCII-printable-only-not-all-numeric, or vice-versa if not. ``` žQ # Push a builtin string of all printable ASCII ∞ # Push an infinite positive list: [1,2,3,...] δ # Apply double-vectorized: ã # Cartesian power ˜ # Flatten this infinite list of lists D # Duplicate it ʒ } # Filter it by: 9Ý # Push list [0,1,2,3,4,5,6,7,8,9] K # Remove all those digits from the string Ā # Python-style truthify to check if anything remains (aka NOT all-numeric) # (Note: `d≠` or `DþÊ` wouldn't work here for test cases like 0.1 or +1) s # Swap, so the other infinite list is at the top again þ # Only keep all all-numeric values I # Push the input 9ÝKĀi } # Pop, and if it's NOT all-numeric (with a similar check as in the filter): s # Swap the two infinite lists on the stack ÅΔ } # Pop the top list, and find the first index that's truthy for: I‚ # Pair the current value with the input 1ì # Prepend a 1 before each (workaround, since "02"=="+2"=="2.0"==2 in 05AB1E) Ë # Check that both values in the pair are the same è # Get the value at the found index from the other infinite list # (after which the result is output implicitly) ``` [See all pairs in the infinite lists.](https://tio.run/##ASsA1P9vc2FiaWX//8W@aMW@UeKAmuKIns60w6PigqzLnGDKkjnDnUvEgH3DuP//) [Answer] # [Haskell](https://www.haskell.org/), 153 bytes ``` c=(head.).filter d=['0'..'9'] e=(mapM id=<<).(<$>[0..]).flip replicate f x=c(/=x).c(elem x).zipWith((.pure).(:))(e d)$filter(any(`notElem`d))$e[' '..'~'] ``` [Try it online!](https://tio.run/##JY2xDsIgFAD3fgUxNDyWZ1dNcXN0dmialMBrSqRIEJPq4K8jxu2Gu9yiHzfyvhSjYCFtUeLsfKbUWDWITiCKgxgbUrDqeGHOqr6XCD0/DR3iWG3vIksUvTM6UzOzTRnYq02iAfK0skpvF68uLwAYn4lqfpQSiFnJ/y/Q4QVTuOdzDSYrJadBsN/7I8ayahdUTC5kPu/adle@ "Haskell – Try It Online") enumerates all all-decimals and all some-non-decimal strings and pairs them for lookup to bypass "0001"→base94(1)→"1" or n→all-decimals-base94(n)→base94(base94(n)) mismatches [Answer] # [R](https://www.r-project.org), ~~172~~ 168 bytes *Edit: -4 bytes thanks to pajonk* ``` \(x,`?`=unlist,m=match){d=?Map(f<-\(n)if(n)?lapply(intToUtf8(32:126,T),paste0,f(n-1)),1:(2*nchar(x))) a=d[e<-grepl("^\\d*$",d)] `if`(i<-m(x,b<-d[!e],0),a[i],b[m(x,a)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PU_BToQwFLzzFVg99G3aZMFEN4SGL_C2ngDDg7ZuE8Cm7Sob45d4wYPRX_JvZIPx8t5k3mRm3vuHm7_8iwndQXweg-a7n--KTqwpGnEce-MDG8SAyxlepSju0FKd84qOYPQyih6t7U_UjGH_dB_0jl6nWZLesD0wiz6oLVtkPAFgSUbTzdgd0NEJACIUslQ5f3TK9pQ8VJXcXBEmoY4aoxtqcj4sPdqcy_JC1WwLDEtTs7Y80wg1vP31zS7jZ-VOcYvedHHCzxHYBeViNeFge-WzaP2QEiTwj28JrA7zvO5f) or [Attempt a simpler version](https://ato.pxeger.com/run?1=VY_PToNAEIfvPMWIHnabJWGrxkogfQLjwXoCDMP-kU3oQmCJbYxP4qUefAAfp29TGjTBy0y-mcmX33x-dYfj0yV0Sg5CSejfjBMV6MEKZxoLI1aAdVthqRw0Ghpb70FU2KFwqusjCIHDEq4BoQQB0psMyffgdLA6_mRkx4p1kQy2Nr1j22SL45q-y2T9gC3RcZARS40ey7rGtq33xFi3aZ6dXhFBblbRLWf3dxEPQ8o2lLXYOxWy8T7glDIekeXCnvOQHaXUw0SmKg5eO9XWxH_JMrm48pmkuVcYXRATB9sxUBkHMr1QORudmJqclel5jDSnH7_BH6c_iI-lT70_4MsZhPwfzImL-epsmLSHw9RP) **How? - ungolfed code** ``` switch=function(x){ f=function(n)if(n)unlist(lapply(c(intToUtf8(32:126,T)),paste0,f(n-1))) # f is a recursive function that generates all 'words' of size n d=unlist(lapply(1:(2*nchar(x)),f)) # d is the 'dictionary' of all words of size 1..n # using a max size of twice the length of input e=grepl("^[0-9]*$",d) # e is the indices of all-number words a=d[e] # a is the set of all-number words b=d[!e] # b is the set of mixed all-letter or number-letter words `if`(i<-match(x,b,0),a[i],b[match(x,a)]) # if the input matches an all-number word, get its index i, # and return the mixed word at the corresponding index; # otherwise vice-versa } ``` ]
[Question] [ Let's have string multiplication to take a string and a positive number and concatenate that string that many times. In Haskell: ``` 0 * s = "" n * s = s ++ ((n - 1) * s) ``` Your task is to write a program that outputs a number \$n > 0\$. When you double your program (with the described procedure) the new program should output \$2n\$. When your program is tripled or quadrupled it should once again output the original \$n\$. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so your answers will be scored in bytes with fewer bytes being better. --- [Related](https://codegolf.stackexchange.com/questions/157876/third-time-the-charm/158144#158144), [Related](https://codegolf.stackexchange.com/questions/132558/i-double-the-source-you-double-the-output). [Answer] # [Python 2](https://docs.python.org/2/), 9 bytes Outputs [via exit code](https://codegolf.meta.stackexchange.com/a/5330/39242). Full credit goes to [Anders Kaseorg](https://codegolf.stackexchange.com/users/39242/anders-kaseorg) for [this answer to *I double the source, you double the output!*](https://codegolf.stackexchange.com/a/132795/59487). ``` ';exit(2) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/X906tSKzRMNI8/9/AA "Python 2 – Try It Online") | [Doubled](https://tio.run/##K6gsycjPM/r/X906tSKzRMNIE874/x8A) | [Tripled](https://tio.run/##K6gsycjPM/r/X906tSKzRMNIE5Px/z8A) | [Quadrupled](https://tio.run/##K6gsycjPM/r/X906tSKzRMNIEw/j/38A) Regularly, this raises a Syntax Error because the string is not closed properly and exists with exit code **1**, then, when doubled, it becomes `';exit(2)';exit(2)` which simply exits with code **2** because the string literal is now quoted properly and has no effect at all, and when repeated any other arbitrary number of times, it raises Syntax Errors. [Answer] # [R](https://www.r-project.org/), ~~27~~ 25 bytes ``` 1+!1-length(readLines()) ``` [Try it online!](https://tio.run/##K/r/31Bb0VA3JzUvvSRDoyg1McUnMy@1WENTk@v/fwA "R – Try It Online") Inspired by [rturnbull's answer to Third time the charm](https://codegolf.stackexchange.com/a/157943/67312), but the simplicity of the check makes it shorter. [Doubled](https://tio.run/##K/r/31Bb0VA3JzUvvSRDoyg1McUnMy@1WENTkwunxP//AA) | [Tripled](https://tio.run/##K/r/31Bb0VA3JzUvvSRDoyg1McUnMy@1WENTk4t0if//AQ) | [Quadrupled](https://tio.run/##K/r/31Bb0VA3JzUvvSRDoyg1McUnMy@1WENTk4uKEv//AwA) ### Why this works: `readLines()` will actually reads the source file itself rather than `stdin`. Hence, adding lines just increments the `length()` of the vector returned by `readLines()`. Therefore, we compute `!(1-length())` to obtain `1` whenever `length()==1` and `0` when `length()!=1`, adding one to have the desired effect. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ ~~6~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage), `n=3` ``` ₆¾Θè¼ ``` -1 byte thanks to *@CommandMaster*. [Try it online](https://tio.run/##yy9OTMpM/f//UVPboX3nZhxecWjP//8A); [try it doubled](https://tio.run/##yy9OTMpM/f//UVPboX3nZhxecWgPEvP/fwA); [try it tripled](https://tio.run/##yy9OTMpM/f//UVPboX3nZhxecWgPdub//wA); [try it quadrupled](https://tio.run/##yy9OTMpM/f//UVPboX3nZhxecWgPQeb//wA). **Explanation:** ``` ₆ # Push 36 ¾ # Push the counter_variable (0 by default) Θ # 05AB1E-style truthify: ==1 (results in 1 if 1; 0 for everything else) è # Use that to index into the 36 ¼ # Increase the counter_variable by 1 # (and output the indexed digit implicitly as result) ``` [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 29 bytes ``` ^w '\ /1@ 3 / ~!4 2'51\w /yyy ``` [Try it online!](https://tio.run/##KyrNy0z@/z@uXEE9hkvf0EHBmEtfoU7RhMtI3dQwppxLv7Ky8v9/AA "Runic Enchantments – Try It Online") Slight alteration from the Third Times A Charm entry, using [Jo King's compressed version](https://codegolf.stackexchange.com/questions/157876/third-time-the-charm/177753#comment428524_177753) and swapping the two reflection locations. [Twice](https://tio.run/##KyrNy0z@/z@uXEE9hkvf0EHBmEtfoU7RhMtI3dQwppxLv7KyEq/k//8A) [Thrice](https://tio.run/##KyrNy0z@/z@uXEE9hkvf0EHBmEtfoU7RhMtI3dQwppxLv7KyknzJ//8B) [And frice](https://tio.run/##KyrNy0z@/z@uXEE9hkvf0EHBmEtfoU7RhMtI3dQwppxLv7KykkaS//8DAA) for good measure. [Answer] # [Klein](https://github.com/Wheatwizard/Klein) 000, 6 bytes ``` \1+@ \ ``` [Try it online!](https://tio.run/##y85Jzcz7/z/GUNuBK@b///8GBgYA "Klein – Try It Online") ## Explanation The idea here is pretty simple, the first 2 copies require the ip to move off the edge of the program but the third does not, that way adding anything extra after the third doesn't change anything. The first program reflects off of both edges the ``` \ \ ``` At the begining is just a fancy noop. So we just run `1+@`. For the two copies this gets interrupted ``` \1+@ \\1+@ \ ``` We hit both `1`s and a `+` to get `2`. On the three we interrupt the path even further ``` \1+@ \\1+@ \\1+@ \ ``` At this point it might not be the clearest, but the ip bounces around in the mirrors a bit before it hits runs the 3rd line. This is what it runs ``` \ \\ \1+@ ``` Since this doesn't go off an edge further additions don't make any change to the program. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes ``` PI⊕⁼²L⊞Oυω ``` [Try it online!](https://tio.run/##AScA2P9jaGFyY29hbP//77yw77yp4oqV4oG8wrLvvKziip7vvK/Phc@J//8 "Charcoal – Try It Online") Based on my answer to [I double the source, you double the output!](https://codegolf.stackexchange.com/questions/132558) but compares the length to 2. [Try it doubled](https://tio.run/##S85ILErOT8z5///9ng3v96x81DX1UeOeQ5ve71nzqGve@z3rz7ee78Qj9f8/AA "Charcoal – Try It Online"). [Try it tripled](https://tio.run/##S85ILErOT8z5///9ng3v96x81DX1UeOeQ5ve71nzqGve@z3rz7ee7yRP6v9/AA "Charcoal – Try It Online"). [Try it quadrupled](https://tio.run/##S85ILErOT8z5///9ng3v96x81DX1UeOeQ5ve71nzqGve@z3rz7ee76S61P//AA "Charcoal – Try It Online"). In verbose syntax this is `Multiprint(Cast(Incremented(Equals(2, Length(PushOperator(u, w)))))));`. [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` vxHQXH4=Q ``` Uses *n* = 1. Try it online! [Original](https://tio.run/##y00syfn/v6zCIzDCw8Q28P9/AA), [doubled](https://tio.run/##y00syfn/v6zCIzDCw8Q2EM74/x8A), [tripled](https://tio.run/##y00syfn/v6zCIzDCw8Q2EJPx/z8A), [quadrupled](https://tio.run/##y00syfn/v6zCIzDCw8Q2EA/j/38A). ### Explanation This uses clipboard H to store state information. Function `H` pastes the clipboard contents onto the stack. Function `XH` copies the top of the stack into the clipboard. The clipboard initially contains the number `2`. Each time the snippet `vxHQXH4=Q` is run it does the following. The stack contents, if any, are deleted (`vx`). The clipboard contents are pushed (`H`) and incremented (`Q`), and the result is copied back into the clipboard (`XH`). This gives `4` the second time, and only that time. The number in the stack is tested for equality with `4` (`4=`) and incremented (`Q`). This gives `2` for `4` (second time), and `1` otherwise (any other time). [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), 36 bytes ``` (({}<>{})[()]<>)(()(){[()](<{}>)}{}) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fQ6O61sauulYzWkMz1sZOU0NDU0OzGsTRsKmutdOsBUr9/w8A "Brain-Flak (BrainHack) – Try It Online") Uses a counter off stack. Each time we run the counter is incremented by the result of the last run. If the counter is equal to exactly 1 (which it is when the program is doubled) then we push 2, otherwise 1 is pushed. The selection is done using a bit of a weird if statement. It is 2 normally but if the if is entered (which it is when the count is not 1) we subtract 1 from it. [Answer] # [Bash](https://www.gnu.org/software/bash/), 8 bytes This is a rip-off of the [Python 2](https://codegolf.stackexchange.com/a/177887/99151) answer. Output is via exit code. Unlike the Python 2 answer, this uses \$n=2\$. ``` ";exit 4 ``` [Try it online!](https://tio.run/##S0oszvj/X8k6tSKzRMHk/38A "Bash – Try It Online") [Try it online (doubled)!](https://tio.run/##S0oszvj/X8k6tSKzRMEERv//DwA "Bash – Try It Online") [Try it online (tripled)!](https://tio.run/##S0oszvj/X8k6tSKzRMEEnf7/HwA "Bash – Try It Online") [Try it online (quadrupled)!](https://tio.run/##S0oszvj/X8k6tSKzRMEEF/3/PwA "Bash – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 4 bytes (n=1) ``` »ɼḂ‘ ``` [Try it online!](https://tio.run/##y0rNyan8///Q7pN7Hu5oetQw4/9/AA "Jelly – Try It Online") ## Explanation ``` Initial value = 0 Initial register value = 0 ɼ Set the register and current value to » maximum of the register and current value Ḃ Parity ‘ Increment ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 24 bytes ``` ';$host.setshouldexit(2) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X91aJSO/uESvOLWkOCO/NCcltSKzRMNI8/9/AA "PowerShell – Try It Online") | [Doubled](https://tio.run/##K8gvTy0qzkjNyfn/X91aJSO/uESvOLWkOCO/NCcltSKzRMNIE5f4//8A) | [Tripled](https://tio.run/##K8gvTy0qzkjNyfn/X91aJSO/uESvOLWkOCO/NCcltSKzRMNIk1ri//8DAA) | [Quadrapled](https://tio.run/##K8gvTy0qzkjNyfn/X91aJSO/uESvOLWkOCO/NCcltSKzRMNIk1ri//8DAA) Outputs through exit code, Shameless port of python answer ;-) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes (n=1) ``` .gΘ> ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fL/3cDLv//wE "05AB1E – Try It Online") ## Explanation ``` .gΘ> .g Push length of stack Θ Equals 1? > Increment ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 4 bytes (n=1) ``` ∴:∷› ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%88%B4%3A%E2%88%B7%E2%80%BA&inputs=&header=&footer=) Same approach as [my Jelly answer](https://codegolf.stackexchange.com/a/215224/98955), but much more aesthetic. ``` ∴:∷› ∴ Pop a, b; push max(a,b) : Duplicate ∷ Parity › Increment ``` ]
[Question] [ Write a program or function to produce the following output in the correct order. **EDIT:** The symbols are not mathematical! The numbers just represent unique data and the `+` and `-` could be any two arbitrary symbols. Take an non-negative integer input n. The first line is always `-`, even for n=0. * If the current line is `-`, the next line is `1+2+ ... (n-1)+n-` + n=4: `-` => `1+2+3+4-` * If the last integer is equal to n, remove all integers from the end that are immediately followed by a `-`, then change the last `+` to a `-` + n=4: `1-2+3-4-` => `1-2-` + **EDIT:** When the string is full (all the integers from 1 to n are included), remove all integers from the end that are followed by a `-`, until you reach an integer followed by a `+`. Leave that integer but change its following `+` to a `-` + Using the same example as immediately above (which does **not** follow `-`), remove `4-`, remove `3-`, change `2+` to `2-`. `1-` doesn't change since we stop at `2`. Result: `1-2-` * If the last integer is less than n, append the remaining integers with a `+` after each one, except the final integer which should have a `-` appended + n=4: `1+2-` => `1+2-3+4-` + **EDIT:** If the current string is not full (does not contain all the integers from 1 to n), add each integer not already included in ascending order up to n-1 with a `+` after each one, and then append the last integer n followed by a `-` + If the current line is `1-`, append `2+`, append `3+` which is n-1 if n=4. Then append `4-`. Result: `1-2+3+4-` * If the current line contains all the integers and each one is immediately followed by a `-`, exit the code + n=4: `1-2-3-4-` => END There must be no leading or trailing spaces on any line. There must be a line break between each line. There may or may not be a line break on the last line. **EDIT:** You should test your code up to at least n=10 (over 1000 lines of output so I can't include it here). Any number that doesn't cause your code to run out of resources should (eventually!) produce the correct output but you don't have to wait for the universe to end! This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! Input n=0: ``` - ``` Input n=1: ``` - 1- ``` Input n=2: ``` - 1+2- 1- 1-2- ``` Input n=4: ``` - 1+2+3+4- 1+2+3- 1+2+3-4- 1+2- 1+2-3+4- 1+2-3- 1+2-3-4- 1- 1-2+3+4- 1-2+3- 1-2+3-4- 1-2- 1-2-3+4- 1-2-3- 1-2-3-4- ``` [Answer] # [Haskell](https://www.haskell.org/), 89 bytes `g` takes an integer and returns a string. ``` g n=unlines$max"-".foldr(\(s,i)r->id=<<[show i++s:r|s:r>"+"])""<$>mapM(mapM(,)"+-")[1..n] ``` [Try it online!](https://tio.run/##LYxBCsMgEAC/IosHxSgN9FSMP@gL0hyk2kSqa9CU9NC/21B6mLkMzGLr08fYkg04BNx8sfeNvjAG9FUlu7JZFW8dV3surraZ4PCvNNk3SFCPHF1hN1a7wIs0wQ1aj3XJOwlC1Ev5HBgQMHEATc3xvLKfOg5CAh97pXBq7Uz60xc "Haskell – Try It Online") # How it works * Loosely speaking, the algorithm constructs a list of all `2^n` combinations `1+2+...n+`, `1+2+...n-` up to `1-2-...n-`, strips away the final `+`-terminated numbers, and if the result is empty, replaces it with `-`. * `mapM(,)"+-"` is a shorter way (using the function monad) to write `\i->[('+',i),('-',i)]`. * `mapM(mapM(,)"+-")[1..n]` generates (using the list monad for the outer `mapM`) a list with all combinations as lists of tuples e.g. `[(1,'+'),(2,'-'),...,(n,'+')]`. * `foldr ... <$> ...` combines each of these lists of tuples into a string, using the lambda expression to build it from the right. + `(s,i)` is a tuple of a sign and a number, and `r` is the string constructed from the tuples to its right. + `id=<<[show i++s:r|s:r>"+"]` prepends `i` and `s` to the string `r` constructed so far, but *not* if the sign `s` is positive and `r` is empty. - This is tested by comparing `s:r` to `"+"`. By luck this is the lexicographically smallest string that can result from concatenating them, so the comparison can use `>` rather than `/=`. * Also by luck, `"-"` is smaller than any nonempty string that can be constructed by the fold, so the empty string can be replaced with it by using `max`. * Finally `unlines` turns the strings into a single string of lines. [Answer] # [Python 2](https://docs.python.org/2/), 101 bytes ``` n=input() for i in range(2**n):s='';m=n;exec"s=`m`+'+-'[i%2]+s;s*='-'in s;i/=2;m-=1;"*m;print s or'-' ``` [Try it online!](https://tio.run/##DcvBCsIwDADQu18RBpKtpYjFkyFfIsJEqubQtDQd6NfXnR@v/vqnaBxDWbRufV4Or9JAQBTaQ99pjs7pcjVGpMxK6Zuek/GaV48@4E2O8e6NzDEG3JORnDhSDnymyWWqTbSDQWm7j3H5Aw "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 136 141 133 bytes ``` def f(n,s="+"): while"+"in s:s=s[:s.rfind("+")]+"-";print s[s>"-":];s+="+".join(map(str,range(len(s)/2+1,n+1)))+"-";print(n>0)*s[1:] ``` [Try it online!](https://tio.run/##RYtBCsMgEADvfYV42q02rYFeDMlHJIdAtLGkG3GF0Nfb5NTbDMykb1k2amudfRABSHMvlUR7EfsSV39wJMGWe3aWmxwizXAGo5I32aUcqQh2PBxmx47VeTfvLRJ8pgRcss4TvTysnoDx3iqjSRlE/P9AwwOv7Iwda4An1h8 "Python 2 – Try It Online") The first `-` (un)surprisingly added a fair few bytes to the code. [Answer] # [Python 2](https://docs.python.org/2/), ~~150~~ ~~164~~ ~~159~~ ~~154~~ ~~146~~ ~~118 bytes~~ ~~115~~ 112 bytes ``` def f(n,i=0): while i<2**n:t=''.join(`j+1`+'+-'[i>>n+~j&1]for j in range(n));print t[:t.rfind('-')+1]or'-';i+=1 ``` [Try it online!](https://tio.run/##DcZBCoMwEADAe1@xp27iVmmEXmLjR0SwYFI3lI2EgHjp19POafazbEn6WlcfICi5sbtre4Fj448HfvZNI7Y4xC4mFrVEMgshtTjxOAp949XMIWWIwAL5JW@vROthzywFymRLlwPLqrBFTWZO@Z@ByZka1EPXHw "Python 2 – Try It Online") Edit: Oops! It has to work for numbers **greater than** 4 as well... then chip away... until I realized I was overthinking it and saved 28 bytes... and then 6 more via little golfs. [Answer] # Pyth, 23 bytes ``` j+\-mssVSQd<Lx_d\-t^"+- ``` [Demonstration](http://pyth.herokuapp.com/?code=j%2B%5C-mssVSQd%3CLx_d%5C-t%5E%22%2B-&input=4&debug=0) The basis of this program is noticing that other than the initial `-`, the plus and minus sequence corresponds to the standard sequence of combinations of `+` and `-` with replacement, with all trailing `+` removed. **Explanation:** ``` j+\-mssVSQd<Lx_d\-t^"+- j+\-mssVSQd<Lx_d\-t^"+-"Q Implicit string completion and variable introduction ^"+-"Q Form all sequences of + and - of length equal to the input, ordered lexicographically. t Remove the first one, which we don't use. <L Take the prefix of each one of length x index in _d the reversed string \- of '-'. m Map the results to sV Apply the sum function to pairs of SQ [1, 2, 3 ... input] d and the previous string s Sum the pairs. +\- Add a '-' on to the front of the list j Join on newlines. ``` [Answer] # [Python 2](https://docs.python.org/2/), 73 bytes ``` f=lambda n,a=2,d='\n1':a<n+2and f(n,a+1,d+'+'+`a`)+d+f(n,a+1,d+`-a`)or'-' ``` [Try it online!](https://tio.run/##TYwxDsIwEAR7XnHdxTqnsMsI/4TChy6GSLCOrDS83rhAIrPdjLT753hWxN5Leun7bkrwmqK3xDcEXvQKiQqjMo0gwZvwWNbsxOQv8zxMbTxzL7URaAM1xWOdQnDLhQZ723AQpx/sCSc/rlz/Ag "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 70 bytes ``` f n=unlines$"-":foldr(\i x->tail[show i++s:y|s<-"+-",y<-"":x])[][1..n] ``` [Try it online!](https://tio.run/##LY5BCoMwFESvMny6UNIE3Ur1Bq66jKEEqhgav2KUKvTuqZXOZh6zeExvw6v1PsYOXK7sHbfhQpKKbvTPOWkcNlkt1nkd@vENJ0Qo9k@4SRKSrvvRVGwm1UbnSrGJg3WMEoOd6geShiErTOtyX2YkVP4DghA4hfwjavhcjg9pCp0plWcmfgE "Haskell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 305 bytes ``` x=int(input()) o=lambda:list(range(1,x+1))or[0] q=o() q[-1]*=-1 print('-') def f(a):print(''.join(str(abs(x))+'-+'[x>0]for x in a)) while any([k>0 for k in q])or[-k for k in q]!=o(): f(q) if-q[-1]==x: while q[-1]<0:q=q[:-1] q[-1]*=-1 elif-q[-1]<x: while q[-1]<x:q+=[abs(q[-1])+1] q[-1]*=-1 f(q) ``` [Try it online!](https://tio.run/##ZY7BTsQgFEXX5StwxXsipo2zIsP8COmCyRQHW6FQjMzX11I1Gt3xzs3l3PmWr8E/rWtRzmdwfn7LgEiCmszr@WLk5JYMyfjnAbqHwjvEkHTbk6gCIIladP29Eh2ZU@0zwZBcBkstGJRfjD2@BOdhyQnMeYGCyJngTJdT29uQaKHOU7NJ369uGqjxN9DjqaU1G2sW@yoV429yV/2SNBYiksZZsU9Rqmys@fxoJ8dWRhW13J5b8LO3Gabv0vFfp8jIla5j9xv5n3KVruvhAw "Python 3 – Try It Online") ]
[Question] [ Based on this [challenge](https://codegolf.stackexchange.com/questions/123685/covfefify-a-string), you must determine if a string is covfefey, that is, could it have been produced as output from a covfefifier? The string will be composed of only alphabet chars (`^[a-z]\*$`, `^[A-Z]\*$` are possible schemes for input. change the regexs appropriately if using caps) To do this, there are a few checks you must do: Do the last four characters follow this scheme: ``` ([^aeiouy][aeiouy])\1 ``` example: ``` fefe ``` follows this scheme. is this consonant at the start of the ending the voiced or voiceless version of a consonant immediately before it? consonant pairings follow this key. find the consonant occuring before the end part consonant we had, and check whether the end part consonant is there ``` b: p c: g d: t f: v g: k h: h j: j k: g l: l m: m n: n p: b q: q r: r s: z t: d v: f w: w x: x z: s ``` does the first part of the word, the part that does not include the `([^aeiouy][aeiouy])\1`, follow this regex: ``` [^aeiouy]*[aeiouy]+[^aeiouy] ``` That is, does it contain one group of vowels, and exactly one consonant after that vowel? If it fulfills all these criteria, it is covfefey. Output a truthy value if covfefey, otherwise falsy Test cases ``` covfefe -> truthy barber -> falsy covefefe -> falsy pressisi -> falsy preszizi -> truthy prezsisi -> truthy president covfefe -> You don't need to handle this input as it contains a space. cofvyvy -> truthy businnene -> falsy (the first part does not follow the regex) ``` [Answer] ## JavaScript (ES6), ~~109~~ 108 bytes Returns `true` for covfefey / `null` or `false` otherwise. ``` s=>(m=s.match`^[^aeiouy]*[aeiouy]+(.)((.)[aeiouy])\\2$`)&&((a="bcdfgszkvtgp")[11-a.search(b=m[1])]||b)==m[3] ``` ### Test cases ``` let f = s=>(m=s.match`^[^aeiouy]*[aeiouy]+(.)((.)[aeiouy])\\2$`)&&((a="bcdfgszkvtgp")[11-a.search(b=m[1])]||b)==m[3] ;[ "covfefe", "barber", "covefefe", "pressisi", "preszizi", "prezsisi", "cofvyvy", "exxaxa" ] .map(s => console.log(s, '-->', f(s))) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 56 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 5ịØYiị“ßȷ%Hẹrȧq’œ?ØY¤⁾cgy Ṛµ4,2ị=ÇȦ Çȧe€ØyµḄ%⁴⁼5ȧŒgLe5,6 ``` A monadic link taking a list of lowercase characters and returning `1` for truthy and `0` for falsey. **[Try it online!](https://tio.run/##y0rNyan8/9/04e7uwzMiM4HUo4Y5h@ef2K7q8XDXzqITywsfNcw8OtkeKHloyaPGfcnplVwPd846tNVExwio2PZw@4llXEBieeqjpjWHZ1Qe2vpwR4vqo8Ytjxr3mJ5YfnRSuk@qqY7Z////lZLz08oqyyqVAA "Jelly – Try It Online")** or see the [test suite](https://tio.run/##y0rNyan8/9/04e7uwzMiM4HUo4Y5h@ef2K7q8XDXzqITywsfNcw8OtkeKHloyaPGfcnplVwPd846tNVExwio2PZw@4llXEBieeqjpjWHZ1Qe2vpwR4vqo8Ytjxr3mJ5YfnRSuk@qqY7Z/6N7DrcDVXgDceT//9FKSYlFSalFSjpKyfllqWlACGQWFKUWF2cWZwKZSaXFmXl5qXmpEBVICqoyqzIhzCqo2uT8tLLKskqlWAA). ### How? ``` 5ịØYiị“ßȷ%Hẹrȧq’œ?ØY¤⁾cgy - Link 1, convert 5th character: list of characters, r 5ị - index into r at 5 ØYi - first index of that in "BCDF...XZbcdfghjklmnpqrstvwxz" ¤ - nilad followed by link(s) as a nilad: “ßȷ%Hẹrȧq’ - base 250 number = 1349402632272870364 ØY - yield consonants-y = "BCDF...XZbcdfghjklmnpqrstvwxz" œ? - nth permutation = "BCDF...XZpctvkhjglmnbqrzdfwxs" ị - index into that (converts a 'b' to a 'p' etc..) ⁾cg - literal ['c','g'] y - translate (convert a 'c' to a 'g' - a special case) Ṛµ4,2ị=ÇȦ - Link 2, check the 3 consonants at the end: list of characters, w Ṛ - reverse w µ - monadic chain separation, call that r 4,2 - 4 paired with 2 = [4,2] ị - index into r Ç - call the last link (1) as a monad (get 5th char converted) = - equal? (vectorises) Ȧ - any and all (0 if empty or contains a falsey value, else 1) Çȧe€ØyµḄ%⁴⁼5ȧŒgLe5,6 - Main link: list of characters, w Ç - call last link as a monad (1 if the 3 consonants are good; else 0) Øy - vowel+y yield = "AEIOUYaeiouy" e€ - exists in? for €ach c in r ȧ - logical and (list of isVowels; or 0 if link 2 returned 0) µ - monadic chain separation, call that v Ḅ - convert from binary (0 yields 0) ⁴ - literal 16 % - modulo (0 yields 0) ⁼5 - equals 5? (1 if ending is consonant,vowel,consonant,vowel; else 0) Œg - group runs of v (e.g. [0,0,0,1,1,0,1,0,1]->[[0,0,0],[1,1],[0],[1],[0],[1]]) ȧ - logical and (the grouped runs if AOK so far, else 0) L - length (number of runs) 5,6 - 5 paired with 6 = [5,6] e - exists in (the number of runs must be 5 or 6 to comply) ``` [Answer] # Java 8, ~~211~~ ~~210~~ ~~166~~ ~~163~~ ~~161~~ 156 bytes ``` s->{int l=s.length()-5;return"bpbdtdfvfgkgszshhjjllmmnnqqrrwwxxcg".contains(s.substring(l,l+2))&s.matches("[^x]*[x]+(.)((.)[x])\\2".replace("x","aeiouy"));} ``` -2 bytes by replacing the regex `[^x]*[x]+[^x]([^x][x])\\1` with `[^x]*[x]+(.)((.)[x])\\2` thanks to [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/123917/52210). **Explanation:** [Try it here.](https://tio.run/##jZGxbsMgEIb3PAViqKBJGCJ1sto3aJaMSSphfLZxMDgcdmxHfnaXtJlbDyBO9/H//0ElO7l1Ddgqu8zKSETyKbW9rwjRNoDPpQKyf5SEpM4ZkJYodghe24IgT2JjWsUNgwxakT2x5J3MuP24x@vEvKMwYItQMr59SzyE1luaNmkWsrzLi0uBI5ZlVRlT19Zer97fbn2vCiqUsyEGQYYC2xR/DJnZmPWO8xcUtQyqBGT0@NWfX4/9ec0EZ3HFIz@ddlR4aEwMz2hPN1SCdu1AOU@mOXnkbdrUxLzP2J3TGamj3XOy45lI/jv0YcAAtXBtEE1sBWOZFYpR5boccnhI/sml0qfg/8WiHCzSazwgatSLwFGPi8BxkaJyeTd0wyJnnUH8/6WPBH0ve/nEptU0fwM) ``` s->{ // Method with String parameter and boolean return-type int l=s.length()-5; // Temp integer value with the length of the input-String - 5 return"bpbdtdfvfgkgszshhjjllmmnnqqrrwwxxcg".contains(s.substring(l,l+2)) // Return if the correct pair is present at the correct location // (i.e. `vf` at index l-5 + l-6 in the String `convfefe` &s.matches("[^x]*[x]+(.)((.)[x])\\2".replace("x","aeiouy")); // and if the String matches the regex-pattern } // End of method ``` [Answer] ## Perl, 80 bytes ``` $_=/[aeiouy]+(*COMMIT)(.)((.)[aeiouy])\2$/&&$3eq$1=~y/bcdfgkpstvz/pgtvkgbzdfs/r ``` Run with `perl -pe`. Due to their length, it’s not often that I get to use the [exotic regex verbs](http://perldoc.perl.org/perlre.html#Special-Backtracking-Control-Verbs) in golf, but this challenge is a perfect fit! Whenever the engine backtracks to `(*COMMIT)`, the entire match fails. This guarantees that the part that comes before it, `[aeiouy]+`, can only ever match the first thing it tries to match, namely the first continuous stretch of vowels. Thus, `[aeiouy]+(*COMMIT)(.)` is equivalent to `^[^aeiouy]*[aeiouy]+([^aeiouy])` (equivalent in terms of which strings match, but matches are on different positions). [Answer] # PHP , 121 Bytes ``` $v=aeiouy;echo preg_match("#^[^$v]*[$v]+([^$v])(([^$v])[$v])\\2$#",$argn,$t)&$t[3]==strtr($t[1],bcdfgkpstvz,pgtvkgbzdfs); ``` [Try it online!](https://tio.run/##LYzLDsIgFET3foWhxICyUZeV@CF9GEopNI32Bq4E@/NYGzczZ85iwEG@3cHBjipvX5KYlFRSpMw0SmXG@f0pjXbzHryxj6dC7Rgp2qqlsTlWa5zYxpz9@@d4XV9oQcR2KSjyA8Xq2kgZ0KNn6zg3otP9YCcIGBcBFuNku6UfAi9z/gI "PHP – Try It Online") ]
[Question] [ The [**continued fraction**](https://en.wikipedia.org/wiki/Continued_fraction) of a number `n` is a fraction of the following form: ![](https://upload.wikimedia.org/wikipedia/en/math/1/1/d/11dc14afeeb64dad18b916638aa287d7.png) which converges to `n`. The sequence `a` in a continued fraction is typically written as: [a0; a1, a2, a3, ..., an]. Your goal is to return the continued fraction of the given rational number (positive or negative), whether it is an: * integer `x` * fraction `x/y` * decimal `x.yz` **Input** May be a string representation, or numbers. For fractions, it may be a string, or some native data type for handling fractions, but you may not take it as a decimal. **Output** May be a delimited list or string of the *convergents* (the resulting numbers). The output **does not have to have a semi-colon** between a0 and a1, and may use a comma instead. Note that although `[3; 4, 12, 4]` and `[3; 4, 12, 3, 1]` are [both correct](https://en.wikipedia.org/wiki/Continued_fraction#Finite_continued_fractions), only the first will be accepted, because it is simpler. ### Examples: ``` 860438 [860438] 3.245 [3; 4, 12, 4] -4.2 [-5; 1, 4] -114.7802 [-115; 4, 1, 1, 4, 1, 1, 5, 1, 1, 4] 0/11 [0] 1/42 [0; 42] 2/7 [0; 3, 2] -18/17056 [-1; 1, 946, 1, 1, 4] -17056/18 [-948; 2, 4] ``` ### Rules * Shortest code wins. * Built-ins are allowed, but I'd also like you to post in the same answer what it would be without built-ins, so that you have to know how to do it. [Answer] ## Ruby, ~~45~~ ~~43~~ 46 bytes ``` f=->n{x,y=n.to_r.divmod 1;[x,*y==0?[]:f[1/y]]} ``` Accepts input as a string. All test cases pass: ``` llama@llama:~$ for n in 860438 3.245 -4.2 -114.7802 0/11 1/42 2/7 -18/17056 -17056/18; do ruby -e 'f=->n{x,y=n.to_r.divmod 1;[x,*y==0?[]:f[1/y]]}; p f["'$n'"]'; done [860438] [3, 4, 12, 4] [-5, 1, 4] [-115, 4, 1, 1, 4, 1, 1, 5, 1, 1, 4] [0] [0, 42] [0, 3, 2] [-1, 1, 946, 1, 1, 4] [-948, 2, 4] ``` Thanks to [Kevin Lau](https://codegolf.stackexchange.com/users/52194/kevin-lau-not-kenny) for 2 bytes! [Answer] # Ruby, ~~50~~ 48 bytes I noticed @Doorknob♦ beat me to a Ruby answer right before posting, and theirs is also shorter! As such this is just here for posterity now. Takes in a string or an integer (floats have rounding issues, so decimal values need to be put in as strings) ``` f=->s{s=s.to_r;[s.floor]+(s%1!=0?f[1/(s%1)]:[])} ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 7 bytes ``` ᶦ{1%ŗ}k ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FqsebltWbah6dHpt9pLipORiqPCCmx4WZgYmxhZcxkYmpvqGBgYGXLomRkAGl66hoYm5hYERWNCAy0Df0JDLUN_EiMtI3xwoaaFvaG5gagZkgSh9QwuIgQA) A port of [@Parcly Taxel's Mathematica answer](https://codegolf.stackexchange.com/a/260825/9288). ``` ᶦ{1%ŗ}k ᶦ{ } Iterate the following function until it fails 1% Modulo 1 ŗ Reciprocal k Floor ``` [Answer] # Jelly, ~~16~~ ~~13~~ 12 bytes ``` :;ç%@¥@⁶Ṗ¤%? ``` [Try it online!](http://jelly.tryitonline.net/#code=OjvDpyVAwqVA4oG24bmWwqQlPw&input=&args=LTE4+MTcwNTY) [Answer] ## JavaScript (ES6), 52 bytes ``` f=(n,d)=>n%d?[r=Math.floor(n/d),...f(d,n-r*d)]:[n/d] ``` Accepts numerator and denominator and returns an array, e.g. `f(-1147802, 1e4)` returns `[-115, 4, 1, 1, 4, 1, 1, 5, 1, 1, 4]`. [Answer] # Java, ~~85~~ 83 bytes ``` String f(int n,int d){return n<0?"-"+f(2*(d+n%d)-n,d):n/d+(n%d<1?"":","+f(d,n%d));} ``` ### Takes integer or fraction or decimal as String, 311 bytes ``` String c(String i){try{return""+Integer.decode(i);}catch(Exception e){int o=i.indexOf(46);if(o>=0)return c((i+"/"+Math.pow(10,i.length()-o-2)).replaceAll("\\.",""));String[]a=i.split("/");int n=Integer.decode(a[0]),d=Integer.decode(a[1]);return n<0?"-"+c(2*(d+n%d)-n+"/"+d):n%d<1?""+n/d:n/d+","+c(d+"/"+(n%d));}} ``` ### Sample input/output: ``` 860438 860438 3.245 3,4,12,4 -4.2 -5,1,4 -114.7802 -115,4,1,1,4,1,1,5,1,1,4 0/11 0 1/42 0,42 2/7 0,3,2 -18/17056 -1,1,946,1,1,4 -17056/18 -948,2,4 ``` ### Actual input/output from full program: ``` 860438 860438 860438 860438 860438 3.245 3,4,12,4 3,4,12,4 3,4,12,4 3,4,12,4 -4.2 -5,1,4 -5,1,4 -5,1,4 -5,1,4 -114.7802 -115,4,1,1,4,1,1,5,1,1,4 -115,4,1,1,4,1,1,5,1,1,4 -115,4,1,1,4,1,1,5,1,1,4 -115,4,1,1,4,1,1,5,1,1,4 0/11 0 0 0 0 1/42 0,42 0,42 0,42 0,42 2/7 0,3,2 0,3,2 0,3,2 0,3,2 -18/17056 -1,1,946,1,1,4 -1,1,946,1,1,4 -1,1,946,1,1,4 -1,1,946,1,1,4 -17056/18 -948,2,4 -948,2,4 -948,2,4 -948,2,4 ``` ### Full program (including ungolfed functions): ``` import java.util.Scanner; public class Q79483 { String cf_ungolfed(String input){ try{ int result = Integer.parseInt(input); return Integer.toString(result); }catch(Exception e){ if(input.indexOf('.')>=0){ int numerator = Integer.parseInt(input.replaceAll("\\.","")); int denominator = (int) Math.pow(10, input.length()-input.indexOf('.')-1); return cf_ungolfed(numerator+"/"+denominator); } int numerator = Integer.parseInt(input.substring(0,input.indexOf('/'))); int denominator = Integer.parseInt(input.substring(input.indexOf('/')+1)); if(numerator%denominator == 0){ return Integer.toString(numerator/denominator); } if(numerator < 0){ return "-"+cf_ungolfed((denominator-numerator+(denominator+2*(numerator%denominator)))+"/"+denominator); } return (numerator/denominator) + "," + cf_ungolfed(denominator+"/"+(numerator%denominator)); } } String c(String i){try{return""+Integer.decode(i);}catch(Exception e){int o=i.indexOf(46);if(o>=0)return c((i+"/"+Math.pow(10,i.length()-o-2)).replaceAll("\\.",""));int n=Integer.decode(i.split("/")[0]),d=Integer.decode(i.split("/")[1]);return n<0?"-"+c(2*(d+n%d)-n+"/"+d):n%d<1?""+n/d:n/d+","+c(d+"/"+(n%d));}} String f_ungolfed(int numerator,int denominator){ if(numerator%denominator == 0){ return Integer.toString(numerator/denominator); } if(numerator < 0){ return "-"+f_ungolfed((denominator-numerator+(denominator+2*(numerator%denominator))),denominator); } return (numerator/denominator) + "," + f_ungolfed(denominator,(numerator%denominator)); } String f(int n,int d){return n<0?"-"+f(2*(d+n%d)-n,d):n/d+(n%d<1?"":","+f(d,n%d));} public static int[] format(String input){ if(input.indexOf('.') != -1){ int numerator = Integer.parseInt(input.replaceAll("\\.","")); int denominator = (int) Math.pow(10, input.length()-input.indexOf('.')-1); return new int[]{numerator,denominator}; } if(input.indexOf('/') != -1){ int numerator = Integer.parseInt(input.substring(0,input.indexOf('/'))); int denominator = Integer.parseInt(input.substring(input.indexOf('/')+1)); return new int[]{numerator,denominator}; } return new int[]{Integer.parseInt(input),1}; } public static void main(String args[]){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String input = sc.next(); System.out.println(new Q79483().cf_ungolfed(input)); System.out.println(new Q79483().c(input)); int[] formatted = format(input); System.out.println(new Q79483().f_ungolfed(formatted[0], formatted[1])); System.out.println(new Q79483().f(formatted[0], formatted[1])); } sc.close(); } } ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 29 bytes ``` `t1e7*Yo5M/kwy-t1e-5>?-1^T}xF ``` [**Try it online!**](http://matl.tryitonline.net/#code=YHQxZTcqWW81TS9rd3ktdDFlLTU-Py0xXlR9eEY&input=LTExNC43ODAy) This works by repeatedly rounding and inverting (which I think is what Doorknob's answer does too). There may be numerical issues due to using floating point, but it works for all the test cases. ``` ` % Do...while t % Duplicate. Takes input implicitly the first time 1e7* % Multiply by 1e7 Yo % Round 5M/ % Divide by 1e7. This rounds to the 7th decimal, to try to avoid % numerical precision errors k % Round w % Swap top two elements of stack y % Copy the secomnd-from-bottom element - % Subtract t % Duplicate 1e-5> % Is it greater than 1e-5? (1e-5 rather than 0; this is again to % try to avoid numerical precision errors) ? % If so -1^ % Compute inverse T % Push true as loop condition (to start a new iteration) } % Else xF % Delete and push false (to exit loop) % End if implicitly % End do...while implicitly % Display implicitly ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 43 bytes *-4 from alephalpha* ``` Floor@NestWhileList[1/t&,#,(t=#~Mod~1)>0&]& ``` [Try it online!](https://tio.run/##HYq9CoMwFEZfJSBICyn33hg1i8WpU1u6dRAHaSMG/AG9W6mvniadzvkO39TxYKeO3avzfeUv47Ks9d1u/BzcaK9u44aAU5nIA1fJflveOx3PmLapf6xu5qaH@mMK1JmRIlM6B0JEKU5aBQsk0qVB9c9hIxBJQaCVFArKeDBAJeZF1Egg8239Dw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 15 bytes ``` M+]/GH?J%GHgHJY ``` [Try it online!](http://pyth.herokuapp.com/?code=M%2B%5D%2FGH%3FJ%25GHgHJYg.*&input=-18%2C17056&debug=0) (The `g.*` at the end is to fetch the input.) [Answer] # APL(NARS), 107 chars, 214 bytes ``` dd←{⍵=0:0⋄0>k←1∧÷⍵:-k⋄k}⋄nn←{1∧⍵}⋄f←{⍵=0:0x⋄m←⎕ct⋄⎕ct←0⋄z←{0=(d←dd⍵)∣n←nn⍵:n÷d⋄r←⌊n÷d⋄r,∇d÷n-r×d}⍵⋄⎕ct←m⋄z} ``` The function of the exercise f, should have as input one rational number (where 23r33 means as "23/33" in math) ...The algo is the same of the one Neil posted as JavaScript solution... test ``` f 860438r1 860438 f 3245r1000 3 4 12 4 f ¯42r10 ¯5 1 4 f ¯1147802r10000 ¯115 4 1 1 4 1 1 5 1 1 4 f 0r11 0 f 1r42 0 42 f 2r7 0 3 2 f ¯18r17056 ¯1 1 946 1 1 4 f ¯17056r18 ¯948 2 4 f 17056r¯18 ¯948 2 4 f 18r¯17056 ¯1 1 946 1 1 4 f 123r73333333333333333333333333373 0 596205962059620596205962059 1 16 1 1 3 +∘÷/f 123r73333333333333333333333333373 123r73333333333333333333333333373 ``` [Answer] # [Python 3](https://docs.python.org/3/), 46 bytes ``` f=lambda n,d:[n//d]+(n%d*[0]and f(d,n-n//d*d)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIU8nxSo6T18/JVZbI081RSvaIDYxL0UhTSNFJ08XJK6Voqn5v6AoM69EI03D2MjEVEfB0MDAQFOTCyaoa2hoYm5hYASRAMr8BwA "Python 3 – Try It Online") Port of [Neil's javascript answer](https://codegolf.stackexchange.com/a/79490/87681) [Answer] # [Scala](https://www.scala-lang.org/), 72 bytes Golfed version. [Try it online!](https://tio.run/##XY3BasMwEETv@opFYFjVMpFdlxYTB0ohkHPoqfSgWlJQcddBVgol5NsVC9@6MIeZ92DnQY86TV/fdojwNlH0dLFmH/QQ/URXxn71CK7DA0W5RPS7YwyeTtAnJGmW7h3SVgle8dJh84CmpMKIKkM7zhZoY0rMUmG2teA8j1xm2chsigRgrIMf7Ql1OM0dvIag/z7WR5@ig3fyEXq4MljuvKxxJHT42LRPEmqllBD/UFXX7fOLala88hu7sXQH) ``` (n,d)=>if(n<0)"-"+f(2*(d+n%d)-n,d)else n/d+(if(n%d<1)""else","+f(d,n%d)) ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 222 bytes/75 bytes ## A function that takes a string, 222 bytes ``` (a,o)=>{var@b=$"{a}/1".Split("/");var@c=$"{b[0]}.0".Split(".");int@n=int.Parse(c[0]),m=int.Parse(c[1]),d=1,r;for(;d<m;d*=10);for(n=n*d+(n>0?1:-1)*m,d*=int.Parse(b[1]);d>0;(n,d)=(d,n-r*d))o.Add(r=(int)Math.Floor(1m*n/d));}; ``` [Try it online!](https://tio.run/##hZPdbpswFMevw1NYqBd2Zj5MIElHyFpNjbSp1Sb1YhdVLgi4jdXEtODsQ8hPsds93V4kOwaWrAtSpRAb/3/n7@NzTFY5WSX2l5kShZxVqhTygaJrUalZzjOxTTfzOVqgBO1xSguSzOuvaXmxSs7sOtUes93bp41Q2PZsEhslM8rqzl9q1z@ILohCqguZwL/7OS0rjjNgCN2@WGGwkieMlvF9UeI4n23jfJgwnzTvMpHD/A2Wc/8de@swMtxSUI/xKxMf53M/xpLmJME5lU45zAkp3Ms8x2WCASY3qVq7i00Bjmw7lB7osY73kDxSvFLv04pXcF7JvyHc1gN9kBR11bhbok87RWCorQG2p2M/HE1t2uBHpG7XNaEGGrlBGJ0yI4pCilgAQwc6oRucck4E1D8QY6E7mfp9JGNRa9pG/J1Eh5XOw/cYOw33O5V5YY@5D@FBRwTepBeAIwWHNKcem/jRuC/NJpnzcPx/Xk4T4bGeiiLnPJyCPcCooXVsWXAteJqtETbdw6ZNpjlIyGMriQWNUuUPawDjwHBl190XlxyTGORF41E2c4MWj8CCpXvLn3dcZvzqeZducAuIe4SLRwIz4zz4UgrFr4Xk@Mz@/esnqsHKYZG@q9tb5H4shMRwMNvsoJd2Y6Lh4ZuK97ksXvVAuE8xNdBLctgAflmqsjW@@p7xJ/OhI07aevRvV3P3hldV@sD16ztoS@//AA "C# (Visual C# Interactive Compiler) – Try It Online") ## Just the part that takes numerator and denominator, 75 bytes ``` (n,d,o)=>{for(int@r;d>0;(n,d)=(d,n-r*d))o.Add(r=(int)Math.Floor(1m*n/d));}; ``` [Try it online!](https://tio.run/##hZTfb9owEMefyV9xiibVhvwyDZQuha2airSJapP6sIeKhzRxwWrqtIlpN6H8FXvdX7d/hJ2dAGvJVAnh5O5zX9/5fElKNynF5jxRIpdnQioHzN9MlOos5Ym4j7PJBKYwhg2RTurkdDxZ3@YFQexjEaWTINJ2OiapI92im1Kae@dpSoqxRuhlrJbeNMsxgt13pY/@qIo2T7lIYbpakFIVQi4gfrUl5NRaWx1V/LQ6uHamWsz7FhclJzF1gDlIRFansjpJrJJlTRncPHWe4gJuMOvYu3rIhCK2b2v@pdLNdTCnpuKdgWmDkdbaW/H/aHqNpnZk6NDh3ozLhVru7BLtzLzhqYHeHASaggiXM8gi6PUERaqLWNCeIXTR3wPzgj8Yj@HIPYIP4DJ4D0z7D0qQ/1RRWZVl6VwUL9WnuOQlJiD5M2xP/zPSzclfz@HrSlFcsGRij4ZBeDyyHYPvkXVtr6ijoWOvHw4OmWMHQuxUH5cGdEOvf8i5A9PPHcRY6J2MgjaSsUEtWkdsHwY7S6MR@IwdhgeNl/lhi3iA4f2G6PsnrQCW1N@lOfLZSTAYtqVpkjkNh6/zck2Ez1pOFNzTcITyCIOhq8iy8MrwOFkC0d0juk26OdjtfStfzonmiqa7LwaKmMugJ06rFOZNw/kd0ijqXfHHFZcJv3hcxRmpAXELJL@j2/v/vRCKz4Tk5J395/cvWKOUywbV9bq@R96XXEiCpdl6h2pu78aIZyVvU5m@qQGkzaNPoZpTe3/D60klFz8S/qC/ZcBpfSLt2625d8nLMl7w6u0dcH42fwE "C# (Visual C# Interactive Compiler) – Try It Online") ## Un-golfed code: ``` (input, output) => { var fracStr = $"{input}/1".Split("/"); // append "/1" so we never get an array out of bounds var decStr = $"{fracStr[0]}.0".Split("."); // append ".0" so we never get an array out of bounds // parse the decimal number first, // if we weren't passed a decimal, m will be 0 int n = int.Parse(decStr[0]); int m = int.Parse(decStr[1]); int d = 1; // denominator will be the next power of 10 larger than m: for (; d < m; d *= 10); // scale the numerator by the denominator, and add the decimal part: n = n * d + (n > 0 ? 1 : -1) * m; // now handle the fraction case // if we weren't passed a fraction then fracStr[1] will be "1" // if we were passed a fraction, d will be 1 d *= int.Parse(fracStr[1]); // now actually calculate the continued fraction: for (; d > 0; ) { int r = (int)Math.Floor(1m * n / d); output.Add(r); (n, d) = (d, n - r * d); } }; ``` ]
[Question] [ You are to make a program that can check the syntax of programs of its same language. For example, if you do it in python, it checks python syntax. Your program will receive a program on standard input, and verify whether or not its syntax is correct. If it is correct, output just "true" on standard output. If not, output just "false" on standard output. Your program must be incorrect in one instance though. If fed its own source code, it will just output "false" on standard output. This is code golf, so shortest program wins! Note: Although this isn't technically a quine, you must follow the quine rules, meaning you can't access your source code through the file system or whatever. Note: You can't claim a program that could not be run due to a syntax error solves this challenge, since it needs to be runnable. [Answer] ## Ruby 2.0, 65 ~~76 164~~ characters ``` eval r="gets p;$<.pos=0;`ruby -c 2>&0`;p$?==0&&$_!='eval r=%p'%r" ``` This uses Ruby's built-in syntax checker (`ruby -c`) to check the input's syntax, which means the code won't be evaluated. Basic usage example: ``` ruby syntax.rb <<< foo true ruby syntax.rb <<< "'" false ruby syntax.rb < synxtax.rb # assumes the file was saved without trailing newline false ``` ### Explanation This solution is (was) based on the standard Ruby quine: ``` q="q=%p;puts q%%q";puts q%q ``` `%p` is the format specifier for `arg.inspect`, which can be compared to `uneval`: when `eval`ing the string returned by `arg.inspect`, you (usually) get the original value again. Thus, when formatting the `q` string with itself as argument, the `%p` inside the string will be replaced with the quoted string itself (i.e. we get something like `"q=\"q=%p;puts q%%q\";puts q%q"`). Generalizing this type of quine leads to something like the following: ``` prelude;q="prelude;q=%p;postlude";postlude ``` This approach has one huge drawback though (at least in [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")): All code needs to be duplicated. Luckily, `eval` can be used to get around this: ``` eval r="some code;'eval r=%p'%r" ``` What happens here is that the code passed to eval is stored inside `r` *before* `eval` is called. As a result, the full source code of the `eval` statement can be obtained with `'eval r=%p'%r`. If we do this inside the `eval`d code and ensure that the top level of our consists only of the one `eval` statement, that expression actually gives us the full source code of our program, since any additional code passed to `eval` is already stored inside `r`. Side note: This approach actually allows us to write a Ruby quine in 26 characters: `eval r="puts'eval r=%p'%r"` Now, in this solution the additional code executed inside `eval` consists of four statements: ``` gets p ``` First, we read all input from STDIN and implicitly save it into `$_`. ``` $<.pos=0 ``` Then, we rewind STDIN so the input is available again for the subprocess we start in the next step. ``` `ruby -c 2>&0` ``` This starts Ruby in its built-in syntax checking mode, reading the source code from stdin. If the syntax of the supplied script (filename or stdin) is ok, it prints `Syntax OK` to its stdout (which is captured by the parent process), but in case of a syntax error, a description of the error is printed to *stderr* - which would be visible, so we redirect that into nirvana (`2>&0`) instead. ``` p$?==0&&$_!='eval r=%p'%r ``` Afterwards, we check the subprocess's exit code `$?`, which is 0 if the syntax was ok. Lastly, the input we read earlier (`$_`) is compared against our own source code (which, as I described earlier, can be obtained with `'eval r=%p'%r`). Edit: Saved 14 characters thanks to @histocrat! [Answer] # Rebol - 69 or 74~~75~~ fully compliant with all rules New working versions thanks to @rgchris! Not sure if the first fails the "don't access the source" requirement as the interpreter holds the loaded and parsed code it has been passed as a cmd line parameter in the system object (`system/options/do-arg`) which is used to recognise itself. ``` probe not any[error? i: try[load/all input]i = system/options/do-arg] ``` This one follows all of the rules: ``` do b:[i: input prin block? if i <> join "do b:" mold b [try [load/all i]]] ``` **Example usage:** First printing a valid integer, the second printing an invalid integer. ``` echo "rebol [] print 123" | rebol --do "probe not any[error? i: try[load/all input]i = system/options/do-arg]" true echo "rebol [] print 1w3" | rebol --do "probe not any[error? i: try[load/all input]i = system/options/do-arg]" false echo "probe not any[error? i: try[load/all input]i = system/options/do-arg]" | rebol --do "probe not any[error? i: try[load/all input]i = system/options/do-arg]" false ``` Fully compliant version: ``` echo 'rebol [] 123' |r3 --do 'do b:[i: input prin block? if i <> join "do b:" mold b [try [load/all i]] true echo 'rebol [] 123a' |r3 --do 'do b:[i: input prin block? if i <> join "do b:" mold b [try [load/all i]]]' false echo 'do b:[i: input prin block? if i <> join "do b:" mold b [try [load/all i]]]' |r3 --do 'do b:[i: input prin block? if i <> join "do b:" mold b [try [load/all i]] false ``` **Explanation:** *First version* This uses Rebols built-in `load` function to parse and load the code from stdin but it does not execute it. The `try` block catches any syntax errors and the `error?` function converts the error to a simple boolean. The `i = system/options/do-arg` compares the input from stdin (assigned to `i`) with the code passed on the `do-arg` argument (sneaky but very golf :). `any` is a great function which returns `true` if `any`-thing in the block evaluates to `true` (for example, `any [ false false true ]` would return `true`). `not` then just inverts the boolean to give us the correct answer and `probe` displays the contents of the returned value. *Fully compliant version* Let's go through this in order ... Assign the word `b` to the block [] that follows. Use the `do` function to interpret the `do` dialect in the `b` block. Inside the `b` block ... Set the word `i` to refer to the contents of stdin (`input`). Now, `if` we `join` the string "do b:" to the `mold`'ed block `b` and it is not equal (`<>`) to the stdin input `i` then we try to `load` the input `i`. If the result is a `block` then we have `load`'ed the passed data correctly otherwise we would receive a `none` from the failed `if`. Use `prin` to display the result of `block?` which returns true if the result is a block. Using `prin` as opposed to `print` does not display a carriage return after the output (and it saves us another char). [Answer] # Javascript - 86 82 ``` !function $(){b=(a=prompt())=='!'+$+'()';try{Function(a)}catch(e){b=1}alert(!b)}() ``` Paste into your browser's Javascript console to test. Explanation: ``` // Declare a function and negate it to call it immediately // <http://2ality.com/2012/09/javascript-quine.html> !function $ () { // Concatenating $ with strings accesses the function source invalid = (input = prompt()) == '!' + $ + '()'; try { // Use the Function constructor to only catch syntax errors Function(input) } catch (e) { invalid = 1 } alert(!invalid) // Call function immediately }() ``` **Note:** @m.buettner brought up the point that the program returns `true` for a naked return statement, such as `return 0;`. Because Javascript doesn't throw a syntax error for an illegal return statement until it actually runs (meaning code like `if (0) { return 0; }` doesn't throw a syntax error), I don't think there's any way to fix this short of writing a Javascript parser in Javascript. For example, consider the code: ``` while (1) {} return 0; ``` If the code is executed, it will hang because of the loop. If the code is not executed, no error will be thrown for the illegal return statement. Therefore, this is as good as Javascript can get for this challenge. Feel free to disqualify Javascript if you feel that this doesn't fulfill the challenge sufficiently. [Answer] # Haskell - 222 bytes Note that this uses a true parser. It does not depend on `eval` like functions of dynamic languages. ``` import Language.Haskell.Parser main=interact(\s->case parseModule s of ParseOk _->if take 89s=="import Language.Haskell.Parser\nmain=interact(\\s->case parseModule s of ParseOk _->if take"then"False"else"True";_->"False") ``` This solution is not particularly pretty but does work. [Answer] I think this follows the rules: **JS** (✖╭╮✖) `function f(s){if(s==f.toString())return false;try{eval(s)}catch(e){return false}return true}` The code will be evaluated if it's correct. Need to take a look at arrow notation to see if it can't be shortened more. `!function f(){try{s=prompt();return"!"+f+"()"!=s?eval(s):1}catch(e){return 0}}()` After a couple failed attempts and reverts - new version! `!function f(){try{s=prompt();"!"+f+"()"!=s?eval(s):o}catch(e){return 1}}()` And I'm back! `!function f(){try{s=prompt();"!"+f+"()"!=s?eval(s):o}catch(e){return !(e instanceof SyntaxError)}}()` And I'm gone! Unfortunately due to nature of eval and thanks to @scragar (damn you @scragar!) this approach will not work (seeing as `throw new SyntaxError` is valid JS code, which ticks this method of) - as such, I'd say it's impossible to create a syntax checker (at least using eval or any variation thereof) (\*see the comments!) [Answer] # Python (95) ``` c=raw_input() try:compile('"'if sum(map(ord,c))==7860 else c,'n','exec');print 1 except:print 0 ``` [Answer] # PHP - 140 ``` <?exec("echo ".escapeshellarg($argv[1])." | php -l",$A,$o);echo$o|(array_sum(array_map(ord,str_split($argv[1])))==77*150)?"false":"true";//Q ``` Comment necessary to keep the 'hash' (a shameless copy of s,ɐɔıʇǝɥʇuʎs). Using php -l / lint to check for errors. ``` $ php finky_syntax_check.php '<?php echo "good php code"; ?>' true $ php finky_syntax_check.php '<?php echo bad--php.code.; ?>' false $ php finky_syntax_check.php '<?exec("echo ".escapeshellarg($argv[1])." | php -l",$A,$o);echo$o|(array_sum(array_map(ord,str_split($argv[1])))==77*150)?"false":"true";//Q' false $ php finky_syntax_check.php '<?exec("echo ".escapeshellarg($argv[1])." | php -l",$A,$o);echo$o|(array_sum(array_map(ord,str_split($argv[1])))==77*150)?"false":"true";//D' true // note that the last character was changed ``` [Answer] ## C 174 Explanation -Wall needed to produce system error while still being compilable. The syntax error is no `return 0;` To enter via stdin in Windows console type Ctrl-Z after pasting and press enter. Golfed ``` char c[256];int i;int main(){FILE *f=fopen("a.c","w");while(fgets(c,256,stdin)!=NULL){fputs(c,f);}fclose(f);i=system("gcc a.c -o -Wall a.exe");printf("%s",i?"false":"true");} ``` Ungolfed: ``` #include <stdio.h> #include <stdlib.h> char c[256];int i; int main() { FILE *f=fopen("a.c","w"); while(fgets(c,256,stdin)!=NULL) { fputs(c,f); } fclose(f); i=system("gcc a.c -o -Wall a.exe"); printf("%s",i?"false":"true"); } ``` [Answer] **T-SQL - 110** Fairly simple, I've been wanting to try a challenge on here for a while, finally got round to doing it. This is not the fanciest code, but I had fun nontheless. The 'golfed' version. ``` BEGIN TRY DECLARE @ VARCHAR(MAX)='SET NOEXEC ON'+'//CODE GOES HERE//'EXEC(@)PRINT'TRUE'END TRY BEGIN CATCH PRINT'FALSE'END CATCH ``` A better formatted version. ``` BEGIN TRY DECLARE @SQL VARCHAR(MAX)='SET NOEXEC ON'+'//CODE GOES HERE//' EXEC(@SQL) PRINT'TRUE' END TRY BEGIN CATCH PRINT'FALSE' END CATCH ``` It's fairly self explanatory, it uses SET NOEXEC on which makes it just parse the query instead of returning any results. the rest is mostly the try/catch that I use to determine what I need to print. EDIT: I should have added that this will technically fail for itself. because it uses dynamic SQL any single quotes in the input have to be doubled ' -> '' ]
[Question] [ Write the shortest function that takes a two-dimensional square array representing the scores of a chess round, and outputs an array of the Neustadtl scores of the players. The two-dimensional array is structured so that `array[i][j]` is the score earned by the player i against player j. The Neustadtl score is used to tie-break in chess tournaments when their conventional scores tie. The Neustadtl score is calculated by adding the scores of the player defeated and half of the scores the player drew with. Here is an example data for a 5 on 5 match. ``` cs ns 1. X 1 ½ 1 0 | 2½ 4.25 2. 0 X 1 ½ 0 | 1½ 2.5 3. ½ 0 X ½ ½ | 1½ 3.5 4. 0 ½ ½ X 1 | 2 4 5. 1 1 ½ 0 X | 2½ 4.75 ``` where `cs` stands for conventional score and `ns` stands for Neustadtl score. For example, the Neustadtl score of the 4th player is: ``` 0(player 1's cs) + ½(player 2's cs) + ½(player 3's cs) + 1(player 5's cs) = 0(2½) + ½(1½) + ½(1½) + 1(2½) = 4 ``` For more details and another example data, see its [Wikipedia article](http://en.wikipedia.org/wiki/Neustadtl_score). Some notes: 1. Assume the diagonal is always zero (`array[j, j] = 0`) 2. No need to check if the array is square 3. No need to check if the data makes sense (a valid scoretable has the property `array[i, j] + array[j, i] = 1, i != j`) [Answer] ## Mathematica ~~11~~ ~~10~~ 8 ``` #.Tr/@#& ``` (Thanks @chyanog!) Usage ``` m = {{0, 1, .5, 1, 0}, {0, 0, 1, .5, 0}, {.5, 0, 0, .5, .5}, {0, .5, .5, 0, 1}, {1, 1, .5, 0, 0}} #.Tr/@#&[m] ``` Result {4.25, 2.5, 3.5, 4., 4.75} **Edit** Some explanations: > > `Tr` is "Trace". When applied to a one-dimensional list returns the elements sum > > `/@` is "Map". Feeds the preceding operator with one element at a time and returns a list > > `.` is "dot product". Multiplies vectors (or matrices and vectors) > > the set `# ... &` is a functional construct. The `&`feeds the `#`with its arguments > > > [Answer] ## APL ~~31 29~~ 24 or 10 or 7 If you will accept decimal input and output then the following takes your score array as screen input via ←⊃⎕ with each row of the array enclosed in parentheses. ``` ((m,'|'),+/m),m+.×+/m←⊃⎕ ``` Your example would look as follows: ``` Input: (0 1 0.5 1 0)(0 0 1 0.5 0)(0.5 0 0 0.5 0.5)(0 0.5 0.5 0 1)(1 1 0.5 0 0) Output: 0.0 1.0 0.5 1.0 0.0 | 2.5 4.25 0.0 0.0 1.0 0.5 0.0 | 1.5 2.50 0.5 0.0 0.0 0.5 0.5 | 1.5 3.50 0.0 0.5 0.5 0.0 1.0 | 2.0 4.00 1.0 1.0 0.5 0.0 0.0 | 2.5 4.75 ``` with the input displayed along with the separator and the two scores as the output. Or if you just want the Neustadtl score then: ``` m+.×+/m←⊃⎕ ``` If the input scores array exists as a global m then: ``` m←⊃(0 1 0.5 1 0)(0 0 1 0.5 0)(0.5 0 0 0.5 0.5)(0 0.5 0.5 0 1)(1 1 0.5 0 0) m+.×+/m 4.25 2.5 3.5 4 4.75 ``` Latest mods prompted by marinus. Thanks. [Answer] # K,13 ``` {+/'x*\:+/'x} ``` . ``` k)input:(0 1 0.5 1 0;0 0 1 0.5 0;0.5 0 0 0.5 0.5;0 0.5 0.5 0 1;1 1 0.5 0 0) k)input 0 1 0.5 1 0 0 0 1 0.5 0 0.5 0 0 0.5 0.5 0 0.5 0.5 0 1 1 1 0.5 0 0 k){+/'x*\:+/'x}[input] 4.25 2.5 3.5 4 4.75 ``` It's unclear whether you just want a 1-d array of Neustadtl scores or if you want the output that's in your example. If it's the latter then: # K, 23 ``` {x!,:'b,'+/'x*\:b:+/'x} ``` . ``` k){x!,:'b,'+/'x*\:b:+/'x}[input] 0 1 0.5 1 0 | 2.5 4.25 0 0 1 0.5 0 | 1.5 2.5 0.5 0 0 0.5 0.5| 1.5 3.5 0 0.5 0.5 0 1 | 2 4 1 1 0.5 0 0 | 2.5 4.75 ``` [Answer] ## R - 25 ``` function(x)x%*%rowSums(x) ``` --- ``` R> input <- matrix(c(0, 1, .5, 1, 0, 0, 0, 1, .5, 0, .5, 0, 0, .5, .5, 0, .5, .5, 0, 1, 1, 1, .5, 0, 0), nrow=5, byrow=TRUE) R> (function(x)x%*%rowSums(x))(input) [,1] [1,] 4.25 [2,] 2.50 [3,] 3.50 [4,] 4.00 [5,] 4.75 ``` [Answer] ## C# 106 (88 function body + 18 required `using` stetement) ``` float[]N(float[][]s){return s.Select(l=>l.Select((v,i)=>v*s[i].Sum()).Sum()).ToArray();} ``` This function requires the `using System.Linq;` directive to be present in the file, so I added that to the character count as well. IdeOne link: <http://ideone.com/cPcfwg> OK, I know it's not very short, but I love C# and LINQ so much that I just had to do it. :) Here's a more readable version of the code: ``` public float[] Neustadl(float[][] scoreTable) { return scoreTable.Select(scoreLine => scoreLine.Select((lineValue, otherPlayerIndex) => lineValue * scoreTable[otherPlayerIndex].Sum()) .Sum() ).ToArray(); } ``` [Answer] ## Ruby, 62 ``` N=->a{a.map{|l|z=0 l.zip(a.map{|l|eval l*?+}){|k,s|z+=k*s} z}} ``` ]
[Question] [ The [Feynman Challenge Cipher #1](http://www.ciphermysteries.com/feynman-ciphers) is as follows: ``` MEOTAIHSIBRTEWDGLGKNLANEAINOEEPEYST NPEUOOEHRONLTIROSDHEOTNPHGAAETOHSZO TTENTKEPADLYPHEODOWCFORRRNLCUEEEEOP GMRLHNNDFTOENEALKEHHEATTHNMESCNSHIR AETDAHLHEMTETRFSWEDOEOENEGFHETAEDGH RLNNGOAAEOCMTURRSLTDIDOREHNHEHNAYVT IERHEENECTRNVIOUOEHOTRNWSAYIFSNSHOE MRTRREUAUUHOHOOHCDCHTEEISEVRLSKLIHI IAPCHRHSIHPSNWTOIISISHHNWEMTIEYAFEL NRENLEERYIPHBEROTEVPHNTYATIERTIHEEA WTWVHTASETHHSDNGEIEAYNHHHNNHTW ``` The solution is [described as](http://web.archive.org/web/20041029025822/http://rec-puzzles.org/new/sol.pl/cryptology/Feynman): > > It is a simple transposition cipher: split the text into > 5-column pieces, then read from lower right upward. What results are the > opening lines of [Chaucer's Canterbury Tales in Middle English](http://home.vicnet.net.au/~umbidas/middle_english_of_chaucer.htm). > > > Which is: ``` WHANTHATAPRILLEWITHHISSHOURESSOOTET HEDROGHTEOFMARCHHATHPERCEDTOTHEROOT EANDBATHEDEVERYVEYNEINSWICHLICOUROF WHICHVERTUENGENDREDISTHEFLOURWHANZE PHIRUSEEKWITHHISSWEETEBREFTHINSPIRE DHATHINEVERYHOLTANDHEETHTHETENDRECR OPPESANDTHEYONGESONNEHATHINTHERAMHI SHALVECOURSYRONNEANDSMALEFOWELESMAK ENMELODYETHATSLEPENALTHENYGHTWITHOP ENYESOPRIKETHHEMNATUREINHIRCORAGEST HANNELONGENFOLKTOGOONONPILGRIM ``` ## The Challenge: Write a function to decrypt the cipher. The output does not need line breaks or spaces. Input is has no line breaks or spaces. Shortest solution wins. (Bonus points if you can solve the other 2 ciphers :P) --- ### My attempt (PHP ~~77~~ 70): ``` $b=strrev($a);for($i=0;$i<5;$i++)for($j=0;$j<381;$j++)$r.=$b[$i+$j*5]; ``` <http://codepad.org/PFj9tGb1> [Answer] ### Golfscript, 10 chars ``` n--1%5/zip ``` Takes input from stdin. It may be separated by newlines, as in the question presentation, or not, as many answers assume. (Stripping the newlines is necessary anyway given that it's likely to arrive with one on the end, which messes up the blocks of 5). If we assume that the input arrives with precisely one newline, being the last character, we can shave one character to ``` )!(%5/zip ``` [Answer] ### Mathematica, 51 Mathematica is quite verbose here, but it is also easy to guess what it's doing. ``` Thread[Characters@#~Partition~5]~Reverse~{1,2}<>""& ``` [Answer] ## [J](http://jsoftware.com/), 13 characters ``` |.@(/:5|i.@#) ``` [Answer] # Haskell, 52 ``` f s=[s!!(x-i)|x<-[length s],j<-[1..5],i<-[j,j+5..x]] ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) -P, ~~4~~ 3 bytes ``` Ôó5 ``` [Try it online!](https://tio.run/##FZAxbsRACEX7HGP7lDkA8XwPaMcwAuyR06VNlSJHyU1yhD2YM4uEhAT//ye@Pr9/ruvx@/h7u67bBksSDnn3xCi11bs2UpCoAR1npHbsZmA3bSluUXiKtHMlQhrHh2VC845OpZ19bouNZTV317bsmGW9bt5YtaxpmPbtDmZQJuuGWDRYfLoV4sbYEulrDBTD87qujCSUyt5Uq81cW7bc3aNlkWIOVp5N55ECZ0zRkq6H2D7JbY4j6JQ1ZpBh83THTvvOxma8lIUTkMDhLe5NWIT6wj7/wj10pImEBLOOCSc4aUVThzbAT@n8DrfE0VnzpCdCyoSgkePgpEAyR9EKAZ3K00c5x@3ltf8D "Japt – Try It Online") I feel like that was too easy? On a positive note, this can't possibly be golfed too much assuming I am getting the correct result :) **EDIT** -1 byte thanks to @Shaggy! ``` Ôó5 # full program Ô # reverse input string ó5 # create a 5-element array by repeatedly # picking every 5th character. # -P flag concatenates array on output! ``` [Answer] ## Python - 56 chars ``` s=raw_input() print"".join(s[-1-x::-5]for x in range(5)) ``` [Answer] ## Scala, 62 characters ``` print((for(x<-0 to 4;y<-379-x to 0 by -5)yield s(y)).mkString) ``` Making the assumption that the string is already in a variable `s` as hammar and stevether do. Taking the input from stdin is a bit uglier (92 chars): ``` var s=io.Source.stdin.mkString print((for(x<-0 to 4;y<-379-x to 0 by -5)yield s(y)).mkString) ``` and it only works if there are no newlines in the input. [Answer] ## [Perl](http://www.perl.org), 58 characters ``` perl -lne'$c[$c++%5].=$_ for split//}END{$"=$,,print$_=reverse"@c"' ``` [Answer] ### Scala 63 chars: ``` (1 to 5).map(n=>s.reverse.drop(n)).map(_.sliding(1,5).mkString) ``` Assuming the input is in s. [Answer] # K, 34 ``` {a::(5*!76)_x;1'{a[;x]@|!#a}@'|!5} ``` [Answer] # ECMAScript 6 - 48 Characters ``` for(c='',i=5;i--;)c+=(x=>s[x]?f(x+5)+s[x]:'')(i) ``` Assumes that the variable `s` contains the input string (without any white space characters) and creates the variable `c` containing the output. [Answer] # [Python 3.6](https://docs.python.org/3.6/), 48 bytes Recursion + f-Strings ``` f=lambda a:a and f'{a[::-5]+f(a[:-1])}'[:len(a)] ``` [Try it online!](https://tio.run/##TZJBa9xADIXv/RUml9iUHErJZSGHiefZGnYsDRrZxg17cEk3CSTb0OZSSn/7dkoLtUCgwyfpPaHXH2@PX08fzy/fH6qbqn5X/YuLAWIuUA63aph9H/s9R8dwgQVIWLJd/Kc5YRQBqXC0oJI9lX5O1DsHE8qfZEObgW2P5HxcUgG9zG0nqsqxHVFC0obuB43E7DsTlP1xDyI4M@IBueVMQTd0WecdRcJgMO3yDC/409h3BHPwPW1ojcy9FI3SDjaq5mg@eFEQU0m3TFuXAUooo1pTnoKMxbCUcs5uCV0uSgQbelBTxejGkYREqPUtGRAyJo15HwOF7WyXWtJyb0qZZ5MQcshEPBcjAYvrELf3VnAEdAmJbqFimBKxLa6waqGodBt6tnkicxlGlD33CHALU5nOZPNfsDkfb57Xl8/3a7XuSp7uq@Plz/Vut7u6Prw/1qW6@nBofl3e7Z6/nOq1OZxfvz2d3upjXX6nac6/AQ "Python 3 – Try It Online") ]
[Question] [ You are given a list of `(x,y)` grid coordinates. Your function should decide whether the figure obtained by coloring in the squares of the grid with the given coordinates is connected or not. Squares adjacent diagonally are not considered connected. Example input: ``` (0,0),(1,0),(2,0),(3,0),(3,1),(3,2),(2,2), (1,2),(0,2),(0,3),(0,4),(1,4),(2,4),(3,4) ``` which looks like: ``` **** * **** * **** ``` Output: ``` YES ``` Example input: ``` (0,0),(1,0),(2,0),(0,1),(0,2),(2,2),(3,2),(4,2),(0,3), (4,3),(0,4),(1,4),(2,4),(4,4),(4,5),(2,6),(3,6),(4,6) ``` which looks like: ``` *** * *** * * * * *** * *** ``` Output: ``` NO ``` Your function must take as input a list of pairs of integers (e.g. in C++, maybe vector<pair<int,int>>) and return a boolean. You may not assume any particular ordering of the input points. The coordinates will be between 0 and 99 inclusive. Smallest code wins. [Answer] c99 -- 620ish neccessary characters ``` #include <stdlib.h> #define S return typedef struct n N;struct n{int x,y;N*n;}; N*I(int x,int y,N*l){if(!l)goto z;N*m=l;do{if((m->x==x)&&(m->y==y)) S m;m=m->n;}while(m!=l);z:S NULL;}N*A(N*n,N*l){if(!l)n->n=n,l=n; else n->n=l->n,l->n=n;S l;}N*R(N*n,N*l){if(!l||(l==n&&n->n==n))goto z; N*m=l;do{if(m->n==n){m->n=n->n;S m;}m=m->n;}while(m!=l);z:S NULL;} int E(N*l){int i=0;if(!l)goto z;N*m=l;do{++i;m=m->n;}while(m!=l);z:S i;} int C(N*l){N*c=NULL,*n=l,*m=l=R(n,l);c=A(n,c);int a=E(l)*E(l);do{ if(!l)S 1;n=m->n;if(I(m->x-1,m->y,c)||I(m->x+1,m->y,c)||I(m->x,m->y-1,c) ||I(m->x,m->y+1,c))l=R(m,l),c=A(m,c);m=n;}while(--a);S 0;} ``` More than half the bulk is taken up by a minimal implementation of a linked list---c is horribly deficient in that sense. The code here includes the definition of the nodes and all the list manipulation functions called by `C`, my connectedness checker. The method is to maintain two lists (one of connected nodes initialized by the first node) and one of yet-to-be-connected nodes (starting with everything else). What follows is an exhaustive cyclic search to find a connection for each node in turn. There is an upper limit on the number of attempts conservatively set to length-of-the-list squared, which marks the end of attempts. Very inefficient, but functional. It completes several simple cases of my own devising and both of the given test cases correctly. **Full program with test scaffold and some comments** ``` #include <stdio.h> #include <stdlib.h> typedef struct n N; struct n{ int x,y; N*n; }; N*I(int x,int y,N*l){ /* Return pointer to node x,y in l or NULL */ if(!l)goto z; N*m=l; do{ if((m->x==x)&&(m->y==y)){ return m; } m=m->n; }while(m!=l); z:return NULL; }; N*A(N*n,N*l){ /* Add node n to list l. Return the new l */ if(!l){ n->n=n; l=n; }else{ n->n=l->n; l->n=n; } return l; }; N*R(N*n,N*l){ /* Remove node n from list l. Return the new l */ if(!l||(l==n&&n->n==n))goto z; N*m=l; do{ if(m->n==n){m->n=n->n; return m;} m=m->n; }while(m!=l); z:return NULL; } int E(N*l){ /* Return the Enumberation of nodes in list l */ int i=0; if(!l)goto z; N*m=l; do{++i;m=m->n;}while(m!=l); z:return i; } int C(N*l){ /* return true if all nodes in list l are connected */ N*c=NULL,*n=l,*m=l=R(n,l); /* put the first node in the connected list, and mark the start of the working list */ c=A(n,c); int a=E(l)*E(l); /* maximum number of times to try to place nodes */ do { if (!l) return 1; /* when l is empty: we win! */ n=m->n; if ( I(m->x-1,m->y ,c) || I(m->x+1,m->y ,c) || I(m->x ,m->y-1,c) || I(m->x ,m->y+1,c) ) l=R(m,l), c=A(m,c); m=n; } while (--a); return 0; } void P(N*l){ /* Print the list */ printf("List: ["); if(!l)goto z; N*m=l; do{printf(" (%d, %d)",m->x,m->y);m=m->n;}while(m!=l); z:printf(" ]\n"); } N*G(int x,int y){ /* generate a new node with (x, y) */ N*n; if(n=malloc(sizeof(N)))n->x=x,n->y=y; return n; } int main(){ N*n,*l=NULL; n=G(0,0); l=A(n,l); n=G(1,0); l=A(n,l); n=G(2,0); l=A(n,l); n=G(0,1); l=A(n,l); n=G(0,2); l=A(n,l); n=G(2,2); l=A(n,l); n=G(3,2); l=A(n,l); n=G(4,2); l=A(n,l); n=G(0,3); l=A(n,l); n=G(4,3); l=A(n,l); n=G(0,4); l=A(n,l); n=G(1,4); l=A(n,l); n=G(2,4); l=A(n,l); n=G(4,4); l=A(n,l); n=G(4,5); l=A(n,l); n=G(2,6); l=A(n,l); n=G(3,6); l=A(n,l); n=G(4,6); l=A(n,l); P(l); if (C(l)) { printf("Connected!\n"); } else { printf("Not connected.\n"); }; } ``` [Answer] # Ruby - 82 ``` c=->s{(a=->x,y{a[x,y-1]&a[x+1,y]&a[x,y+1]&a[x-1,y]if s.delete [x,y];s})[*s[0]][0]} ``` Ungolfed: ``` def c(s) a=->x,y{ if s.delete([x,y]) a[x,y-1] a[x+1,y] a[x,y+1] a[x-1,y] end } x,y=s.first a[x,y] s.size != 0 end ``` Usage: ``` print s([ [0,0],[2,0],[3,0],[3,1],[3,2],[2,2],[1,2], [0,2],[0,3],[0,4],[1,4],[2,4],[3,4] ]) ? "NO" : "YES" ``` [Answer] ## Prolog - 118 ``` c([_]). c([[X,Y]|L]):-member([A,B],[[X+1,Y],[X-1,Y],[X,Y+1],[X,Y-1]]),C is A,D is B,select([C,D],L,N),c([[C,D]|N]),!. ``` Usage: ``` ?- c([[0,0],[1,0],[2,0],[3,0],[3,1],[3,2],[2,2],[1,2],[0,2],[0,3],[0,4],[1,4],[2,4],[3,4]]). true. ?- c([[0,0],[1,0],[2,0],[0,1],[0,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[4,4],[4,5],[2,6],[3,6],[4,6]]). false. ``` [Answer] My first python version (loosely) translated into golfscript. Urgh. 80 chars. ``` {1$!!1$!!&{(~:v;:u;[1u+v u 1v+u 1- v u v 1-]2/@.@&.@\-\@|g}{;!}if}:g;{([.;]g}:f; ``` test cases: ``` # test cases [[0 0] [1 0] [2 0] [3 0] [3 1] [3 2] [2 2] [1 2] [0 2] [0 3] [0 4] [1 4] [2 4] [3 4]]:a0; [[0 0] [1 0] [2 0] [0 1] [0 2] [2 2] [3 2] [4 2] [0 3] [4 3] [0 4] [1 4] [2 4] [4 4] [4 5] [2 6] [3 6] [4 6]]:a1; a0 f p a1 f p ``` python 2.6; second attempt ``` def f(a): a = set(a) e = lambda (x, y) : set([(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]) p = lambda k : a.discard(k) or map(p, e(k) & a) p(a.pop()) return not a ``` python 2.6; first attempt ``` def f(a): a = set(a) e = lambda (x, y) : set([(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]) b = set([a.pop()]) while b and a: c = a & e(b.pop()) a -= c b |= c return not a ``` usage: ``` a_0 = [ (0,0),(1,0),(2,0),(3,0),(3,1),(3,2),(2,2), (1,2),(0,2),(0,3),(0,4),(1,4),(2,4),(3,4) ] a_1 = [ (0,0),(1,0),(2,0),(0,1),(0,2),(2,2),(3,2),(4,2),(0,3), (4,3),(0,4),(1,4),(2,4),(4,4),(4,5),(2,6),(3,6),(4,6) ] for a in (a_0, a_1): print 'YES' if f(a) else 'NO' ``` [Answer] ## Perl, 130 ~~133~~ A simple mark-and-sweep depth-first traversal, made much longer than I'd like by Perl sigils. ``` sub g{my($a,$b)=@_;g($a-1,$b),g( $a+1,$b),g($a,$b-1),g($a,$b+1)if delete$m{$a,$b}}sub f{($a,$b)=@_; $m{pop,pop}++while@_;g$a,$b;!%m} ``` Sample use: ``` say f( (0,0),(1,0),(2,0),(3,0),(3,1),(3,2),(2,2), (1,2),(0,2),(0,3),(0,4),(1,4),(2,4),(3,4) ) ? 'YES' : 'NO'; say f( (0,0),(1,0),(2,0),(0,1),(0,2),(2,2),(3,2),(4,2),(0,3), (4,3),(0,4),(1,4),(2,4),(4,4),(4,5),(2,6),(3,6),(4,6) ) ? 'YES' : 'NO'; ``` [Answer] # Perl - 150 ``` sub f{$m[pop][pop]++while@_;for$i(0..@m){for$j(0..9){$_.=$m[$i][$j]||0}$_.="3"}s/1/2/;for$n(0..99){s/(?<=2)1|1(?=2)|1(?=.{10}2)|(?<=2.{10})1/2/}!m/1/} ``` Works for 10 columns. For more I'd need another character. Expands the color of one square a lot of times with one regex. Building the string takes a lot more space than I'd like it to. Ungolfed: ``` sub f{ $m[pop][pop]++ while @_; for $i (0..@m) { for $j (0..9) { $_ .= $m[$i][$j] || 0 } $_ .= "3"; } s/1/2/; for$n(0..99) { s/(?<=2)1|1(?=2)|1(?=.{10}2)|(?<=2.{10})1/2/ } !m/1/ } print f((0,0),(1,0),(2,0),(3,0),(3,1),(3,2),(2,2), (1,2),(0,2),(0,3),(0,4),(1,4),(2,4),(3,4)) ? YES : NO; ``` [Answer] ## Haskell 98, 98 ``` g p@(x,y)z|elem p z=foldr g(filter(/=p)z)[(x-1,y),(x+1,y),(x,y-1),(x,y+1)]|0<1=z f z=null$g(z!!0)z ``` Sample use: ``` *Main> f [(0,0),(1,0),(2,0),(3,0),(3,1),(3,2),(2,2), (1,2),(0,2),(0,3),(0,4),(1,4),(2,4),(3,4)] True *Main> f [(0,0),(1,0),(2,0),(0,1),(0,2),(2,2),(3,2),(4,2),(0,3), (4,3),(0,4),(1,4),(2,4),(4,4),(4,5),(2,6),(3,6),(4,6)] False ``` [Answer] **Sage: 55 53 char** ``` graphs.GridGraph([100]*2).subgraph(x).is_connected() ``` Where x is a list of coordinates, ``` x=[(0,0),(1,0),(2,0),(3,0),(3,1),(3,2),(2,2),(1,2),(0,2),(0,3),(0,4),(1,4),(2,4),(3,4)] ``` ]
[Question] [ Consider the following binary matrix: $$\begin{matrix} 1 & 0 & 1 \\ 1 & 0 & 0 \\ 0 & 1 & 1 \end{matrix}$$ The (1-indexed) co-ordinates of the \$1\$s here are \$(1,1), (1,3), (2,1), (3, 2), (3, 3)\$. We can also notice that there are three "shapes" of \$1\$s in the matrix, made of orthogonally connected \$1\$s: $$\begin{matrix} \color{red}{1} & 0 & \color{cyan}{1} \\ \color{red}{1} & 0 & 0 \\ 0 & \color{blue}{1} & \color{blue}{1} \end{matrix}$$ We can then group the coordinates into those shapes: \$((1, 1), (2, 1)), ((3, 2), (3, 3)), ((1,3))\$. Given a non-empty list of coordinates, group them into the shapes that can be found in the binary matrix represented by those coordinates. You may take the input as any reasonable format for a list of pairs, including complex numbers. You may also choose to use 0 or 1 indexing. You may also instead choose to take the binary matrix as input, rather than the coordinates. In this case, the output should still be the groups. The output may be any format where the groups (lists of pairs) are clearly recognisable, as are the pairs themselves. One example may be newline delimited lists of complex numbers. You may also output the groups as lists of indices (0 or 1 indexed, your choice) from the original input (so the example would be `[[1,3], [4,5], [2]]`) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ## Test cases I've used `(a, b)` for the output to try to show some distinction ``` input -> output lines [[1, 2], [2, 1], [2, 3], [3, 2]] -> [(1, 2)] [(2, 1)] [(2, 3)] [(3, 2)] [[1, 1], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [3, 3]] -> [(1, 1), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (3, 3)] [[1, 1], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [3, 3]] -> [(1, 1), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (3, 3)] [[1, 3], [1, 4], [3, 1], [3, 2], [5, 2]] -> [(1, 3), (1, 4)] [(3, 1), (3, 2)] [(5, 2)] [[1, 3], [3, 1], [3, 2], [4, 2], [5, 2], [5, 3]] -> [(1, 3)] [(3, 1), (3, 2), (4, 2), (5, 2), (5, 3)] [[2, 2]] -> [(2, 2)] [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 4], [3, 1], [4, 1], [4, 3], [4, 4], [4, 5], [5, 1], [5, 4], [5, 5], [6, 4], [6, 5]] -> [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 4)] [(3, 1), (4, 1), (5, 1)] [(4, 3), (4, 4), (4, 5), (5, 4), (5, 5), (6, 4), (6, 5)] [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 1], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5], [4, 5], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5], [5, 6]] -> [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6)] [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 5], [3, 1], [3, 4], [4, 1], [4, 2], [4, 4], [4, 5], [4, 6], [5, 1], [5, 4], [5, 5], [6, 1], [6, 4], [6, 5]] -> [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 5)] [(3, 1), (4, 1), (4, 2), (5, 1), (6, 1)] [(3, 4), (4, 4), (4, 5), (4, 6), (5, 4), (5, 5), (6, 4), (6, 5)] ``` And [this](https://tio.run/##y0rNyan8/5/r6KSHO1dxGRWZHtqqEKHwcOdsy4hDSw/vA7JVjR/u7jq0BqIArG6Nu2bWo8Z9h7Yd2vb///9oruhoQx0Fo1gdhWgjHQVDKG0Moo1B4rE6XBAlYClDqBQWpYZwLRDaGFOrEflGGEO1mmBTaoriUKymmSArhdAw042wehPFrTCLgbQp1M0oDjFB0MZQ2gRKm0JtM4TSJlAaLG4G5ZuB@CQ7wRBnsEFomBNNcTgFERBYnAakzUh3kimak0zQQscIW@iYgKzCH0qG2EIrFgA) is a visualisation of the matrices themselves [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 bytes Full program. Takes input as list of complex numbers. Returns list of lists of indices into the input. ``` ⍸¨↓∪∨.∧⍣≡⍨1≥|∘.-⍨⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT//v/6htQvWjvqlACkh6Bfv7PerdVcsFZAe7AonwYHXXstS8EnUN9eDU4uLM/LyAokwgV0HdX12T61FHe8H/R707Dq141Db5UceqRx0r9B51LH/Uu/hR58JHvSsMH3UurXnUMUNPF8gBmvYfqIHLE2xj7y5tAy/Dw9Mf9W6t1T@0Amr3fwUwKODyVFCPjjbUUTCK1VGINtJRMITSxiDaGCQeq84FVwxRC1ZjCFWDRY8hXC@ENsZjhhEVzDKGmmGCTY8pdj9gNd8EWQ@ExrDPCH@YoPgH5iYgbQr1F4obTRC0MZQ2gdKmUPsNobQJlAaLm0H5ZiA@@W4xxBnGEBrmVlMcbkKEERY3AmkzCtxmiuY2E7TwMsIWXiYgO/GHmyGW8AMA "APL (Dyalog Unicode) – Try It Online") `⎕` prompt for evaluated input via stdin `∘.-⍨` differences between all pairs of indices `|` absolute value `1≥` Boolean matrix indicating where no more than 1 (points have 0 distance from themselves) `∨.∧⍣≡⍨` transitive closure `∪` unique rows `↓` split into list of lists `⍸¨` indices where true in each [Answer] # [J](http://jsoftware.com/), 24 bytes ``` </.~[:+./ .*^:_~1>:|@-/~ ``` [Try it online!](https://tio.run/##bZI9T8QwDIb3/gqLpRT6gWO7QwUnJCQmJtaq3IDuBF1YGBhQ/3pxGrdN6Q2vnjiOXydu@/GqTM/w0EAKOdxBoypKeHp9eR7vq3Jom9uygvLmrTkOeGh@H4tqGLPk9P7xBWfA3oHrUUVAvVu3UUVRCn1aResRUvGSkrh6reCQUi2V7n8ft5hhL5oOpjyJVKwSdUAVqwRqZd1Lcvr5/E7TpG0xB9fl0Loc0Eie5Pc7KA5Je@3PZJ0u/KF5QdOCQioYTQZoBhcMcTEOpKgBZjl4kqez2FlMFk/dAmnpStaVL3WR7TPIuvB8@dXWb0j8mou35tg3kDb@O18lG2Ul7Ybm4uHNz1GKDXHzPF5JRjaKXQuNbJz2a4trH@@H7@KPMI0pUOxjbMfGRpn/CrZKtkq2SrFYLK4t9rfIuvEP "J – Try It Online") Very similar approach to Adam's APL answer, though arrived at independently. Input as complex numbers: * `|@-/~` Table of absolute differences. * `1>:` Is it elementwise less than or equal to 1? Returns a 0-1 matrix representing direct neighbors. * `[:+./ .*^:_` Do a matrix multiply replacing sum with boolean OR until a fixed point. The rows now represent connected groups. * `</.~` Use those groups to group the original input. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ạþ`Ịæ*LṠĠ ``` [Try it online!](https://tio.run/##y0rNyan8///hroWH9yU83N11eJmWz8OdC44s@H@47eHu7sPtj5rWHJ30cOcMIB35/380V3S0oY6CUayOQrSRjoIhlDYG0cYg8VgdiAqwjCFUBotKQ7gOCG2ModOIbBOMoTpNsKk0RXYlVrNMkFVCaKjZRth8iOJOmK1A2hTqXhRXmCBoYyhtAqVNoXYZQmkTKA0WN4PyzUB8Ul1giDPEIDTMhaY4XIIIBSwuA9JmJLvIFM1FJmhhY4QtbExANuEPI0NsYRULAA "Jelly – Try It Online") ### How it works ``` ạþ`Ịæ*LṠĠ Monadic link. Input: list of coordinates in complex ạþ` Table of absolute differences Ị <= 1 æ*L Raise the matrix to the power equal to length Ṡ Sign (mat[i][j] == 1 if a path exists between i and j) Ġ Group indices by identical rows of the matrix ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 61 bytes ``` Xor@@List/@#//.a_⊻b_/;Min@DistanceMatrix[a,b]==1:>a~Join~b& ``` [Try it online!](https://tio.run/##rZPRatswFIbv/RTGG2MFtUGWlIsZBw0aWMcC3bqLgjBF8ZxW4NrGUSBQ2gfYK/Vt@iKZZB03duKstDQ33zmydM7Rrz@3Ut9kt1KrVG4W8eayrDn/oZZ6xD@MRify6unv4/xqFM1UwU/NsizSbCZ1rdZConkSx/jLRD58L1XxMP@0@blSmeanpfDuFCrv41wVWeQp3/zi3@V0XdXZcqnKgl@YCsX1r6zKZZoJhQIRHE8C21cESeRN05tSKBOY/atc@7G/4CryzhbiWyb/cLcax7E9gM5NKY1msuJNlMDnyGtSXnrozs6BXM/pWtcy1eLjRVqrSp8V1Uq7LyjwPDPF1zxHgX88gTi5TzZCYOSHCfJFiHwMJJbErid2t/hs9xwlJrCb2oA0AXGfvKZQUwBDgYGC@LmwI@k0wEfItySWIeQh5ATyppsj2esavkP38M1TEOhOh7qxvpgEutBWwm1Zu8C6mg5OT7t1HUmv/l5dQwpkW8L4YWe8cOhBe9K2lzRkIHHv0nRLAqRABsNiIAU262PIxzZ/4Wka8RwZPFFfTApkrWMpnKRwksJJBjmDfAy5neLVOuCDVnNsdWIH9Ng@5oA@huM36IIPWteRAtmOKnjPKwNq2ZlerRLbUYnuuCYccg21t/@/e/A7uIgNuqjz18FgDtxupEOustO@7K5/ "Wolfram Language (Mathematica) – Try It Online") Returns an `Xor` of coordinate lists, unless there is only one group, in which case just a single coordinate lists is returned (since `Xor[something]==something`). Repeatedly concatenates adjacent groups. Runtime balloons quickly. ### Also 61 bytes ``` Thread[Sign@MatrixExp@Ramp[1.1-DistanceMatrix@#]->#]~Merge~D& ``` [Try it online!](https://tio.run/##rZNfS@swGMbv@ylKlcMRMiX/djM2KmwXwhE8zrvQi1DjFtja0kUYiH71mTRvXbtliuJufnnb5HnfPnm2lmap1tLoXO6exruHZa3ko5jrRZHeSlPr7WxbpfdyXQl8iQdTvTGyyJV/lZ5lg8lZ9nar6oV6m/7Z/X/WyqTTUkQvGpWv45Uu1CjSsf2NH0qrVKvNRpdFOrfHi8W9qlYyV0KjRCSDSfLPqoskG0WzfFmmehTd2V3mKn36WKdlhF6cKvIKs62pZW7E@TyvdWVuiurZ@DcoiSKreb1aoSQeTGCdvWY7ITCKSYZiQVCMgdSRuueZ2y3@uj0XmV24Te2CNgvqX0WNUCOAQSAgiD@EPWmnAb5AsSN1JFATqCnUTTdPetSV/EJ38uMpKHRnoW68byaFLqy1cC/rHvCup8HpWVfXk/b0j3QtGZDvCeOTzngkdKE9a9uPtORgce@j2Z4UyIAchsVABmyeD6EeuvqLq2nM8@RwRX0zGZC3iWVwksFJBic51BzqIdRuim/7gE9GzbP1iZ/wY3@ZAX8shz/wBZ@MricD8gNX8FFWAm65mb7tEj9wiR2khoRSw9zXf54e/Asp4sEUdf46GMKB240slCo37dfpegc "Wolfram Language (Mathematica) – Try It Online") Returns an association with coordinate lists as its values. Same approach as several other answers: build an adjacency matrix by zeroing entries of a distance matrix that are greater than 1, take the closure, group. --- Alternate approach with a built-in that performs most of the task: **63 bytes** ``` ConnectedComponents@Subgraph[##&@@Table[#->#+I^i,{i,4}]&/@#,#]& ``` [Try it online!](https://tio.run/##rZPNauMwFIX3fgpjlzBllCn6yyYkeOhkEZjFMOlOuOC6aiNwLOOoUAh59oxlXTd2okxpaTafriyfe310ssnMWm4yo/Ls8DQ73OqylLmRj7d6U@lSlmabrF4enuusWos4HiXJXfZQSBGP5/H35b1CO4XYPh3dJDGK09HhlxZBs6X3s0KVchqosPnN7vTitarldqt0maxMrcrnv7IqslwKhSIRjefRb7U1Ikp/7DBa7qfBIl/rRE2DP81Zc5M8va0THaCd1UZOZ/Fq6iw34mqV16oyy7J6Me4JioKgUf5ZFCgKx3NYp/v0IARGIUlRKAgKMZBaUruf2tPimz1znTYLe6hb0HZB3aOgFWoFMAh4BPGbsCPtNcDXKLSklgRqAjWFuu3mSM@6ki/oTj49BYXuzNeND82k0IV1Fh5l7Qbve@qdnvV1HelA/0y3IQPyI2F80huP@C50YG33kQ05WDz4aHYkBTIgh2ExkAHb/QnUE1u/czWteY4crmhoJgPyLrEM3mTwJoM3OdQc6gnUdooP@4AvRs2x84lf8ON4mR5/Gk4@4Qu@GF1HBuQnruCzrHjcsjN92CV@4hI7SQ3xpYbZr/9/evAXpIh7U9T762AIB@4OMl@q7LTvp@sf "Wolfram Language (Mathematica) – Try It Online") Input a list of complex numbers. Returns a list of complex number lists. With `ConnectedComponents`, all that remains is building the adjacency graph. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~91~~ 81 bytes ``` ≔E²⊕⌈Eθ§λιηE§η¹⭆§η⁰℅¬№θ⟦λι⟧≔²ζF⊟ηFΣη«Jκι¿¬℅KK«¤℅ζ≦⊕ζ»»F…²ζ⊞υ⌕AKA℅ι⎚IEυEι⟦﹪λΣη÷λΣη ``` [Try it online!](https://tio.run/##XVGxboMwEJ3hKzwekisBKxOiipRIaVHTDTFY4IAVY1NjoihVvp2eTdqm9XD2@c7vvXtuemYazeSy5NMkOgV7NkJKyVY1hg9cWd7i1UUM8@BLH5TkdqtafgFJiYjcoqSPsrA0Qlnf893QU5Jg8WCx0v0rxFgokJs1lht40RYKPeN7xK8ccO2REfYuCyVdMTtqQ6DUI/RRRHxyQGEu@QyD3TyM7xpOTlcWBuJIPPCraYViEkrOT@BAXW@wEVLCr4Kr4woCVHknfDBgpQ5u4W3lf2Oq46uiiJTz1MNMyUaoNpcri9v/zCf8KIXkzMCPVQWbVr/wtdsEjr7X7Sy1s/Y@l/sJ@yzOouUPt96dbFmqqoppXFOMKcbEn1Oa@JjWdb08neUX "Charcoal – Try It Online") Link is to verbose version of code. Output is a triple-spaced list of double-spaced list of pairs of coordinates, each on their own line. Explanation: ``` ≔E²⊕⌈Eθ§λιη ``` Find the size of the matrix. ``` E§η¹⭆§η⁰℅¬№θ⟦λι⟧ ``` Create an area of that size on the canvas with holes at all of the points provided. ``` ≔²ζ ``` Start tracking the next shape. ``` F⊟ηFΣη« ``` Loop through the matrix. ``` Jκι¿¬℅KK« ``` If there is a hole at this position, then... ``` ¤℅ζ≦⊕ζ»» ``` ... fill it in and increment the shape tracker. ``` F…²ζ ``` Loop through the found shapes. ``` ⊞υ⌕AKA℅ι ``` Get the flattened list of coordinates of each shape. ``` ⎚IEυEι⟦﹪λΣη÷λΣη ``` Clear the canvas and convert the coordinates back to pairs. [Answer] # JavaScript, 103 bytes ``` a=>new Set(a.map(p=>a[r=a.reduce(b=>a.filter(q=>b.some(([x,y])=>(x-=q[0])*x+(y-=q[1])*y<2)),[p])]??=r)) ``` ``` f= a=>new Set(a.map(p=>a[r=a.reduce(b=>a.filter(q=>b.some(([x,y])=>(x-=q[0])*x+(y-=q[1])*y<2)),[p])]??=r)) console.log(JSON.stringify([...f([[1, 2], [2, 1], [2, 3], [3, 2]])])); console.log(JSON.stringify([...f([[1, 1], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [3, 3]])])); console.log(JSON.stringify([...f([[1, 1], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [3, 3]])])); console.log(JSON.stringify([...f([[1, 3], [1, 4], [3, 1], [3, 2], [5, 2]])])); console.log(JSON.stringify([...f([[1, 3], [3, 1], [3, 2], [4, 2], [5, 2], [5, 3]])])); console.log(JSON.stringify([...f([[2, 2]])])); console.log(JSON.stringify([...f([[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 4], [3, 1], [4, 1], [4, 3], [4, 4], [4, 5], [5, 1], [5, 4], [5, 5], [6, 4], [6, 5]])])); console.log(JSON.stringify([...f([[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 1], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5], [4, 5], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5], [5, 6]])])); console.log(JSON.stringify([...f([[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 5], [3, 1], [3, 4], [4, 1], [4, 2], [4, 4], [4, 5], [4, 6], [5, 1], [5, 4], [5, 5], [6, 1], [6, 4], [6, 5]])])); ``` Input `Array<[number, number]>`. Output `Set<Array<[number, number]>>`. 18 bytes are used to remove duplicate groups, maybe someone may find out a better way to golf it down. --- # [Python 2](https://docs.python.org/2/), 100 bytes ``` lambda a:set(tuple(reduce(lambda b,_:[P for P in a if any(abs(P-Q)<=1for Q in b)],a,[p]))for p in a) ``` [Try it online!](https://tio.run/##nVDLDoIwELz7FT22AQ/bBwej/4BnNKYoRAxig3Dg67FdUbHiQS@TZmd2Z6ama46Xivf5atOX@pweNNGLa9bQpjVlRuvs0O4zOjBpuFskMckvNYlJURFNipzoqqM6vdJ4vmbLFThy7ciUbUMdJmbLmJsZXGC9qYuqoTlNIOCnkPAAEIVFYSdWPRtJHAlIvgthkDsU00v8n1WBS9ITqs9g/i35FDr07vJvxV4Z76YQKEz6CiAHFIgSUaEHIEpEN4nwHdn3T1Yw8SkO7xHUh@Gj4Lu5CqLfbNXIVo56cq@ntIen24Lfub8B "Python 2 – Try It Online") Input `List[complex]`. Output `Set[Tuple[complex, ...]]`. Try to port above JavaScript codes to Python results 100 bytes. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/208906/edit). Closed 3 years ago. The community reviewed whether to reopen this question 6 months ago and left it closed: > > Original close reason(s) were not resolved > > > [Improve this question](/posts/208906/edit) There are two types of people in this world: users and admins. Let's find out who the real admins are. The task is simple: If the script is run with elevation, print 'True' and only 'True' (only trailing newlines permitted as extra). If the script is run as an unelevated user, print 'False' and only 'False', exceptions granted for trailing new lines. The code can be run on any operating system which is currently available free of charge, or on any CPU architecture as a code insertion OR it can run on Windows 10. The selected operating system must have at least 3 privilege levels, and should return 'True' for any execution of code above the default user privilege level. I couldn't find any tags for this, so please if you have suggestions, name them. Good luck! [Answer] # [Python 3](https://docs.python.org/3/), 32 bytes -13 bytes thanks to @Arnauld -1 byte thanks to @Dingus ``` import os print(os.getuid()<1e3) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRCG/mKugKDOvRCO/WC89taQ0M0VD08bQwMBA8/9/AA "Python 3 – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~39~~ ~~31~~ 27 bytes Saved 4 bytes thanks to [Gilles 'SO- stop being evil'](https://codegolf.stackexchange.com/users/994/gilles-so-stop-being-evil)!!! ``` a=False >/a&&a=True echo $a ``` [Try it online!](https://tio.run/##S0oszvj/P9HWLTGnOJXLTj9RTS3RNqSoNJUrNTkjX0El8f9/AA "Bash – Try It Online") Works on any \*nix system. **Explanation** ``` a=False # set env variable a to False >/a # try to create (>) (or overwrite if it exists) file /a # but directory / has root write privileges # and if /a is created by root in a # previous run the file will have root only # write privileges &&a=True # if this succeeds set a to True # if this fails a will be left as is echo $a # will be True for root and False otherwise ``` [Answer] ## Batch, 32 bytes ``` fltmc>nul&&echo True||echo False ``` Taken from [this](https://stackoverflow.com/a/28268802/182705) Stack Overflow answer. ]
[Question] [ **This question already has answers here**: [Creating a HQ9+ interpreter](/questions/12956/creating-a-hq9-interpreter) (18 answers) Closed 7 years ago. Your task is "simple" should you choose to accept it. Write an HQ9+ compiler in a language of your choice. HQ9+ has four commands (as you may be able to tell) H prints "Hello, World!" Q prints out the source code (this can either be the compiled source or HQ9+ source for the purpose of this challenge),9 prints out the lyrics to 99 bottles of beer on the wall, and + is essentially a noop. Your submission should be written in some language X, and should take input of HQ9+ source and output a program in X. Wait, I know what you're thinking. This is not a duplicate of [Creating a HQ9+ interpreter](https://codegolf.stackexchange.com/questions/12956/creating-a-hq9-interpreter) as it should not run HQ9+ code, but rather compile it. It should output a fully functional program. --- Rules 1. Language X should satisfy the traditional definition of a language 2. Standard loopholes disallowed 3. This is code golf (shortest program in bytes wins) 4. Your solution must be testable 5. X cannot be HQ9+ or an extension of HQ9+ --- Clarifications There has been some confusion as to what the q command should do. I had originally thought that it would output the compiled code (i.e code in langauge X), but my reference implementation outputs the hq9+ code. I would like to see either one depending on your golfing preferences. [Answer] ## Actually, 17 bytes ``` "HQ9"∩εj'N'9(t'.j ``` [Try it online!](http://actually.tryitonline.net/#code=IkhROSLiiKnOtWonTic5KHQnLmo&input=IjlIOCI) This program compiles HQ9+ to Actually. Actually is (almost) a superset of HQ9+ - the only difference is that the `9` command in HQ9+ is `N` in Actually. Because `+` is a NOP in HQ9+ (the accumulator is never actually used or displayed, and thus many implementations treat it as a NOP), it is stripped out. Explanation: ``` "HQ9"∩εj'N'9(t'.j "HQ9"∩εj strip all characters not in "HQ9", preserving order 'N'9(t replace all occurrences of "9" with "N" '.j insert a "." between every pair of characters ``` -1 byte from Christian Irwin [Answer] # Java only 551 bytes Joined in on the fun! This is a java compiler which compilers HQ9+ to java.Java is not verbose at all. Some code shamelssly stolen borrowed from ["99 Bottles of Beer"](https://codegolf.stackexchange.com/questions/64198/99-bottles-of-beer?rq=1). --- ``` public class a{public static void main(String[]a){System.out.printf("public class a{public static void main(String[]z){String p=\"%s\";for(char a:p.toCharArray()){if(a=='H')p(\"Hello, World\\n\");if(a=='Q')p(p);if(a=='9'){String b=\" of beer\",c=\" on the wall\",n=\".\\n\",s;for(int i=100;i-->1;){s=\" bottle\"+(i>1?\"s\":\"\");p(i+s+b+c+\", \"+i+s+b+n+(i<2?\"Go to the store and buy some more, 99\":\"Take one down and pass it around, \"+(i-1))+\" bottle\"+(i!=2?\"s\":\"\")+b+c+n);}}}}public static void p(String s){System.out.print(s);}}",a[0]);}} ``` [Answer] # Mathematica, 453 bytes ``` "("<>#~StringReplace~{"H"->"Print[\"Hello, world!\"]; ","Q"->"Print[ToString[#0, InputForm]]; ","9"->"a = StringJoin[ToString[#1], {\" bottle\", If[#1 < 2, \"\", \"s\"], \" of beer\"}] & ; b = StringJoin[a[#1], \" on the wall\"] & ; Do[Print[b[i], \", \", a[i], c = \".\n\", If[i < 2, StringJoin[\"Go to the store and buy some more, \", b[99], \".\"], StringJoin[\"Take one down and pass it around, \", b[i - 1], c]]], {i, 99, 1, -1}]; ",_->""}<>") & "& ``` "99 Bottles" code adapted from [@alephalpha's program](http://ppcg.lol/a/64208). Outputs a function that, when run, will print the output. (Could probably still find a less verbose quine method.) [Answer] # Haskell, 383 bytes ``` s#'Q'="putStrLn\""++s++"\"\n" s#'H'="putStr\"Hello, World\\n\"\n" s#'9'="f\n" s#_="" c s="o=\" of beer on the wall\"\na 1=\"1 bottle\" \na n=shows n\" bottles\"\nb 1=\"Go to the store and buy some more, \"++a 99\nb n=\"Take one down and pass it around, \"++a(n-1)\nf=putStr$[99,98..1]>>= \\n->[a n,o,\", \",a n,\" of beer.\\n\",b n,o,\".\\n\\n\"]>>=id\nmain=do\n"++(concat.map(s#)$s) ``` Thanks to nimi for the [beer](https://codegolf.stackexchange.com/a/64217/31441). # Sample outout ``` o=" of beer on the wall" a 1="1 bottle" a n=shows n" bottles" b 1="Go to the store and buy some more, "++a 99 b n="Take one down and pass it around, "++a(n-1) f=putStr$[99,98..1]>>= \n->[a n,o,", ",a n," of beer.\n",b n,o,".\n\n"]>>=id main=do putStr"Hello, World\n" putStrLn"HQ9+" f ``` [Answer] # Dyalog APL, 244 ``` H P h←'''hello, world''' q←M,(P/⍨1+P=M),M←'''' n←'∊{z←8↑k←'' of beer on the wall''⋄r←{r←'' bottles''↑⍨8-⍵=1⋄⍵=0:''No'',r⋄r,⍨⍕⍵}⋄m,k,g,(m←r⍵),z,g,''Take one down and pass it around'',z,g,(r⍵-1),k,g,g←3⌷⎕tc}¨⌽⍳99' ⎕FX'F',h h q q n''['HhQq9'⍳P] ``` This is a tfn `H`, which takes a HQ9+ program as its input and defines in the workspace a tfn `F`, which runs that program. Example: ``` H 'QhqH' ⍝ compile 'QhqH' F ⍝ run compiled function F QhqH hello, world QhqH hello, world ⎕CR 'F' ⍝ source code for function F F 'QhqH' 'hello, world' 'QhqH' 'hello, world' ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/41417/edit). Closed 1 year ago. [Improve this question](/posts/41417/edit) In 1984, Michael Crichton wrote a security program in BASIC that was published in Creative Computing magazine. The program would ask the user to type a phrase of their choice, record the intervals between the keystrokes, then ask them to retype the phrase. If the timings differed by too much, the program would identify the user as an imposter. Your assignment: create a version of Crichton's program in the language of your choice. Rules: 1. Phrases for communicating with the user ("Please type the key phrase," "Please type the key phrase again," etc.) count as one byte each regardless of actual length. This is for user communication only, do not try to hide program code in the strings. 2. The pass/fail test should be based on the average absolute value of the percentage variances from the original intervals. If the strings don't match, either return fail or allow the user to try again, at your discretion. 3. The key phrase should not allow a null string. In the event the key phrase is too long for your string datatype, either truncate or disallow and start over, at your discretion. 4. The sensitivity of the test (the threshold for the pass/fail test) should be adjustable in the source code. 5. I originally provided a bonus of 20% of total byte count if your source code can be formatted to recognizably resemble a dinosaur. It has been pointed out that this is highly subjective and perhaps more appropriate for a popularity contest, so I have removed this bonus. *However* I still heartily encourage dinosaur formatting, and if you format your code to look like a dinosaur, you can deduct any purely cosmetic comments, linebreak or whitespace characters from your byte total. 6. Shortest byte count wins, subject to string-length and dinosaur formatting adjustments. Note that my specification above does not exactly match the operation of Crichton's code, copies of which may be found online. Follow the spec, don't try to clone the original. [Answer] # Ruby, ~~171 167~~ 157 bytes ``` require'io/console';t=Time;f=->a{loop{x=t.now;STDIN.getch==?\r?break: a<<t.now-x};a};p"Please type the key phrase";f[r=[]];p"Please type the key phrase again";p r.zip(f[[]]).map{|x,y|(1-x/y).abs}.reduce(:+)/r.size>0.2 ``` Outputs `true` if average variance is above 20%, otherwise outputs `false`. Dinosaur ASCII art attempt: ``` (_=/\ \ \ \ \ \ \ _...---..__ \ \ .∕` #{t=Time} `\._ \ \ .∕ #{z='io/console'} `\. \ \.__.∕ #{require z;s=STDIN} `\. \ #{p'1:';f=->a{loop{x=t.now;# \. s.getch==?\r?break: a<<t.now-x;# `\. };a};f[r=[]];p'2:';p r.zip(f[[]])#\ .map{|x,y|(1-x/y).abs}.reduce(:+)#| .fdiv(r.size)>0.2}###########\ \ `-._ ,___...----...__, ,__\ \ | |_| |_| | \ \ |___| |___| \\/) ``` Ungolfed: ``` require 'io/console' # so we can read one char at a time t = Time f = ->(a) { loop { x = t.now # record start time break if STDIN.getch == ?\r a << t.now - x # push (start time - end time) into array } a } puts "Please type the key phrase" f[r = []] puts "Please type the key phrase again" # interweave timing arrays, compute variances, sum elements # then divide by array length. Check to see if average # is greater than threshold (0.2) p r.zip(f[[]]).map { |x,y| (1-x/y).abs }.reduce(:+) / r.size > 0.2 ``` `require 'io/console'` could be removed when run in some Ruby REPLs, as the library is already loaded. [Answer] # Java 768 bytes *what? Java? for code golf?* This is probably the worst thing to do, but I tried it anyway. It displays any messages in the console window, but the actual typing occurs in the JTextField. Not exactly nice looking. Oh, and to save 5 bytes, you have to resize the JFrame yourself. Also, it doesn't check for string correctness the second time. Not sure if that is against the specs. To Use: Type your key in the textfield. Don't press enter, go to the console and type something. It will display another message Type the same thing in the textfield (which should now be cleared). Go to the console and press something again. It will display whether you are an intruder or not. ungolfed: ``` import java.util.*; import javax.swing.*; import javax.swing.event.*; public class CrichtonsMousetrap { public static void main(String[]a){ new CrichtonsMousetrap(); } long start; List<Long>elapsed = new ArrayList<>(); List<Long>e2; public CrichtonsMousetrap(){ JFrame f = new JFrame(); f.setSize(199,70); f.setVisible(true); JTextField t = new JTextField(); System.out.println("please type in the key phrase."); f.add(t); t.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent e) {} @Override public void insertUpdate(DocumentEvent e) { long r = System.nanoTime(); if(start!=0){elapsed.add(r-start);} start=r;} @Override public void removeUpdate(DocumentEvent e) {} }); Scanner s = new Scanner(System.in); s.next(); System.out.println("please type that again!"); e2=elapsed; elapsed=new ArrayList<>(); start=0; t.setText(""); s.next(); double sum=0; for(int i=0;i<e2.size();i++){ sum+=Math.abs(1-elapsed.get(i)/(double)e2.get(i)); } System.out.println("your average percent error was " + sum/e2.size()); double okLimit = .2; System.out.println(sum/e2.size() < okLimit ? "you're ok":"INTRUDER!"); } } ``` golfed: ``` import java.util.*;import javax.swing.*;import javax.swing.event.*;class q{static long p;static List<Long>y=new ArrayList<>(),o;public static void main(String[]a){JFrame f=new JFrame();f.setSize(0,0);f.setVisible(true);JTextField t=new JTextField();System.out.println("please type in the key phrase.");f.add(t);t.getDocument().addDocumentListener(new DocumentListener(){public void changedUpdate(DocumentEvent e){}public void insertUpdate(DocumentEvent e){long r=System.nanoTime();if(p!=0){y.add(r-p);}p=r;}public void removeUpdate(DocumentEvent e){}});Scanner s = new Scanner(System.in);s.next();System.out.println("please type that again!");o=y;y=new ArrayList<>();p=0;t.setText("");s.next();double b=0;for(int i=0;i<o.size();b+=Math.abs(1-y.get(i)/(double)o.get(i++)));System.out.print(b/o.size() < .25 ? "you're ok":"INTRUDER!");}} ``` [Answer] # HTML, JavaScript (ES6), 328 Total bytes count of the code is 402 bytes and the messages to interact with the user: ``` "Valid User" "Imposter alert!!" "Please Enter the Key again" Please Enter the Key ``` are total 78 bytes, so total score => 402 - 78 + 4 = 328 Run the snippet below in a **latest Firefox** and type the key in the input box followed by Enter key. The code checks that both the entered and re-entered keys are same, (prompts for re-entering again if not), calculates the average absolute difference percentage and checks if it is less than the the value of the variable `V` ``` <a id=t >Please Enter the Key</a><input id=f /><script>V=.3,a=[],i=0,s=b="",q=0 c=_=>(j=0,_.slice(1).map(v=>j+=Math.abs(v)/i),alert(j<V?"Valid User":"Imposter alert!!")) r=_=>(a=[],i=0,t.textContent="Please Enter the Key again",f.value="") f.onkeyup=_=>_.keyCode==13?q++?s==f.value?(A=a,B=b,A=a.map((v,i)=>v-A[i-1]),c(b.map((v,i)=>(v-B[i-1]-A[i])/A[i]))):r():r(b=a,s=f.value):a[i++]=Date.now()</script> ``` [Answer] # C, 154 (86+68 for flags) ``` d[99],i,a,b;main(x,y){P"Please type the key phrase"W(E-13)U,x=y;U;P"Please type the key phrase again"W(a<i)E,b+=abs(Y-Z)*99/Z,++a,x=y;b<a*9||P"No cake for imposters");} ``` Compile with `-DY=(y=clock())-x`, `-DZ=a[d]`, `-DE=getch()`, `-DW=);while`, `-DU=i++[d]=Y` and `-DP=puts(`. Newlines added for presentation purposes and may be removed (byte count given is without). Ungolfed+comments: ``` d[99],i,a,b; main(x,y,z){ puts("Please type the key phrase"); do z = getch(), i++[d] = (y = clock()) - x, // save amount of time from last key. first value is garbage. x = y; while((z = getch())-13); // read until carriage return. for(;a < i && getch(); ++a) // don't check for validity, just get a char b += abs((y = clock())- x - d[a])*99/d[a], // (y=clock())-x is time from last key. // subtract from original time, *99, divide by new // then get sum of these x = y; b < i*9 // check that the average difference is less than 9/99 || puts("No cake for imposters"); // identify as imposter if greater/equal // don't output anything if not an imposter } ``` This does not check that the retyped phrase is identical, nor does it output anything if the user is not identified as an imposter. This also does not consider the time taken after prompting before the first keystroke. [Answer] ## Scala REPL 233 ``` def l:Stream[(Int,Long)]=(Console.in.read,System.nanoTime)#::l def m={ println("Enter"); l.takeWhile(_._1!=13).map(_._2).toList.sliding(2).map(a=>a(1)-a(0)) } val k=m.zip(m) k.map(a=>Math.abs(a._2-a._1)/(a._1.toDouble*k.length)).sum<0.2 ``` With all the spacing removed, you have: ``` def l:Stream[(Int,Long)]=(Console.in.read,System.nanoTime)#::l;def m={println("Enter");l.takeWhile(_._1!=13).map(_._2).toList.sliding(2).map(a=>a(1)-a(0))};val k=m.zip(m);k.map(a=>Math.abs(a._2-a._1)/(a._1.toDouble*k.length)).sum<0.2 ``` Which I'm sure somebody more talented than I am could make into a dinosaur! Brief explanation: The `l` method read characters and keeps tract of the `nanoTime` of when each character was typed. The `m` method prints `"Enter"`, breaks the `l` method upon hitting enter (character 13), then maps it to just the `nanoTimes`, and then gets the time intervals between each character. The next 2 lines reads in 2 strings, zips them, then finds the average absolute value of the percentage difference between the second intervals and the first, and finally prints whether or not this average was less than `0.2`. [Answer] # Common Lisp : 660 ``` (ql:quickload'(cl-charms alexandria))(defun m(&key(ok 0.2))(labels((^(s)(fresh-line)(princ s)(return-from m))(d(a b)(abs(/ (- b a) b)))($(x)(princ x)(force-output))(?(m)(charms:with-curses()($ m)(clear-input)(charms:enable-raw-input)(loop for c = (read-char)for n = (get-internal-real-time)for x = nil then (/(- n b)internal-time-units-per-second)for b = n when (eql c #\Esc)do (^"QUIT")when x collect x into % until (eql c #\Newline) collect c into ! finally(progn(terpri)(return(cons(coerce !'string)%)))))))(let*((ip(?"INIT PASSWORD: "))(ps(car ip))(sp(if(equal""ps)(^"NO EMPTY PASSWORD ALLOWED")(?"ENTER PASSWORD: ")))(r(if(equal ps(car sp))(alexandria:mean(mapcar #'d(cdr sp)(cdr ip)))(^"YOU DIDN'T SAY THE MAGIC WORD!"))))(if(> r ok)($"YOU ARE A FAKE!")($"IDENTITY CONFIRMED")))))(m) ``` # Ungolfed ``` (ql:quickload'(cl-charms alexandria)) (defun m(&key(ok 0.2)) (labels ((^(s)(fresh-line)(princ s)(return-from m)) (d(a b)(abs(/ (- b a) b))) ($(x)(princ x)(force-output)) (?(m)(charms:with-curses() (clear-input) ($ m) (charms:enable-raw-input) (loop for c = (read-char) for n = (get-internal-real-time) for x = nil then (/ (- n b) internal-time-units-per-second) for b = n when (eql c #\Esc) do (^"QUIT") when x collect x into % until (eql c #\Newline) collect c into ! finally (progn (terpri) (return (cons (coerce !'string) %))))))) (let* ((ip (?"INIT PASSWORD: ")) (ps (car ip)) (sp (if (equal "" ps) (^"NO EMPTY PASSWORD ALLOWED") (?"ENTER PASSWORD: "))) (r (if (equal ps (car sp)) (alexandria:mean(mapcar #'d(cdr sp)(cdr ip))) (^"YOU DIDN'T SAY THE MAGIC WORD!")))) (if (> r ok) ($"YOU ARE A FAKE!") ($"IDENTITY CONFIRMED"))))) (m) ;; call function ``` # Additional remarks * Complies with all rules * When user first gives an empty password, the program aborts cleanly * When typing `Escape`, the program aborts cleanly. * Tested on recent SBCL and CCL implementations * Requires cl-charms, which is a wrapper around Ncurses. This is the easiest way to capture raw input. * This is inspired by (but not copied from) [the original](https://ia601600.us.archive.org/BookReader/BookReaderImages.php?zip=/12/items/creativecomputing-1984-06/Creative_Computing_v10_n06_1984_Jun_jp2.zip&file=Creative_Computing_v10_n06_1984_Jun_jp2/Creative_Computing_v10_n06_1984_Jun_0180.jp2&scale=2&rotate=0) version found by [squeamish-ossifrage](https://codegolf.stackexchange.com/users/11006/squeamish-ossifrage) # Dinosaur bonus I should have a bonus because everybody knows that "[Common Lisp is a moribund dinosaur](http://xahlee.info/UnixResource_dir/writ/whats_your_fav_lisp.html)". ]
[Question] [ Consider the digits of any integral base above one, listed in order. Subdivide them exactly in half repeatedly until every chunk of digits has odd length: ``` Base Digits Subdivided Digit Chunks 2 01 0 1 3 012 012 4 0123 0 1 2 3 5 01234 01234 6 012345 012 345 7 0123456 0123456 8 01234567 0 1 2 3 4 5 6 7 9 012345678 012345678 10 0123456789 01234 56789 11 0123456789A 0123456789A 12 0123456789AB 012 345 678 9AB ... 16 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F ... ``` Now, for any row in this table, read the subdivided digit chunks as numbers in that row's base, and sum them. Give the result in base 10 for convenience. For example... * for base 3 there is only one number to sum: 0123 = 123 = **510** * for base 4 there are 4 numbers to sum: 04 + 14 + 24 + 34 = 124 = **610** * base 6: 0126 + 3456 = 4016 = **14510** * base 11: 0123456789A11 = **285311670510** # Challenge Write a program that takes in an integer greater than one as a base and performs this subdivide sum procedure, outputting the final sum **in base 10**. (So if the input is `3` the output is `5`, if the input is `6` the output is `145`, etc.) Either write a function that takes and returns an integer (or string since the numbers can get pretty big) *or* use stdin/stdout to input and output the values. The shortest code [in bytes](https://mothereff.in/byte-counter) wins. # Notes * You may use any built in or imported base conversion functions. * There is no upper limit to the input value (besides a reasonable `Int.Max`). The input values don't stop at 36 just because [*"Z"* stops there](http://en.wikipedia.org/wiki/Base_36). *p.s. [this is my fiftieth question](https://codegolf.stackexchange.com/users/26997/calvins-hobbies?tab=questions) :)* [Answer] ## Python, ~~82~~ 78 ``` def f(b):G=b^b&b-1;return sum(b**(b/G-i-1)*(G*i+(G-1)*b/2)for i in range(b/G)) ``` **Huh?** * The number of digit groups that the subdivison yields, ***G***, is simply the greatest power of two that divides the number of digits (i.e. the base), ***b***. It's given by *G = b ^ (b & (b - 1))*, where *^* is bitwise-XOR. If you're familiar with the fact that *n* is a power of two iff *n & (n - 1) = 0* then it should be pretty easy to see why. Otherwise, work out a few cases (in binary) and it'll become clear. * The number of digits per group, ***g***, is simply *b / G*. * The first digit group, *012...(g-1)*, as a number in base *b*, is ![F3](https://i.stack.imgur.com/03rTH.png). * The next group, *g(g+1)...(2g-1)*, as a number in base *b*, is the sum ![F4](https://i.stack.imgur.com/zOzru.png). * More generally, the *n*-th group (zero-based), as a number in base *b*, ***an***, is ![F5](https://i.stack.imgur.com/NDjKp.png). * Recall that there are *G* groups, hence the sum of all groups is ![F6.1](https://i.stack.imgur.com/kWwaO.png) ![F6.2](https://i.stack.imgur.com/P4rel.png) [Answer] # CJam, 17 15 ``` q5*~W*&/\,/fb:+ ``` Works if there is a trailing newline in the input. A more obvious version for those who don't know `x & -x`: ``` q5*~(~&/\,/fb:+ ``` ### How it works ``` q5*~ " Push 5 times the input as numbers. "; W*&/ " Calculate n / (n & -n). (Or n / (n & ~(n-1))) "; \, " List the digits. "; / " Split into chunks. "; fb:+ " Sum in the correct base. "; ``` [Answer] # CJam (snapshot), 19 bytes ``` li__,\mf2m1+:*/fb:+ ``` Note that the latest stable release (0.6.2) has a [bug](https://sourceforge.net/p/cjam/tickets/8/ "Wrong return type for some elements in mf") that can cause `mf` to return Integers instead of Longs. Quite paradoxically, this can be circumvented by casting to integer (`:i`). To run this with CJam 0.6.2 (e.g., with the [online interpreter](http://cjam.aditsu.net/ "CJam interpeter")), you have to use the following code: ``` li__,\mf:i2m1+:*/fb:+ ``` Alternatively, you can download and build the latest snapshot by executing the following commands: ``` hg clone http://hg.code.sf.net/p/cjam/code cjam-code cd cjam-code/ ant ``` ### Test cases ``` $ cjam <(echo 'li__,\mf2m1+:*/fb:+') <<< 3; echo 5 $ cjam <(echo 'li__,\mf2m1+:*/fb:+') <<< 4; echo 6 $ cjam <(echo 'li__,\mf2m1+:*/fb:+') <<< 6; echo 145 $ cjam <(echo 'li__,\mf2m1+:*/fb:+') <<< 11; echo 2853116705 ``` ### How it works ``` li " N := int(input()) "; _, " A := [ 0 1 ... (N - 1) ] "; _ \mf " F := factorize(N) "; 2m1+ " F := F - [2] + [1] "; :* " L := product(F) "; / " A := A.split(L) "; fb " A := { base(I, N) : I ∊ A } "; :+ " R := sum(A) "; ``` [Answer] # Haskell, ~~74~~ ~~69~~ 55 ``` f n=sum[(n-x)*n^mod(x-1)(until odd(`div`2)n)|x<-[1..n]] ``` examples: ``` *Main> map f [2..15] [1,5,6,194,145,22875,28,6053444,58023,2853116705,2882,2103299351334,58008613,2234152501943159] ``` [Answer] ## CJam, 41 bytes This is basically [Ell's solution](https://codegolf.stackexchange.com/a/38269/31414) in CJam: ``` ri:B__(^2/):G/,{_BBG/@-(#G@*G(B2/*+*}/]:+ ``` [Try it online here](http://cjam.aditsu.net/) --- **My original submission:** Doesn't work correctly for base 11 and above ``` ri:B2%BB{2/_2%!}g?B,s/:i:+AbBb ``` Will try to see if I can get it to work for base 11 and above, without increasing the size much. [Answer] ## Mathematica, 114 bytes (or 72 bytes) Hm, this got longer than I thought: ``` f@b_:=Tr[#~FromDigits~b&/@({Range@b-1}//.{a___,x_List,c___}/;EvenQ[l=Length@x]:>Join@@{{a},Partition[x,l/2],{c}})] ``` And ungolfed: ``` f@b_ := Tr[#~FromDigits~ b & /@ ({Range@b - 1} //. {a___, x_List, c___} /; EvenQ[l = Length@x] :> Join @@ {{a}, Partition[x, l/2], {c}})] ``` Alternatively, if I just port Ell's nifty formula, it's 72 bytes: ``` f=Sum[#^(#/g-i-1)(g*i+(g-1)#/2),{i,0,#/(g=Floor[BitXor[#,#-1]/2+1])-1}]& ``` [Answer] # J - 22 char Function taking a single argument (call it `y` for the purposes of this golf) on the right. ``` +/@(#.i.]\~-%2^0{1&q:) ``` First we use `1&q:` to get the number of times `y` is divisible by 2, and then divide `-y` by 2 that many times. This gives us the negative of the width that we need to split things into, which is perfect, because `]\` will take overlapping pieces if the argument is positive, and non-overlapping if it's negative. So then we split up `i.y`—the integers from 0 to `y-1`—into vectors of these widths, and use `#.` to convert them from base `y` to base 10. Finally, `+/` does the summing, and we're done. Examples: (input at the J REPL is indented, output is flush left) ``` +/@(#.i.]\~-%2^0{1&q:) 6 145 f =: +/@(#.i.]\~-%2^0{1&q:) f 11 2853116705 (,: f every) 1+i.14 NB. make a little table for 1 to 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 1 5 6 194 145 22875 28 6053444 58023 2853116705 2882 2103299351334 58008613 f every 20 30 40x NB. x for extended precision 5088086 7455971889417360285373 368128332 ":"0 f every 60 240 360 480 720 960x NB. ":"0 essentially means "align left" 717771619660116058603849466 3802413838066881388759839358554647144 37922443403157662566333312695986004014731504774215618040741346803890772359370271801118861585493594866582351161148652 256956662280637244030391695293099315292368 2855150453577666748223324970642938808770913717928692581430408703547858603387919699948659399838672549766810262282841452256553202264 17093564446058417577302441219081667908764017056 ``` [Answer] ## JavaScript, ~~99~~ 89 bytes ``` function f(n){m=n/(n&-n);for(r=s=i=0;;){if(!(i%m)){r+=s;s=0;if(i==n)return r;}s=s*n+i++}} ``` or ``` function g(n){c=n&-n;for(s=i=0;i<n/c;++i)s+=Math.pow(n,n/c-i-1)*(c*i+(c-1)*n/2);return s} ``` The second function is similar to Ell's one. The first one uses a more traditional approach. Both are 89 characters in size. Try here: <http://jsfiddle.net/wndv1zz8/1/> [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes ``` Ḷœs&N$ðḅS ``` [Try it online!](https://tio.run/##ASAA3/9qZWxsef//4bi2xZNzJk4kw7DhuIVT/zE2UsOH4oKs/w "Jelly – Try It Online") Essentially just a translation of jimmy23013's CJam answer, except using `n & -n` directly as the number of chunks to split into. ``` S The sum of Ḷ the range from 0 to the input minus one œs split into sublists of length equal to & the input bitwise AND N$ its negation ðḅ with each sublist converted from base-the-link's-argument. ``` (The `ð` has nothing to do with mapping: `ḅ` just vectorizes over its left argument, and `ð` is there to separate `ḅS` off as a new dyadic chain which takes the result of `ḶœsÇ` as its left argument and the argument to the main link as its right argument.) ]
[Question] [ # Hash Un-hashing The basic goal of this challenge is to exploit the high probability of collision in the *Java Hash* function to create a list of plausible inputs that created an outputted hash. The program that can print the most results in one hour wins. For example, hashing `golf` produces the number `3178594`. Other 'words' you could hash to get the same number would be: `hQNG`, `hQMf`, `hPlf` ## Details The basic Java hash function is defined as: ``` function hash(text){ h = 0; for(i : text) { h = 31*h + toCharCode(i); } return h; } ``` You can use an altered or more efficient variant of the hash function (such as using bitwise to replace multiplication) if it produces the same results. If your language of choice does not use signed ints or have integer overflow, you must implement a wrap function in the hash to emulate integer overflow so that 2147483648 would overflow to -2147483648. You can choose not to worry about inputs that wrap around multiple times, such as those with 6-7 characters or more. If you choose to include those, you have a better chance of winning. ## Additional Requirements * Your code should have at least one input: the hash itself. An optional second input is the maximum number of letters to guess. For example, `guessHash(53134)` might produce a list of all input combinations up to the absolute maximum amount (see the next requirement), and `guessHash(53134, 4)` will display all input combinations that contain 1-4 letters. * As there are an infinite amount of results, the most letters that can be in a single result will be set at 256. If your program can manage to output all 256 letter results in a reasonable amount of time (see next requirement), you automatically win. * Your program should not run for more than an hour on any `non-specialized` computer you use. `Non-specialized` means it can't run on a server system using 256 different cores or on a super-computer, it must be something that any regular consumer would/could buy. The shorter time period is for practicality, so that you don't have to use all your processing power for too long. * All the results in your final list of inputs must produce the same hash as the inputted hash. * You are to implement your own search, brute-force, or any algorithm to produce the final list. * Using a native search method or search method from another library is not allowed (example: binary search library). Using `String.search(char)` or `Array.find(value)` is okay if it is not a primary feature of your search algorithm (such as to spot duplicate results or find if a letter exists in given string). * The final list of input values should use all readable ASCII characters (32 to 126). ## Example I went ahead and created a very inefficient version of this challenge to produce an example list! Each result I gave is separated by spaces, although you can print each result on a new line or any other readable method of organization. ``` i30( i3/G i2NG hQNG hQMf hPlf golf ``` You do not have to print results to a file, just record how many results you get. ## Judging The number to un-hash is: `69066349` I will pick the best answer based on which-ever code produces the most results. If you remember above where I said wrapping was optional, it'd be a good idea to include multiple wrappings if you want the most results in your final list. --- If you have any questions or additional comments, feel free to ask. **Good Luck!** [Answer] # C#, 1.052 × 1010 The idea is to do the hash function in reverse to get all possible un-hashed strings from the given number. Integer overflow of the 32-bit hash value is also emulated in reverse by incrementing the given hash value by 2^32 on each iteration. **UPDATE:** I've made several micro-optimisations that significantly improved the performance of my program. The new version produced 10.52 billion results in 15 minutes (compared to 9.05 billion in 1 hour for the previous version). Futher improvement may be difficult since the output file was 117GB in size and that's about how much free space I have on my SSD. Writing results to the screen doesn't seem to be a viable option since it's almost a thousand times slower than writing to a file. ``` using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace Unhash { class Program { const int minChar = 32; const int maxChar = 126; // limit maxStrLength to make sure that max hash value does not exceed long.MaxValue (2^63 - 1) const int maxStrLength = 12; static long[] minHashValues; static long[] maxHashValues; static Program() { minHashValues = new long[maxStrLength + 1]; for (int strLength = 0; strLength <= maxStrLength; strLength++) minHashValues[strLength] = Pow(31, strLength) / (31 - 1) * minChar; maxHashValues = new long[maxStrLength + 1]; for (int strLength = 0; strLength <= maxStrLength; strLength++) maxHashValues[strLength] = Pow(31, strLength) / (31 - 1) * maxChar; } static void GuessHash(int hash, int maxLength = 256) { Stopwatch sw = Stopwatch.StartNew(); var timeLimit = new TimeSpan(0, 15, 0); if (maxLength > maxStrLength) maxLength = maxStrLength; long currentHash = (uint)hash; long step = 1L << 32; const int bufferSize = 32 * 1024; using (var writer = new StreamWriter("output.txt", false, new UTF8Encoding(false), bufferSize)) { for (int strLength = 0; strLength <= maxLength; strLength++) { long maxHash = maxHashValues[strLength]; if (currentHash > maxHash) continue; long minHash = minHashValues[strLength]; while (currentHash < minHash) currentHash += step; while ((currentHash <= maxHash) && (sw.Elapsed < timeLimit)) { GuessLongHash(writer, currentHash, new char[strLength], strLength - 1); currentHash += step; } } } } static void GuessLongHash(StreamWriter writer, long hash, char[] chars, int charPos) { if (hash <= maxChar) { char ch = (char)hash; if (ch >= minChar) { chars[charPos] = ch; writer.WriteLine(new string(chars)); } return; } char c = (char)(hash % 31); while (c < minChar) c += (char)31; while (c <= maxChar) { chars[charPos] = c; GuessLongHash(writer, (hash - c) / 31, chars, charPos - 1); c += (char)31; } } static long Pow(int value, int exponent) { long result = 1; for (int i = 0; i < exponent; i++) result *= value; return result; } static void Main(string[] args) { const int hash = 69066349; GuessHash(hash); } } } ``` [Answer] # Scala One ["useful" characteristic](http://www.kb.cert.org/vuls/id/903934) of Java's `String.hashCode` method is that if you have a string `z` with `z.hashCode() == 0`, then you also have that `(z + x).hashCode() == x.hashCode()` for any other string `x`. So even if we can find a relatively small number of strings with a given hashCode, we can just prefix it with a bunch of zero-hash strings, and generate as many strings as we like with that hashCode - the performance limit becomes string concatenation and IO at that point. So how do we find a string with a particular hashCode? In truth, brute force would probably be enough, due to the zero-hash trick, but we can easily get more speed with a meet-in-the-middle trick. Let's suppose we want a string of length 10. To do this, we calculate the hashes of all strings of length 5. In this case, the hash of `x + y` will be `x.hashCode() * 31 ** 5 + y.hashCode`, so we can either start with `x`, and look for strings `y` whose hash is `target - x.hashCode() * 31 ** 5`, or start with `y` and look for strings whose hash is `(target - y.hashCode) / (31 ** 5)` (where division is modulo 2^32). In fact, we do both. Right now, even length strings are better optimised than odd length strings, for reasons that are probably apparent. Using the zero-hash trick, I can get 1.6 million strings per second on my laptop - printing the output is the main bottleneck. Without the zero-hash trick (for example, if you want short strings - too short to pad with zero-hash strings), the performance is more modest. The birthday paradox means it gets faster as it runs, but it seems to level-off at around 70000 strings per second, for strings of length 10. There's one worthwhile optimisation to note. If we're storing the hashes for a large number of strings, it would seem to make sense to either keep them in a hashtable, or an equivalent on-disk structure. However, an on-disk structure is too slow, and there isn't room for everything in memory (on my laptop, at least). So instead, we keep the data in a fixed-size 1-way cache. This means that data can be lost from the cache, but it improves performance. By increasing `hashtableSize`, you can increase the size of this cache, using more memory, and leading to more matches. ``` import scala.collection.mutable import scala.collection.JavaConversions._ import java.io.File import java.io.RandomAccessFile import java.io.FileWriter object Unhash { val maxChar = 126.toChar val minChar = 32.toChar val hashtableSize = 0x4000000 def allStrings(l: Int): Iterator[String] = { new Iterator[String] { val currentArray = Array.fill(l)(minChar) var _hasNext = l > 0 def hasNext = _hasNext def next(): String = { if (!_hasNext) throw new NoSuchElementException val result = new String(currentArray) var i = 0 while (i < l) { if (currentArray(i) != maxChar) { val result = new String(currentArray) currentArray(i) = (currentArray(i) + 1).toChar return result } else { currentArray(i) = minChar i += 1 } } _hasNext = false return result } } } def pow(x: Int, n: Int) = { var r = 1 var p = n var m = x while (p > 0) { if ((p & 1) == 1) r *= m m *= m p >>= 1 } r } def guessHash(target: Int, length: Int) = { length match { case l if l % 2 == 0 => findEven(target, length / 2) case _ => findOdd(target, (length - 1) / 2) } } def findEven(target: Int, halfLength: Int) = { val hashes = new HashCache(halfLength, hashtableSize) val multFactor = pow(31, halfLength) val divideFactor = BigInt(multFactor).modInverse(BigInt(2) pow 32).intValue new Traversable[String] { def foreach[U](f: String => U) = { for (string <- allStrings(halfLength)) { val hash = string.hashCode hashes.put(string) // Find possible suffixes { val effectiveTarget = target - hash * multFactor for (x <- hashes.get(effectiveTarget)) f(string + x) } // Find possible prefixes { val effectiveTarget = (target - hash) * divideFactor for (x <- hashes.get(effectiveTarget)) f(x + string) } } } } } def findOdd(target: Int, halfLength: Int) = { val hashes = new HashCache(halfLength, hashtableSize) val multFactor = pow(31, halfLength) val divideFactor = BigInt(multFactor).modInverse(BigInt(2) pow 32).intValue new Traversable[String] { def foreach[U](f: String => U) = { for (string <- allStrings(halfLength); hash = string.hashCode; _ = hashes.put(string); firstChar <- minChar to maxChar) { // Adjust the target, by subtracting the contribution from the first char val currentTarget = target - firstChar * pow(31, 2 * halfLength) // Find possible suffixes { val effectiveTarget = currentTarget - hash * multFactor for (x <- hashes.get(effectiveTarget)) f(firstChar + string + x) } //Find possible prefixes { val effectiveTarget = (currentTarget - hash) * divideFactor for (x <- hashes.get(effectiveTarget)) f(firstChar + x + string) } } } } } def guessAnyLength(target: Int) = { new Traversable[String] { def foreach[U](f: String => U) = { val zeroHashes = findEven(0, 4).toArray for (len5 <- findEven(target, 4); zero1 <- zeroHashes.iterator; zero2 <- zeroHashes.iterator; zero3 <- zeroHashes.iterator) f(zero1 + zero2 + zero3 + len5) } } } def main(args: Array[String]) = { val startTime = System.nanoTime val Array(output, length, target) = args val t = target.toInt val resultIterator = length match { case "any" => guessAnyLength(t) case _ => val l = length.toInt guessHash(t, l) } var i = 0L var lastPrinted = System.nanoTime var lastI = 0L val outputWriter = new FileWriter(output) try { for (res <- resultIterator) { outputWriter.write(res + "\n") i += 1 val now = System.nanoTime if (now > lastPrinted + 1000000000L) { println(s"Found $i total, at ${i - lastI} per second") lastPrinted = System.nanoTime lastI = i } } } finally { outputWriter.close() } } } class HashCache(stringLength: Int, size: Int) { require ((size & (size - 1)) == 0, "Size must be power of 2") val data = new Array[Char](stringLength * size) def get(hash: Int) = { val loc = hash & (size - 1) val string = new String(data, stringLength * loc, stringLength) if (string.hashCode == hash) Some(string) else None } def put(string: String) = { val loc = string.hashCode & (size - 1) string.getChars(0, stringLength, data, stringLength * loc) } } ``` [Answer] # C, 3.2 × 1010 preimages ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char output[29] = { 0 }, preimages[64][8], zeros[512][8] = { "/*$+06(" }; unsigned i, j, k, l, t; t = atoi(argv[1]); for(i = 7; i --> 0; t /= 31) preimages[0][i] = zeros[0][i] + (t % 31); for(i = 0, j = 2, k = 1; i < 6; i += 1, j *= 2) for(l = 0; k < j; k++, l++) strcpy(preimages[k], preimages[l]), preimages[k][i] -= 1, preimages[k][i + 1] += 31; for(i = 0, j = 3, k = 1; i < 6; i += 1, j *= 3) for(l = 0; k < j && k < 512; k++, l++) strcpy(zeros[k],zeros[l%(j/3)]), t = 1 + (l/(j/3)), zeros[k][i] -= t, zeros[k][i + 1] += 31 * t; for(i = 0, k = 0; i < (1L << 36); i++) { strcpy(&output[0], zeros[(i >> 27) & 511]); strcpy(&output[7], zeros[(i >> 18) & 511]); strcpy(&output[14], zeros[(i >> 9) & 511]); strcpy(&output[21], zeros[(i >> 0) & 511]); for(j = 0; j < 64; j += 4) { // k += 4; // if(k++ % 1000000 == 0) printf("%d\n", k); printf("%s%s\n%s%s\n%s%s\n%s%s\n", output, preimages[j + 0], output, preimages[j + 1], output, preimages[j + 2], output, preimages[j + 3] ); } } return 0; } ``` Calculates a preimage and adds and prefixes strings with hash 0. The time spent to generate the preimages should be negligible; all the code has to do is piece together five strings. That means that most of the time will be spent printing the results. In one hour, only 3.2 × 1010 preimages can be printed. If I comment the *printf* statement out, the program reports that it has found **5.5 × 1012 preimages**. However, I don't know if the compiler just ignores parts of the code (and I don't have the assembly knowledge to verify). [Answer] **PHP** I found **81** possible solutions for 69066349 within 0.016 seconds with this code! Btw I didn't try to implement the overflow functionality. ``` $results = 0; /** * Get the string for a hash * @param integer $hash hash value * @param integer $length length of the returned string * @return string $string */ function reverseHash($hash,$length=false,$val='',$counter=0) { global $results; if (!$length) { $length = 0; $copyHash = $hash; while (($copyHash-32)/31 > 0) { $copyHash = ($copyHash-126)/31; $length++; } echo 'MaxLength: '.$length.'<br>'; } // if at least one more recursion is needed if ($counter < $length) { for ($i = 32; $i <= 126; $i++) { $string = false; $newhash = ($hash-$i)/31; $newval = chr($i).$val; if ($newhash > 0) { // if the new hash isn't an integer => $newval is wrong if (floor($newhash) == $newhash) { $string = reverseHash($newhash,$length,$newval,$counter+1); } if ($string) { return $string; } } else if ($counter <= $length-1 and $newhash == 0) { echo $newval.'<br>'; $results++; } } } else { return false; } } $start = microtime(true); reverseHash($_GET['hash']); $end = microtime(true); $dif = $end-$start; echo "Time ".$dif." sec (".$results.")"; ``` ]
[Question] [ # Winner: [Ian D. Scott's answer](https://codegolf.stackexchange.com/a/35655/10961), by one byte (48 bytes)! Superb! Your program must accept input from a fraction that can be simplified, then simplify it. Rules: * If the fraction is already in its most simplified form, you must inform the user * No built-in functions to do this * The user must type the number at some point, however the method the program reads it does not matter. It can be with stdin, console.readline, etc. As long as the user types `9/18` (for example) at some point, it is valid * Output must be done with stdout, console.writeline, etc... * The fraction will be put in as `x/y`, and must output as `a/b` * The fraction must output the most simplified form. For example, 8/12 -> 6/9 is *not valid*, the only valid solution is 2/3. --- * This contest ends on August 9th, 2014 (7 days from posting) * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question, so the shortest code wins [Answer] # [><>](http://esolangs.org/wiki/Fish) (92) ``` 0v +>>>>>>a*ic4*-:0(?v v@:{:~^?=2l0 ,a~ < >:?!v:@% =1:~<;no-1*4c,n,@:/? |oooo;!'simplest' / ``` I know I can get this lower, I'll golf it a bit more in the morning. Basic explanation: First two lines, and the latter half of the third, are all for reading numbers. Sadly, ><> has no way to do that, so the parsing takes up half the program. 4th line is a simple iterative gcd calculation. I'm surprised at how well ><> did on byte count for the actual algorithm. If it wasn't for the terrible i/o, it could actually be a reasonable golf language. Last two lines are just for printing the result and dividing the original numbers by the gcd. [Answer] ### GolfScript, 49 characters ``` '/'/{~}%.~{.@\%.}do;:G({{G/}%'/'*}{;'simplest'}if ``` Run the two testcases [here](http://golfscript.apphb.com/?c=IjgvMTIiIAonLycve359JS5%2Bey5AXCUufWRvOzpHKHt7Ry99JScvJyp9ezsnc2ltcGxlc3QnfWlmCnB1dHMKCiI3LzEyIgonLycve359JS5%2Bey5AXCUufWRvOzpHKHt7Ry99JScvJyp9ezsnc2ltcGxlc3QnfWlmCnB1dHMK&run=true): ``` > 8/12 2/3 > 7/12 simplest ``` [Answer] # JavaScript 101 For once, a solution not using EcmaScript 6 ``` v=prompt().split('/');for(a=v[0]|0,b=v[1]|0;a-b;)a>b?a-=b:b-=a; alert(a>1?v[0]/a+'/'+v[1]/a:'Reduced') ``` But with E6 could be 93 ``` [n,d]=prompt().split('/');for(a=n|0,b=d|0;a-b;)a>b?a-=b:b-=a; alert(a>1?n/a+'/'+d/a:'Reduced') ``` [Answer] # PHP>=7.1, 76 Bytes ``` for([$x,$y]=explode("/",$argn),$t=1+$x;$y%--$t||$x%$t;);echo$x/$t."/".$y/$t; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/f662c26022ce9a6723360b5b62cd4c81cdda3e83) [Answer] # Python 2.7, 124 ``` from fractions import gcd;x,y=map(int,raw_input().split('/'));g=gcd(x,y);print'%d/%d'%(x/g,y/g)if g!=1 else'Already reduced' ``` Very simple solution, though I know it would be shorter in many other languages. I used an imported `gcd` but if it counts as a built-in fraction reducer it could be implemented directly. [Answer] # Python 2 (82) ``` A,B=a,b=map(int,raw_input().split("/")) while b:a,b=b,a%b print`A/a`+"/"+`B/a`,a<2 ``` Prints a Boolean afterward to say whether the original was in simplest form. Just does the usual GCD algorithm. Most of the characters are spent on input/output. [Answer] # Python - ~~69~~ 48 The first thing to do is to represent it in python's native format for storing fractions, namely the Fraction class. ``` print(__import__("fractions").Fraction(input())) ``` Now we simplify... but look! It's already simplified. Does this count as using a built-in function? It is not intended specifically for simplifying, and Fraction is a class anyway, not a function. I didn't call any simplifying function, so it's not my fault if python decides to do it itself. [Answer] **C, 94** Just brute force guess and check, for GCD starting at a|b down to 1; ``` main(a,b,c){scanf("%d/%d",&a,&b);for(c=a|b;--c;)if(a%c+b%c<1)a/=c,b/=c;printf("%d/%d\n",a,b);} ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 0 bytes ``` ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIiLCIiLCI4LzEyIl0=) Yes. It really is 0 bytes. It doesn't use any built-in functions, as inputted fractions are simplified by default. The benefits of using rational numbers internally! [Answer] # [ARBLE](https://github.com/TehFlaminTaco/ARBLE), 54 bytes ``` (a/c.."/"..b/c)(a,b,index(range(a+b,1)&nt(a%c+b%c),1)) ``` ## Explained ``` (a/c.."/"..b/c)(a,b,index(range(a+b,1)&nt(a%c+b%c),1)) range(a+b,1) -- All numbers from (a+b) down to 1. & -- Filter nt(a%c+b%c) -- Both a and b divisible by the iterator index( ,1) -- Get the first value (Naturally the highest) ( )(a,b, ) -- Pass a, b, and the gcd of a and b to the stringifier a/c.."/"..b/c -- Format as a fraction. -- Returns a two argument function. ``` Takes input as two numbers. Outputs as `1.0/2.0`. The trailing `.0` can be removed for +2 bytes by replacing `(a/c.."/"..b/c)` with `(a//c.."/"..b//c)` [Try it online!](https://tio.run/##DcfBCoAwCADQfxkslIljnfoddRJBeBgd@nvr3Z4svT0TpBtz6YVZuyEIKV0x/YUlcTpIUxq4xQNSrWk1/IuZOfYcxwc "ARBLE – Try It Online") [Answer] # [Rebmu](http://rebmu.hostilefork.com/) (104 characters) ``` P"/"rSst[a b]paSp AtiA BtiB Ca DbFOiMNcD 1 -1[izADmdCiMDdI[CdvCi DdvDi]]QapAPtsCpTSdIa^e?aCe?bD[Q"Err"]Q ``` Unmushed: ``` P"/" rS ; extract numerator to a, denominator to b st [a b] pa s p ; convert a,b to integers AtiA BtiB ; set c=a, d=b Ca Db ; loop from min(c,d) to 1 fo i mn c d 1 -1[ ; check if (c mod i) + (d mod i) is 0 iz ad md c i md d i [ ; divide c, d by i Cdv c i Ddv d i ] ] ; set Q to c/d Qap ap ts c p ts d ; check if a==c and b==d i a^ e? a c e? b d[ ; set q to "err" Q"err" ] ; print q Q ``` [Answer] # PHP 156 *meh.* ``` $f=$argv[1];$p=explode('/',$f);$m=max(array_map('abs',$p));for(;$m;$m--)if(!($p[0]%$m||$p[1]%$m)){$r=$p[0]/$m.'/'.$p[1]/$m;break;}echo $r===$f?'reduced':$r; ``` Run: ``` php -r "$f=$argv[1];$p...[code here]...:$r;" 9/18; 1/2 ``` * prints "reduced" if the fraction is already in its simplest form * works with negative fractions * works with improper fractions (e.g. 150/100 gives 3/2) * *kinda* works with decimals (e.g. 1.2/3.6 gives 0.75/2.25) * 99/0 incorrectly gives 1/0 *?* * won't reduce to a whole number (e.g. 100/100 gives 1/1) Here's an ungolfed version with some testing (modified into function form): ``` <?php $a = array( '9/18','8/12','50/100','82/100','100/100','150/100','99/100', '-5/10','-5/18','0.5/2.5','1.2/3.6','1/0','0/1','99/0' ); print_r(array_map('r',array_combine(array_values($a),$a))); function r($f) { $p = explode('/',$f); $m = max(array_map('abs',$p)); for ( ; $m; $m-- ) if ( !($p[0] % $m || $p[1] % $m) ) { $r = $p[0]/$m.'/'.$p[1]/$m; break; } return $r === $f ? 'reduced' : $r; } /* Array( [9/18] => 1/2 [8/12] => 2/3 [50/100] => 1/2 [82/100] => 41/50 [100/100] => 1/1 [150/100] => 3/2 [99/100] => reduced [-5/10] => -1/2 [-5/18] => reduced [0.5/2.5] => 0.2/1 [1.2/3.6] => 0.75/2.25 [1/0] => reduced [0/1] => reduced [99/0] => 1/0 ) */ ?> ``` [Answer] **Java, 361 349 329 (thanks @Sieg for the `int` tip)** ``` class P{public static void main(String[]a){String[]e=a[0].split("/");String f="";int g=new Integer(e[0]),h=new Integer(e[1]);if(g>h){for(int i=h;i>=1;i--){if(g%i==0&&h%i==0){f=g/i+"/"+h/i;break;}}}else if(g<h){for(int i=g;i>=1;i--){if(g%i==0&&h%i==0){f=g/i+"/"+h/i;break;}}}else if(g.equals(h)){f="1/1";}System.out.println(f);}} ``` I know it's not short, but I'm just mesmerized of what I did. To use it, compile the code and run it passing the arguments through the command-line. * Integers only (I'm not into `doubles` and the task doesn't require it). * If the fraction is already simplified, returns itself. * Doesn't work with negative fractions. * Dividing by zero? No cookie for you (Returns an empty string). Ungolfed (if anyone wants to see this mess): ``` class P{ public static void main(String[]a){ String[]e=a[0].split("/"); String f=""; int g=new Integer(e[0]),h=new Integer(e[1]); if(g>h){ for(int i=h;i>=1;i--){ if(g%i==0&&h%i==0){ f=g/i+"/"+h/i; break; } } }else if(g<h){ for(int i=g;i>=1;i--){ if(g%i==0&&h%i==0){ f=g/i+"/"+h/i; break; } } }else if(g.equals(h)){ f="1/1"; //no processing if the number is THAT obvious. } System.out.println(f); } } ``` [Answer] ### Ruby — 112 characters `g` is a helper lambda that calculates the GCD of two integers. `f` takes a fraction as a string, e.g. `'42/14'`, and outputs the reduced fraction or `simplest` if the numerator and denominator are relatively prime. ``` g=->a,b{(t=b;b=a%b;a=t)until b==0;a} f=->z{a,b=z.split(?/).map &:to_i;y=g[a,b];puts y==1?:simplest:[a/y,b/y]*?/} ``` Some test cases: ``` test_cases = ['9/18', '8/12', '50/100', '82/100', '100/100', '150/100', '99/100', '-5/10', '-5/18', '0/1'] test_cases.map { |frac| f[frac] } ``` Output: ``` 1/2 2/3 1/2 41/50 1/1 3/2 simplest -1/2 simplest simplest ``` Note, although against the rules, Ruby has `Rational` support baked in, so we could do ``` a=gets.chomp;b=a.to_r;puts b.to_s==a ?:simplest:b ``` [Answer] # JavaScript (91) (73) Returns '/' when the fraction is already in it's simplest form. The function g calculates the gcd. BTW: Is there any shorter way for '1==something' where something is a non negative integer? `function s(f){[n,m]=f.split(b='/');g=(u,v)=>v?g(v,u%v):u;return 1==(c=g(n,m))?b:n/c+b+m/c;}` Thanks to @bebe for an even shorter version: ``` s=f=>([n,m]=f.split(b='/'),c=(g=(u,v)=>v?g(v,u%v):u)(n,m))-1?n/c+b+m/c:f; ``` [Answer] # Lua - 130 115 characters *10/10 i really tried* ``` a,b=io.read():match"(.+)/(.+)"u,v=a,b while v+0>0 do t=u u=v v=t%v end print(a+0==a/u and"reduced"or a/u.."/"..b/u) ``` * prints "reduced" if fraction is in simplest form * works with negatives * works with improper fractions * presumably works with decimals (1.2/3.6 gives 5.4043195528446e+15/1.6212958658534e+16) * any number/0 gives 1/0 * does not reduce to whole numbers I fully took advantage of Lua's ability to auto convert a string to a number when doing arithmetic operations on a string. I had to add "+0" in place of tonumber for some comparison code. Sorry, I don't have an ungolfed version, the above is actually how I wrote it [Answer] # Batch - 198 ``` for /f "tokens=1,2delims=/" %%a in ("%1")do set a=%%a&set b=%%b&set/ac=%%b :1 set/ax=%a%%%%c%&set/ay=%b%%%%c% if %x%%y%==00 set/aa/=%c%&set/ab/=%c% if %c% GTR 0 set/ac=%c%-1&goto 1 echo %a%/%b% ``` Input is split as `a/b`, then for every `c` in `b,b-1,...1` we check if `a` and `b` are divisible by `c`, and divide them by `c` if they are. Then we return `a/b` [Answer] # Befunge 93 (192) ``` &04p~$&14p2 > :24p v >34g#v_0"tselpmiS">:#,_@ >134p 24g> ^+1g42$<>04g` | >04g."/",14g.@ ^p41/g42p40/g42< |%g42:g41< # |!%g42:g40< 0 ^+1g42< ``` [Answer] ## C 135 Accepts input for 2 space-separated integers. Keeps dividing by minimum of a & b down to 1 to find GCD. ``` int a,b,m; void main() { scanf("%d %d", &a, &b); m=a<b?a:b; for (;m>0;m--){if (a%m==0&&b%m==0)break;} printf("%d/%d",a/m,b/m); } ``` [Answer] # Java (200) The previous best solution in Java still had >300 bytes, this one has 200: ``` class M {public static void main(String[]args){String[]s=args[0].split("/");int a=Integer.parseInt(s[0]),b=Integer.parseInt(s[1]),c=a,d=b;while(d>0){int g=c;c=d;d=g%d;}System.out.print(a/c+"/"+b/c);}} ``` This uses the (faster) modulo to determine the gcd instead of iterating all numbers. ]
[Question] [ You must take input in the form of ``` title|line1|line2|(...)|line[n] ``` And output an information card. It's hard to explain how to make the card, so here's a quick example: Input ``` 1234567890|12345|1234567890123|pie|potato|unicorn ``` Output ``` /===============\ | 1234567890 | |===============| | 12345 | | 1234567890123 | | pie | | potato | | unicorn | \---------------/ ``` Detailed specifications: * The title must be centered (if there are an odd number of characters you can decide whether to put an extra space after or before it). * The remaining lines must be left-aligned. * All of them must have at least one space of padding before and after. * Each line must be the same length. * The lines must be the smallest length possible in order to fit all of the text. * The first and last character of each row (except for the first and last rows) must be a `|`. * There must be a `/`, a row of `=`s, and a `\` in the line right before the title. (the first line) * There must be a `|`, a row of `=`s. and a `|` in the line right after the title. (the third line) * There must be a `\`, a row of `-`s, and a `/` in the last line. * For the example input provided, your program's output must exactly match the example output provided. * The input will always contain at least one `|`; your programs behaivior when a string like `badstring` is input does not matter. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in character count wins. [Answer] ## Ruby, ~~153~~ ~~147~~ 140 characters ``` h,*d=s=gets.chop.split(?|) puts"/%s\\ |%s| |%s|"%[e=?=*k=2+l=s.map(&:size).max,h.center(k),e] d.map{|x|puts"| %%-%ds |"%l%x} $><<?\\+?-*k+?/ ``` Double format string in the second-to-last line `:D` [Answer] # Python 2.7 - 168 = 166 + 2 for quotes. This assumes we can accept the input with surrounding quotes, hence the possible +2. Either way +2 is better than the +4 required if you use `raw_input()` vs. just `input()`. ``` b="|" s=input().split(b) w=max(map(len,s)) x=w+2 S="| %s |" print"\n".join(["/"+"="*x+"\\",S%s[0].center(w),b+"="*x+b]+[S%i.ljust(w)for i in s[1:]]+["\\"+"-"*x+"/"]) ``` Thanks to Volatility for the `max(map(len,s))` tip. A very cool tip. **edit:** Corrected top row problem. And the above outputs this: ``` > python i.py "1234567890|12345|1234567890123|pie|potato|unicorn" /===============\ | 1234567890 | |===============| | 12345 | | 1234567890123 | | pie | | potato | | unicorn | \---------------/ ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 66 bytes ``` ≔∕S|ι≔⁺⌈EιLκ²ς/×=ς↓\↓⁺Lι¹←/←ς↑\↑⁺Lι¹↘M∕⁻ςL§ι⁰¦²→P§ι⁰M±²¦¹P×=ςM↘✂ι¹ ``` My first Charcoal answer! I wasn't getting a proper result with reflection, so I made the box manually. [Try it online!](https://tio.run/##S85ILErOT8z5//9R55RHHVPf79lcc24niN2461FPx/s9S8/tfL9nzbldhzadb9I/PN32fNOjtskxQAxUAJLYeWjno7YJ@kAMkpkIlJmILDPj/Z61QGMfNe4@3wQUPLQcaHjjhkPLDm161Dbp/Z4NUAGgqkMbD20CigNt2wC2BqSxbcajOU0gg/7/NzQyNjE1M7ewNKgBM2sQAkBWTUFmak1BfkliSX5NaV5mcn5RHgA "Charcoal – Try It Online") # [Charcoal](https://github.com/somebody1234/Charcoal) (Verbose), 385 bytes ``` Assign(Divide(InputString,"|"),i) Assign(Add(max(Each(i,Length(k))),2),v) Print("/") Print(Times("=",v)) Print(:Down,"\\") Print(:Down,Length(i)+1) Print(:Left,"/") Print(:Left, v) Print(:Up, "\\") Print(:Up,Length(i)+1) Move(:DownRight) Move(Minus(v,Length(AtIndex(i,0)))/2,:Right) MultiPrint(AtIndex(i,0)) Move(Negate(2),1) MultiPrint(Times("=",v)) Move(:DownRight) Print(Slice(i,1)) ``` [Try it online!](https://tio.run/##ZY/LasMwEEX3@YqglURlErtvQxeGdBFISmnaXTaqPbGHOpKxZTUF/bsqajut6G64c3RGN69EmytRO5d1HZaSrtBgAXQtm17vdIuy5MQSxpHNRiIrCnoUJ/oo8ooi34AsdUU/GGM8Ydyw2bN/pSlZkGl8xSN0lDwQv52ydKU@JSf7PQmTUYfsIj4vNnDQ/I9vCObnU@lbw@eBygeBaKsMDAdesKz0GGxR9h01E5rptSzg5DstfZlFwtMJ7muNgzlgBssTlEID9d3jAA1b//vBAO1qzMHbYsaci5PLq@ub27v7pf0Z7W/gJ9sg2EZpoZXtJeaqlS4yLooKMNC@qw4PX98 "Charcoal – Try It Online") [Answer] ### GolfScript, 97 characters ``` '|'/{' ':!{1/*}:E~}%.{,}%$-1=:L'='*:§'/\\'E\(.,L\-)2/{!E}*L<'||':^E§^E@{!L*+L<^E}/L'-'*'\\/'E]n* ``` [Example](http://golfscript.apphb.com/?c=OyIxMjM0NTY3ODkwfDEyMzQ1fDEyMzQ1Njc4OTAxMjN8cGllfHBvdGF0b3x1bmljb3JuIgoKJ3wnL3snICAnOiF7MS8qfTpFfn0lLnssfSUkLTE9OkwnPScqOsKnJy9cXCdFXCguLExcLSkyL3shRX0qTDwnfHwnOl5FwqdeRUB7IUwqK0w8XkV9L0wnLScqJ1xcLydFXW4qCg%3D%3D&run=true): ``` > 1234567890|12345|1234567890123|pie|potato|unicorn /===============\ | 1234567890 | |===============| | 12345 | | 1234567890123 | | pie | | potato | | unicorn | \---------------/ ``` [Answer] ## Haskell, 292 ``` import Data.List.Split z=replicate l=length p w s=' ':s++z(w-l s)' ' c w s=p w$z(div(w-l s-1)2)' '++s t(i:s)=let r=z m;m=(+)1$maximum$map l(i:s)in"/="++r '='++"\\\n"++"|"++c m i++"|\n|="++r '='++"|\n"++concat['|':p m x++"|\n"|x<-s]++"\\-"++r '-'++"/" main=do l<-getLine;putStrLn$t$splitOn"|"l ``` … I’m a little new to this one :D [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 60 bytes ``` \|/DvLG⇧D\=*\/p\\+,„h⋏\|pǏ,:\|$-Ǐ,‹£Ḣƛ¥↲ðp\|pǏ,;¥›\=*\\p\/+, ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%5C%7C%2FDvLG%E2%87%A7D%5C%3D*%5C%2Fp%5C%5C%2B%2C%E2%80%9Eh%E2%8B%8F%5C%7Cp%C7%8F%2C%3A%5C%7C%24-%C7%8F%2C%E2%80%B9%C2%A3%E1%B8%A2%C6%9B%C2%A5%E2%86%B2%C3%B0p%5C%7Cp%C7%8F%2C%3B%C2%A5%E2%80%BA%5C%3D*%5C%5Cp%5C%2F%2B%2C&inputs=1234567890%7C12345%7C1234567890123%7Cpie%7Cpotato%7Cunicorn&header=&footer=) Longer than I'd like... [Answer] # C# 4.5 - 375 347 chars `;)` [If someone is interested to see how C# differs from others] --- ``` var c = input.Split('|').ToList(); int l = c.Select(s => s.Length).Max() + 2; Console.WriteLine("/{0}\\\r\n| {1} |\r\n|{0}|\r\n{2}\r\n\\{3}/\r\n", "=".PadRight(l, '='), c[0].PadLeft(c[0].Length + ((l - c[0].Length) / 2)-1).PadRight(l-2), string.Join("\r\n", c.Select(s => "| " + s.PadRight(l - 2) + " |").Skip(1)), "-".PadRight(l, '-')); ``` --- [Answer] # Javascript, ~~373~~ 364 ``` l="length";m=" ";a="\\";b="/";c="|";p=m+c;v="join";u="concat";o=[];q=Array;i=prompt().split(c);j=i.slice().sort(function(d,e){return e[l]-d[l]})[0][l]+3;i=i.map(function(d,e){s=q(o[l]=0|(e?j-d[l]-1:(j-d[l])/2))[v](m);return(e?p:c+s+(d[l]&1?m:""))+d+(e?s:s+m)+p});x=q(o[l]=j)[v]("=");r=[b+x+a,i.shift(),c+x+c][u](i)[u](a+q(o[l]=j)[v]("-")+b);console.log(r[v]("\n")) ``` Output ``` /===============\ | 1234567890 | |===============| | 12345 | | 1234567890123 | | pie | | potato | | unicorn | \---------------/ ``` Edit Notes: Thanks @Doorknob!: -9 Characters =) [Answer] # Java - ~~549~~ ~~492~~ ~~468~~ ~~453~~ 432 ``` class a{static<T>void p(T p){System.out.println(p);}public static void main(String[]a){String b="/=";int l=0,t,i;a=a[0].split("\\|");for(String s:a)l=(t=s.length())>l?t:l;for(t=0;t<l;t++)b+="=";b+="=\\";p(b);i=a[0].length();p(String.format("| %"+(l+i)/2+"s%"+(l-i)/2+"s |",a[0]," "));b="|=";for(t=0;t<l;t++)b+="=";b+="=|";p(b);for(t=1;t<a.length;t++)p(String.format("| %-"+l+"s |",a[t]));b="\\-";for(t=0;t<l;t++)b+="-";b+="-/";p(b);}} ``` **With line breaks and tabs** ``` class a{ static<T>void p(T p){System.out.println(p);} public static void main(String[]a){ a=a[0].split("\\|"); String b="/="; int l=0,t,i; for(String s:a)l=(t=s.length())>l?t:l; for(t=0;t<l;t++)b+="="; b+="=\\"; p(b); p(String.format("| %"+(l+i)/2+"s%"+(l-i)/2+"s |",a[0]," ")); b="|="; for(t=0;t<l;t++)b+="="; b+="=|"; p(b); for(t=1;t<a.length;t++)p(String.format("| %-"+l+"s |",a[t])); b="\\-"; for(t=0;t<l;t++)b+="-"; b+="-/"; p(b); } } ``` ]
[Question] [ Given a floating point `x` (`x<100`), return [`e^x`](http://en.wikipedia.org/wiki/Exponential_function) and [`ln(x)`](http://en.wikipedia.org/wiki/Natural_logarithm). The first 6 decimal places of the number have to be right, but any others after do not have to be correct. You cannot have any "magic" constants explicitly stated (e.x. `a=1.35914` since `1.35914*2 ~= e`), but you can calculate them. Only use `+`, `-`, `*`, and `/` for arithmetic operators. If x is less than or equal to 0, output `ERROR` instead of the intended value of ln(x). Test Cases: ``` input: 2 output: 7.389056 0.693147 input: 0.25 output: 1.284025 -1.386294 input: 2.718281828 output: 15.154262 0.999999 (for this to output correctly, don't round to 6 places) input: -0.1 output: 0.904837 ERROR ``` Shortest code wins. [Answer] ## PHP ~~109~~ 107 bytes ``` <?for($g=1e4;--$g;$l=$y/$g+abs($y=$x>1?1-1/$x:$x-1)*$l)$e=1+$e/$g*$x.=fgets(STDIN);echo"$e ",$x>0?$l:ERROR; ``` \$e^x\$ is a fairly straight-forward calculation. I use a nested form of the sum of inverse factorials, which not only increases the convergence rate, but also allows for exponentiation at the same time: $$e^x = 1 + x \left( 1 + \frac x 2 \left( 1 + \frac x 3 \left( 1 + \frac x 4 \bigg( 1 + \dots \bigg)\right)\right)\right)$$ \$\ln x\$ is slightly more complicated. All convergent series seem to work for \$x \le 1\$ or \$x \ge 1 \$, but not both (Newton's iteration does not have this limitation, but requires the calculation of \$e^{x\_n}\$ each step). This isn't really a problem, though, given the log identity: $$\ln x = -\ln \frac 1 x$$ This means that if, for example, the iteration you're using only works on \$0 < x \le 1\$ and \$x > 1\$, you can use the multiplicative inverse of \$x\$ and negate the result. Because I was using a nested identity for \$e^x\$, I also chose to use a nested identity for \$\ln x\$: $$\ln(1 + x) = x\left(1 - x\left(\frac 1 2 - x\left(\frac 1 3 - x\left(\frac 1 4 - \dots \right)\right)\right)\right)$$ where \$0 < x \le 1\$ Or equivalently, as demonstrated by [Paul Walls' implementation](https://codegolf.stackexchange.com/questions/9080/calculate-ex-and-lnx/9097#9097): $$\ln(1 + x) = x - x\left(\frac x 2 - x\left(\frac x 3 - x\left(\frac x 4 - \dots \right)\right)\right)$$ I define the \$0 < x \le 1\$ case as \$x-1\$ (which is necessarily negative), using the absolute value for the inner product, and then allowing a bare \$x\$ value in the fraction to correct the sign. Sample I/O: ``` $ echo 2 | php exp_ln.php 7.3890560989307 0.69314718055995 $ echo 0.25 | php exp_ln.php 1.2840254166877 -1.3862943611199 $ echo 2.718281828 | php exp_ln.php 15.154262234523 0.99999999983113 $ echo -0.1 | php exp_ln.php 0.90483741803596 ERROR ``` --- ## Perl ~~95~~ ~~93~~ 89 bytes ``` $e=1+$e/$?*($x.=<>),$l=$_/$?+$l*abs,$_=$x>1?1-1/$x:$x-1while--$?;print"$e ",$x>0?$l:ERROR ``` Nearly identical to the PHP solution above, with a slightly larger iteration (`65535` down to `0`). Edits: * Both 2 byte improvements due to Paul Walls. * Four more bytes saved in Perl by (ab)using `$?`, which is stored internally as an unsigned short, and by using `$_` to save parentheses in `abs`. [Answer] ## Python 2 (168 char) basic implementation of power series I need to learn a golfing language =/ I increased the bound to 1e-14 (twice from 1e-7) since some values were off a bit in 6 decimal places, works well for input from 1e-5 to 100 (slows down at input approaches 0) ``` x=input();t,r,i=1,0,1. while abs(t)>=1e-14:t,r,i=t*x/i,r+t,i+1 if x<=0:s='Error' else:z=(x-1.)/(x+1);t,s,i=2*z,0,1 while abs(t/i)>=1e-14:t,s,i=t*z*z,s+t/i,i+2 print r,s ``` [Answer] ## Haskell, 166 (89 without I/O) ``` s=1e-7 e x|x>s=1/e(-x)|x>0=1+x|y<-e$x+s=y-y*s l x|x<1=0-l(1/x)|1>0=sum$map(s/)[1,1+s..x] n x|x<0="ERROR"|1>0=show$l x main=interact$unwords.(\x->[show$e x,n x]).read ``` Takes an alternative approach: we use that *∂/∂x ex* = *ex* and solve the differential equation numerically, with a simple euler method. Similarly, use ln *x* = 1*∫x* 1/*x* d‌*x* and calculate the integral with the rectangular method. Example: > > $ echo 2 | ./exp-and-log > > 7.389056835370484 0.6931472554471929 > > $ echo 0.25 | ./exp-and-log > > 1.284025432730133 -1.3862944228194163 > > $ echo 2.718281828 | ./exp-and-log > > 15.15426430695358 1.0000000576151333 > > $ echo -0.1 | ./exp-and-log > > 0.9048374135134576 ERROR > > > It's quite amazingly inefficient, in fact it uses about 4 GB of memory even for these examples (since it's non-tail–recursive... you need to compile (in GHC) with `-with-rtsopts=-K2G` so it even accepts such a ridiculous stack size). [Answer] ## JavaScript, 103 101 99 97 93 90 This implementation is based on primo's comprehensive description of the algorithm he used. ``` for(e=l=x=prompt(g=1e5);--g;y=x-1,l=(x>1?y/=x:-y)*l+y/g) e=1+e/g*x; alert([e,x>0?l:"ERROR"]) ``` Edit: - Trying to catch Perl. Stole a byte back from primo by copying his branch. :) - 2 more bytes courtesy of primo. - Finally, caught primo's version! With primo's help, of course... :) - Simplified the assignment to L. Shaved 3 more bytes. [Answer] # R (101 bytes) Note that $$e^{x} = \lim\_{n \to \infty}\left(1 + \frac{x}{n}\right)^n.$$ Then, for large enough n, we can approximate e by a product. ``` n=1e+08;prod(rep(1+x/n,n)) ``` Similarly, note that $$\log(x) = \int\_{1}^{x}\frac{1}{t}dt \leq \Delta t \cdot \sum \frac{1}{t+\Delta t}$$ ``` dt=0.1;sign(x-1)*sum((1/seq(min(1,x),max(1,x),by=dt))*dt)) ``` Combined into one **answer** (80 bytes): ``` n=1e+08;c(prod(rep(1+x/n,n)),sign(x-1)*sum((1/seq(min(1,x),max(1,x),by=1/n))/n)) ``` Will produce `-Inf` instead of `ERROR` in case `x < 0`. ``` [1] 7.3890560 0.6931472 [1] 1.284025 -1.386294 [1] 15.15426 1.00000 [1] 0.9048374 -Inf ``` --- Or, with the `ERROR` handling, `101 bytes`: ``` n=1e+08;gsub("-Inf","ERROR",c(prod(rep(1+x/n,n)),sign(x-1)*sum((1/seq(min(1,x),max(1,x),by=1/n))/n))) ``` ``` [1] "7.38905602540599" "0.693147188059945" [1] "1.28402541433558" "-1.38629438611989" [1] "15.154261581541" "1.00000000372749" [1] "0.904837420549773" "ERROR" ``` ]
[Question] [ Select any word from [https://websites.umich.edu/~jlawler/wordlist](https://websites.umich.edu/%7Ejlawler/wordlist) with length greater than 1. For each letter on that word, remove it and check if any rearrangement of the remaining letters is present in the wordlist. If it is, this rearrangement is a *child anagram* of the original word. For example, `theism`: * removing the `t` and rearranging `heism` gives nothing present in the wordlist * removing the `h` and rearranging `teism` gives **`times`**, **`items`**, **`metis`** and **`smite`** * removing the `e` and rearranging `thism` gives **`smith`** * removing the `i` and rearranging `thesm` gives nothing present in the wordlist * removing the `s` and rearranging `theim` gives nothing present in the wordlist * removing the `m` and rearranging `theis` gives **`heist`** Therefore, the child anagrams of "theism" are *"times", "items", "metis", "smite", "smith" and "heist"*. Note that this needs to be done only once: you must not apply the algorithm again to "times", for example. If the word contains any repeated letter, only a single instance of it must be considered. For example, the child anagrams of "lightning" are only *"tingling" and "lighting"* instead of *"tingling", "lighting"* (first *n* removed) *and "lighting"* (last *n* removed). In other words, remove child repeated anagrams. Ignore words from the wordlist that contain additional characters apart from letters, such as "apparent(a)", "gelasma/gr" and "half-baked". They will not be passed as input and should not be handled as a child anagram of any other word. ## Input A string of length ***l*** containing the word to be searched, where ***2 ≤ l ≤ 10***. This string is guaranteed of being on the wordlist and it'll not contain any characters apart from letters (no hyphens, all lowercase). You don't necessarily need to include the wordlist in your source code (compressed or not) nor fetch it every time from the network: you can assume it's provided by any [standard method](https://codegolf.meta.stackexchange.com/a/13143/91472) (e.g. as a function argument, as additional STDIN lines, as a predefined saved file, etc). ## Output All child anagrams of the input word. You may output a list/array of strings or output them using any separator. The output doesn't have to maintain the same order on each run, only the same elements. [Standard I/O](https://codegolf.meta.stackexchange.com/q/2447/91472) applies. ### Test cases ``` theism -> times,items,smite,metis,smith,heist lightning -> tingling,lighting learning -> leaning today -> tody,toad,toda response -> persons,spenser tongue -> genou,tonue,tongu code -> doe,deo,ode,cod many -> any,nay,mya,may,yam,man,nam interested -> something -> masculine -> ``` [Sandbox](https://codegolf.meta.stackexchange.com/a/26230/91472) [Answer] # JavaScript (ES6), 58 bytes *-22 (!) thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)* Expects `(dictionary)(word)`, where *word* is given as an array of characters. ``` d=>w=>d.filter(W=>w.sort().some(c=>w==[...W+c].sort()+'')) ``` [Try it online!](https://tio.run/##fVNNb4MwDL3vVyAuA82lP2Bil@2y@6Qeph4icCETSSqSbuLXd8@Grt2BcvAzcfz17HyZbxOb0R7TxoeWz4f63NYvP/VLWx3skHgsdvitYhhTUQIcF43Y68@qqnZPzX4xPT0@luW5CT6m7O399SOrs8/c@CmnvAktZMtBZGDIjn04AXu2MQFtYheBAxtvfSea7fo0q854lRLKcbJy0U0G0hunUiyoHfLIY0QJ0KJD0AV7wSP7yCO0ZB1HRd8Nc4oUTKvQmhkmBd@dZjxJpAnZ9s8PD9JjGLgaQlccCum1LISMPEk7Ls/w7csy224zTUXaHWlBpA2o3pN2vx5OKVA6ruHmiunCzh1nNuPse3FeuL1TPrqftPq/fCCChBsS27rnyPEIG1@TLXOghfV7SUEy33Kmu0FKOql13bmRoWe3FWO9CItGMBCs665OVvOfKw4Iq0RYLcKyEcYN9Dhz62GsxwvhmLjNlzCb9cvyeFJ/O9DNvQJjc8Kw@Xr5/As "JavaScript (Node.js) – Try It Online") ### Commented ``` d => // d[] = dictionary (array of strings) w => // w[] = word (array of characters) d.filter(W => // for each word W in d[]: w.sort() // sort w[] in lexicographical order .some(c => // for each character c in w[]: w == // is w[] equal to ... [...W + c] // ...W + c turned into an array .sort() + '' // and sorted in lexicographical order? ) // end of some() ) // end of filter() ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` WS¿⊙θ⬤⁺θι⁼№θμ№⁺ικμ⟦ι ``` [Try it online!](https://tio.run/##LZFNTsNADIX3c4pZTqRyAlYVYsGuEkvEoqoMYzGTUuyAOH3we6ZSPj@7jv9y6eevy/U89v2n65DantbPzZ/9S9f3tixV32o7rr/tdqjHMdppbAaty6E@3rbzsPZw3VZHbEYsHWbpoX4siOJXT1HQ24u@Lvf77l3UZpGpTlgRc5FZEPekhUFghtAQCmsJgXE8VtQjDYC0MkWcgLROCHWCOjJ0ChEuWk52jFGEsGIieCZBl4jJwzDPooyhT4DK@YojgqyOSUgEVMhJUMZwFksYa2VPLGBZ/H@KMD0ZDjY1bmqOemjIszlndMlYvOE5aZRwgn9gQ0a7EPgEnhd33BqQJBONjikcQKVkW9zOeTtXFgTDwTWk7Hff4w8 "Charcoal – Try It Online") Link is to verbose version of code. Takes the original word as the first line of input followed by the newline-terminated wordlist to search. Explanation: ``` WS ``` Loop through all of the words. (On the first pass this will actually be the original word but that won't match the condition so it doesn't matter.) ``` ¿⊙θ⬤⁺θι⁼№θμ№⁺ικμ ``` For each letter of the original word, check whether the current word plus that letter is an anagram of the original word. ``` ⟦ι ``` Output the successful match on its own line. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 63 bytes Python3 port of the Javascript answer. ``` lambda w,d:[i for i in d if sorted(w)in[sorted(i+c)for c in w]] ``` [Try it online!](https://tio.run/##VVC7bsMwDJybrxA0xSjbpUsRIP2RJINq0TYBixIkGoa@3qUcF0UHkUfxcUemKlPkj8@Ut@F632YXvr0zK/jLjcwQsyFDbLyhwZSYBf157YhvB6bXvmtFfStaH4/NUy8U2eV6tUIBC5BgKFCCeggo9MQTTEhFQIjHWR/MNE6yA3TcvERf1TjfkIOEuUTW5oRcMMOIHBdN8YLNjgv4iOAxQvQIffTguAK7CqE6COqrC@pZ/4J9L2kmOVuw3em0xuyLuRorTVN4SuFDS/4VoxMylqQaDsKdBdvICsSCmtWTQIm65dSagiv9osvhf7p2r0a5n6xRX04vKeuEc4vA2LcvC2Y4or@Ddt32Aw "Python 3.8 (pre-release) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 64 bytes ``` s`\w+(?<=^(\w+).*?) $&,$&,$1, /,\w+/_O`. L$`,(.*)(.*),\1.\2, $%` ``` [Try it online!](https://tio.run/##LZHBTsRACIbvPEc17Trppp41@wIm@wKN1gPJcBgPQuLjV/6fTTofP5QCQ3817Od7O08/9r@X@fb2/jmnWNbLbZHpueHZmlxbBq9f92OVj@lo83pZcNq@rftrk@npOM/oaj5EhwXhoh6qQxCPoqdBYKSwFAbrBYUJHBeLTAMgXYZqEJDeCaUuUGeGDSXSRcvBjjmKEi6uijMIukROnoZ5nmUcfRJUwU8CEWR1TEIiYEoOgjKH87yEs1b1xAW8ij@mSNOL6eCmzpt6oB4acm3BGUMrll9ETZolguAL3JDRrgR@QdTGA7sGtMhEp@MGBzCVaovdBXcXxoJgOtiG/gM "Retina – Try It Online") Link includes `theism` example compared against a selection from `/usr/share/dict/words` and therefore includes `emits` which isn't in the given wordlist for some reason. Takes the original word as the first line of input followed by the wordlist to search. Explanation: ``` s`\w+(?<=^(\w+).*?) $&,$&,$1, ``` To each word append a copy of itself and a copy of the first line of input, all words being terminated by commas. ``` /,\w+/_O`. ``` For each copy, sort its characters. ``` L$`,(.*)(.*),\1.\2, $%` ``` For each sorted word that's missing exactly one letter from the sorted first word, output its original word. [Answer] # [Perl 5](https://www.perl.org/) Algorithm::Permute, 88 bytes ``` sub{($_,$d,%r)=@_;s{.}{@s="$`$'"=~/./g;permute{$$d{$w=join'',@s}&&$r{$w}++}@s}ge;keys%r} ``` [Try it online!](https://tio.run/##bVTBcpswED2Xr9ixFRvGBCeHXqAk5NL20plOp9OL43EVIxu1gLAkwjCE/rq7EtjjtPGB2ff27Wq12nXFZP7@OK0Vg4d8LyTXWRGGX5ksas1gXg3GPIJpEARPtX5DFYajyvWAKyiFBvpMeU6fcga8BM1FIOsSlIBa8XIPOkPZVhQV1dxoTNqGtqBy0TAJqn7CMKUZTUPHgDE9uLPHxIPOAShal@x8Qr042UQWQ0LjhNAT4BDDTRCQqWWajOfMvfVMKMCM7CJroJBUKCRTDi8vkFOlB8f1NfIjMwQD4StSXd@u4W4w14OyqlWGp/kg2TOT2ERV5XzLLFW05BCTahAuFuTwdqrDmCoZaB8JrMmgg291o5vgBekq4Rb3zomJnN4xF9nFR@xV55KNT1L/StrWqC7ou0TFE/KTzCfxn2Ww3EdjOztC0o408S/By/ncT1Q/mxGJTL9Y9Ij2LPrNWnUl@2PkmPn4zpQOwy9CssicmGjECkt1bX0rfFbGVQHxHRwaFwzQwDUrFBRM44urApH9ZjgTBVPgwdofg3O@z3RppmOM12jnBluPMS7VjMpLMeLyH4kWKY7UKZlIW/zQ1NKXMslUJUq83ajE5ijE@I4MWfk6Y7mvz8I9K0VtOKSs51K6FelZmAoGKRNgKOQvZQUtzyUas8SKi5Yi30JLC@NHrrgM4aVmWLNm6Snw0qsEtjq7aMzr09S2xpay/52efdGrRsjUvGhBK@gAR8kobz3oIXn49ukH3ONlOhDYGrs7Hz/7oDK@05GNWD42i@U9mYU3PnxA5x3GhdaT4FCO8xI5OyHdwR730SwzL6tao6ahpfbM@JPNeUeTPf6jxGZtXTgJH8davUHF1SZlrMpbF1ZKSG1j1j4472D4jaxJj1c@sRObLRyzImH84SBDhDlCm2lizumdVJRsYyrHBkfHvw "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ṣe¥ƇṢ-Ƥ} ``` A dyadic Link that accepts the word list on the left and the word on the right and yields a list of the child anagrams. **[Try it online!](https://tio.run/##y0rNyan8///hzkWph5YeawfSh3bqHluiUvv/8HLv//@jlRKVdBSUEgsKclJBjIzUzOISOKMYxMosSc2F0WCB3NSSTDCjGCgEpnMzc2AMuEhJBohRAjInF8EqhjMRrAowKzM3FSIE1JuRqhT7H6YXAA "Jelly – Try It Online")** (using a reduced word list with some made-up edge cases for the "theism" example). ### How? ``` Ṣe¥ƇṢ-Ƥ} - Link: list of lists of characters, WordList; list of characters, Word } - using the right argument, Word: -Ƥ - for overlapping outfixes of length Length(Word)-1 Ṣ - sort -> e.g. Word="order" -> ["derr", "deor", "eorr", "dorr", "deor"] Ƈ - {Wordlist} filter keep those for which: ¥ - last two links as a dyad - f(CandidateWord, Outfixes): Ṣ - sort {CandidateWord} e - exists in {Outfixes}? ``` [Answer] # Google Sheets, 161 bytes ``` =let(_,lambda(w,join(,sort(mid(w,sequence(len(w)),1)))),l,len(B1),j,sequence(l),ifna(filter(A1:A,match(map(A1:A,_),map(sort(left(B1,j-1)&mid(B1,j+1,l-j)),_),)))) ``` Paste the dictionary in cells `A1:A`, or add enough blank rows and put this formula in cell `A1`: ``` =importdata("https://websites.umich.edu/~jlawler/wordlist") ``` Put the search string in cell `B1` and the formula in cell `C1`. ### Commented ``` // function that sorts letters into alphabetical order; _("code") → cdeo _, lambda(w, join(, sort(mid(w,sequence(len(w)),1)))), // generate sequence 1,2,3..l l, len(B1), j, sequence(l), // "code" → ode, cde, coe, cod → deo, cde, ceo, cdo n, map(sort(left(B1, j - 1) & mid(B1, j + 1, l - j)), _), // show words where _(word) appears in n ifna(filter(A1:A, match(map(A1:A, _), n, ))) ``` ### Results | A1 | B1 | C1 | | --- | --- | --- | | a | theism | heist | | a-horizon | | items | | a-ok | | metis | | aardvark | | smite | | aardwolf | | smith | | ab | | times | | aba | | | | abaca | | | | abacist | | | | aback | | | | ... | | | [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` æ¤g<ù€œ˜Ã ``` Takes the dictionary-list as additional input. [Try it online.](https://tio.run/##LY0xDsIwDEV3jtGZI3ATxGCIlUaq7apJh6xwBFZGxMQFulIxcQsuEuyE5b0v@etbIhwDlrI@Xne/W5fv@fm@fm7rpZTUY4i02XfAudt2J3FKh2IUVHpkmdXWS@qQkKJ6QODA3lLwfWqRgCttijAFK1IGJQNV2kWcDY84RWFrRNLRv3vziBxx0pQCYaxmP7QXScBVOWjKVezn5tmWsn47/AA) (It's too slow for a test suite of multiple test cases. The example dictionary-list is taken from *@Arnauld*'s answer.) **Explanation:** ``` æ # Get the powerset of the first (implicit) input-string ¤ # Push its last item (without popping), which is the first input itself g # Pop and push its length < # Decrease it by 1 ù # Keep all powerset strings of that length (inputLength-1) € # Map over each remaining string: œ # Get all permutations ˜ # Flatten it à # Only keep those values from the second (implicit) input-list of words # (after which the resulting list is output implicitly) ``` ]
[Question] [ This is the robbers' thread. See the cops' thread [here](https://codegolf.stackexchange.com/questions/264047/magic-oeis-formulae-cops-thread). In this cops and robbers challenge, the cops will be tasked with writing an algorithm that computes some function of their choice, while the robbers will try to come up with their algorithm. The catch is, the 'algorithm' must be a *single* closed-form mathematical expression. Remarkably, a function that determines whether a number is prime has been [shown](https://codegolf.stackexchange.com/questions/170398/primality-testing-formula) to be possible using only Python operators. ## Robbers Your goal as the robber is to crack the cops' submissions. To begin, pick any submission from the cops' thread that isn't marked as *safe* and is less than a week old. The submission should contain an OEIS sequence and a byte count representing the length of the intended expression. To submit a crack, write a single closed-form expression that takes an integer `n`, and provably computes the `n`th term of this sequence. You only need to handle `n` for which the sequence is defined. In addition, pay attention to the offset of the OEIS sequence. If the offset is `0`, the first term should be evaluated at `n=0`. If the offset is `1`, it should be evaluated at `n=1`. The specification for the closed-form expression is described in detail in the cops' thread. Your expression must be **at most twice** the length of their expression to be considered a crack. This is to ensure that you can't crack their submission with an overly long expression. Bonus points if you are able to match or reduce their byte count. ## Scoring Your score is the number of answers you have cracked, with more cracks being better. ## Example Crack > > ### [A000225](https://oeis.org/A000225), 6 bytes, [cracks @user's answer](https://www.youtube.com/watch?v=dQw4w9WgXcQ) > > > > ``` > 2**n-1 > > ``` > > [Answer] # [A000120](https://oeis.org/A000120), 86 bytes, [cracks @xnor's answer](https://codegolf.stackexchange.com/a/264054/92727) ``` 4**n**2*2**n/(2*4**n-1)*(4**n**2*2**n/(2*4**n-1)&4**n**2/(4**n-1)*n)>>2*n*n-n-1&2**n-1 ``` [Try it online!](https://tio.run/##dYpBDsIgFETX7Sn@qoUfaoF01YSexA3VoiT6aSguPD1ioytjZjPz5q3PdA2kszM3e5/PFmg85gGREHUJUs80vnenOLI/R/PhPfuaxKdJF0ZdmY3eaXYhggdPEC1dFqYEKCklH@vKbtsSEzjmORgDs6fSDqfwoMRa1fK6WqOnBF7sjvg18gs "Python 2 – Try It Online") I was hoping I could do something with \$v\_2(\binom{2n}{n})\$, but it was too long because I needed to copy the expression for \$\binom{2n}{n}\$ multiple times, so I just used bitwise operators to separate the bits of \$n\$, and then using multiplication we can count the number of \$1\$s. [Answer] # [Python 2](https://docs.python.org/2/), 161 bytes ``` (((8**n**2/(8**n-1)**2*(8**n**4/(8**n**2-1)**2)+8**n**4/(8**n-1)*(8**n/2-1-n)&~(8**n**4/(8**n-1)*(8**n/2)))+8**n**4/(8**n-1)>>n*3-1)&8**n**4/(8**n-1))%(8**n-1)+1 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZpuTmJuUkqiQZ6UQ819DQ8NCSytPS8tIH8zQNdQEsrWggib6MFmIuKY2ijhIEMzQB8rr5mmq1WngktfUxNRrZ5enZQyk1dAlNFVhLG3D/wVFmXklChppGkBxLjjHCJljjMwxQeaYInPMkDnmQM5/AA "Python 2 – Try It Online") <https://codegolf.stackexchange.com/a/264066/76323> [Answer] # [Python 2](https://docs.python.org/2/), 29 bytes ``` 4**(n*-~n)%(16**n+~4**n)%4**n ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZpuTmJuUkqiQZxXz30RLSyNPS7cuT1NVw9BMSytPuw4oBOSByP9p@UUKeQqZeQpFiXnpqRqGBgaaVlwKBUWZeSUKaRp5mv8B "Python 2 – Try It Online") Cracks [Command Master's Fibonacci numbers](https://codegolf.stackexchange.com/a/264075/20260) [A00045](https://oeis.org/A000045) with `/` banned. [Answer] # [Python 2](https://docs.python.org/2/), 25 bytes ``` (1<<2*n*n-2)%((4<<2*n)-3) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGaNNucxNyklESFPKuYpaUlaboWOzUMbWyMtPK08nSNNFU1NEzAPE1dY02I_E2ltPwihUyFzDyFosS89FQNQx0jA00rLoWCosy8Eo00jUxNqMoFCyA0AA) cracks [@xnor's powers of 3](https://codegolf.stackexchange.com/a/264094/107561). [Answer] # [A007953](https://oeis.org/A007953), 151 bytes, [cracks @dingledooper's answer](https://codegolf.stackexchange.com/a/264137/92727) ``` 10*n+((10**n*16**n**3/(10*16**n**2-1)*((n*16**n+~n)*16**n**2+1)/(16**n-1)**2+16**n**3/(16**n-1)*(16**n/2+~n)>>4*n-1&16**n**3/(16**n-1))%(4**n-1)-n*n)*9 ``` [Try it online!](https://tio.run/##ZY3NDoIwDMfP8BS9aNoBgSExkQSexMuMoEukkG0evPjquAnqwUvb3/8jnR7uOnI5981NDaezAq6PsywEJ4h@CRZyH6bY5YFXKDNJAnE1kyfT10kk@WSAkAn863/U5crLUGzbKojb/xhtsFqujIX/cJj70YAGzWAUXzqUKciioDqOlLWdcdCjJmgasPcBBzWhZpdaZ7xKFEeT8Qw6fcfmFw "Python 2 – Try It Online") Uses the formula (for \$d=10\$) $$s\_{d}(n) = d n-(d-1)\sum\_{k=0}^\infty {\left\lfloor \frac{n}{d^k} \right\rfloor}$$ calculating the sum by counting the numbers which can be formed as \$a 10^b\$ with \$1 \leq a \leq n\$ and \$0 \leq b \leq n\$ and are less than \$n\$ (for each particular \$b\$, there will be \$\left\lfloor \frac{n}{10^b} \right\rfloor\$ such numbers). At first I tried to calculate it with a smarter approach, by looking at \$\sum\_{i=0}^n {(10^{2n-1})^i n}\$ and then reinterpreting it as a base \$10^{n}\$ number, but while the even digits sum to the number you want, the odd digits have junk and you can't use bitwise operators to get rid of it since the base isn't a power of two. [Answer] # [Python 2](https://docs.python.org/2/), 206 bytes ``` (((~16**k)**2-(((8**(4*k<<8*k)/~-8**(4*k<<4*k)*(8**(4*k*(16**k+2))/(~-4096**k)**3)+8**(4*k<<4*k)/~-4096**k*(8**(4*k<<8*k)/~-8**(4*k<<4*k))**3>>8*k-1)&(8**(4*k<<8*k)/~-4096**k))%~-4096**k))*5**~-k>>7*k-1)%10 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMHWtPwihWyFzDwFDUMdI02rgqLMvBKNpaUlaboWN89paGjUGZppaWVramkZ6QJ5FlpaGiZa2TY2FkAx_TpdON8EpAYmraUB1qRtpKmpr1Gna2JgCTXDWFMbRYc-XFILv9EgvXZ2QBldQ001DKUwCzRVkdhaplpadbrZdnbmYF2qhgYQXy3UhNALFkBoAA) cracks [@Command Master's decimals of pi](https://codegolf.stackexchange.com/a/264195/107561) (I think) Times out at k=3, so I couldn't really test it that much. It makes an ortho grid and counts points outside a circle of radius R=16\*\*k with centre just between grid points. I have no proof but as the error is O(1/R) this should converge faster than 1 digit per step. [Answer] # [Python 2](https://docs.python.org/2/), 6 bytes, cracks @The Empty String Photographer's answer `999>>9` [tio](https://tio.run/##K6gsycjPM/r/v6AoM69Ew9LS0s7OUvP/fwA) [Answer] # [Python 2](https://docs.python.org/2/), 157 bytes ``` ((128**(N*~-(2*10**~-N))/~-128**N*2*(16*128**~-N-100**~-N)+128**(N*-~(2*10**~-N))/(~-128**N)**3*-~128**N)>>7*N-3&128**(N*~-(2*10**~-N))/~-128**N)%~-128**N%10 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGutPwiBT-FzDyFosS89FQNQx1LTauCosy8Eo2lpSVpuhY352poGBpZaGlp-GnV6WoYaRkaaAEZfpqa-nW6YAk_LSMtDUMzLTAHKKNraABVog3TqFuHolEDplNTS8sYKAnl2NmZa_npGqsRsE5TFcZSNTSAOHKhJoResABCAwA) cracks @CommandMaster's [decimals of \$\sqrt 2\$](https://codegolf.stackexchange.com/a/264458/107561) Updated using a suggestion by @CommandMaster. Works by counting integer squares below 2,200,20000,2000000,... ]
[Question] [ # Challenge Make a triangle of numbers like below. # How to? Let say we get a numbers in the form of ab, for example `12`. We then create a triangle like below: [![Sorry for bad drawing!](https://i.stack.imgur.com/tLjh7.png)](https://i.stack.imgur.com/tLjh7.png) Sorry for my bad drawing! First we have `12`, and we take sum of the two numbers `1` and `2`, which is `3`. In case the sum of two numbers are greater than 9, we just take the second number from the sum. For example if we have `49` then the sum will be `4+9=13`, we just take 3. `12` is the number we input, which is line 1, `3` - its sum, is line 2. We now create line 3 by cross-adding. For example, Line 1 contain `12` is split to `1` and `2`, line 2 contain 3, so the line 3's first element will be the second element of line 1 plus line 2, and the second element of line 3 will be the first element of line 1 plus line 2. And remember, if the sum is greater than 9, just take the second number of the sum just like explained. Now we come to line 4: the first element of line 4 now is calculated by line 2 plus the first element of line 3, and the third element of line 4 is line 2 plus the second element of line 3. The second element of line 3 - the middle, is the sum of all element in the previous line, which is line 3. Now we come to line 5. Like line 4, the first and the last element of line 5 is calculated by the line 3's first element plus line 4 is first element and line 3's last element and line 4's last element. And the middle element of line 5, of course is the sum of all element in line 4. Now come to the second and the fourth element. You may notice that line 4 started to have the *middle element*, and the line 5's second element is just line 3's last element plus that middle element, and the line 5's fourth element is line 3's first element plus that middle element. Line 6 is the same as line 5. And from now on, all the line just has 5 elements :) # Rule * The integer ab will be a positive integer and contain only two digits (from 10 -> 99) Program will let user input two line: the first line is the ab number, and the second line is the number of lines they want to output. * The program will output the triangle as a bunch of numbers. See the example in the Output section below. * The number of lines will always be greater than or equal to 5. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! # Output example If we input: ``` 12 6 ``` It should print out: ``` 12 3 54 897 33441 11528 ``` Have fun and good luck! ## Note that I will select the winner after 4 more hour since the time edited. [Answer] # [Python 3](https://docs.python.org/3/), ~~195~~ ~~184~~ 181 bytes -3 bytes thanks to [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush)! Based on OP's code ``` def f(a,b):w=a//10;s=w+a;t=[[w,a],[s],[a+s,s+w],[2*s+a,s*3,2*s+w]];exec('*_,(x,*_,z),y=t;Y=y[len(y)//2];r,*t=t+[[x+y[0],z+Y,sum(y),x+Y,z+y[-1]]];print(*[x%10for x in r],sep="");'*b) ``` [Try it online!](https://tio.run/##FYztCsIgGIVvRQYxP95wbr9KvJAhEq4cBeXGNNTd/LIf5/DwHDhric/FD8fxcDOasYWJXJOynItOBpWYlVFpncAa0KHGsgCBpUo9DcxCoAP8KRkjXXZ33NIb4Ay1dwJFRTmqot/O40I4743cgEYVmdaZFd0Z2NkI4fupM@SKe7VnYerbur18xFTnk@jmZUMZvTzaDAS3qqYhsqUTOWYsekAXcvwA "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 102 bytes ``` ≔I⪪⮌S¹θ⊞υ⮌θ⊞υ⟦Σθ⟧≧⁺Σθθ⊞υθ≔⁺§υ¹θζ≔Eζ⁺ι§ζ⊕κη⊞υη≔ηζF⁻N⁴«≔⁺⊞OEθ⁺κ§ηλΣζEθ⁺κ§η⊕λζ⊞υζ≔Φη¬﹪λ²θ≔Φζ¬﹪λ²η»Eυ⭆ι﹪λχ ``` [Try it online!](https://tio.run/##dZFNa4QwEIbP66/IcQIp1KX0sqelUPDgVtZj6cFqasLGqPlYiqW/3SZR0ZbuJSQz77zzTKZkhSrbQozjUWteS3gqtIG8E9zAmV6p0hQS2VmTG8VlDRgTFPujx4cos5qBJWgR9ngTfM1t4yJvLpQW3eR@5jUzkAmrCZrSv438febwIjiaRFb006fiICVoWCXOFgaCgpITtIhdKJGlog2VhlZwwdjzsk0btnqwyfGjVQhSLp1TmPZkm3eqwNU9YIy@ot2Wytu8dFQVplUBop8hLiuE8xWhrx9z8Jfbwi2tL8LzmLuFNzxmgmcujCNzZafWQNpWVrQgCNrjZSt/lMP/Sv8H31HmlmrCDK7NtGL/cL@56uN7j3QYx3gfPY53V/ED "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔I⪪⮌S¹θ ``` Input the two digits, reverse them, split them, and cast to integer. ``` ⊞υ⮌θ ``` Push the reverse of this (i.e. the original integers) to the list of results. ``` ⊞υ⟦Σθ⟧ ``` Push the sum as a list to the list of results, giving the second row. ``` ≧⁺Σθθ ``` Add the two together, giving the third row. This is also the first row that takes part in diagonal calculations. ``` ⊞υθ ``` Push this to the list of results. ``` ≔⁺§υ¹θζ ``` Concatenate the second and third rows. ``` ≔Eζ⁺ι§ζ⊕κη ``` Rotate the result and add it elementwise to produce the fourth row. This is also the second row that takes part in diagonal calculations. ``` ⊞υη ``` Push this to the list of results. ``` ≔ηζ ``` This is also the last result so far. ``` F⁻N⁴« ``` For the remaining rows... ``` ≔⁺⊞OEθ⁺κ§ηλΣζEθ⁺κ§η⊕λζ ``` Calculate the diagonal sums before and after the sum of the previous row, thus producing the next row. ``` ⊞υζ ``` Push this to the list of results. ``` ≔Φη¬﹪λ²θ≔Φζ¬﹪λ²η ``` Shift all the rows back one, removing elements that do not participate in the diagonal sums. ``` »Eυ⭆ι﹪λχ ``` Output just the last digit of every element. [Answer] # Python 3, ~~517~~ ~~501~~ ~~410~~ 408 bytes -32 bytes thanks to mypetlion -3 bytes thanks to Dion After fixing a bunch of bugs :), i come up with this: ``` a=int(input());b=int(input());t=[[a//10,a%10]];t.append([(t[0][0]+t[0][1])%10]);t.append([(t[0][1]+t[1][0])%10,(t[0][0]+t[1][0])%10]);t.append([(t[1][0]+t[2][0])%10,(t[2][0]+t[2][1])%10,(t[1][0]+t[2][1])%10]) for i in range(4,b):x=t[i-2];y=t[i-1];t.append([(x[0]+y[0])%10,(x[-1]+y[len(y)//2])%10,sum(y)%10,(x[0]+y[len(y)//2])%10,(x[-1]+y[-1])%10]) for i in range(b): for j in t[i]:print(end=str(j)) print() ``` Input and output: ``` D:\Data\dev>python codegolf1.py 12 6 12 3 54 897 33441 11528 ``` The first `12` and `6` is the input, all other number is output. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 54 bytes ``` .ị+U,$€Ḣ$}Ṛṭ@FṖS;`ʋ “½“¿“€“ç!‘Dṫ-ç@/ṭƊ⁸¡EÐḟUṚ;@Ʋ€ḋ%⁵ḣ⁸ ``` [Try it online!](https://tio.run/##y0rNyan8/1/v4e5u7VAdlUdNax7uWKRS@3DnrIc71zq4Pdw5Ldg64VQ316OGOYf2goj9QAKoCkgeXq74qGGGy8Odq3UPL3fQB6o/1vWoccehha6HJzzcMT8UaIa1w7FNYCO7VR81bn24YzFQ/v///2b/DXWMAA "Jelly – Try It Online") A set of links taking the left argument as the number of rows and the right as the initial integers. Returns a list of lists of integers. If the IO is inflexible, [here](https://tio.run/##y0rNyan8/1/v4e5u7VAdlUdNax7uWKRS@3DnrIc71zq4Pdw5Ldg64VQ316OGOYf2goj9QAKoCkgeXq74qGGGy8Odq3UPL3fQB6o/1vWoceehha6HJzzcMT8UaIa1w7FNYCO7XapVHzVufbhjceT///8Njf6bAQA) is a solution for 56 bytes that takes the arguments in the opposite order, the starting point as a single integer and prints the number triangle to STDOUT. ## Explanation ### Helper link Take the previous line on the left and the last but one on the right and generate the next line ``` .ị | Last and first items in the most recent line + $} | Add to the following applied to the last but one line: U,$€ | - Pair a reversed version of each list member to itself Ḣ | - And then just take the first of these Ṛ | Reverse order ṭ@ ʋ | Tag on the following (effectively applied to the previous line) F | - Flatten Ṗ | - Remove last S | - Sum ;` | - Concatenate to itself ``` ### Main link ``` “½“¿“€“ç!‘ | [[10],[11],[12],[23,33]] D | Convert to decimal digits [[[1,0]],[[1,1]],[[1,2]],[[2,3],[3,3]]] Ɗ⁸¡ | Repeat the following the number of times indicated by the original left argument ṫ- | - Take the last two list members ç@/ | - Call the helper link using the last line as the left argument and the penultimate one as the right ṭ | - Tag the new line onto the end of the list Ʋ€ | For each line: EÐḟ | - Filter out items where both members of the list are equal U | - Reverse each list member Ṛ | - Reverse order of list members ;@ | - Concatenate to existing list ḋ | Dot product with starting integers %⁵ | Mod 10 ḣ⁸ | Take the number of lines indicated by the original left argument ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 53 bytes ``` ЈO©D¸ˆ+ˆ®+®3*ªÀ©ˆI4-F®н®ÅsD®Os®θ)¯¨θ‚€н0ª5∍+©ˆ}¯T% ``` [Try it online!](https://tio.run/##AWoAlf9vc2FiaWX//8OQy4ZPwqlEwrjLhivDgsuGwq4rwq4zKsKqw4DCqcuGSTQtRsKu0L3CrsOFc0TCrk9zwq7OuCnCr8KozrjDguKAmuKCrNC9MMKqNeKIjSvCqcuGfcKvVCX//1sxLCAyXQo5 "05AB1E – Try It Online") This uses lists of digits as I/O, [56 bytes](https://tio.run/##AWoAlf9vc2FiaWX//1PDkMuGT8KpRMK4y4Yrw4LLhsKuK8KuMyrCqsOAwqnLhkk0LUbCrtC9wq7DhXNEwq5Pc8Kuzrgpwq/CqM64w4LigJrigqzQvTDCqjXiiI0rwqnLhn3Cr1QlSsK7//8xMgo5) with the format in the challenge. The output is built row by row in the global array: ``` Ð # push three copies of the input [w, a] ˆ # append one copy to the global array O© # take the sum s=w+a and store it in the register D¸ # duplicate s and wrap in a list ˆ # append [s] to the global array + # add s to each [w, a]  # duplicate and reverse the copy ˆ # append [a+s, w+s] to the global array ®+ # add s to [w+s, a+s] ®3* # push 3*s ª # append: [w+2*s, a+2*s, 3*s] À # rotate left © # store in the register, from now the register always stores the last row ˆ # append [a+2*s, 3*s, w+2*s] to the global array I4- # push second input - 4 F } # iterate this many times ®н # get the first value of the last row y ®Ås # middle value of last row ®O # sum of last row D s # middle value again ®θ # last value of last row ) # wrap all these numbers into a list [y[0], y[m], sum(y), y[m], y[-1]] ¯¨θ # push second-to-last row of global array (x) ‚ # pair with its reverse [x, x[::-1]] €н # push first element for each [x[0], x[-1]] 0ª # append a 0 [x[0], x[-1], 0] 5∍ # extend to length 5 [x[0], x[-1], 0, x[0], x[-1]] + # add both lists element-wise [y[0]+x[0], y[m]+x[-1], sum(y)+0, y[m]+x[0], y[-1]+x[-1]] ©ˆ # save new row in register and add to global array ¯ # push the global array T% # each number modulo 10 ``` [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 226 bytes ``` R=readline v=R() h=(n,k=--n<4?n:5,g=(i,j,s=`1 12 233 35845 51508`.split` `[i])=>s?s[j]*v[0]+v*s[(i<3?i:4)-j]:j-2?g(i-2,j%3*4)+g(i-1,j&4|j%2*2):(v- -v[0])*'093859835433'[i%12])=>k--?h(n,k)+g(n-1,k)%10:n?h(n)+` `:v print(h(R())) ``` [Try it online!](https://tio.run/##FY/NaoQwGEX3eYpu7CQxKfkFJ0zqO8xWBKUj4xenqRgJFPru1izvhcM9N4x5TF8brDtPKzym7fsnLtPvcdz9No2PF8QJZX/HBM0eR7Z4zuPNtNFZ9vQYWGDJDxJJhZTWSNvGWGSlFc3wkdYX7AMaOuiJ/0xt6kJPcyf6OtPUYbjpFpwhPPQucNU@MXDFQqWpIXUJkoV38xcqRRVxOPM3XmBCL@KqG3tttDVaXzqopCoDC@ftXBQLHU96IZUULpaS1KeHy2jdIO54xucfQo6jWIt/ "JavaScript (SpiderMonkey) – Try It Online") [Answer] # JavaScript (ES6), ~~203~~ 198 bytes Expects `(N)(n)`, where `N` is the initial number as a string and `n` is the number of lines. ``` N=>n=>(s=7,g=k=>k<n?`${F=n=>n>k-2?k-n:F(++n)+F(++n),A=[d=s+F(1),b=F``,c=s+F(2),s+=a,a=F(-1)],[41,1,14,134][k]||10324} `.replace(/./g,n=>(A[n]*N[0]+A["24031"[n]]*N)%10)+g(k+1,a+=k>3?b+c+d:b):'')(a=0) ``` [Try it online!](https://tio.run/##JY7NSsQwFEb3PkZRJndy20naiFC8Kd10OS8QAk1/pmhKOkzEjeOz16h8i8M5q@/dfbo43t6uH3nYpnm/0H4mHUizSC@4kCftX0PTP351lGrQPi8bn4e6Y5wH4P/AlsxEMZkEHKjrexz/tASMnBw66lguwaJREtMUykpZ4@39LkVVqu@HvrjN19WNMzsVpwV/H7Qm2OPZCMtbk5VKVDJLJSV4kgL4wjyX6Dh5XTUDH/lUD1AfDsAcCdjHLcRtnYt1W9iFZbLMgMlngP0H "JavaScript (Node.js) – Try It Online") [Answer] # [Julia 0.7](http://julialang.org/), ~~162~~ ~~159~~ ~~153~~ ~~148~~ 144 bytes -6 bytes from [ovs's answer](https://codegolf.stackexchange.com/a/229374/98541) ``` !x=x.%10 ~L=L[end] (a,b)$n=.![(a,b);c=a+b;((b,a).+c,(b,c,a).+2c)>n] (l,L)>n=n<3?l:[l;(L,(l[1]+L[1],(N=L[end÷2+1])+~l,sum(L),N+l[1],~l+~L))>n-1] ``` [Try it online!](https://tio.run/##JcxBCsIwFATQfU/RQoUf8i2mLkRr6gVCLxCySFMXlW8QSqGC5FoewIPFWDfDW8zMbabRHmIsFrlUG7HLgpJKX/1gMrDYs9LLqtArGyct7xuAHi2ruMMEt7J2rPVpQKgSpD/vL3TS1IBCIC0MVykQuv/z511zYRgPhNN8B8Ww478WBuJBsfSwFSaCwJqVx/zV5sM4Pcg@4xc "Julia 0.7 – Try It Online") takes the initial number as 2 numbers and output is a list of tuples [+10 bytes with stricter I/O](https://tio.run/##JcxBCoMwFEXRuatQsPBDfsXYQWlt7AaCGwgZJNqBkqYFESyUbMsFuLA0bSePM3jccbaDPoaQLXx8DA6WYsdKknjBhby5XiUmd7zIpJSam21lJRql6o5ramoAg5oUtMOI7seqI41TCVgUEdxdDld7lrYGgWAlU1TEQWj/9W2tKFOEeovTfAdBsKXfF3pLvSCxsGcqsCo/pe8m7YfpafUrfAA "Julia 0.7 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~295~~ ~~292~~ ~~289~~ ~~281~~ 272 bytes ``` a,b=map(int,input()) e=[[a,b],[a+b],[b+a+b,a+a+b],[3*b+a+a,3*a+3*b,3*a+b+b]] for i in range(3,int(input())-1):f=e[i];e.append([e[i-1][0]+f[0],e[i][len(e[i])//2]+e[i-1][-1],sum(f),f[len(f)//2]+e[i-1][0],e[i-1][-1]+f[-1]]) for i in e: for j in i:print(j%10,end="") print() ``` [Try it online!](https://tio.run/##VU7LDoMgELzzFcSkCchaX0kPNn4J4YAptJiKxOqhX28XtWl6YHaHmZ1MeM@P0dfrqqFrBx2Y8zM4H5aZcU5MKyUKCqQWETuBE7TYWZ1GrqFOtcB9mx0qithxoo46Tyft74bVmDizb2pW8sa2Rjp1NWcdgvE3JpFmpZKFEhYBoiqfxrO48DyvlDgc@OC1DMxysJvD/sn77WHELETFf31MQ2gkfSSuCVMs1p/KArBFmySc0P2Pr2tZkcsH "Python 3 – Try It Online") -11 bytes thanks to @raspiduino -9 bytes thanks to @MarcMush [Answer] # [Haskell](https://www.haskell.org/), 205 bytes ``` l=last x%y|m<-y!!div(length y)2=x:y%[x!!0+y!!0,l x+m,sum y,x!!0+m,l x+l y] a#b|s<-a+b=[a,b]:[s]:[s+b,a+s]%[3*s-a,3*s,3*s-b] main=do[a,b]<-getLine;n<-readLn;mapM(putStrLn.map(l.show))$take n$read[a]#read[b] ``` [Try it online!](https://tio.run/##HYpLCoMwGIT3niJSBW0SaS10UfUGdtVlyOIPBhWTtJjYGvDuVl18M8yjAztIpdZVVQqsC@bYL7qkPgyb/psoaVrXIZ/m1fzwMZvD8IK37UIUmrEmdtLIk6PVR6WQ5wGcxGJLClhUDIjgD2Z3sCCALY/Z7WwpkE13qOCBht5Uzfs4l7SVru6NLExJRwlNbQoNn2fymdzLjbXJtpSozHbvX5pGDgaJTLQfGfDT4YKv6zUP7n8 "Haskell – Try It Online") ]
[Question] [ ## Input A string S of length between 10 and 16 inclusive. The characters are taken from the 95 printable ASCII characters, byte values `32` (`0x20`) to `126` (`0x7E`) ( to `~`) ## Output Your code must compute and output all strings within [Levenshtein](https://en.wikipedia.org/wiki/Levenshtein_distance#:%7E:text=Informally%2C%20the%20Levenshtein%20distance%20between,considered%20this%20distance%20in%201965.) distance 2 of S. You can have duplicates as long as you also have all the different strings and the output can be in any order. ## Scoring I will generate a set of 5 strings of random lengths between 10 and 16, each consisting of a selection of printable ASCII characters. Each answer will be tested on the same set of strings, and your score is the total runtime over all 5, when run on my computer (spec details below). This means you need to give me simple and complete instructions on how to compile and run your code in Linux. ## Example Input string `obenquillo`. Using my test code the first output string is `8benquifllo` and the last is `o^be9quillo`. There are 1871386 different strings in the output. ## My PC I have an AMD Ryzen 5 3400G running Ubuntu 20.04. ## Winning The fastest code wins. # League table * My test Python code. 14.00s * **C++** by the default. 0.15s. Bounty awarded. * **C** by ngn. 0.07s * **Python** by ReedsShorts sped up by ovs. 10.5s * **Rust** by wizzwizz4 . 2.45s [Answer] # C ``` cat >a.c <<. #define _(a...) {return({a;});} #define F(i,x,n,a...) for(I i=(x),n_=(n);i<n_;i++){a;} #define i(a...) F(i,0,a) #define j(a...) F(j,0,a) #define k(a...) F(k,0,a) #define I(a...) F(i,a) #define S static #define O const #define mc __builtin_memcpy #define sl __builtin_strlen typedef void V;typedef char C;typedef int I; #include<sys/syscall.h> #define M1(x) #x #define M2(x) M1(x) #define h(x,a...) ".globl "#x";"#x":"a"mov $"M2(SYS_##x)",%rax;syscall;ret;" asm(".globl _start;_start:pop %rdi;mov %rsp,%rsi;call main;"h(write)h(exit));I write(I,C*,I);V exit(I); V*memcpy(V*x,O V*y,I n)_(C*a=x;O C*b=y;i(n,a[i]=b[i])a)I strlen(O C*s)_(I r=0;while(*s++)r++;r) S O C A0=32,A1=126+1,AN=A1-A0;S C o0[1<<20],*o=o0; S V rpt(C*a,I n,I m){m*=n;while(2*n<m){mc(a+n,a,n);n+=n;}mc(a+n,a,m-n);} S I fd(C*s,I n,I p)_(i(p,j(n,*o++=s[j+(i<=j)]))p) S I fc(C*s,I n,I p)_(mc(o,s,n+1);rpt(o,n+1,p*AN);I(A0,A1,j(p,o[j]=i;o+=n+1))p) S I fi(C*s,I n,I p)_(p++;i(p,j(n+2,o[i*(n+2)+j]=s[j-(i<j)]))rpt(o,p*(n+2),AN);I(A0,A1,j(p,o[j]=i;o+=n+2))p) I main(I c,C**v)_(S C s[32];I n=sl(v[1]);mc(s,v[1],n);s[n]=10;S typeof(fd)*f[]={fd,fc,fi}; i(3,o=o0;I g=f[i](s,n,n);j(g*(i?AN:1),C*b=o;k(3,f[k](o0+(n+i)*j,n+i-1,j%g))write(1,b,o-b);o=b)) exit(0);0) . clang -O3 -march=native -nostdlib -ffreestanding a.c && strip a.out -R .comment time ./a.out abcdefghijklmnop >/dev/null ``` [Try it online!](https://tio.run/##fVRdb6s4EH3nV1jJ9soGQyGV9qGOu4oircTDttJGirSKosh8BROwESa5RFV/e3ccctne@7APgD1nzszxzJhEmPLzMxU9ehFBipbLwJlneSFVjg5YBEFA0HuX9@dO4XfBPgj7mPA/saQDVXT0KnSHYyQ5HghVB44VYXKpDkx6HrHMiSbvYS09pIJMQDUB1c/AaQJOPwPxl1BfzBtketHLdDK8oVQr00/7JkWHQ3KWdS/VocmbtL1OmKm/YKbv6lw5/bXNAUYXLTO0ZT@2aSk6tJ62UvUoZo4zlyqtz1m@NFfzCE8q6jooX6YMf0VQIzQf/jMsrOFmnmwlHu6FnQXHWic1ms2HGbOv55mYNfqCfpsBcfPP5jCfD2RGHzoxsHs6Bi1jM0eYBv@gw1lE17Px89zqFj10mWQ20ENnWqAbySwXNUIqNivx9072OSlxPsieEBajmwHHdO3SmLAtsgCGlbN1xyLirTvQN7R1rzRGihzw2hV8YG9o7Sb8yiSGYdnJPU/gRQSJ0VhfbB0MuMeo4yH7Xso6x66Bwek8j3XEcTbQwjVahfxpQVcRjxa/exFdvfJV5K9CtgFMh7touVyEe@pqrkMGlC3q2t5KsGLgach743J1j79w1dJaUiw8kEVhXpUH6MdkaXxlx32DYlRkEMfc47SgVOKWVnAcV3seN7vKw3LJK7InpCUjI/2FAWE1NVR5EWFWl7ZL2rqrVygtXoVwLojYUr2r9lwyDVrAdQonfwnXQmXuIrwFkKRrF8QDMsjxQc5NzZipHUH6f7kWt1zxrfvQiBS67F4gkS2u2T0t9jAAipsaX3bRnjA4jqF2aQtndmrPI9sIexd0gYuMuMVuz9@LjBYpLeQHc@DiP9Fbb2J05AWMAERQll7ho4vlH6vX54hQOyqancC32J32WIceaJfEraBe0gfdD0dCxkmMaEK1nxCmeUKIM85jSFhInMBJa6GOyH97Qn4jurTkCn4Jlxz5Sps@q2WC/KLo8hzug8okuNrf37dvdiRlCxt97pH/NwpS3TS56p1eNjkKHkdAJCnc02Mpq1PdKLhLL49ZfnlU57r@/PwX "Bash – Try It Online") for the record, here's why this answer didn't win the bounty: <https://chat.stackexchange.com/transcript/message/56646474#56646474> [Answer] # C++ ('C with operator overloading') edit: no longer outputs any duplicates if the set of characters allowed for insertions and substitutions doesn't intersect with the string's character set! (further improvement will probably require something smarter) edit2: now even less duplicates: doesn't consider cases like inserting `abcd` -> `abbcd` twice edit3: tiny optimization in bufprint. I don't know how to optimize it further :( edit4: optimized bufprint some more; edit5: found a better bufsize ``` #include <cstdio> #include <cstdint> #include <cstdlib> #include <cmath> #include <climits> #include <cstring> const char rStart = 32; //for testing purposes, I often set these to 48 and 49 const char rEnd = 126; const bool enableio = true; const int bufsize = 524288; //char printbuf[bufsize]; int printbuf[bufsize / 32][8]; //using a size of 24 bytes per fixed-length string caused a SIMD unaligned store and was slightly slower int printbufi = 0; void bufflush() { if(enableio) fwrite(printbuf, 32, printbufi, stdout); printbufi = 0; } void bufprint(const char* x) //not confusing because printbuf is the print buffer and bufprint prints using the buffer { //most of the time is spent in this function if(printbufi >= bufsize/32 - 1) bufflush(); __builtin_memcpy(&printbuf[printbufi], x, 20); //printbuf[printbufi][5] = 0x0a0a0a0a; //not necessary! it's possible to just set these newlines in the beginning and never change them again printbufi++; //bufflush(); } struct string //not null-terminated { char data[20] = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 }; int len; bool operator < (const string& rhs) const { return memcmp(data, rhs.data, 24) < 0; } bool operator == (const string& rhs) const { const uint64_t* p1 = (const uint64_t*)this, *p2 = (const uint64_t*)&rhs; bool eq = p1[0] == p2[0] && p1[1] == p2[1] && p1[2] == p2[2]; return eq; } string insert(int i, char c) const { string copy; copy.len = len + 1; for(int j = 0; j < i; j++) copy[j] = data[j]; for(int j = i; j < len; j++) copy[j+1] = data[j]; copy[i] = c; return copy; } string prepend(char c) const { string copy; copy.len = len + 1; for(int j = 0; j < len; j++) copy[j+1] = data[j]; copy[0] = c; return copy; } string pop_front() const { string copy; copy.len = len - 1; for(int j = 0; j < len-1; j++) copy[j] = data[j+1]; return copy; } string erase(int i) const { string copy; copy.len = len - 1; for(int j = 0; j < i; j++) copy[j] = data[j]; for(int j = i; j < len; j++) copy[j] = data[j+1]; return copy; } inline char& operator[](int i) { //if(i >= len) while(true) throw "abc"; return data[i]; } void print() const { bufprint(data); } }; void changeloop(string x, int skip = -2) //all strings exactly 1 change away { for(int i = 0; i < x.len; i++) { if(i == skip || i == skip+1) continue; char oc = x[i]; for(int nc = rStart; nc <= rEnd; nc++) { if(nc == oc) continue; x[i] = nc, x.print(); } x[i] = oc; } } void changeloop2(string x, int skip = -2) //same with different skip { for(int i = 0; i < x.len; i++) { if(i == skip) continue; char oc = x[i]; for(int nc = rStart; nc <= rEnd; nc++) { if(nc == oc) continue; x[i] = nc, x.print(); } x[i] = oc; } } void insertloop(string x, int max = INT_MAX) //all strings exactly 1 insertion away { //example: //?abcd //a?bcd //ab?cd //abc?d //abcd? //it can be observed that each character simply iterates over all possible values, and then gets set to the ith character of the string string s = x.prepend(x[0]); max = std::min(max, s.len); for(int i = 0; i < max; i++) { for(char nc = rStart; nc <= rEnd; nc++) { if(i != 0 && x[i-1] == nc) continue; s[i] = nc, s.print(); } if(i < x.len) s[i] = x[i]; } } void deleteloop(string x, int max = INT_MAX) { //example: //bcde //acde //abde //abce //abcd //erase first character, print and then copy the original character n-1 times string s = x.pop_front(); s.print(); max = std::min(max, x.len - 1); for(int i = 0; i < max; i++) { s[i] = x[i]; s.print(); } } void dist1(string x) { x.print(); changeloop(x); insertloop(x); deleteloop(x); } //options: //insert //insert, change //insert, insert //change //change, change //delete //strings with distance at most 1 from delete void dist2(string x) { string s = x.prepend(x[0]); for(int i = 0; i < x.len+1; i++) { for(char nc = rStart; nc <= rEnd; nc++) { //string s = x.insert(i, nc); if(i != s.len-1 && s[i+1] == nc) continue; s[i] = nc; //s[s.len] = 0; s.print(); //insert insertloop(s, i+1); //insert, insert. only do the second insert before this one changeloop(s, i); //insert, change. the change can be anywhere except i and i+1 } if(i < x.len) s[i] = x[i]; } //changeloop(x); //change. can always be replaced by delete->reinsert for(int i = 0; i < x.len; i++) for(int j = i+1; j < x.len; j++) { char oci = x[i], ocj = x[j]; for(int nci = rStart; nci <= rEnd; nci++) for(int ncj = rStart; ncj <= rEnd; ncj++) { if(nci == oci) continue; if(ncj == ocj) continue; x[i] = nci; x[j] = ncj; x.print(); //change, change } x[i] = oci; x[j] = ocj; } s = x.pop_front(); s.print(); changeloop(s); insertloop(s); for(int i = 0; i < x.len-1; i++) { s[i] = x[i]; //s[s.len] = 0; s.print(); changeloop2(s, i); insertloop(s); deleteloop(s, i); //deletion must be before i } } int main(int argc, char*argv[]) { if(argc < 2) { printf("input the string as a command line argument! :(\n"); return 1; } memset(printbuf, 0x0a, sizeof(printbuf)); string s; strcpy(s.data, argv[1]); s.len = strlen(argv[1]); s.data[s.len] = 10; //fix the null byte that should not be there //for(int i = 0; i < 200; i++) //{ // dist2(s); // fprintf(stderr, "%d\r", i); //} dist2(s); bufflush(); } ``` This outputs many empty lines between strings (to avoid unaligned memory writes to the IO buffer). This outputs much fewer duplicates than the C answer: for `abcdefghijklmnop` the C answer outputs 10237362 lines, and my answer outputs only ~~4920334~~ ~~4774446~~ 4724312 non-empty lines, while only 4720038 are necessary. I compile with `g++ a.cpp -std=c++17 -march=native -Ofast -no-pie -fno-stack-protector`. [Answer] # Python 3 ``` cat >a.py <<. strs=[input()] def a(b): new = [] for x in range(32, 127): c = chr(x) for strn in b: for y in range(0, len(strn)): start = strn[:y] end = strn[y+1:] new.append(start + c + end) new.append(start + end) new.append(start + c + strn[y:]) new.append(strn + c) return new print(len(a(set(a(strs))))) . time python3 a.py <<<abcdefghijklmnop ``` [Try it online!](https://tio.run/##jZHBbsIwDIbveQofExVVAw6TqsKLVD2kJdBs4EaJ0cjTd/YKQxUX/kMkx9/vOHZn0zBNvSXY2zJkqOtSJYpp13gMV9KmVQd3BKs7UylgofuBHTTtX3AcI9zAI0SLJ6e3mxWsN593UtQz2w9R38z/lXj4BRRb9yQfqfws97GCs0MtsDFLUpTIRuL6km@q3L4ADg@PdC7W1SvAfyltCMzpuVjBDRfiM@@w73JSc@6iapeGBcwjYXYGoqMrx5xXIXokLYOwOjmSk/djRKpU5C8OQqZhxC3cN1jbruelnQb/9X2@4Bim6Rc "Bash – Try It Online") Optimized by ovs, thanks. [Answer] # Rust Tested with `rustc 1.51.0-nightly (e22670468 2020-12-30)`. Must be compiled with `-O1` (or above) so functions are properly inlined, or it segfaults. Please build with `cargo build`, then time the binary in `target/debug/q216902`. It's segfaulting in release mode at the moment, and I don't know why. ## `Cargo.toml` ``` [package] name = "q216902" version = "0.1.0" authors = ["wizzwizz4"] edition = "2018" [dependencies] rlibc = "1.0.0" [profile.dev] debug-assertions = true opt-level = 1 panic = "abort" [profile.release] panic = "abort" # debug = 2 ``` ## `main.rs` ``` #![feature(asm)] #![feature(const_in_array_repeat_expressions)] #![feature(const_maybe_uninit_assume_init)] #![feature(link_args)] #![feature(naked_functions)] #![feature(test)] #![no_std] #![no_main] #[allow(unused_attributes)] #[link_args = "-nostartfiles"] extern "C" {} extern crate rlibc; use core::convert::TryInto; use core::hint::{black_box, spin_loop, unreachable_unchecked}; use core::panic::PanicInfo; use core::ptr; use core::slice; use core::sync::atomic::{AtomicUsize, fence, Ordering}; use core::mem::MaybeUninit; static PRINTABLES: [u8; 95] = *b" !\"#$%&'()*+,-./0123456789:;<=>?\ @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\ `abcdefghijklmnopqrstuvwxyz{|}~"; const FRAMECOUNT: usize = 4; static mut FRAMES: [Frame; FRAMECOUNT] = [ unsafe { MaybeUninit::<Frame>::uninit().assume_init() }; FRAMECOUNT ]; static FRAMELENS: [AtomicUsize; FRAMECOUNT] = [ AtomicUsize::new(0); FRAMECOUNT ]; #[repr(C)] struct iovec { iov_base: *const u8, iov_len: usize } const FRAMESIZE: usize = 256; #[repr(C)] struct Frame { iovecs: [MaybeUninit<iovec>; FRAMESIZE] } #[no_mangle] #[naked] pub unsafe extern "C" fn _start() -> ! { // Escape naked without clobbering stack pointer // https://fasterthanli.me/series/making-our-own-executable-packer/part-12 asm!( "mov rdi, rsp", "call main", options(noreturn) ); } #[no_mangle] pub extern "C" fn main(stack: *const u8) -> ! { let input: &'static [u8] = unsafe { let arg1 = *stack.offset(16).cast(); slice::from_raw_parts(arg1, cstr_strlen_cheat(arg1)) }; unsafe { spawn_printer(); } let mut frame_i = 0; let mut frame_j = 0; let mut frame = unsafe { get_frame(0) }; macro_rules! main_write { (@iovec $iov: expr) => {{ frame.iovecs[frame_j] = MaybeUninit::new($iov); frame_j += 1; if frame_j > FRAMESIZE { unsafe { unreachable_unchecked(); } } if frame_j == FRAMESIZE { unsafe { write_frame(frame, frame_i, FRAMESIZE); } frame_j = 0; frame_i += 1; frame_i %= FRAMECOUNT; frame = unsafe { get_frame(frame_i) }; } }}; (@single $slice: expr) => {{ main_write!( @iovec iovec { iov_base: &$slice[0], iov_len: $slice.len() } ); }}; ($($x: expr),*) => {{ $( main_write!(@single $x); )* }}; } macro_rules! main_writeln { ($($x: tt)*) => {{ main_write!($($x)*); main_write!(b"\n"); }}; } /////////// // No-op /// // No-op // Insert // // I. // .I. // .I // Delete ///////// // Predel // Delete // Appdel // Insert insert // // II. // I.I. // I.I // .II. // .I.I. // Insert append // Append append // Insert delete ////// (also includes Substitute) // Prepend predel // Prepend delete // I.D // Insert predel // Insert delete // .I.D. // .S. // .D.I. // Insert appdel // D.I // Append delete // .S // Insert substitute ////// // IS. // I.S. // Prepend substappend // S.I. // .SI. // .S.I. // Insert substitute // .I.S // Subsprepend append // .S.I // .SI // Substitute substitute // // SS. // .SS. // .SS // S.S // S.S. // .S.S. // .S.S // Delete delete ////////// // Del2 XX. // Del2 .XX. // Del2 .XX // Del2 X.X // Del2 X.X. // Del2 .X.X. // Del2 .X.X // Delete substitute // // DS. // .DS. // .DS // D.S // S.D // D.S. // S.D. // .D.S. // .S.D. // .D.S // .S.D /////////////////////// let len = input.len(); main_writeln!(input); // No-op main_writeln!(input[1..]); // Predel main_writeln!(input[2..]); // Del2 XX. main_writeln!(input[.. len-1]); // Appdel main_writeln!(input[.. len-2]); // Del2 .XX main_writeln!(input[1 .. len-1]); // Del2 X.X for i in 1 .. len-1 { main_writeln!(input[..i], input[i + 1..]); // Delete } for i in 1 .. len-2 { main_writeln!(input[..i], input[i+2 ..]); // Del2 .XX. main_writeln!(input[1 .. i+1], input[i+2 ..]); // Del2 X.X. main_writeln!(input[..i], input[i+1 .. len-1]); // Del2 .X.X for j in i+2 .. len-1 { // Del2 .X.X. main_writeln!(input[..i], input[i+1 .. j], input[j+1 ..]); } } for ai in 0..PRINTABLES.len() { let a = &PRINTABLES[ai .. ai+1]; main_writeln!(a, input); // I. main_writeln!(input, a); // .I for i in 1..len { main_writeln!(input[..i], a, input[i..]); // .I. } for bi in 0..PRINTABLES.len() { let b = &PRINTABLES[bi..bi + 1]; main_writeln!(a, b, input); // II. main_writeln!(a, b, input[1..]); // IS. main_writeln!(a, b, input[2..]); // SS. main_writeln!(a, input, b); // I.I main_writeln!(a, input[.. len-1], b); // Prepend substappend main_writeln!(a, input[1 ..], b); // Subsprepend append main_writeln!(a, input[1 .. len-1], b); // S.S main_writeln!(input, a, b); // Append append main_writeln!(input[.. len-1], a, b); // .SI main_writeln!(input[.. len-2], a, b); // .SS for i in 1..len { main_writeln!(a, input[..i], b, input[i..]); // I.I. main_writeln!(input[..i], a, input[i..], b); // Insert append main_writeln!(input[..i], a, b, input[i..]); // .II. } for i in 1 .. len-1 { main_writeln!(a, input[..i], b, input[i+1 ..]); // I.S. main_writeln!(a, input[1 .. i+1], b, input[i+1 ..]); // S.I. main_writeln!(input[..i], a, input[i .. len-1], b); // .I.S main_writeln!(input[..i], a, b, input[i+1..]); // .SI. for j in i+1 .. len { // .I.I. main_writeln!(input[..i], a, input[i..j], b, input[j..]); } for j in i+2 .. len { // .S.I. main_writeln!( input[..i], a, input[i+1 .. j], b, input[j..] ); } for j in i+2 .. len-1 { // .S.S. main_writeln!( input[..i], a, input[i+1 .. j], b, input[j+1 ..] ); } for j in 1..i { // Insert substitute main_writeln!(input[..j], a, input[j..i], b, input[i+1..]); } main_writeln!(input[..i], a, input[i+1 ..], b); // .S.I } for i in 1 .. len-2 { main_writeln!(input[..i], a, b, input[i+2 ..]); // .SS. main_writeln!(a, input[1 .. i+1], b, input[i+2 ..]); // S.S. main_writeln!(input[..i], a, input[i+1 .. len-1], b); // .S.S } } main_writeln!(a, input[1..]); // Prepend predel main_writeln!(a, input[2..]); // DS. main_writeln!(a, input[.. len-1]); // I.D main_writeln!(a, input[1 .. len-1]); // S.D main_writeln!(input[1..], a); // D.I main_writeln!(input[1 .. len-1], a); // D.S main_writeln!(input[.. len-1], a); // .S main_writeln!(input[.. len-2], a); // .DS for i in 1..input.len() - 1 { main_writeln!(a, input[..i], input[i+1 ..]); // Prepend delete main_writeln!(input[..i], input[i+1 ..], a); // Append delete main_writeln!(input[1 .. i+1], a, input[i+1 ..]); // Insert predel main_writeln!(input[..i], a, input[i .. len-1]); // Insert appdel main_writeln!(input[..i], a, input[i+1 ..]); // .S. for j in 1..i { // .I.D. main_writeln!(input[..j], a, input[j..i], input[i+1 ..]); } for j in i+2..len { // .D.I. main_writeln!(input[..i], input[i+1 .. j], a, input[j..]); } } for i in 1 .. len-2 { main_writeln!(input[..i], a, input[i+2 ..]); // .DS. main_writeln!(input[1 .. i+1], a, input[i+2 ..]); // D.S. main_writeln!(a, input[1 .. i+1], input[i+2 ..]); // S.D. main_writeln!(input[..i], input[i+1 .. len-1], a); // .D.S main_writeln!(input[..i], a, input[i+1 .. len-1]); // .S.D for j in i+2 .. len-1 { // .D.S. main_writeln!(input[..i], input[i+1 .. j], a, input[j+1 ..]); // .S.D. main_writeln!(input[..i], a, input[i+1 .. j], input[j+1 ..]); } } } unsafe { write_frame(frame, frame_i, frame_j); } while FRAMELENS[frame_i].load(Ordering::SeqCst) > 0 { sched_yield(); } unsafe { exit_group(0); } } /// strlen, if the string's length is >= 10 and <= 16. #[inline] unsafe fn cstr_strlen_cheat(ptr: *const u8) -> usize { for i in 10..=16 { if *ptr.offset(i) == 0 { match i.try_into() { Ok::<usize, _>(i) => return i, Err(_) => unreachable_unchecked() } } } unreachable_unchecked(); } /// Gets a frame for writing, assuming nobody else has it. #[inline] unsafe fn get_frame(i: usize) -> &'static mut Frame { loop { let count = FRAMELENS[i].load(Ordering::SeqCst); if count == 0 { break; } sched_yield(); } &mut FRAMES[i] } #[inline] unsafe fn write_frame(_frame: &'static mut Frame, i: usize, count: usize) { FRAMELENS[i].store(count, Ordering::SeqCst); } #[inline(never)] // for correctness unsafe extern "C" fn spawn_printer() { let stack_pointer: *const u8; asm!( "mov {0}, rsp", out(reg) stack_pointer ); let new_stack = stack_pointer.offset(-0x1000); let spawn_addr = (new_stack as *mut (extern "C" fn() -> !)).offset(1); ptr::write(spawn_addr, printer); clone(new_stack) } extern "C" fn printer() -> ! { loop { for i in 0..FRAMECOUNT { let mut count; loop { count = FRAMELENS[i].load(Ordering::SeqCst); if count > 0 { break; } // sched_yield(); } fence(Ordering::SeqCst); unsafe { writev((&FRAMES[i].iovecs[0]).as_ptr().cast(), count); } FRAMELENS[i].store(0, Ordering::SeqCst); } } } // https://thevivekpandey.github.io/posts/2017-09-25-linux-system-calls.html #[inline] unsafe fn writev(iovecs: *const iovec, count: usize) { asm!( "syscall", in("rax") 20, in("rdi") 1, in("rsi") iovecs, in("rdx") count, options(nostack) ); } #[inline] fn exit(code: i32) -> ! { unsafe { asm!( "syscall", in("rax") 60, in("rdi") code, options(nostack, noreturn) ); } } #[inline] unsafe fn exit_group(code: i32) -> ! { asm!( "syscall", in("rax") 231, in("rdi") code, options(nostack, noreturn) ); } #[inline] unsafe fn just_exit() -> ! { asm!( "syscall", in("rax") 231, options(nostack, noreturn) ) } #[inline] fn sched_yield() { unsafe { asm!( "syscall", in("rax") 24, options(nostack) ) } } /// Wait for signal. #[inline] fn pause() { unsafe { asm!( "syscall", in("rax") 34, options(nostack) ) } } #[inline(always)] // for correctness unsafe fn clone(new_stack: *const u8) { const CLONE_FILES: u64 = 0x400; // Keep stdout as fd 1 const CLONE_FS: u64 = 0x200; const CLONE_IO: u64 = 0x80000000; // I/O scheduling efficiency const CLONE_PARENT: u64 = 0x8000; const CLONE_SIGHAND: u64 = 0x800; const CLONE_THREAD: u64 = 0x10000; // Same thread group const CLONE_VM: u64 = 0x100; // Same memory map const flags: u64 = CLONE_FILES | CLONE_IO | CLONE_VM | CLONE_THREAD | CLONE_FS | CLONE_PARENT | CLONE_SIGHAND; asm!( "syscall", in("rax") 56, in("rdi") flags, in("rsi") new_stack, options(nostack) ); return; } #[panic_handler] fn panic(_info: &PanicInfo) -> ! { unsafe { if cfg!(debug_assertions) { // just_exit(); } // unreachable_unchecked(); asm!( "ud2", options(nostack, noreturn) ) } } ``` This is cleaner code; I'm making a better version, hopefully less segfaulty in release mode. I also haven't tweaked the `FRAMECOUNT` and `FRAMESIZE` parameters for optimal speed. ]
[Question] [ Partially inspired by [this](https://web.archive.org/web/*/https://codegolf.stackexchange.com/questions/204147/solution-to-google-kids-code) question. ## Overview The execution of Goggle kids Code starts with an empty binary tape with 100 items, with the pointer starting at the index 0: ``` 00000... ^ ``` At the end of the execution, you can assume that the tape is implicitly outputted. ## Instructions Goggle kids Code is a simple language involving a stack-like tape. * `/`: Move the pointer right. * `\`: Move the pointer left. * `>`: Take two items from the tape, the left item and the current item. Zero the current item, move left, and set the item as 1 if `left` is larger than `current`, else 0. * `=`: Similar to `>`, but performs an equality comparison instead. The only looping structure in Goggle kids Code is the repeat loop, which takes a *strictly positive* number on the right introduced by a `x` symbol. (So things like `(...)x0` is impossible here.) The syntax for this is: ``` (...)xI ``` The parentheses can only contain single instructions, although you can introduce other instructions with commas. ## Sample program + Explanation ``` ((/,>)x4,/)x13 ( )x13 Do this 13 times: ( )x4 Do this 4 times: / Move right , After that, > Greater than , After that, / Move pointer right. ``` Another example that does something useful (fills 13 items from the tape with 1's): ``` ( )x13 Do this 13 times: / Move right , After that, = Equality ``` ## Rules * You can assume the tape pointer never wraps around. + The test cases won't abuse out-of-bounds tape-moving. * To simplify the solution, you are allowed to output part of the tape, as long as that part is modified. * You are allowed to have a different instruction mapping, but if you do that, please make sure to clarify which mapping you used. * You could ignore checking the commas in the source code, they'll always be there. + Instructions are always separated by the comma. ## Test cases The trailing `0` digits are omitted here, for compactness of example outputs. ``` ((/,>)x4,/)x13 -> 0000000000000 (doesn't modify the tape) (/,=,/)x13 -> 1111111111111 (/,=,/,/)x13 -> 1010101010101010101010101 (/,=)x13,/,= -> 00000000000000000 (/,/,=,\)x3 -> 0100 ``` ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~131 126 123 110~~ 104 bytes *Saved 13 bytes thanks to @dingledooper's approach of flattening nested list using backtick.* *Saved 2 bytes thanks to @l4m2* ``` p,t=0,[0]*100 for i in`input()`: if"/"<i:i=int(i);p+=i/3-1 if i<2:t[p:p+2]=cmp(*t[p:p+2])==i,0 print t ``` [Try it online!](https://tio.run/##NctBCoMwEEbhfU4RXCUxxUkEF6lzEhGEgvRfNA4yLnr6tF10@fh48tbnUXNrEpUpLrSGRGT247SwqBuqXOr8VozF3g3djAJGVQd/l54xjLf0I4s5F12kSJ9XfrzEhX95ZkQycn43q625KVKcfEjjBw) or [Verify all test cases](https://tio.run/##dZFNbsIwEIX3PsXIG2wwxAlVFynmIoCUEEI7VX6s2G1DL5@OUwKoUscb2@@bN8@Jvfi3tkmGoj2VYKDjnA9WeaPVTh/msdbs3HaAgE2Gjf3wQmYpAzzziG8wRYONFyhf7MJgtF7GQQLcJKnf2dQukoMpaivm00kag0oz21EbcL56b7ER2aLPIEzpaQp4OVAGxtylPraVo0wnLLz4RisY8Gi/NUL2XNH@OYm1kHPOpGQMa9t2HtzFjYErbMrgRueV8ydsKDQ4BXnjvsqOTOvcCuc7Eju0auRXzlboxWy5nZEj4YRNGa9pVq@lF4Uq5Ji3GCcEdPw0hFd5fTzlKZSfeSVG5fpU87f4TXO0K/uygPALbre/Qe8GfBAiUlvZP6lI9vEaYLkF/ViMdDOJoQiIH@sK3JEA6H/WCAeQGswV1n8rQMFzL/v1NJKa9Q8) Takes input from `STDIN`, where `/\>=x` are replaced with `6210*` ### Big idea: Python 2 `input()` implicitly evaluates the string read from `STDIN`. Thus, reading modified input like `((6,1)*4,2)*13` returns a nested tuple of integers, aka ``` ((6, 1, 6, 1, 6, 1, 6, 1), 2, (6, 1, 6, 1, 6, 1, 6, 1), 2, ...) ``` Note that loops containing single instruction must be terminated with comma, e.g `(1,)*10`. Now that all loops have been automatically unrolled for us, we just have to flatten the resulting tuple, and decode the instructions. To flatten the nested tuple, we simply convert it to string, then takes all numerical characters. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 149 bytes ``` s=>eval(`[${s.replace(/ \d+/g,'.toString().repeat($&)')}]+6`).replace(/\d/g,c=>c>4?p+=c-6:(X[p-1]=X[p-1]-X[p]==c,X[p--]=0),X=Array(100).fill(p=0))&&X ``` [Try it online!](https://tio.run/##bY1Na4NAFEX3/RVZBN97OI5K0xSEZ@k@u24EI3EYPzBYFbXBkuS325FQUkg3c3jnXuYe1UkNuq@60WnaLJ8LngcO85OqMY3X50H2eVcrnaO72me2WwqQY/sx9lVTIi1hrkZcWwR0TextSvf@PjNtzaEON2@dzdrZBhjFneMnfINjkDBrsZxOwh6JiN/7Xn2j73kki6qusTOaLCua@6@GJ/Nb2wxtncu6LbHA6T4nb2t4BoYAPBCwg@BFQAiBL8CF4FUAmiQ2CRkmhsJweSfDFVwp1snloonkp@rwwKF9IHlsqyZN6cnsIyC6IqRpI1ya/Gf4ta7g/8yjW27j@Y9bmjualtr8Aw "JavaScript (Node.js) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 89 bytes ``` t=[i=0]*100;(eval"[#$_]").flatten.map{|x|x<2?t[i-=1,2]=[x==t[i]-t[i+1]?1:0,0]:i+=x-3};p t ``` [Try it online!](https://tio.run/##VYlBDoIwFET3ngIrixZaaIEV@OEgpSGYYNIEgWA1NerVrWWns5i8N7PeTg8XdolZ9wHCxELd@qSIBkiqiIusQM6A1MBVJDiv8HDvRyQPYacQSc5jb8wwJZd@eb7syx6zxkjNQNBMgbQA3hTzFQvViJJTrkodg2X5u1oC4xzGKa2JLWhKrMh33uAPf2QDP8Am29cSm3/mxeh5ujo2fQE "Ruby – Try It Online") The translation map of the characters used for instructions is indicated in TIO header. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 135 bytes ``` , \d+ $* +`\([^()]+\)x|(?<=\(([^()]+)\)x1*)1 $1 ^ 0 {`(\d)/(\D*)((1)|0)? $1$#4$2 (\d)\\(\D*) $2$1 (?=(10>|(.)\2=))?.\d[>=](\D*) $#1$+0 ``` [Try it online!](https://tio.run/##VY4xDsIwDEV3X6NB@m6qNikdSbMgcYi6VZHKwMKAGCrRuwcHdYDt//ds2c/b6/64pgMuc6qIZLFkSrKzYJjAoxVeN8RTEOyAlfiSPRlPEzl6z5CFG8i5ZMDz5jiqM0VnWspK5OvItLqBGOBdv6FmaQNzrGUZ@jDuI4U31qUENFXPa1c1eutI2sJf/Ck5KAi5ZKffHT8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` , ``` Delete commas. ``` \d+ $* ``` Convert the multipliers to unary. ``` +`\([^()]+\)x|(?<=\(([^()]+)\)x1*)1 $1 ``` Expand all repetitions from the inside out. (The last two stages can be performed by a single stage in Retina 1 at a saving of 19 bytes although you do then have to use `${3}` instead of `$+` in the last stage.) ``` ^ 0 ``` Start with a tape with a `0`. (The tape is automatically extended to the right as necessary, as this was slightly golfier than predefining the tape..) ``` {` ``` Process the instructions until they have all been executed. ``` (\d)/(\D*)((1)|0)? $1$#4$2 ``` Move right, extending the tape as necessary. ``` (\d)\\(\D*) $2$1 ``` Move left. ``` (?=(10>|(.)\2=))?.\d[>=](\D*) $#1$+0 ``` (In)equality. (`$+` is used instead of `$3` because the next character is a digit.) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 235 bytes ``` p=>{s=[],l=Array(13).fill(i=q=0),e={'(':`s.unshift(1,i)`,')':`++s[0]<=parseInt(p.substr(i+1))?i=s[1]:s.splice(0,2)`,'/':`q++`,'\\':`q--`,'>':`l[q]=0,q--`,'=':`l[q]=0,q--,l[q]=+!l[q]`};while(i<p.length)eval(e[p[i++]]);return l.join('')} ``` [Try it online!](https://tio.run/##fY/RbsIgFIbv9xTOG84JSMvclYrLLvcMbRM7hxZDKELrXIzP3lGXLKuLHi748iffD2dXHsqw9to1E1t/qM63VnZOLk9BZgUz8tX78gvEFPlGGwNa7mWKTMkTATJbBd7aUOlNA4JpXDGCMaQ0ZGmxkK70Qb3ZBhwP7XtoPGgqEF@0DJkoZoEHZ/RaQcqeejWJ6p7SSHne42QScRnJZPtCpuwnkIOAXZA@9tfqPP@stFGgF44bZbdNhepQGlCZyzSlRYFzr5rW25Hhu1pbIATP3bq2oTaKm3oLcXkYAyRsicdnluBRTMfIRiS36WByS3D@8N9MmBxY4u/ct4Zeeuvc6ej92CMvHaOrL9/2@tfzHI@/m4prrfsG "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 231 bytes ``` p=>{s=[],l=Array(13).fill(i=q=0),e={'(':`s.unshift(1,i)`,')':`++s[0]<=parseInt(p.substr(i+1))?i=s[1]:s.splice(0,2)`,'/':`q++`,'\\':`q--`,'>':`l[--q]=0`,'=':`l[q]=0,l[--q]=+!l[q]`};while(i<p.length)eval(e[p[i++]]);return l.join('')} ``` [Try it online!](https://tio.run/##jY/BbsIwDIbvewrGJbaSps3YCQjTjnuGthIdCzQoSkPSMibEs3cpmibYNDT78v@Wvt/2ttpXYeW1axPbvKned1b2Ti6OQeYlM/LZ@@oDxAT5WhsDWu5khkzJIwEyXQbe2VDrdQuCaVwygnFIacizci5d5YN6sS04HrrX0HrQVCA@aRlyUU4DD87olYKMPQxoGtEdpVEVxSCTJMpFVCZPkl0ps2jl2Q6GfU3p/eCXp9l7rY0CPXfcKLtpa1T7yoDKXa4pLUucedV23o4M3zbaAiF46leNDY1R3DQbiI/DGCBlCzw8shQPYjJGNiKFzS6rsARnd7/BlMkrSFzWbeqay/7qGxkDH3PkOWP074uH7UWBh@9HxU@s/wQ "JavaScript (Node.js) – Try It Online") ]
[Question] [ In this challenge, your task is to input a rectangle ASCII pattern (You may assume only printable characters need to be handled, and you may assume a trailing newline or not), C4\_4 symmetrify, and output it. Here, C4\_4 symmetric means symmetric under 90-degree rotation around a corner of the corner character. The corresponding "symmetrify" process is copy and rotate 90-degree clockwise three times, and then put all four copies together. For the precise arrangement, you can look at Test Cases. # Test Cases ``` Input: asdf jkl; Output: ja ks asdfld jkl;;f f;;lkj dlfdsa sk aj Input: .O. ..O OOO Output: .O.O.. ..OO.O OOOOO. .OOOOO O.OO.. ..O.O. Input: gc oo ld fe Output: gc oo ldflog feedoc codeef golfdl oo cg ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes ``` A⟲C²⁴⁶ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMzr6C0RENT05orKL8ksSTVOb@gUsPIxEzT@v//aCUlpcTilDSurOwcayA79r9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: `A` implicitly prints the input, `⟲` performs the rotation, `C` signifies to keep copies, and `²⁴⁶` represents the numbers of 45-degree rotations to make. (Charcoal defaults to rotating around the bottom-right corner as desired.) [Answer] # [Python 3](https://docs.python.org/3/), 193 bytes ``` def f(s):q=len(s[0])-len(s);s=[[" "]*len(s[0])]*q+s;s=[[" "]*-q+l for l in s];j=lambda a,b:[x+y for x,y in zip(a,b)];r=lambda x:[*map(list,zip(*x[::-1]))];return j(s,r(s))+j(r(r(r(s))),r(r(s))) ``` [Try it online!](https://tio.run/##TY5LboQwEETX8SlarNz8lCg7I05ieeERoJgY27g9EszliWE0SdSbUr@qUoU9fXn3eRzDOMHECcXa29Fxku8Km0thR72UBRSq/CWqXCv6@zdrZWHyESwYB6S6ubd6uQ0adH0Tcqv2i271fvKHCTz/UXXxZduELBcduDWU6pOXmxSi@VB4usZ0jw5mTnXMc7Caebwua6xf4jBL8DEB7cSYcQF6kGdd7nQjPtdldQ3cqaU0GNfGUQ8cWwrWpJMSR8WYv6ecnnhuQcb@JzMR7C1E4xIvinb2xj378dA0TGz@tt0P "Python 3 – Try It Online") [Answer] # [J](http://jsoftware.com/), 38 bytes ``` (,|."1@|.)@(,.|:@|.)@((2$_1*>./)@${.]) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NXRq9JQMHWr0NB00dPRqrCAsDSOVeEMtOz19TQeVar1Yzf@aXApcqckZ@QppCkYKJgoqCuqJxSlpWdk51uoQcXV1mLwxEALl9Qz09PT8gQBDgYmCIUhBcn5Kqvp/AA "J – Try It Online") No doubt it can be golfed much further. [Answer] # JavaScript (ES6), ~~178~~ 173 bytes Takes input as an array of strings. Returns a string. ``` m=>(g=x=>~y?(Y=y<w?y:W-y,X=x<w?x:W-x,Z=y<w^x<w?Y:X,(m[Z-z*d]||0)[(X^Y^Z)+!z*d]||' ')+[` `[x-W]]+g(x<W?x+1:!y--):'')(0,w=m[0].length,h=m.length,d=w-h,(z=d>0)?0:w=h,y=W=w*2-1) ``` [Try it online!](https://tio.run/##dcvJboMwFIXhPU/hrGzHg0iXNBcewUsGCxQUpiYMUYmKHUV9dRqCKnXR7L579N9T/pWPx8@Py1X0Q1HOFcwd@KQGA/63DUgMdj8F1guF5RGYh83DhifLni137EWcdDoRt22R3u8u1STK4iyhbLMuGGHK9ME5aCPCNGU1MfswMGznbawQ1MOYEpdP0Gk3lW3Z19eGN9D9soBJNJzcoPBdGrjeBA23EMK0fRM7Oh@HfhzaUrZDTSqiHYRwPhYV5otO5/YdOymljvNPJ5VcMynVCqXU6xwptFYI/cmfEMw8/@Yf "JavaScript (Node.js) – Try It Online") [Answer] # [Red](http://www.red-lang.org), 217 bytes ``` func[a][n: max(l: length? a)length? a/1 p: copy""insert/dup p" "n loop n - l[insert a copy p]forall a[pad/left a/1 n]repeat y n[repeat x n[append a/:y a/(n - x + 1)/:y]]repeat y n[append a reverse copy a/(n - y + 1)]] ``` [Try it online!](https://tio.run/##jY6xbsMwDER3fcVBU4KiMLK6Q/@hq6CBsKg4LSsRshLYX@8qsVG0QIcOBA7kuzsWDusbB@dN7Nd4TYMj71KPT5oP0kM4nev4Cjp@q@5ktMeQdbH2kiYutQtXhVrYZCRnRcIzxG030AOF@pgLiYCcUuiEY71HIfnCylSxILldzk2SKqdgqOuXxh3ukTOecDq2hf/p2cBWU/jGZeKtbrcsD4v3aytnGkYURDhLU4jt3fcPebEeTsslVRSPTUg0v/EhBz5nif9hx5bLbWSf/Kdp/QI "Red – Try It Online") Returns a list of strings [Answer] # [Icon](https://github.com/gtownsend/icon), ~~255~~ 206 bytes ``` procedure f(a) n:=*a;n<:=t:=*a[1] 1to n-*a&push(a,repl(" ",t))&\z (!a)[1:1]:=repl(" ",n-t)&\z i:=1to n&j:=1to n&a[i]||:=a[n-j+1,i]&\z i:=1to n&put(a,"")&j:=1to 2*n&a[n+i]||:=a[n-i+1,2*n-j+1]&\z return a end ``` [Try it online!](https://tio.run/##jY9NbsMgEIX3nILMwgIHL@gSl5NQFsgeN7gOWAQnapW7p9hK@rOo1JGeNJr3Ps2M72K43eYUO@yXhHRgjpOgdO3a8Kx0XjsjLZE50tDUrpqX04E5kXCeGFAQmfPq5YOwneNGKmmV/rJCkzfPK73h1fhonPH2elXamdCMeym8/ZWbl1xWAPAH8VSvTNh/U75QZbrSG5swLylQRzD0P945Oh8YJ7QUnjG900vyGdluYAbcqR9AUBjfphYs5@3d/CPexR5f4zT8I3oAAVg03RVXZrvsEw "Icon – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 140 bytes ``` def f(a):l=len(a[0]);k=len(a)-l;b=[k*' '+i for i in-k*[l*' ']+a];b+=[*map(''.join,zip(*b))][::-1];return[i+j[::-1]for i,j in zip(b,b[::-1])] ``` [Try it online!](https://tio.run/##ZY49bsQgEEZ7n4IOxj8oUTojn4EDIAqITYJNALFO4b28d8FJETLVzON9n4jH/hn823nOi0GGKBjd5BZPlHiRwLZrh8ExPYmtxQh3FpmQkEXWD1srXGayU5LpbhLtl4oEY7oG6/u7jaTVAFKM4/AqWVr27@SF7dYLlJp@fRahrOpeXxxk@cxsb9Gpg6iU1AFjg56TI876JWcKH1FM1u8kQyjKdUPT/OYNEVjdZoP78v4zeN0cwxLgj/fxXlkhVMDNFTDLvxbKaSVRyivCOc@58wE "Python 3 – Try It Online") Expects and returns a list of lines. ### Explanation ``` def f(a): l=len(a[0]);k=len(a)-l; # Extract dimensions b=[k*' '+i for i in-k*[l*' ']+a]; # Make it square b+=[*map(''.join,zip(*b))][::-1]; # Construct left half of the output return[i+j[::-1]for i,j in zip(b,b[::-1])] # Construct the right half and return ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 bytes ``` {(⌽⍪⊖)(⍉,⌽)⍵↑⍨-2/⌈/⍴⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1rjUc/eR72rHnVN09R41NupA@RqPurd@qht4qPeFbpG@o96OvQf9W4BCtX@T3vUNuFRb9@jruZHvWuAgofWG4PU9U0NDnIGkiEensH/0xSAQuoeqTk5@eoK6uH5RTkp6gA "APL (Dyalog Unicode) – Try It Online") ]
[Question] [ # Introduction Output all the numbers in specific base that would appear in an adapted version of the game of seven. # Challenge Your task is to output all the numbers in a given base in a given range, skipping the ones matching certain conditions. You will be given four inputs: `base` `elim` `start` and `end`. The roles of the four variables are as follows: * `base` specifies what base we are using for the other three variables, and also for output. One way to express it is using a single character that is '8', '9' or a capital letter from 'A' to 'Z', using 'A' for decimal system, and 'G' for hexadecimal system. The bases expected to be supported are 8 to 35 (inclusive). This is just my suggested way to express the `base` and I will use it in the **Example Input and Output** section, but it is also fine to use your own way to express it. For example, you may choose to format `base` as its usual decimal representation. * `start` and `end` are two strings that specify the range of numbers to be output, expressed in the given `base`. If `base` is `G` and `start` is `10` and `end` is `1F`, you need to output `10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F`, but you also need to eliminate some out them based on what `elim` is, to be explained soon. * `elim` is a single character and must be a valid digit in the given `base`. All numbers containing the digit `elim` or are multiples of `elim` should be eliminated from the list to generate the final output. In the case above, if `elim` is `7`, then `17` need to be eliminated because it contains the digit `7`. `15` and `1C` also need to be eliminated because they are multiples of `7`. So the final output would be `10 11 12 13 14 16 18 19 1A 1B 1D 1E 1F` # Test Cases ``` Input -> Output G,7,10,1F -> 10 11 12 13 14 16 18 19 1A 1B 1D 1E 1F A,3,1,100 -> 1 2 4 5 7 8 10 11 14 16 17 19 20 22 25 26 28 29 40 41 44 46 47 49 50 52 55 56 58 59 61 62 64 65 67 68 70 71 74 76 77 79 80 82 85 86 88 89 91 92 94 95 97 98 100 G,A,96,C0 -> 97 98 99 9B 9C 9D 9E 9F B0 B1 B2 B3 B5 B6 B7 B8 B9 BB BC BD BF C0 ``` The third test case is added after the original post. All the answers posted before the edit has been tested and passed the third test. # Specs * The input will always be valid so don't worry about exception handling. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the lowest number of bytes wins. * You can take input and provide output through [any standard form](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and you are free to choose the format. * As usual, [default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply here. * This is based on the (real-life version of) [the game of sevens](https://codegolf.stackexchange.com/questions/65924/the-game-of-sevens-who-said-what). * I require `base` to be at least 8 purely due to personal taste. I just don't want to see the number of digits in the sequence grow too fast. # Scoreboard Snippet taken from [this question](https://codegolf.stackexchange.com/questions/133109/sum-of-all-integers-from-1-to-n). Run the snippet to get the scoreboard. ``` var QUESTION_ID=154147,OVERRIDE_USER=77134;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [Emojicode](http://www.emojicode.org/), ~~141~~ 116 bytes *thanks to @NieDzejkob for 25 bytes!* ``` 🍇a🚂b🚂c🚂d🚂🔂i⏩c➕1d🍇🍊🎊❎😛0🚮i b☁️🔍🔡i a🔡b a🍇😀🔡i a🍉🍉🍉 ``` [Try it online!](https://tio.run/##S83Nz8pMzk9J/f9hfn@jwof5ve1cCiBqWVppXvJ/ED/xw/xZTUkgIhlEpICID/OnNGU@6l@Z/GjeVMMUkCog7vowv6/r0dy@D/NnzDYAqlqXqZD0aEbj@x39QOW9QLwwUyERRCWBKJCWGQ1w0d5OGP4Ptn@tAsgBCoZmCuYgwtgQ7KwZDUBiyhIQ5kJRZqBgrGAIpAy4wEYAAA "Emojicode – Try It Online") ``` 🍇 a🚂 b🚂 c🚂 d🚂 👴 4 arguments of type 🚂 (integer) 🔂 i ⏩ c ➕ 1 d 🍇 👴 for i in range(c, d+1) 🍊 🎊 👴 if cond_a and cond_b ❎ 😛 0 🚮 i b 👴 cond_a: i%b != 0 ☁️ 🔍 🔡 i a 🔡 b a 👴 cond_b: i in base-a doesnt have b in base-a 🍇 👴 then 😀 🔡 i a 👴 print i in base-a 🍉 🍉 🍉 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to Erik the Outgolfer (use of "order" `ọ` in place of divisible with swapped arguments, `ḍ@`) ``` r/ọÐḟ⁵bċÐḟ⁵ ``` A full program taking three inputs as command line arguments, all of which employ decimal notation - a list `[start, end]`, and two numbers, `base` and `elim` - which prints the Jelly representation of a list of lists, where each represents the digits of a number in `base` and each digit is a decimal number (e.g. 1043 in base 20 would be `[2,12,3]`, i.e. 2×202+12×201+3×200). **[Try it online!](https://tio.run/##y0rNyan8/79I/@Hu3sMTHu6Y/6hxa9KRbhjz////0YZmOsaGsf8Nzf6bAwA "Jelly – Try It Online")** A small note: this won't work for ranges that include negative values, but the linked challenge starts from 1 and counts up. ### How? ``` r/ọÐḟ⁵bċÐḟ⁵ - Main link: list, [start, end]; number, base / - reduce [start, end] with: r - inclusive range => [start, start+1, ..., end] Ðḟ - filter discard if: ⁵ - program's 5th argument (the 3rd input), elim ọ - order (how many times the element is divisible by elim, or 0 if not) b - convert to base "base" Ðḟ - filter discard if: ⁵ - program's 5th argument (the 3rd input), elim ċ - count (0 if elim is not a digit) ``` [Answer] # [Julia 0.6](http://julialang.org/), 69 bytes ``` f(b,e,r,g=filter)=g(z->!contains(z,base(b,e)),base.(b,g(x->x%e>0,r))) ``` Inputs are `base, elim, start:end` where `start:end` is a `UnitRange`. as base 10 integers. Outputs a list of strings of the numbers in the given base. Filters for divisibility in integer form, uses `base.` to elementwise convert to strings, then filters on digit containment. Called example: `f(10,3,1:100)` [Try it online!](https://tio.run/##yyrNyUw0@/8/TSNJJ1WnSCfdNi0zpyS1SNM2XaNK104xOT@vJDEzr1ijSicpsTgVpEpTE8zUA7LTNSp07SpUU@0MdIo0NTX/OxRn5JcrpGkYGugY6xhaGRoYaHLBxcx0zHUMzayMDTX/AwA "Julia 0.6 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~102~~ 94 bytes ``` lambda b,e,l,u:[i for i in range(l,u+1)if i%e*x(i,b,e)] x=lambda n,b,e:n<1or(e-n%b)*x(n/b,b,e) ``` [Try it online!](https://tio.run/##PctBCsIwEIXhfU8xm0JGR8xYUCj2JOoiwUQH6qSECvX0MYq4eYuP/02v@Z50V@JwLqN7@KsDT4FGevYngZgyCIhCdnoLpuqaUSJIG1aLEaopXppl@D31A70eOWUTNtp6rJVu/bcrUxadIRq21BETW4vN3/Z0oDodY3kD "Python 2 – Try It Online") Input and output is in base 10. [Answer] # [Perl 6](https://perl6.org), ~~ 94 ~~ 57 bytes ``` ->\a,$b,\c,\d {grep {!/$b/},grep({$_%$b.parse-base(a)},[...] (c,d)».parse-base(a))».base(a)} ``` [Test it (94)](https://tio.run/##VZDNbtNAFIX3fopDZYitTty5k/nFNEoRLRuW7OoKOfaALLmpZbuIKsqTdceLBY/bgNCsztz5zjl3Ot@3@vg4ePzUWZVH9094Vz3UHpfH5booWbxlRcWKGvsfve@wf3MRby8OLIhkH397G2@zruwHv9yWg0/K9MBusyy7Q1KxOv39/P8wXJzeHaekzeiHEZdom50fkjAdurYZkwWWayz@6dsFmw4Wd2kehapfJyyPurbc4Xz2yKPvD/2r3YQmm2bXPY5I4pDGCt8296wYxrIfJ7GrU7bxvzpfjb5OsY@AZljW3nftE8LuyfnZ@5X@MMPrMzbTL3Bgsy/NMDL8dTjpOTLrpv/Mo8PxMzOMOKOb0Ic4iEACtAJJkAZZkANdgT6CPoGuQTfRFVsxmig@MxCQUDCwJ/6FNIEUHEJAKAgNYSEcJIckSAmpIQ2kg@JQAkpBaSgL5aAJWkBLaAVtoC0MhyEYCaNhDIyD5bACVsFqWAvr4AhOwEk4BWfgQh/@Bw "Perl 6 – Try It Online") Since the rules have changed: ``` ->\b,$e,\r{grep {!/"$e.base(b)"/},grep(*%$e,r)».base(b)} ``` [Test it](https://tio.run/##TZHNbtswEITveoppoNZSSytamr81EiRFml567K3KQbbZQIDsCJJSNDD8ZLn1xRySjoLcRM18O7Nk5/pWHR8Hh7@qWC@T7RM@rR82DhfH@WW1YqljVb@/712H/Yfzs9QVq3pw2So/Oz@w8Dv7/NF7@vz/86Qcjn7I1eiGERdom50bsqAOXduM2QzzS8zyYlt3X7FPgOBtdt5Z/C7vJhOb5cuTloahXvWeoHd1P7h5DFqoyZOlrm22LB3Guh99490mfyWoKBZ3PvsdFgd60qOnb/aeLoqIM9@G3tqEvj@bYUwOSbioX36zZdK19Q5f4prL5M9D/7qx3y7zyd3jiKyK46s4vurr3b3L2ZX717n16HzFsH0zzDfOde0TwqVnEYj@kz3GMrxB0zkGFJ1/u2VyOP5gmlHJ6DakUwkiEActQAKkQAZkQdegb6Ab0HfQbXLNFow8VUYGHAISGmbiT6QOJC/BObgEV@AG3EKUEAQhIBSEhrCQJSSHlJAK0kBaKILiUAJKQmkoA11CE7SAVtAa2sKUMBxGwigYA2NhCZbDClgJq2FDn/IF "Perl 6 – Try It Online") ( Int, Int, Range ) Output is a list of strings in the base ## Expanded ``` -> \b, # base (Int) $e, # elim (Int) \r # range (Int Range) { grep {!/"$e.base(b)"/}, # remove the values that contain the character grep( * % $e, # remove values that are divisible by elim r # the input Range )».base(b) # convert each into base 「b」 } ``` [Answer] # JavaScript, 82 bytes A quickie before I hit the boozer! Takes input in base-10 in the order `base`, `elim`, `start` & `end` and outputs a space delimited string of base-10 numbers with a single trailing space. ``` (b,l,s,e)=>(g=o=>++s>e?o:g(s%l&&!~s[t=`toString`](b).search(l[t](b))?o+s+` `:o))`` ``` [Try it online](https://tio.run/##HcuxCsIwEADQX9HBckdisQgVCml3Bx06FiFtTdJKyEkuCC7@ekTHN7zH@Bp5jusz7QPdTbYqwyS9ZGlQteAUqVYIbk1HjQPe@aLYfnhISifqU1yD0zeYsGQzxnkBP6QfsSPBQm90Q4ha55kCkzelJwfn/nop@V9X@wYLx1pWtTzIU4WI@Qs) [Answer] # [Japt](https://github.com/ETHproductions/japt/), 16 bytes Hastily rewritten after the spec was changed to allow decimal input so can probably be improved upon. Takes input in the order `start`, `end`, `base`, `elim` and outputs an array of numbers in the given base. ``` òV kvX msW køXsW ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=8lYgZnVYIG1zVyBr+FhzVw==&input=MAozNQozNgo4) --- ## Explanation ``` :Implicit input of integers U=start, V=end, W=base & X=elim òV :[U,V] k :Remove vX : elements divisible by X m :Map sW : Convert to base-W string kø :Remove elements containing XsW : X converted to a base-W string :Implicit output of resulting array ``` [Answer] # Java 8, 92 bytes ``` (b,k,s,e)->{String r="",t;for(;s<=e;r+=t.contains(k)?"":t+" ")t=b.toString(s++,b);return r;} ``` Input as `Integer (base), String (elem), int (start), int (end)`. **Explanation:** [Try it online.](https://tio.run/##hZDBTsMwDIbvPIWVU6J6VcsEE4SCOHJgF46IQ5plU9cuqRJ3Epr67MWsvSKkOFHi7/dv52jOZhV654@7drKdSQneTeMvNwCNJxf3xjrY/l4BPig2/gBWvnHm4CLUuDy1yDCk6@6UZnrk4JXIUGNhCx4qmGSNLSZ0avV8WZSxEgJJ70OUOj1VTsesotwGT9xFkq16EeKRMgFCUVXnFGadTFmGtdLR0RA9RD1Oenbsh7pjx8X4HJodnLiUnHWfX0Ytw3wncqc8DJT3nKHOS59bWd6j2AjkY12q6yR/owWKNaNYFsV/KFd9ZfSO4YdbtfzQOP0A) ``` (b,k,s,e)->{ // Method with the four parameters, and String return-type String r="", // Result-String, starting empty t; // Temp-String for(;s<=e; // Loop from start to end (inclusive) r+= // After every iteration: append the result-String with: t.contains(k)? // If the temp-String contains the elem we exclude "" // Don't append anything to the result-String : // Else: t+" ") // Append the temp-String + a space t=b.toString(s++,b); // Convert the number to the given base and set the temp-String return r;} // Return the result-String ``` The three test cases are inputted like this: ``` 16,"7",16,31 10,"3",1,100 16,"A",151,192 ``` ]
[Question] [ # Introduction - What is a necklace? A necklace is something that OEIS people are obsessed with. The OEIS challenge has like 5 necklace sequences. A binary necklace of length `n` is a loop with `n` beads that are either `0` or `1`. Two necklaces are the same if one can be rotated to become the other, and two reversible necklaces are the same if one can be rotated, reversed, or reversed and rotated to become the other. A primitive necklace is one that cannot be expressed as more than one copy of a string of beads chained together. Note that the copies must be assembled all in the same order (no reversing) for a necklace to be considered non-primitive. For example, let's take a look at this necklace: `0 1 1 0 1 1`. It is not primitive because it can be expressed as `0 1 1` repeated twice. `0 1 0 1 1` is primitive. `0 1 1 0` is primitive because `0 1` and `1 0` are not considered the same string. This necklace is equivalent to `1 1 0 0` because it can be rotated left one bead to become this one, but not equivalent to `0 1 0 1` (which isn't primitive by the way). # Challenge Given an non-negative integer `n`, return the number of distinct reversible primitive binary necklaces of length `n`. Input and output as a single integer each. The first few terms of this sequence are `1, 2, 1, 2, 3, 6, 8, 16, 24, 42, 69, 124, 208, 378, 668, 1214, 2220, 4110`, 0-indexed. **This is [OEIS A001371](http://oeis.org/A001371)** [Reference Implementation in Python 3](https://tio.run/##hVPLboMwELz3K7Y3Ow1NIDck/qI3hCo32I0VZ6HGNO3XU@OAzSNVOFjg3Z3dmVnqX3Oq8NB1JRcgCNL0CeyD/HhW7MgbyCDP9wVsAAsXcYeoNEiQCJrhJycJbGwcIoiH8v45tlpzNBbAg@VRXORp4VMklvzHJkSxv7qepOLwplsekFyqGAFzV1VAlsF@njPpOia9ZBCvcj40Z@fZLVcNf4hl@61SbgyiaRfP9pXVNceSDDA0yNdrXWt5edfsSsb8iXSam1YjMKWID@cp9i4QxTGUwG4HSCk8B5GdNxi8ibcwK6GLOXRlmJEVNncHqYzbgGDZwvk59FzCvnjUwLOQqTUFAilZ0H@L@vfbyqT2pEt5@vBaU2nkN38gqtd@JE8dr/HL0VvLshCOf7VMEbT6YrJug/ECJZmUC4lMBV39L@U9tKV@jQK0vMsQGJaOFVZmGErgFkK8RxaOlOu7cMndLW2azDrw6Y2@lXd2BjREycaQC6uJ2IZNixO7X7Q7/AE) - quite slow [Answer] # [Python 2](https://docs.python.org/2/), ~~178~~ ~~171~~ ~~139~~ 137 bytes ``` lambda n:sum(1-any(i>int(b[j::-1]+b[:j:-1],2)or j*(i>=int(b[j:]+b[:j],2))for j in range(n))for i in range(2**n)for b in[bin(i+2**n)[3:]]) ``` [Try it online!](https://tio.run/##RYxBDoMgFESvwvKjmFS6I7EXQRaQlvYT@RK0C09PRdt0N3lvZtK2vmaSxQ9jmWx0d8tILe8IfWdpA7whreB0UKrrTeu0CjUIyefMQrP74Vc4bVXcV8mQWLb0fACdBP9ENg0dzO1MOyTA9mD6qozhJeX6OuGyQrQJvPjuLoL1@z/n5QM "Python 2 – Try It Online") Edit: Saved ~~7~~ 21 bytes thanks to @HalvardHummel. [Answer] # JavaScript (ES6), ~~198~~ 192 bytes I was curious to know what a fully mathematical answer would look like. So here it is. Quite long but very fast. ``` n=>(g=d=>d&&(n%d?0:(q=n/d,C=(a,b)=>b?C(b,a%b):a<2,M=n=>n%++k?k>n?(q%2+3)/4*(1<<q/2)+(R=d=>d&&(q%d?0:(P=k=>k--&&C(q/d,k)+P(k))(q/d)<<d)+R(d-1))(q)/q/2:M(n):n/k%k&&-M(n/k))(d,k=1))+g(d-1))(n)||1 ``` ### Demo ``` let f = n=>(g=d=>d&&(n%d?0:(q=n/d,C=(a,b)=>b?C(b,a%b):a<2,M=n=>n%++k?k>n?(q%2+3)/4*(1<<q/2)+(R=d=>d&&(q%d?0:(P=k=>k--&&C(q/d,k)+P(k))(q/d)<<d)+R(d-1))(q)/q/2:M(n):n/k%k&&-M(n/k))(d,k=1))+g(d-1))(n)||1 for(n = 0; n <= 30; n++) { console.log('a(' + n + ') = ' + f(n)) } ``` ### How? This is based on the following formulas: ``` A000029(n) = (n % 2 + 3) / 4 * 2 ** floor(n / 2) + sum(φ(n / d) * 2 ** d, for d in divisors(n)) / (2 * n) A001371(n) = 1 if n = 0 sum(μ(d) * A000029(n / d), for d in divisors(n)) if n > 0 ``` Where ***φ*** is [Euler's totient function](https://en.wikipedia.org/wiki/Euler%27s_totient_function) and ***μ*** is [Möbius function](https://en.wikipedia.org/wiki/M%C3%B6bius_function). ``` n => (g = d => // if d = 0, stop the recursion of g() d && ( // if d is not a divisor of n, ignore this iteration n % d ? 0 : ( // define q = n / d, C = function that tests whether a and b are coprime, // M = Möbius function (requires k to be initialized to 1) q = n / d, C = (a, b) => b ? C(b, a % b) : a < 2, M = n => n % ++k ? k > n || M(n) : n / k % k && -M(n / k) )(d, k = 1) * ( // invoke M with d // first part of the formula for A000029 (q % 2 + 3) / 4 * (1 << q / 2) + // 2nd part of the formula for A000029 (R = d => // if d = 0, stop the recursion of R() d && ( // if d is not a divisor of q, ignore this iteration q % d ? 0 : // compute phi(q / d) * 2 ** d (P = k => k-- && C(Q, k) + P(k))(Q = q / d) << d // recursive call to R() ) + R(d - 1) )(q) / q / 2 // invoke R with q, and divide the result by q * 2 ) // recursive call to g() ) + g(d - 1) )(n) || 1 ``` NB: In the current golfed version, the 2nd part of the code is now directly embedded inside ***M()***. But that makes the code harder to read. [Answer] # Mathematica, ~~128~~ ~~125~~ ~~124~~ ~~109~~ 99 bytes ``` 1~Max~(L=Length)@(U=Union)[U[#,Reverse/@#]&/@MaximalBy[U@Partition[#,L@#,1,1]&/@{0,1}~Tuples~#,L]]& ``` ## How it works * `{0,1}~Tuples~#` finds all binary sequences of the given length * `U@Partition[#,L@#,1,1]&/@...` finds all possible rotations of each one of them * `MaximalBy[...,L]` picks out the entries with the most distinct rotations; these correspond to the primitive necklaces. * `U[#,Reverse/@#]&/@...` puts the rotations in each entry, and their reversals, into a canonical order... * `(L=Length)@(U=Union)[...]` ...so that we can delete duplicate primitive necklaces, and then count the elements remaining. * `1~Max~...` we make sure the result is at least 1 to get the zeroth term right. --- *-2 bytes thanks to Jonathan Frech, and -2 thanks to me learning from him* *-15 more bytes from switching to* `MaximalBy` *and related changes* *-10 from switching to* `Partition` [Answer] # [Husk](https://github.com/barbuz/Husk), 21 bytes ``` Ṡ#▲mLüOmȯṁSe↔U¡ṙ1ΠRḋ2 ``` [Try it online!](https://tio.run/##ATkAxv9odXNr/yBt4oKBOjDhuKMxMP/huaAj4paybUzDvE9tyK/huYFTZeKGlFXCoeG5mTHOoFLhuIsy//8 "Husk – Try It Online") The link shows results from 0 to 10. ## Explanation ``` Ṡ#▲mLüOmȯṁSe↔U¡ṙ1ΠRḋ2 Implicit input, say n=4. Rḋ2 The list [1,0] repeated n times: [[1,0],[1,0],[1,0],[1,0]] Π Cartesian product: [[1,1,1,1],[0,1,1,1],[1,0,1,1],...,[0,0,0,0]] mȯ For each list, say x=[0,1,0,0]: ¡ṙ1 Iterate rotation by one step: [[0,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,0],[0,1,0,0],... U Take prefix of unique values: [[0,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,0]] ṁSe↔ After each element, insert its reversal: [[0,1,0,0],[0,0,1,0],[1,0,0,0],[0,0,0,1],[0,0,0,1],[1,0,0,0],[0,0,1,0],[0,1,0,0]] üO Remove duplicates with respect to sorting. mL Get length of each list of lists. Ṡ#▲ Count the number of maximal lengths. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` 2ḶṗµṙJ;U$ṢḢµ€QµsJṖE€ẸṆµ€S ``` [Try it online!](https://tio.run/##y0rNyan8/9/o4Y5tD3dOP7T14c6ZXtahKg93Lnq4Y9GhrY@a1gQe2lrs9XDnNFcg@@GuHQ93toGFg////29oBgA "Jelly – Try It Online") Very inefficient. [Answer] # Javascript (ES7), 180 bytes ``` n=>[...Array(2**n)].filter((_,m)=>![...m=m.toString(2).padStart(n,0)].some(_=>s[m=m.replace(/(.)(.*)/,"$2$1")]|s[[...m].reverse().join``])&!/^(.+)\1+$/.test(m)&(s[m]=1),s=[]).length ``` Explanation: ``` n=>[...Array(2**n)].filter((_,m)=>( // For every number m from 0 to 2^n-1 m=m.toString(2).padStart(n,0), // Take the binary representation (padded) ![...m].some(_=>( // Repeat once for every digit in m m=m.replace(/(.)(.*)/,"$2$1"), // Rotate m one step s[m]|s[[...m].reverse().join``] // Search for m and the reverse of m in the )) // lookup table &!/^(.+)\1+$/.test(m) // Test if m is primitive &(s[m]=1) // Add m to the lookup table ),s=[]).length // Get the length of the list of numbers that // satisfy the above conditions ``` ``` f=n=>[...Array(2**n)].filter((_,m)=>![...m=m.toString(2).padStart(n,0)].some(_=>s[m=m.replace(/(.)(.*)/,"$2$1")]|s[[...m].reverse().join``])&!/^(.+)\1+$/.test(m)&(s[m]=1),s=[]).length ``` ``` <input id=i type=number value=5/><button onclick="o.innerText=f(i.value)">Test</button><br><pre id=o></pre> ``` ]
[Question] [ One problem on a website like this is that you often don't know if you are talking to a male or female. However, you have come up with a simple NLP technique you can use to determine the gender of the writer of a piece of text. # Theory About 38.1% of letters used in English are vowels **[a,e,i,o,u]** (see References below, `y` is NOT a vowel in this case). Therefore, we will define any word that is at least 40% vowels as a *feminine word*, and any word that is less than 40% vowels as a *masculine word*. Beyond this definition we can also find the *masculinity* or *femininity* of a word. Let *C* be the number of consonants in the word, and *V* be the number of vowels: * If a word is feminine, it's femininity is `1.5*V/(C+1)`. * If a word is masculine, it's masculinity is `C/(1.5*V+1)`. For example, the word `catch` is masculine. Its masculinity is `4/(1.5*1+1) = 1.6`. The word `phone` is feminine. Its femininity is `1.5*2/(3+1) = .75`. # Algorithm To figure out the gender of the writer of a piece of text, we take the sum of the masculinity of all the masculine words (ΣM), and the sum of the femininity of all the feminine words (ΣF). If ΣM > ΣF, we have determined that the writer is a male. Otherwise, we have determined that the writer is a female. # Confidence Level Finally, we need a confidence level. If you have determined that the writer is female, your confidence level is `2*ΣF/(ΣF+ΣM)-1`. If you have determined that the writer is male, the confidence level is `2*ΣM/(ΣF+ΣM)-1`. # Input Input is a piece of English text including punctuation. Words are all separated by spaces (You don't have to worry about new-lines or extra spaces). Some words have non-letter characters in them, which you need to ignore (such as "You're"). If you encounter a word that is all non-letters (like "5" or "!!!") just ignore it. Every input will contain at least one usable word. # Output You need to output an M or F depending on which gender you think the writer is, followed by your confidence level. # Examples 1. `There's a snake in my boot.` * Gender + masculinity/femininity of each word: `[M1.0,F1.5,F.75,F.75,M2.0,F1.0]` * ΣM = 3.0, ΣF = 4.0 * CL: `2*4.0/(4.0+3.0)-1` = .143 * Output: `F .143` 2. `Frankly, I don't give a ^$*.` * `[M2.4,F1.5,M1.2,F1.0,F1.5]`, ΣM = 3.6, ΣF = 4.0, CL: `2*4.0/(4.0+3.6)-1` = .053, Output: `F .053` 3. `I'm 50 dollars from my goal!` * `[F.75,M1.25,M1.2,M2.0,F1.0]`, ΣM = 4.45, ΣF = 1.75, CL: `2*4.45/(4.45+1.75)-1` = .435, Output: `M .435` # References 1. [Percentage of vowels in English dictionary words](https://en.wikipedia.org/wiki/Letter_frequency#Relative_frequencies_of_letters_in_the_English_language) (38.1%) 2. [Percentage of vowels in English texts](http://www.sttmedia.com/characterfrequency-english) (38.15%) [Answer] # [Python 3](https://docs.python.org/3/), ~~320~~ ~~317~~ ~~307~~ ~~286~~ ~~253~~ 189 bytes ``` h=S=0 for v in input().split():V=sum(map(v.count,'aeiouAEIOU'));C=sum(x.isalpha()for x in v);H=V<.4*C;C-=V;K=[1.5*V/(C+1),C/(1.5*V+1)][H];h+=K*H;S+=K-K*H print('FM'[h>S],2*max(S,h)/(S+h)-1) ``` [Try it online!](https://tio.run/##HU/RasIwFH3PV9zJoEmt1W7zxS6DURRFhg91fREHWY2m2DYhSbv267tUuHDO5Zx7uEf1Vsj6dcjlhdPJZDIImtIFukoNLRS1G9VYTEKjysLhKqOmqXDFFG7DXDa1DTzGC9l8rneHb4@QOHkYurAwrFSCYTJGdWNUS@Itzd7DNz@JkxnN4j09ReHSz@Y4mUYkSOb4sTp@Pm3PsZjSvb@NUwczR5DSRW2xt/nyTuIjPQcvfsU6nAaCzHE6FWQWkcE1QFb3KwTwJ4qSw1E3fNwAeMdzPNYkiHc5VxbWh81aa6lHXTFjhqPgmnsGGJia3fn4dNXDr5Q2RBvN6nvZB7CDi6w9C7ei5c758@yHaOdVsFw4oSyZNnDVshovb5KVT/8 "Python 3 – Try It Online") **Ungolfed**: ``` def evaluateWord(s): V = len([*filter(lambda c: c in 'aeiou', s.lower())]) C = len([*filter(lambda c: c in 'bcdfghjklmnpqrstvxzwy', s.lower())]) isMasculine = V < 0.4*(V+C) return C/(1.5*V+1) if isMasculine else 1.5*V/(C+1), isMasculine def evaluatePhrase(s): scores = [] for word in s.split(): scores.append(evaluateWord(word)) masc = 0 fem = 0 for score in scores: if score[1]: masc += score[0] else: fem += score[0] return ('M', 2*masc/(fem+masc)-1) if masc > fem else ('F', 2*fem/(fem+masc)-1) print(evaluatePhrase("There's a snake in my boot.")) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~205 201 197~~ 192 bytes -Thanks @Value Ink for 4 bytes: `lower()` beforehand -Thanks @Coty Johnathan Saxman for 9 bytes: Inverted condition `.4*(v+c)>v` and `-~c` for `(c+1)` bitshift-based consonant check instead of literal. # [Python 3](https://docs.python.org/3/), 192 bytes ``` M=F=0 for i in input().lower().split(): v=sum(j in'aeiou'for j in i);c=sum(33021815<<98>>ord(k)&1for k in i) if.4*(v+c)>v:M+=c/(1.5*v+1) else:F-=1.5*v/~c print('FM'[M>F],2*max(M,F)/(F+M)-1) ``` [Try it online!](https://tio.run/##JY3NboMwEITvPMX2UtuQAA5FSknM0VIPfoKqB4tA6sTGlvlJk0NfnTpUGmm1M99o3H38tn2xLIJxlked9aBA9UFuGjFJtb21PtzBaRX@KoKZDZPBl0Ag2So7oWfnsnbIoVnDosh3dE/L4/F9X9fWn/CVvNInd/3nIlBd@hbjOWlIPVciYU2GaVrGc0JD2OqhrfiWrU7220TOq37EiAv0KWr@tdnFRv5gseEkwzwRZEvJsnwgA2UOJ6u19AN03howd3Dq8ZDgpNdh/2ylfvkD "Python 3 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) `-ap`, ~~154~~ 140 bytes `-ap` loops over input and splits on spaces, storing the result in `$F`, then outputs `$_` after the program finishes. ``` m=f=0 $F.map{s=_1.upcase.gsub(/[^A-Z]/){} k=s.size-v=s.count('AEIOU') k>v*1.5?m+=k/(1.5*v+1):f+=1.5*v/-~k} $_=m>f ??M:?F,2*[m,f].max/(m+f)-1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY7NSsNAFIX3eYprCeR3Jo1QkMIkdGEgC3FjN4a0TOtMDJPJhEwSjKU-gW_gxoXizvfp2xi1q_PBPefc8_bR9rvxK5sh2szy76bvNJQcTAwRhJ99x9HV6VUSTuaGmWBJm4Mm2xD3zZ5qhgvd7-wg26zQfR44h6MhiMa6fGZomGCv-rqzrdV1eru2HENEgxviRSw9IgJ7InfwQmfJPfLHAXoRR8PcEhlxiOObZZz4l24mfZ5Pf58CW3rcQedN72c5re8eWcssDRR0TQWDsgY5wk6pDhtJS2tRjT6k8KBqq4OiHNjk3JguNlJLwmI-HaqKthp4q-RvslC0uvhv_wE) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~237~~ ~~229~~ ~~222~~ 216 bytes Boy I though I could do this in a LOT LESS BYTES... ``` v,c;float m,f;g(char*s){for(m=f=0;*s;v*1.0/(c+v)<.4?m+=c/(1.5*v+1):1?f+=1.5*v/(c+1):0,s+=*s!=0)for(v=c=0;*s&&*s^32;s++)isalpha(*s)?strchr("AaEeIiOoUu",*s)?++v:++c:0;printf("%c %.3f",m>f?77:70,(m>f?2*m:2*f)/(f+m)-1);} ``` [Try it online!](https://tio.run/##bY1da8IwFIbv/RUxTM2XNdWJ0Cwru9jAq91st0KWNW2xaSSpARF/e9cKuxjsXL3n5TnP0ctS676PTAvTONUBy4woka6UJwFfjfPISiO5IEFEkiZ8hTSN@Cl5zC2VeoXSZEsiTXGW5obK@zYiQ8FZoJKEqeR41ESp75r5nITDZi0CpbgOqjlVCg2v8tB5XXkEX9Rrsa/f3ecZsrGnNGaU6oyLk6/bziA402CWbAxk9tnku1224wyNcU1stiYGr5ChFi9TLG69VXWL8OQ6AcOUCH5UhS8WASgQWnUsQN0CewFfznUJxOJ07gKCQ/jF37xqj82FgT34du2iA2Udi@H48ED@5fcLC7Z8YJtG@QCMd3b0l0410z/8bdL/AA "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 61 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ð¡εálžNžM‚δÀg©`3;*‚Â>/®¤sO/.4@©è®‚}0š.¡θ}€€нODZk„MFèsZ·sO/<‚ ``` [Try it online](https://tio.run/##yy9OTMpM/f//8IZDC89tPbww5@g@v6P7fB81zDq35XDzo6Y16YdWJhhbawEFDjfZ6R9ad2hJsb@@nonDoZWHVxxaBxSuNTi6UA@oeUctUDUQXdjr7xKV/ahhnq/b4RXFUYe2A9XbANX9/x@SkVqUql6skKhQnJeYnaqQmaeQW6mQlJ9fogcA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/wxsOLTy39fDCnKP7/I7u833UMOvclsPNj5rWpB9amWBsrQUUONxkp39o3aElxf76eiYOh1YeXnFoHVC41uDoQj2g5h21QNVAdGGvv0tU9qOGeb5uh1cURx3aDlRvA1T3X@d/tFJyYklyhkJBRn5eqpKOUkhGalGqerFCokJxXmJ2qkJmnkJupUJSfn6JHlDWrSgxLzunUkfBUyElP0@9RCE9sywVqDZORQsk7ameq2BqAJTKyUksKlZIK8rPBelOz0/MUQRKJyYlK8UCAA). **Explanation:** Step 1: Split the input into words, and get the amount of consonants and vowels of each word: ``` ð¡ # Split the (implicit) input-string by spaces # (NOTE: builtin `#` doesn't work if the input is just a single word) ε # Map over each word: á # Only leave its letters (removing any punctuation) l # And convert it to lowercase žN # Push the lowercase consonants: "bcdfghjklmnpqrstvwxyz" žM‚ # Pair it with the vowels: ["bcdfghjklmnpqrstvwxyz","aeiou"] δ # Map over both using the lowercase word: à # And only keep those characters € # Then map over the pair: g # And get the length of each # (we now have a pair [amount_of_consonants,amount_of_vowels], # let's call these [C,V] like in the challenge description) © # Store this pair in variable `®` (without popping) ``` [Try step one online.](https://tio.run/##AUEAvv9vc2FiaWX//8OwwqHOtcOhbMW@TsW@TeKAms60w4Pigqxnwqn//1RoZXJlJ3MgYSBzbmFrZSBpbiBteSBib290Lg) Step 2: Apply the formulas: \$\left[\frac{C}{1.5V+1},\frac{1.5V}{C+1}\right]\$ ``` ` # Pop and push both values separated to the stack 3;* # Multiply V by 1.5 (3 halved) ‚ # And pair it back together with C  # Bifurcate; short for Duplicate & Reverse copy > # Increase both values in the reversed duplicate by 1 / # Divide the pairs at the same positions: # [C/(V*1.5+1),V*1.5/(C+1)] ``` [Try the first two steps online.](https://tio.run/##AUwAs/9vc2FiaWX//8OwwqHOtcOhbMW@TsW@TeKAms60w4PigqxnwqlgMzsq4oCaw4I@L///VGhlcmUncyBhIHNuYWtlIGluIG15IGJvb3Qu) Step 3: Check if the word was feminine or masculine by checking if the amount of vowels is at least 40%: ``` ® # Push the pair from variable `®` again ¤ # Push its last item (without popping the pair): V s # Swap so the pair it at the top of the stack again O # Sum them together: C+V / # Divide them: V/(C+V) .4@ # Check if this is larger than or equal to 0.4 # (1 if >=0.4; 0 if <0.4) © # Store this boolean as new `®` (without popping) è # 0-based index it into the [C/(V*1.5+1),V*1.5/(C+1)]-pair ®‚ # And pair it together with boolean `®` } # Close the map ``` [Try the first three steps online.](https://tio.run/##AWAAn/9vc2FiaWX//8OwwqHOtcOhbMW@TsW@TeKAms60w4PigqxnwqlgMzsq4oCaw4I@L8KuwqRzTy8uNEDCqcOowq7igJp9//9UaGVyZSdzIGEgc25ha2UgaW4gbXkgYm9vdC4) Step 4: Group all masculine and feminine values together: ``` 0š # Prepend a 0 to the list of pairs # (this is to ensure the first group are the falsey/masculine pairs; # and the second group the truthy/feminine pairs) .¡ # Group the pairs (and the leading 0) by: θ # Their last item, which is the boolean }€ # After the group-by, map over each group: € # Map over each inner pair: н # And only leave the first item ``` [Try the first four steps online](https://tio.run/##yy9OTMpM/f//8IZDC89tPbww5@g@v6P7fB81zDq35XDzo6Y16YdWJhhbawEFDjfZ6R9ad2hJsb@@nonDoZWHVxxaBxSuNTi6UA@oeUctUDUQXdj7/39IRmpRqnqxQqJCcV5idqpCZp5CbqVCUn5@iR4A). Step 5: Get the sums of both groups, and check if the masculine or feminine sum is larger: ``` O # Take the sum of each inner group D # Duplicate this pair of sums Z # Get the maximum (without popping the pair itself) k # Get the index of this maximum in the pair (0 or 1) „MFè # Index it into the string "MF" ``` [Try the first five steps online](https://tio.run/##yy9OTMpM/f//8IZDC89tPbww5@g@v6P7fB81zDq35XDzo6Y16YdWJhhbawEFDjfZ6R9ad2hJsb@@nonDoZWHVxxaBxSuNTi6UA@oeUctUDUQXdjr7xKV/ahhnq/b4RX//4dkpBalqhcrJCoU5yVmpypk5inkViok5eeX6AEA). Step 6: Apply the confidence formula: \$\frac{2\max\left(\sum{F},\sum{M}\right)}{\sum{F}+\sum{M}}-1\$ ``` s # Swap so the duplicated pair of sums is at the top again Z # Get the maximum again (without popping) · # Double this maximum s # Swap so the pair is at the top of the stack again O # Sum them together / # Divide the doubled maximum by this sum < # Decrease it by 1 ``` [Try the first six steps online](https://tio.run/##yy9OTMpM/f//8IZDC89tPbww5@g@v6P7fB81zDq35XDzo6Y16YdWJhhbawEFDjfZ6R9ad2hJsb@@nonDoZWHVxxaBxSuNTi6UA@oeUctUDUQXdjr7xKV/ahhnq/b4RXFUYe2A9Xb/P8fkpFalKperJCoUJyXmJ2qkJmnkFupkJSfX6IHAA). Step 7: And finally pair the two results together, and output it as result: ``` ‚ # And pair it together with the "M"/"F" # (after which the result is output implicitly) ``` [Answer] # JavaScript, ~~336~~ ~~328~~ ~~297~~ ~~286~~ ~~278~~ ~~276~~ 260 bytes ``` t=>['FM'[+(g=((m=(r=s=>t.split` `.map(c=>[p=(v=(c=[...c][u='filter'](a=>/[a-zA-Z]/.test(a)))[u](a=>/[aeiouAEIOU]/.test(a)).length)>=(q=c.length)*.4?0:1,p?(q-v)/(1.5*v+1):1.5*v/(q-v+1)])[u](e=>e[0]==s).reduce((a,c)=>a+c[1],0))(1))>(f=r(0))))],2*(g?m:f)/(f+m)-1] ``` This took me a really long time to golf but it still is 260 bytes long. *-8 bytes thanks to my own efforts: removed `return` statement and curly braces* *-31 bytes thanks to my own efforts: replaced long alphabet string literal inclusion test with regular expression test: why did I not think of that before. Code is also becoming more and more unreadable as time goes by.* *-11 bytes thanks to my own efforts: come to think of it, why not replace the other `includes` as well?* *-8 bytes thanks to my own efforts: noticed similarity between possible confidence levels and refactored* *-2 bytes thanks to my own efforts: new `q` variable set to `c[h]` used multiple times.* *day 2 of golfing super-long answer: -16 bytes thanks to my own efforts* Ungolfed: ``` function determine(text) { let words = text.split(' '); words = words.map(cur => { cur = [...cur].filter(a=>"abcdefghijklmnopqrstuvwxyz".includes(a.toLowerCase())).join``; let vowels = [...cur].filter(a=>"aeiou".includes(a.toLowerCase())).length; let output = [vowels>=cur.length/2.5?'f':'m']; output.push(output[0]=='m'?(cur.length-vowels)/(1.5*vowels+1):1.5*vowels/(cur.length-vowels+1)); return output; }); let femi = words.filter(e=>e[0]=='f').reduce((a,c)=>a+c[1],0); let masc = words.filter(e=>e[0]=='m').reduce((a,c)=>a+c[1],0); let gender = (masc>femi?'m':'f'); let confidence = (gender=='f'?2*femi/(femi+masc)-1:2*masc/(femi+masc)-1); console.log(gender , confidence); } ``` [Answer] # Common Lisp, 404 bytes ``` (defun f(x &aux(a 0)c(f 0)m v u)(labels((w(x &aux(p(position #\ x)))(cons(#1=subseq x 0 p)(and p(w(#1#x(1+ p)))))))(dolist(e(w(coerce x'list)))(setf v(#2=count-if(lambda(x)(member x(coerce"aeiouAEIOU"'list)))e)u(#2#'alpha-char-p e)c(- u v)m(and(> c 0)(<(/ v c)4/6)))(and(> u 0)(if m(incf a(/ c(1+(* v 3/2))))(incf f(/ v 2/3(1+ c))))))(format t"~:[F~;M~] ~4f~%"(> a f)(-(/(* 2(if(> a f)a f))(+ a f))1)))) ``` Good old verbose lisp! [Try it online!](https://tio.run/##NVHLbtQwFP2V06SQ65aQmWlh0VIkFlSaBWIDKx6S49gdq7Ed4nhIN/n16fV0GsmRdV73Hln1Ng6HA3XaJA9DM97KNJPESigy/HfYIwnqZav7SPT/VTHQEKKdbPAofwOzEIJU8JHK9V1MbdT/MGOFQZD0HQY2lutypvUlQy8fdYGHT6SZU0GPSmOuMpK5qCeDPZWbOxWSn2preAXXdpJmQU67Vo@YT7ZCahvSl6/b7z@L1wAtEpvLSvbDTtZqJ8d6gOZONRL2wuWt6DMUN6RP1HBJJa6bj3n0C5MyYw0cWa8MJGsUb08XLL1qNscCR8Yc3ZvmKndTp2omjE5OmIrl5tf9cvtt@YPl2ixvCk6WMIJqajhqwxNOSD6CLo93sc4hB@pDGMBRsID1qKj4sdOjriKropePOqPuCW0I0/sCxf0o/WP/9A5bdMFXEx7sXrP27/lFpreVw4cVU30vxwgzBpfdD0H2Z4VgHPzilgc/Aw) Ungolfed version: ``` (defun f(x &aux (a 0) c (f 0) m v u) ; parameter & auxiliary variables (labels ((w (x &aux (p (position #\ x))) ; recursive function to split input into words (cons (subseq x 0 p) (and p (w (subseq x (1+ p))))))) (dolist (e (w (coerce x 'list))) ; for each word (setf v (count-if (lambda (x) (member x(coerce"aeiouAEIOU"'list))) e) ; count vowels u (count-if 'alpha-char-p e) ; count all alfabetic letters c (- u v) ; calculate consonants m (and (> c 0) (< (/ v c) 4/6))); is male or not? (and (> u 0) ; if non-empty word (if m (incf a (/ c (1+ (* v 3/2)))); increase masculinity (incf f (/ v 2/3 (1+ c)))))) ; increase femininity (format t "~:[F~;M~] ~4f" ; print (> a f) ; “gender” (-(/ (* 2 (if (> a f)a f)) (+ a f)) 1)))) ; and confidence ``` [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 147 bytes ``` {{"{<M F>[[<] $_]} {2*.max/.sum-1}"}(@([Z+] map {my \v=1.5*.comb(rx:i/<[aeiou]>/);my \c=.comb(/<:L>/)-2*v/3;(c>v)*c/(v+1),(v>=c)*v/(c+1)},.words))} ``` [Try it online!](https://tio.run/##TcxfT4MwFAXwdz/FlSzSMlZkZj6MP/FpyRJ925MMTdeVQUYpaVkdIXx27KKJPt57fue0XNXPk@gfimQaBmeI32CTZlmcw@wzH2FYekTQa0D0RSzC0RnRC8re5zkI2sIgetibJCQrjzApDkhd11UQZ5RX8pKnAY5ugCU/YRCvX@1vsfRM8BQhlhrssQCZeYh9ZNKEYRsgZs/RJ19SHTXG46RpDwU4u5Ir7mqgoBt65lA1YLcPUnbEie5@0UbR5lz3PmzhKBu3g1NluK187GfeP7Z1BaweLalrqjQUSorb2EnS@v5PMdqxEtpSNtyJpm8 "Perl 6 – Try It Online") ]
[Question] [ There exists a brain game called [Enumerate](https://zachgates7.github.io/enumerate/) (which I made, based on [Takuzu](https://en.wikipedia.org/wiki/Takuzu)). Your challenge is to play this game. --- # Task Solve a game of 4x4 Enumerate/Takuzu. * Receive a starting grid via STDIN or command line. * Output the solved grid via STDOUT or writing to file. --- # Rules A game is characterized by a 4x4 board, made up of red and purple cells. * There must be the same number of red and purple cells in each row and column (2 red and 2 purple in each). * There must be no identical rows or columns. --- # Input The starting grid will be given as a 16 character/byte string consisting of only `0`, `1`, and `2`. Here is an example: ``` 0001100002001200 ``` `1` represents a red cell and `2` represents a purple cell. All input boards will be solvable. --- Note: ***If your language does not support string literal input***, you may take input as an array of integers. Please state in your answer that this is the case. So there is no confusion, this is what said array should look like: ``` [0, 0, 0, 1, 1, 0, 0, 0, 0, 2, 0, 0, 1, 2, 0, 0] ``` No nested arrays are allowed. --- # Output The solved board should be output in the same format as above; a 16 character/byte string, consisting of only `1` and `2`. Here is the solution for the input above: ``` 2121112222111212 ``` Again, `1` represents a red cell and `2` represents a purple cell. --- # Bonuses A **-25 byte bonus** is offered for any answer that outputs the solved board as an ASCII grid. Here is an example of the previously mentioned board. ``` 2|1|2|1 -+-+-+- 1|1|2|2 -+-+-+- 2|2|1|1 -+-+-+- 1|2|1|2 ``` --- A **-50 bytes bonus** is offered for any answer that outputs the solved board in color. This can be output as an image or colored text. If colored text is chosen, the output should look like this: ``` 2121 1122 2211 1212 ``` However, if an image is the chosen output method, the resulting file should be 20x20 pixels, where each cell is a colored 5x5 pixel block. Here is an example: ![](https://i.stack.imgur.com/c6leu.jpg) Here are the color codes: ``` Red - #a73cba OR (167, 60, 186) Purple - #f94a32 OR (249, 74, 50) ``` --- # Samples ``` In: 0020010100000100 Out: 1221212112122112 In: 0010000200121000 Out: 2211112221121221 In: 1000100102000000 Out: 1122122122112112 ``` [Answer] ## CJam (score 13) With coloured text bonus, only printable characters: 64 chars - 50 = 14 ``` l:~:L,Eb2*e!4m*_:z&{_M*L1$.e|.=1-!*_&,4=},~{27c'[@_4*27+'m@}f%N* ``` This can be improved by one char using a non-printable character: `27c'[@` becomes `"^["\` where `^` represents character 27, giving a score of 13. xxd version: ``` 0000000: 6c3a 7e3a 4c2c 4562 322a 6521 346d 2a5f l:~:L,Eb2*e!4m*_ 0000010: 3a7a 267b 5f4d 2a4c 3124 2e65 7c2e 3d31 :z&{_M*L1$.e|.=1 0000020: 2d21 2a5f 262c 343d 7d2c 7e7b 221b 5b22 -!*_&,4=},~{".[" 0000030: 5c5f 342a 3237 2b27 6d40 7d66 254e 2a \_4*27+'m@}f%N* ``` --- Straight solution with no bonus: 42 chars ``` l:~:L,Eb2*e!4m*_:z&{_M*L1$.e|.=1-!*_&,4=}, ``` [Online demo](http://cjam.aditsu.net/#code=l%3A~%3AL%2CEb2*e!4m*_%3Az%26%7B_M*L1%24.e%7C.%3D1-!*_%26%2C4%3D%7D%2C&input=0001100002001200) --- With grid bonus: 59 chars - 25 = 34 ``` l:~:L,Eb2*e!4m*_:z&{_M*L1$.e|.=1-!*_&,4=},~'|f*2N*'-4*'+*** ``` [Online demo](http://cjam.aditsu.net/#code=l%3A~%3AL%2CEb2*e!4m*_%3Az%26%7B_M*L1%24.e%7C.%3D1-!*_%26%2C4%3D%7D%2C~'%7Cf*2N*'-4*'%2B***&input=0001100002001200) --- With image output, 83 chars - 50 = 33. Output is in netpbm format. ``` 'P3NKSKS255Nl:~:L,Eb2*e!4m*_:z&{_M*L1$.e|.=1-!*_&,4=},~4f*M*:("§<ºùJ2":i3/f=4f*M*S* ``` [Online demo](http://cjam.aditsu.net/#code='P3NKSKS255Nl%3A~%3AL%2CEb2*e!4m*_%3Az%26%7B_M*L1%24.e%7C.%3D1-!*_%26%2C4%3D%7D%2C~4f*M*%3A(%22%C2%A7%3C%C2%BA%C3%B9J2%22%3Ai3%2Ff%3D4f*M*S*&input=0001100002001200) [Answer] # CJam, 74-50=24 bytes (color output) ``` l:~:L;5ZbGm*{_L.-L.*:|!\[4/_z]_:::+e_6-!\__.&=**},s4/{"["\_~4*27+'m@}f%N* ``` I don't think this is very well-golfed, but it works! [Try it here.](http://cjam.aditsu.net/#code=l%3A~%3AL%3B5ZbGm*%7B_L.-L.*%3A%7C!%5C%5B4%2F_z%5D_%3A%3A%3A%2Be_6-!%5C__.%26%3D**%7D%2C&input=0001100002001200) Warning: **slow**. `l:~:L;` reads a line of input into `L`. Then, `5Zb` is `[1 2]`, and we take the 16th Cartesian power (`Gm*`) of this list, to get all possible solutions `[[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2] ...]`. The filter `{ },` contains the Takuzu logic. I added a ANSI code color output bonus: [![color output](https://i.stack.imgur.com/LtJsV.png)](https://i.stack.imgur.com/LtJsV.png) This doesn't work on the website, of course. There is an unprintable `ESC` byte in the string `"["`. [Answer] # C, Score ~~278~~ 257 (~~328~~ 307 bytes - 50 bytes for coloured output, or 291 bytes without colour bonus) ``` t,b,c,u,r,p;v(g){for(b=0,u=59799;b<16;b+=4)u&(c=1<<(g>>b&15))?b=u:0,u|=c;return b>16;}main(i,a)char**a;{for(char*A=a[1];*A;p=p*2|*A++>49)r=r*2|*A==49;for(;++i<6e4;t=0){for(b=16;b--;)t|=(i>>b&1)<<b%4*4+b/4;if(!(p&i^p|r&~i^r|v(i)|v(t))){for(b=16;b--;)printf("\x1b[3%s%s",i&1<<b?"5m2":"1m1",b&3?"":"\n");break;}}} ``` This is a brute-force method which prints the first matching grid. It actually works on a 180-degree rotated grid to simplify some loops, and uses a lookup table (59799) to figure out which rows are valid. Internally all grids are just 16-bit numbers. It takes a single string input from its arguments. Due to the escape codes used for colouring, you might want to reset your terminal styling after running this (execute `printf "\x1b[0m"`) Breakdown: ``` // Globals initialise to 0 t, // Transpose of current guess b, // Bit counter for loops c, // Current row value when validating u, // Invalid row mask when validating r, // Red squares mask (1s in input) p; // Purple squares mask (2s in input) // Validation function for rows (returns 0 if valid, shell-style) v(g){ for(b=0,u=59799;b<16;b+=4) // "magic" value 59799 is a map of invalid rows // For each row: u&(c=1<<(g>>b&15))?b=u:0, // Check if row is valid u|=c; // Add row to mask (rows cannot be duplicates) return b>16; // b = <some massive number> + 4 if a check failed } main(i,a)char**a;{ // K&R style function declaration to save 2 bytes // Read input (in reverse to save some bytes when reading & printing) for(char*A=a[1];*A; p=p*2|*A++>49) // Find 2s (input is strictly 012) and go to next r=r*2|*A==49; // Find 1s for(;++i<6e4;t=0){ // Brute-force grids (<3 and >=60000 are invalid anyway) for(b=16;b--;)t|=(i>>b&1)<<b%4*4+b/4; // Calculate transpose if(!( // Check... p&i^p| // Matches input purples r&~i^r| // Matches input reds v(i)| // Rows are valid v(t) // Columns are valid )){ // Display grid (use ANSI escape codes for colour) for(;b--;) // b starts at 16 from last v() call // printf(b&3?"%c":"%c\n",(i>>b&1)+49); // no colour variant printf("\x1b[3%s%s",i&1<<b?"5m2":"1m1",b&3?"":"\n"); break; // Stop search } } } ``` # So what's 59799? There are only 16 possible states for each row/column (it's a 4-bit binary number). Out of those, the valid options are: ``` 0011 = 3 (decimal) 0101 = 5 0110 = 6 1001 = 9 1010 = 10 1100 = 12 ``` Taking those values as bit indexes, we can create a mask: ``` 0001011001101000 = 5736 (dec) ``` But here we want to know the *invalid* rows: ``` 1110100110010111 = 59799 (dec) ``` [Answer] ## Ruby, 196 bytes ``` ->g{[o=?1,p=?2].repeated_permutation(16).find{|x|a=x.each_slice(4).to_a t=a.transpose a.uniq.size==4&&t.uniq.size==4&&(a+t).all?{|y|y.count(o)==2}&&x.zip(g.chars).none?{|y|y==[o,p]||y==[p,o]}}*''} ``` `repeated_permutation`, why must your name be so long? -\_- This simply goes through all possible solutions until one of them matches the input pattern. [Answer] # C (function) (with gcc builtins), 283 This seemed like an interesting challenge to tackle in C. Pretty sure it can be golfed more, but here's a start: ``` #define m(a,b)for(j=0;j<4;j++){l[j]=i&a<<j*b;if(__builtin_popcount(l[j])-2)goto l;for(k=0;k<j;k++)if(l[j]==l[k])goto l;} i,j,k,l[4];f(char*s){for(i=0;i<65536;i++){m(15,4)m(4369,1)for(j=0;j<16;j++)if((!(i&1<<j)==s[j]-49)&&(s[j]!=48))goto l;for(j=0;j<16;j++)putchar(50-!(i&1<<j));l:;}} ``` Input passed as string to function `f()`. Output to STDOUT. [Try it online.](https://ideone.com/JimsvW) [Answer] # JavaScript (ES6), 263 ~~300~~ ``` g=>{[...g].map(c=>(t+=t+(c>1),u+=u+(c&1)),u=t=0);for(m=15,n=4369,i=0;i++<6e4;){for(x=y=i,s=new Set;x;x>>=4,y>>=1)[3,5,6,9,10,12,17,257,272,4097,4112,4352].map(v=>(x&m)==v|(y&n)==v&&s.add(v));if(s.size>7&!(i&u)&!(~i&t))return g.replace(/./g,c=>1+(i>>--p&1),p=16)}} ``` Given the constraints, the number of possible solution seems surprisingly small: **72** The whole board can be seen as a 16 bit number. Allowed values for rows (masking 1111): 0011, 0101, 0110 and the inverted values 1100, 1010, 1001 Same for for columns, just with different masking and intermixed bits (masking 1000100010001): 0...0...1...1, 0...1...0...1, 0...1...1...0 and the inverted values Note that rows and columns bit arrangements are different, so to check for uiniqueness you can add both rows and columns to a set and verify that the set size is == 8. Code to enumerate all possible solutions in a grid 4x4 ``` for(m=0xf,n=0x1111,t=i=0;i<0x10000;i++) { // loop condition: row != 0, as valid values have 2 bits set in each row for(x=y=i,s=new Set; x; x>>=4, y>>=1) [3,5,6,9,10,12,17,257,272,4097,4112,4352].map(v=>((x&m)==v||(y&n)==v)&&s.add(v)) if (s.size==8) console.log(++t,i.toString(2)) } ``` **Test** ``` F=g=>{ // input as a string [...g].map(c=>(t+=t+(c>1),u+=u+(c&1)),u=t=0); for(m=15,n=4369,i=0;i++<6e4;) // max valid is 51862 { for(x=y=i,s=new Set;x;x>>=4,y>>=1) [3,5,6,9,10,12,17,257,272,4097,4112,4352].map(v=>(x&m)==v|(y&n)==v&&s.add(v)); if(s.size>7&!(i&u)&!(~i&t)) return g.replace(/./g,c=>1+(i>>--p&1),p=16) } } // Basic test console.log=x=>O.textContent+=x+'\n' ;[ ['0020010100000100','1221212112122112'], ['0010000200121000','2211112221121221'], ['1000100102000000','1122122122112112'] ].forEach(t=>{ var i = t[0], x=t[1], r=F(i); console.log(i+' -> '+r+(r==x?' OK':' Fail (Expected '+x+')')) }) ``` ``` <pre id=O></pre> ``` ]
[Question] [ ## Background (F#) Let there be trees: ``` type Tree<'T> = Node of 'T * Tree<'T> list ``` Now lets fold them nicely with a function called... ``` foldTree f:('a -> 'b -> 'c) -> g:('c -> 'b -> 'b) -> a:'b -> t:Tree<'a> -> 'c ``` ...taking two functions `f` and `g`, an initial state `a` and of course a tree structure `t`. Similar to the well known function [fold](http://en.wikipedia.org/wiki/Fold_(higher-order_function)) which operates on lists, this function should "merge" siblings with `g` and parents with their children with `f` resulting in an accumulated simple value. ## Example (F#) The tree... ``` // 1 // / \ // 2 3 // / \ \ // 4 5 6 let t = Node (1, [Node (2, [Node (4, []); Node (5, [])]); Node (3, [Node (6, [])])]) ``` ...passed to `foldTree` with the operators for addition and multiplication along with the initial state `1`... ``` let result = foldTree (+) (*) 1 t // = (1 + ((2 + ((4 + a) * ((5 + a) * a))) * ((3 + ((6 + a) * a)) * a))) // = (1 + ((2 + ((4 + 1) * ((5 + 1) * 1))) * ((3 + ((6 + 1) * 1)) * 1))) ``` ...should return the value `321` to `result`. ## The Challenge In any programming language, define the function `foldTree` in the most concise way you can come up with. Fewest number of characters wins. [Answer] ## Haskell, ~~37~~ 35: ``` data T a=a:*[T a] (f%g)z(x:*t)=x`f`foldr(g.(f%g)z)z t ``` not counting the type definition. With it, ~~54~~ **52** (shortened by using infix operator, similarly to the answer by *proud haskeller*, but in a different way). Ungolfed: ``` data Tree a = Node a [Tree a] foldTree :: (a -> b -> c) -> (c -> b -> b) -> b -> Tree a -> c foldTree f g z (Node x t) = f x $ foldr (g . foldTree f g z) z t -- = f x . foldr g z . map (foldTree f g z) $ t -- 1 -- / \ -- 2 3 -- / \ \ -- 4 5 6 t = Node 1 [Node 2 [Node 4 [], Node 5 []], Node 3 [Node 6 []]] result = foldTree (+) (*) 1 t -- ((+)%(*)) 1 t {- = 1 + product [2 + product[ 4 + product[], 5 + product[]], 3 + product[ 6 + product[]]] = 1 + product [2 + 5*6, 3 + 7] = 321 -} -- product [a,b,c,...,n] = foldr (*) 1 [a,b,c,...,n] -- = a * (b * (c * ... (n * 1) ... )) ``` This is the `redtree` ("*red*uce *tree*") function from John Hughes paper, "Why Functional Programming Matters", where it is presented in a more verbose formulation. [Answer] # F#, 70 61 ``` let rec r f g a (Node(n,c))=f n<|List.foldBack(g<<r f g a)c a ``` Not going to win the contest, but I think you can't get less with F# [Answer] # Haskell, 35 ``` data T a=a:>[T a] h(%)g a(e:>l)=e%foldr(g.h(%)g a)a l ``` the data type declaration is not counted. [Answer] # Prolog, 85 Logic programming ``` b([],A,A). b([E|N],A,R):-b(N,A,T),c(E,A,Y),g(Y,T,R). c((C,S),A,R):-b(S,A,T),f(C,T,R). ``` Ungolfed ``` b([],A,A). b([Element|Siblings],A,R):- b(Siblings,A,RSiblings),c(Element,A,RElement), g(RElement,RSiblings,R). c((Parent,Children),A,R):- b(Children,A,RChildren),f(Parent,RChildren,R). ``` Functions f and g ``` f(A,B,R):-R is A+B. g(A,B,R):-R is A*B. ``` Example ``` c((1,[(2,[(4,[]),(5,[])]),(3,[(6,[])])]),1,R). ``` [Try it online](http://swish.swi-prolog.org/p/QzXQJITa.pl) Edit: correction of error signaled by [Will Ness](https://codegolf.stackexchange.com/users/5021/will-ness), thanks for the feedback [Answer] # Mathematica, 48 ``` Head@#~#2~Fold[##3,#0[x,##2]~Table~{x,List@@#}]& ``` Example: ``` In[1]:= foldTree = Head@#~#2~Fold[##3,#0[x,##2]~Table~{x,List@@#}]&; In[2]:= foldTree[1[2[4[], 5[]], 3[6[]]], Plus, Times, 1] Out[2]= 321 ``` [Answer] # JavaScript (ES6), 62 Javascript seems functional enough, function objects can be easily defined and passed as parameters. Define a node as an object {v:value, c:list of children}, the example tree is: ``` t={v:1, c:[{v:2,c:[{v:4},{v:5}]},{v:3,c:[{v:6}]}]} ``` (here the `c` is optional. Making `c` a mandatory field with value [] if there are no children, the fold function can be 5 chars shorter) and the fold function is: ``` F=(t,a,f,g)=>{ var r=a t.c && t.c.forEach(t=>r=g(r,F(t,a,f,g))) return f(t.v,r) } ``` **Golfed** (there is little to golf) ``` F=(t,a,f,g,r=a)=>(t.c&&t.c.map(t=>r=g(r,F(t,a,f,g))),f(t.v,r)) ``` **Test** In Firefox ``` t={v:1, c:[{v:2,c:[{v:4},{v:5}]},{v:3,c:[{v:6}]}]} F=(t,a,f,g,r=a)=>(t.c&&t.c.map(t=>r=g(r,F(t,a,f,g))),f(t.v,r)) document.write(F(t, 1, (a,b)=>a+b, (a,b)=>a*b)) ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/7056/edit). Closed 7 years ago. [Improve this question](/posts/7056/edit) What's the shortest, well-formed C++ code that exhibits undefined behavior? [Answer] ``` int main(){main;} ``` > > ### 3.6.1 Main function [basic.start.main] > > > 3 - [...] The function main shall not be used within a program. > > > Edit: this is diagnosable, so not UB. --- ``` int main(){for(;;);} ``` > > ### 1.10 Multi-threaded executions and data races [intro.multithread] > > > 24 - The implementation may assume that any thread will eventually do one of the following: > — terminate, > — make a call to a library I/O function, > — access or modify a volatile object, or > — perform a synchronization operation or an atomic operation. > > > --- ``` int main(){int i=i;} ``` > > ### 4.1 Lvalue-to-rvalue conversion [conv.lval] > > > 1 - [...] If the object to which the glvalue refers is [...] uninitialized, a program > that necessitates this conversion has undefined behavior. > > > --- ``` //^L. ``` Here `^L` is the form feed character, which is part of the basic character set. 4 characters (a newline is not required per 2.2:2). Undefined behaviour is per > > ### 2.8 Comments [lex.comment] > > > 1 - If there is a > form-feed or a vertical-tab character in [a `//`-style] comment, only white-space characters shall appear between it > and the new-line that terminates the comment; no diagnostic is required. > > > [Answer] ``` \u\ 0000 ``` This has eight characters, and has undefined behaviour, according to §2.2/1. > > Each instance of a backslash character (`\`) immediately followed by a > new-line character is deleted, splicing physical source lines to form > logical source lines. Only the last backslash on any physical source > line shall be eligible for being part of such a splice. If, as a > result, a character sequence that matches the syntax of a > universal-character-name is produced, the behavior is undefined. > > > [Answer] ``` #include. /*Imagine a new-line right after the dot*/ ``` §16.2/4: > > A preprocessing directive of the form > > >              `#include`  > *pp-tokens   new-line* > > > (that does not match one of the two previous forms) is permitted. [..] > If the directive resulting after all replacements does not match one > of the two previous forms, the behavior is undefined. > > > [Answer] ``` int main(){int i=1>>-1;} ``` Explanation: C++98 and C++11 §5.8/1 both state that > > The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand. > > > [Answer] If one is to believe wikipedia, here's a few: Modifying strings is said to cause undefined behavior. It's always worked for me. ``` int main(int c,char*v){v[0]='.';} ``` A non-void function with no return causes undefined return values. ``` int a(){} int main(){return a();} ``` Division (of int?) by zero is supposedly undefined. All I know is that it crashes. ``` int main(int c){c/0;} ``` [Answer] ``` int main() { int* a; return a[0]; } ``` ]
[Question] [ # Background (feel free to skip) Ordinals are the abstract representation of well-orders. A well-order of a set is a total order, which basically means that every element in the set can be compared against any other element in the set, and one of them is either smaller or larger. Also there are no cycles. The crucial difference between total orders and well-orders is that a well order is always well-founded. This means that every nonempty subset of a well-ordered set has a least element, which implies that an infinite descending chain is impossible; An infinite sequence \$a\_1\gt a\_2\gt a\_3\gt a\_4 \gt ...\$ doesn't exist. This is useful for many things, one of them being proving that recursion terminates. For example, here is the definition of the Ackermann function: \$ A(0,n)=n+1\\ A(m+1,0)=A(m,1)\\ A(m+1,n+1)=A(m,A(m+1,n)) \$ Can you see why it always terminates? We call the Ackermann function with a 2-tuple of natural numbers, and when we recurse, the tuple is smaller under the standard tuple ordering (lexicographic ordering: first compare the first elements, then the second ones). Because the standard tuple ordering is a well-ordering (\$\omega^2\$ in fact), the recursion must eventually terminate. With the knowlege that \$\omega^2\$ is well-founded we were able to prove that the Ackermann function is total. There are of course larger ordinals, one of them being \$\varepsilon\_0\$. All ordinals below \$\varepsilon\_0\$ can be represented with a simple ordinal notation using ragged lists. We can use the standard lexicographic ordering of ragged lists. However there is a problem. The ordering, while a total order, is not a well order. For example, `[ [[]] ] > [ [], [[]] ] > [ [], [], [[]] ] > [ [], [], [], [[]] ] > ...` There is a solution though. We can just make sure that in every list, the elements are in decreasing order. This means that `[ [], [[]] ]` is not an ordinal, since `[[]]` is larger than `[]` Here is a table of some valid ordinal notations | Notation | Value | | --- | --- | | `[]` | \$0\$ | | `[[]]` | \$\omega^0=1\$ | | `[[],[]]` | \$\omega^0+\omega^0=2\$ | | `[[[]]]` | \$\omega^{\omega^0}=\omega\$ | | `[[[[]],[]],[],[]]` | \$\omega^{\omega^{\omega^0}+\omega^0}+\omega^0+\omega^0=\omega^{\omega+1}+2\$ | # Task You are given a ragged list containing only lists. Your task is to determine if that list is an ordinal. A list is an ordinal iff each of its elements are ordinals, and the list is decreasing. Comparison between ordinals can be done with simple lexicographic comparison. That is, given two lists, compare the first elements. If they are equal, compare the second ones and so on. If one of the lists runs out of elements, that list is smaller. For example, say you got the ragged list `[a,b,c,d]`. You must first make sure that `a`, `b`, `c` and `d` are ordinals. Then, make sure that \$a\ge b\ge c\ge d\$, using lexicographic ordering. If both conditions are true, then it's an ordinal. When there is just one element in the list, the second condition is always true. And when the list is empty, both conditions are vacuously true. Standard [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") rules apply. # Test cases ``` [] -> True [[]] -> True [[[]]] -> True [[], []] -> True [[[[]]]] -> True [[[], []]] -> True [[[]], []] -> True [[], [[]]] -> False [[], [], []] -> True [[[[[]]]]] -> True [[[[], []]]] -> True [[[[]], []]] -> True [[[], [[]]]] -> False [[[], [], []]] -> True [[[[]]], []] -> True [[[], []], []] -> True [[[]], [[]]] -> True [[[]], [], []] -> True [[], [[[]]]] -> False [[], [[], []]] -> False [[], [[]], []] -> False [[], [], [[]]] -> False [[], [], [], []] -> True [[[[[[]]]]]] -> True [[[[[], []]]]] -> True [[[[[]], []]]] -> True [[[[], [[]]]]] -> False [[[[], [], []]]] -> True [[[[[]]], []]] -> True [[[[], []], []]] -> True [[[[]], [[]]]] -> True [[[[]], [], []]] -> True [[[], [[[]]]]] -> False [[[], [[], []]]] -> False [[[], [[]], []]] -> False [[[], [], [[]]]] -> False [[[], [], [], []]] -> True [[[[[]]]], []] -> True [[[[], []]], []] -> True [[[[]], []], []] -> True [[[], [[]]], []] -> False [[[], [], []], []] -> True [[[[]]], [[]]] -> True [[[], []], [[]]] -> True [[[[]]], [], []] -> True [[[], []], [], []] -> True [[[]], [[[]]]] -> False [[[]], [[], []]] -> False [[[]], [[]], []] -> True [[[]], [], [[]]] -> False [[[]], [], [], []] -> True [[], [[[[]]]]] -> False [[], [[[], []]]] -> False [[], [[[]], []]] -> False [[], [[], [[]]]] -> False [[], [[], [], []]] -> False [[], [[[]]], []] -> False [[], [[], []], []] -> False [[], [[]], [[]]] -> False [[], [[]], [], []] -> False [[], [], [[[]]]] -> False [[], [], [[], []]] -> False [[], [], [[]], []] -> False [[], [], [], [[]]] -> False [[], [], [], [], []] -> True [[[[[[[]]]]]]] -> True [[[[[[], []]]]]] -> True [[[[[[]], []]]]] -> True [[[[[], [[]]]]]] -> False [[[[[], [], []]]]] -> True [[[[[[]]], []]]] -> True [[[[[], []], []]]] -> True [[[[[]], [[]]]]] -> True [[[[[]], [], []]]] -> True [[[[], [[[]]]]]] -> False [[[[], [[], []]]]] -> False [[[[], [[]], []]]] -> False [[[[], [], [[]]]]] -> False [[[[], [], [], []]]] -> True [[[[[[]]]], []]] -> True [[[[[], []]], []]] -> True [[[[[]], []], []]] -> True [[[[], [[]]], []]] -> False [[[[], [], []], []]] -> True [[[[[]]], [[]]]] -> True [[[[], []], [[]]]] -> True [[[[[]]], [], []]] -> True [[[[], []], [], []]] -> True [[[[]], [[[]]]]] -> False [[[[]], [[], []]]] -> False [[[[]], [[]], []]] -> True [[[[]], [], [[]]]] -> False [[[[]], [], [], []]] -> True [[[], [[[[]]]]]] -> False [[[], [[[], []]]]] -> False [[[], [[[]], []]]] -> False [[[], [[], [[]]]]] -> False [[[], [[], [], []]]] -> False [[[], [[[]]], []]] -> False [[[], [[], []], []]] -> False [[[], [[]], [[]]]] -> False [[[], [[]], [], []]] -> False [[[], [], [[[]]]]] -> False [[[], [], [[], []]]] -> False [[[], [], [[]], []]] -> False [[[], [], [], [[]]]] -> False [[[], [], [], [], []]] -> True [[[[[[]]]]], []] -> True [[[[[], []]]], []] -> True [[[[[]], []]], []] -> True [[[[], [[]]]], []] -> False [[[[], [], []]], []] -> True [[[[[]]], []], []] -> True [[[[], []], []], []] -> True [[[[]], [[]]], []] -> True [[[[]], [], []], []] -> True [[[], [[[]]]], []] -> False [[[], [[], []]], []] -> False [[[], [[]], []], []] -> False [[[], [], [[]]], []] -> False [[[], [], [], []], []] -> True [[[[[]]]], [[]]] -> True [[[[], []]], [[]]] -> True [[[[]], []], [[]]] -> True [[[], [[]]], [[]]] -> False [[[], [], []], [[]]] -> True [[[[[]]]], [], []] -> True [[[[], []]], [], []] -> True [[[[]], []], [], []] -> True [[[], [[]]], [], []] -> False [[[], [], []], [], []] -> True [[[[]]], [[[]]]] -> True [[[], []], [[[]]]] -> False [[[[]]], [[], []]] -> True [[[], []], [[], []]] -> True [[[[]]], [[]], []] -> True [[[], []], [[]], []] -> True [[[[]]], [], [[]]] -> False [[[], []], [], [[]]] -> False [[[[]]], [], [], []] -> True [[[], []], [], [], []] -> True [[[]], [[[[]]]]] -> False [[[]], [[[], []]]] -> False [[[]], [[[]], []]] -> False [[[]], [[], [[]]]] -> False [[[]], [[], [], []]] -> False [[[]], [[[]]], []] -> False [[[]], [[], []], []] -> False [[[]], [[]], [[]]] -> True [[[]], [[]], [], []] -> True [[[]], [], [[[]]]] -> False [[[]], [], [[], []]] -> False [[[]], [], [[]], []] -> False [[[]], [], [], [[]]] -> False [[[]], [], [], [], []] -> True [[], [[[[[]]]]]] -> False [[], [[[[], []]]]] -> False [[], [[[[]], []]]] -> False [[], [[[], [[]]]]] -> False [[], [[[], [], []]]] -> False [[], [[[[]]], []]] -> False [[], [[[], []], []]] -> False [[], [[[]], [[]]]] -> False [[], [[[]], [], []]] -> False [[], [[], [[[]]]]] -> False [[], [[], [[], []]]] -> False [[], [[], [[]], []]] -> False [[], [[], [], [[]]]] -> False [[], [[], [], [], []]] -> False [[], [[[[]]]], []] -> False [[], [[[], []]], []] -> False [[], [[[]], []], []] -> False [[], [[], [[]]], []] -> False [[], [[], [], []], []] -> False [[], [[[]]], [[]]] -> False [[], [[], []], [[]]] -> False [[], [[[]]], [], []] -> False [[], [[], []], [], []] -> False [[], [[]], [[[]]]] -> False [[], [[]], [[], []]] -> False [[], [[]], [[]], []] -> False [[], [[]], [], [[]]] -> False [[], [[]], [], [], []] -> False [[], [], [[[[]]]]] -> False [[], [], [[[], []]]] -> False [[], [], [[[]], []]] -> False [[], [], [[], [[]]]] -> False [[], [], [[], [], []]] -> False [[], [], [[[]]], []] -> False [[], [], [[], []], []] -> False [[], [], [[]], [[]]] -> False [[], [], [[]], [], []] -> False [[], [], [], [[[]]]] -> False [[], [], [], [[], []]] -> False [[], [], [], [[]], []] -> False [[], [], [], [], [[]]] -> False [[], [], [], [], [], []] -> True ``` [Answer] # Haskell + free, 34 bytes To represent ragged lists we use the free package and represent them as free monads generated by the list. ``` f(Free x)=all f x&&scanl1 min x==x ``` ATO seems to be broken and TIO doesn't have free so no link for now. :( Since there are now elements in the list a better representation of this type would be `Fix []`. However I don't know of any Haskell libraries (other than hgl) which export a fully featured version of this. [Answer] # [Python](https://www.python.org), 43 bytes ``` f=lambda a:1in map(f,a)or a<sorted(a)[::-1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hZhNbttADIX3XvcAA60kVA6SrgohybInyM7wQm2kVoAsC7JSpAhykm68aW_SQ7SnqW39kZz3JpsAFoczFB_5DZWfv9sf_bd9czz-eurL9ce_78u7Ot99fsxdnt1UjdvlbVymebLvXH572Hd98RjnySbL1jfb0WVXnoy1Oy3et0UTXyfZylWp69ydq68OfVe1cXJ1aOuqjyO3vndRsnJtVzV9XEYvVfbh-jVKXbS-P_1t9r0r4-J7XsdVkqSujOLiuS2-9FXz1b10r0mUDIce_737s9med3vonorVZrOVP06_lC11xn5eoB0uS8we1u38YFr1Ka8P897-_pcDzJHDETYOcPB4jDpHHOS9iXf88MR_LF9AvyZ8VS-IwX8JQj9fNrHJoUkDiRsyZ7M55s5LMszplD-dQJlBXyyU2SWLQDSmJdETBCSziSwg0SqjpD5AwJfVoAmGpag7SAGNJ3tCi5Nhr6G6m1azig5UNalskBRWsfPReCtUtOJs3C2-xGNUQOIpXtZLSOLlXYgXlEZkgNhYh9pke10NIwwx4i1OvMkKxIsRGB5GJmT4fCEwmbFhuKHAAWiFkSLggajFcUaRBoNTEIE2SBgNEgZKGP4CEwxpzB_KUokUCmzCNIxhCRYM-iDsKfBhqjjENWLIVcHcglcJKgSNGmgLXDW4ECxw8K6QrgY67HoLXn3Ek2lh4UMvzsC-PKaAKFM0AE5TKMgk2wXPLx4nlRpwTwN6NMsAo2pCNtN4xkUIP1ApBLOabeGMw63sZaaASIdjk2IGmXh40cA958QwMZjRkIjNX4HM0J0XxfAkBmkkpSQDHCScFJkNfixInm9qlXnhZxKz5CoYEwlSNFfJ4Mn8KOI0V-k4S62wjC1W8cRLYrUiIyuLh6vpU9WfqDf-TTdJlYKbbpYRyLUIyfyEInhXkAJZHtQKy0AWD_FcNGFfCCxaqQn_huC-oagI8lWjMCspXdUs3BryJpDWDcP0wUA1zUbsuHFkKzIVWOPoXuW-PCqGM9HopHI40hQIuG-gcjjYDGQCdpYRxDf4dUkjD2kVwpzFWMgfoG74d-Z_) Outputs inverted: `False` for valid ordinals, and `True` for invalid ordinals. This is a [DeMorgan's Law](https://en.wikipedia.org/wiki/De_Morgan%27s_laws) conversion of the below, which would be a completely direct translation of the problem statement: ### 46 bytes ``` f=lambda a:all(map(f,a))and a==sorted(a)[::-1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hZhNbttADIX3XvcAA600gG2kXRUCnGVP0J3gxbSWWgGKLMhK0SDISbLxpr1JD9Geprb1R868N9kEiSkOKT7yGzqvv9un_vuxOZ9_Pfbl5uPfbbmr3cOXgzMuc3WdPrg2LdfOWtccjNvtTseuLw6ps3mWbd7vR6-qPHamNlVjjm3RpHc2W5lqbTqzM_X21HdVm9rtqa2rPk3M5t4kdmXarmr6tEyeq-zD3UuyNsnm_vKzTIsfrk4ray-_J2nxsy2-9lXzzTx3LzaxQ8Dzv3d_8v31pM_dY7HK87384_KXsq2NZ78-oB1uj3hn-G7XD6anPrn6NJ8dnn8L4IUcQvh5gMBjGBVHBAreJAg_fBJ-LF9AvyZ81SCJwX9JQn--HOIXhxYNFG6onF_NsXZBkWFNp_rpAsoKhmKhyi5VBKIxLYmeICFZTWQBhVYVJf0BEr49DYZgeBRNB2mgMXIgtIgMZw313fQ06-hIV5POBkVhHTuHxkehphWx8bSEEo9ZAYmnfNksIYmXdyFeUBpRAWJjE-oXO5hqmGGMEW9x4k1WIF6MwAgwMiEj5AuByYwNjxsKHIBWGCkCHohaHGcUaTA5BRFog4TRIGGghOkvMMGQxvyhLJVIocAmTMMYlmDBoI_CngIflopDXCOGXBXMLXqVoEbQqIG2yFWDG8EHDj4V0tWDDrveolcf8WRa-PChF2fkXJ5TRJQpGwCnKRVkkuOC95eAk0oNeKYHerTLAKMaQrbTBMZFiDBRKQSzesfCHYdb2ctMCZEJxybFDLLx8KaBZ86FYWIwo0citn9FKkNPXhTDmxikkZSSLHCQcFJktvixJHm9qVXWhcckZslVsCYSpGiuksWT-VHEaa7SdZZaYRv7WMUbL8nVFxlZWT5czZCq4UadhzfdJNUa3HSzjECuRUjmJxTBp4ISyPagVtgGsnmI56IJ-4bAspWa8O8Q3DeWFUG-GhRmJa2rhoVbY94E0npgmD4YqN6wETseHDmKTAU2OHpWuS_PiuFMDDrpHI40BQLuG-kcDjYPMhE7qwjiG_x2STOPaRXDnI-xmD9A3fDvzP8) But by inverting it, `all` becomes `any`, which can then be changed to `1in` (using [this tip of mine](https://codegolf.stackexchange.com/a/241476)), which saves a byte on parentheses. Also, `and` becomes `or`, for another -1. Finally, by the magic of the properties of lexicographic comparison, we can use `<` instead of `!=` in the inverted form, for a total of 3 bytes saved. --- # [Python](https://www.python.org), 44 bytes ``` f=lambda a:{*map(f,a)}<={a==sorted(a)[::-1]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hZhBbtNQEIb3WXOAJ69s5FSFFYpwl5yAnZWFoTZYch3LcREoyknYZAM34RBwGpLYjmfm_f_rpmoznjfj-We-N-nP392P4euuPZ1-PQ_V-t3ftMqa4unTY-GKzeH1U9HFVVokx_fZociy_a4fyse4SPLNZv1me5x86mrXu8bVrdt1ZRvfJ5uVq1PXu8w1d_uhr7s4udt3TT3EkVs_uChZua6v2yGuokO9eXt_jFIXrR_OP6u4_FY0cZ0k59-juPzelZ-Huv3iDv0xiZIx4Onfqz_59nLSx_65XOX5Vv5x_kvZUmfslwe0w_URc4Z1u3wwP_WhaPa3s_3zrwFMyDGEzQMEnsKoOCKQ9yZe-PET_2P5Avo14at6SYz-SxL68-UQWxxaNFC4sXK2mlPtvCLDms710wWUFfTFQpVdqghEY1oSPUFCsprIAgqtKkr6AyR8fRoMwfgomg7SQFNkT2gRGc4a6rv5adbRga4mnQ2Kwjr2FhofhZpWxMbT4ks8ZQUknvNls4QkXt6FeEFpRAWIjU2oLbY31TDDECNe4sSLrEC8mIDhYWRGhs8XApMbNgw3FDgArTBSBDwQtTjOKNJgcgoi0AYJo0HCQAnTX2CCIY35Q1kqkUKBTZiGMSzBgkEfhD0FPiwVh7hGDLkqmFvwKkGNoFEDbYGrBjeCBQ4-FdLVQIddb8Grj3gyLSx86MUZOJfnFBBlzgbAaU4FmeS44P3F46RSA55pQI92GWBUQ8h2Gs-4COEnKoVgVnMs3HG4lb3MnBCZcGxSzCAbD28aeOatMEwMZjQkYvtXoDL05EUxvIlBGkkpyQIHCSdFZosfS5LXm1plXXhMYpZcBWsiQYrmKlk8mR9FnOYqXWepFbaxxSreeEmuVmRkZflwNX2q-ht17t90s1QpuOluMgK5FiGZn1AEnwpKINuDWmEbyOYhnosm7BsCy1Zqwr9DcN9QVgT5alCYlbSuGhZuDXkTSOuBYfpgoJphI3Y8OHIUmQpscPSscl-eFcOZGHTSORxpCgTcN9A5HGwGMgE7qwjiG_x2STMPaRXCnMVYyB-gbvx35n8) Bonus answer, outputting non-inverted. [Answer] # Rust Nightly + `#![feature(is_sorted)]`, 101 bytes ``` #[derive(PartialOrd,PartialEq)] struct T(Vec<T>);fn f(t:&T)->bool{t.0.is_sorted()&&t.0.iter().all(f)} ``` [Playground Link](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=7b20fdd6201977a371206875fc39bed8) [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` f=lambda a:[`a`][a<sorted(a,key=f)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hZhNjtNAEIX3XnOAnrCxpUwErFAYs-QE7KxIY4gNFh7bsj1AzsAR2GSDOAmHgNPgxH9V3e_1LOPq6i7Xq_q6nJ-_m1P_ua5enc-_Hvv89vXf53lcpg8fjqlJ98l9en9I0ruubvvsGKbbL9kpzqPDtPRH8dAMFtOduiCvW1Oaorr82HX9sah2bZYey6LKujDaB6bYmtbEphyMbdGE0a5ryqIPN-b2rdlEgenb0z4Ps69pGRZR9KaOXwYm-_4xa_p9Hb8Y_HNT38RXe3vZzzRtUQ3-39q6-rSJxpDO_579SQ6XLd-3j1mQJAf5Y_ilbFtj2S8LtMN1ibWH7XZ5MK96l5bdsre7__UA68jxCDsOcPB0jDpHHOS8iXP8-MR9LF9AvyZ8VSeI0X8NQj9fN7GTQ5MGEjdmzs7mlDsnyTCnc_50AmUGXbFQZtcsAtGYlkRPEJDMJrKARKuMkvoAAV9XgyYYl6LuIAU0newILU6GvYbqbl7NKtpT1aSyQVJYxS5H461Q0Yqzcbe4Ek9RAYnneFkvIYnXdyFeUBqRAWJjHWon2-lqGKGPEU9x4klWIF5MwHAwMiPD5QuByYINixsKHIBWGCkCHohaHGcUaTA4BRFog4TRIGGghOGvMMGQxvyhLJVIocAmTMMYlmDBoPfCngIfpopDXCOGXBXMzXuVoELQqIE2z1WDC8EGDt4V0tWCDrvevFcf8WRa2PChF6dnXx6TR5Q5GgCnORRkku2C5xeHk0oNuKcFejTLAKNqQjbTOMZVCDdQKQSzWtvCGYdb2cvMAZEOxybFDDLx8KKBey6JYWIwo0UiNn95MkN3XhXDkxikkZSSDHCQcFJkNvixIHm-qVXmhZ9JzJKrYEwkSNFcJYMn86OI01yl4yy1wjK2sYonXhKrLTKysni4mi5V3Yk6cW-6WaotuOkWGYFcq5DMTyiCdwUpkOVBrbAMZPEQz1UT9oXAopWa8G8I7uuLiiBfNQqzktJVzcKtPm8Cad0wTB8MVKvZiB03jmxFpgJrHN2r3JdHxXAmGp1UDkeaAgH39VQOB5sFGY-dZQTxDX5d0sh9WvkwZ2PM5w9QN_6d-R8) Heavily based on (same logic as) [@pxeger's python answer](https://codegolf.stackexchange.com/a/249480/107561). My additions: 1. Use the fact that string representation of lists has the correct ordering. 2. Use `sort` `key` to save `map` construction. 3. Use exit code for signalling freeing up return value for use with 1,2. [Answer] # [Factor](https://factorcode.org/), 40 bytes ``` [ [ [ after=? ] monotonic? ] deep-all? ] ``` [Try it online!](https://tio.run/##lZnPctMwEMbveQrxAO0DwAA3GC5cgFOHg0nVNjOObRzn0PlGzx6SKUyxIml/214SZ6Ostav9/vih2y7jfPrx7cvXz2/D4zwep93wGPbd8nQ7zvdxDof4@xiHbTy8vrq9j3EK0xyX5Xmad8MSdmN4t9loE85/Cim8CTcfwvf5GP9euVwrXX25Xo6vf@fft2orqvlpfeWUZ/Sp6w95Sq20XhOrJy4zwrqBqw1Yp7lOtL2DMndRxk6SvW7vd/NmUqmk5ZDV75Qrh4rbLvD/JW61gVAUaYdCW@UFz0tu9adQjwr0Ke1mu6PNm0zlA1QLa/bMdUuYR0loZ62xJRRFDl/xELcmgcA0EJirwpOFTRd7wpg1AlNinbvAzAKLsfFmdHaqQUMtDE1Dx1wV@1FjvhYbrT6p8UAHQ928U4giDiRxoYmFKGtMaWOPcCTFoCKmXSPMNcbYICkMlIJg6YFVBq3o5lMN1euhJlCVMAjgu/DuE8wSjqSsoMIy2pRFkLYI0mu5qBCnQ4wSoXpCOlPCLZtswUU5NwOnJNW5bz0U0zknQRRPABDFSqO2qKeLpUKminbAQZOdVNlNl4UHlS2rhSMpya6QdktbCesrYY0lrLOEtZaw3hLXXOK6S1x7iesvQQ0m6MIIjlQijiprtjWZR1ZyacnlJZeYDpnJpCaz8UThLCH3TzAyL6awLhbUxqBJUGheI666ifIGmAMFbF5OUU3vkv/iCRgtDUVtXnzbEOXWh8P@cFggQObmfeLyQmw/xGSTqeWk1kOxheI0ZcQTgHaKeCj0chCbTNxwTdx0Tdx4Tdx8TS0Dtl0C04NCnCa1/FjLdRN33kTdN7ivKBQhe2qZtS1vDxXW@WzHYS66DUZkMoID4/ByHX6uw9N1@LoOb9fh7zo8XqfP6/B6HX6v0/N1@745GKbN6S5c/ruHJc7vP4afYT8O4zIOu@3lzeXR@k3X9@fXp303nQOnl0fsv/rzp7HbPoWhP/0B "Factor – Try It Online") Using a depth-first search, is every element non-increasing? [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ṢṚ⁼ȧ߀Ạ ``` [Try it online!](https://tio.run/##y0rNyan8///hzkUPd8561LjnxPLD8x81rXm4a8H///@jo6NjY3UUoCQYxwIA "Jelly – Try It Online") [Test all cases given](https://tio.run/##fZe7UQRBDER9oiAAGUcARKI6E4ciAUxwyAEHCgcHlyqgsMAhjSOR5bjbj2b69Xq7Wu2MpFG3ei4vrq6uh2H3/rR7v/@9@fx5/n74vX3ZfTwOX6@7t6fvu/Ov171hGPIkcxunZ9vYP@R2edw/F3s0n/6/Vc/I9r11378dv2@Wxbr1Dgs2G0T2Ftklpjg2JY7O6fCWEmxnmiNsMpAk2u0OP0WKafyvSZby70twrEFblUi1QWliLuCmFlAcp2pIpbVqkXgAcAb91ktdemNXrVIbPcQ@oqNXQpNIa8IBR2mEvlu0taUbAlpkXJCbC/qrTxPaZ9pF/@5baN5Fe7Q7juPWkWCk5g3T5OoqBZ0TUisgoNaphYoEwECzWPNwE8SNkOtgGElWxGIsqN00qAXnGXwKcQJqpME@wl/DKDAUs8CzQhFYROOb4Qh8BdBFjonKR0JcRABASoFcVcBJXId0p8kjk1WQAj2StyNOObQKVjEzp4blX3KHgjewBcZ2RM5cDsG4ebAyEtamgvTFuGXi6FSdgTMj6nzRGQpqhSZHJNub8aPzVGcVBFNIMHmw0nSzUw/CHDclyNDwo5k474iHqqtMebq57ka7m@52wOOMJxWrg3pKKIwmQMGZRnUauYEVI/uSp9UdJD0ElagK5vRRlYRVMOQOjcf6YCmLKnCnpYyccooKlEKpltVVIK16wh6LG4lmVl1hFRq5K2EvR4eajAQcEfZ0phAMEfbSArjMmm6EMJXfSkOC3cjK8CIUfwBuKk3pFK4VuaxzoQ4rN0Unl9cUM4pmPUen/J34d/rfXgHcLcBeBNxdYO064G4E9lKwdi9YvRpMeD/Z/gE) ## Explanation ``` ṢṚ⁼ȧ߀Ạ given a candidate list: ȧ check that the following two conditions are satisfied: ⁼ 1. the list is equal to Ṛ the reverse of Ṣ the sorted version of the list ߀Ạ 2. and the same is true for every element in the list ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` ¹⊞υAFυWι«⊞υ§ι±¹¿‹⌊ι⊟ι⎚ ``` [Try it online!](https://tio.run/##NUw9CwIxFJvvfsUb34M6ODuJ04FKd@lQzp590GuPfqgg/vbaE82QhJBktDqOQbtaZWSfcUu7XpZksQgY/FIyUkumEAELwcOyM4BM8Oq7f22fB381T2QBZ3PT2bSTddTxBHg0KeGJPc9lbjsBMixNieDgjI7Yeu9aLyuUEvCjr1F1c3cf "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a valid ordinal, nothing if invalid. Explanation: ``` ¹ ``` Assume the input is an ordinal. ``` ⊞υA ``` Start by checking the input. ``` Fυ ``` Loop through the ragged lists to check. ``` Wι« ``` Loop though the elements of the current ragged list. ``` ⊞υ§ι±¹ ``` Add the last element of the current ragged list to the list of lists to check. ``` ¿‹⌊ι⊟ι⎚ ``` Check that the last element is also the minimum element, and also remove it from the current ragged list, so that the rest of the current ragged list can be checked. Note that Charcoal's input format is a list of inputs, so if you accidentally enter `[[], [[]]]` you're actually providing two inputs, and the program will happily tell you that the first input is a valid ordinal. ]
[Question] [ The Mathematica SE question [Creating the Yin Yang symbol with minimal code](https://mathematica.stackexchange.com/q/246309/47301) seems to be an out-of-the-box ready-to-go Code Golf SE question! > > The following code creates the Yin Yang symbol > > > ``` Graphics[{Black, Circle[{0, 0}, 1], White, DiskSegment[{0, 0}, 1, {1/2 \[Pi], 3/2 \[Pi]}], Black, DiskSegment[{0, 0}, 1, {3/2 \[Pi], 5/2 \[Pi]}], White, Disk[{0, 0.5}, 0.5], Black, Disk[{0, -0.5}, 0.5], Black, Disk[{0, 0.5}, 0.125], White, Disk[{0, -0.5}, 0.125] }] // Show ``` > > Knowing that 'there is always someone who can do things with less code', I wondered what the optimal way is, in Mathematica, to create the Yin Yang symbol. > > > Not really an urgent question to a real problem, but a challenge, a puzzle, if you like. I hope these kind of questions can still be asked here. > > > From my current understanding what's actually sought in this question is not the symbol for Yin and Yang which is just the complementary black and white halves of a circle, but the [Taijitu or "Diagram of the Utmost Extremes"](https://en.wikipedia.org/wiki/Taijitu) which is rotated by 90 degrees so that the circles halves are roughly left and right, and with two small circular spots are added along the vertical axis at half radius. Answers to the meta question [Default acceptable image I/O methods for image related challenges](https://codegolf.meta.stackexchange.com/q/9093/85527) already show a high level of community acceptance; I wouldn't want to specify further. Regular code golf; fewest bytes to generate Code Golf SE-acceptable graphics output per the meta link above. In response to (and including recommendations from) helpful comments: * border thickness must be between 1 pixel and 4% of the overall diameter * spot diameter must be between 1/10 and 1/7 of the overall diameter * overall diameter at least 200 pixels * error 2 pixels / 1%. * Should resemble black ink on white paper as the original symbol is defined. However since some anti-aliasing uses color, use of color is not excluded as long as the image looks monochrome. * same orientation as the image specimen left side white, small dots along central vertical axis. --- [![This is the Taijitu (太極圖), with black representing yin and white representing yang. It is a symbol that reflects the inescapably intertwined duality of all things in nature, a common theme in Taoism.](https://i.stack.imgur.com/FYtID.png)](https://i.stack.imgur.com/FYtID.png) [Source](https://commons.wikimedia.org/wiki/File:Yin_yang.svg): > > This is the Taijitu (太極圖), with black representing yin and white representing yang. It is a symbol that reflects the inescapably intertwined duality of all things in nature, a common theme in Taoism. No quality is independent of its opposite, nor so pure that it does not contain its opposite in a diminished form: these concepts are depicted by the vague division between black and white, the flowing boundary between the two, and the smaller circles within the large regions. > > > [Answer] # [R](https://www.r-project.org/), ~~153~~ ~~152~~ ~~145~~ 144 bytes *Edit: -8 bytes thanks to pajonk* ``` plot(NA,,,l<-c(-8,8),l,an=F,ax=F) Map(function(r,c,y,h)polygon(r*1i^(1+1:(h*99)/99)+y*1i,b=c,c=c),c(8.2,8,4,4,1,1),1:0,c(0,0,l/2,4,-4),-.75:5*8) ``` [Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=plot(NA%2C%2C%2Cl%3C-c(-8%2C8)%2Cl%2Can%3DF%2Cax%3DF)%0AMap(function(r%2Cc%2Cy%2Ch)polygon(r*1i%5E(1%2B1%3A(h*99)%2F99)%2By*1i%2Cb%3Dc%2Cc%3Dc)%2Cc(8.2%2C8%2C4%2C4%2C1%2C1)%2C1%3A0%2Cc(0%2C0%2Cl%2F2%2C4%2C-4)%2C-.75%3A5*8)) [![enter image description here](https://i.stack.imgur.com/V04QC.png)](https://i.stack.imgur.com/V04QC.png) ``` plot(NA,,,l<-c(-8,8),l,an=F,ax=F) # initializes a new plot area # from x,y = -8 to 8 # without annotation, without axes ``` ``` Map( # apply function... function(r,c,y,h) # with arguments r=radius, c=colour, y=y position, h=half-circle? polygon(r*1i^(1+1:(h*99)/99)+y*1i, # draw polygon using complex coordinates b=c,c=c), # border=c, colour=c # ...to these values: c(8.2,8,4,4,1,1), # radii for 6 circles 1:0, # colours (recycled; 0=white, 1=black) c(0,0,-4,4,4,-4), # y positions -.75:5*8 # abs≥4:full circle, 2:half circle (only 2nd) ) ``` [Answer] # JavaScript (ES6), ~~141~~ ~~110~~ 96 bytes ``` X=>Y=>(e=y=>((R=X-210)**2+(Y-y*100-10)**2)**.5/5)(2)<42&&e(2)>40|R>0^e(R>0?3:1)<20^e(3)<5^e(1)<5 ``` A pixel-shader function taking x and y coordinates between 0 and 420 and returning a boolean value, as allowed by [this](https://codegolf.meta.stackexchange.com/a/18305/100664) consensus. The below snippet creates a 420x420 image. -14 bytes thanks to tsh ``` f= X=>Y=>(e=y=>((R=X-210)**2+(Y-y*100-10)**2)**.5/5)(2)<42&&e(2)>40|R>0^e(R>0?3:1)<20^e(3)<5^e(1)<5 let canvas = document.getElementById('x').getContext`2d` for(let i = 0; i < 420; i++){ for(let j = 0; j < 420; j++){ canvas.fillStyle = f(i)(j) ? 'black' : 'white' canvas.fillRect(i,j,1,1); } } ``` ``` <canvas id=x width=420 height=420 ></canvas> ``` ## Explanation (old) ``` X=>Y=> // Curry function taking x and y parameters (e = y => ( // Euclidean distance function named e (X-210)**2+ // To (x = 200, (Y-y*100-10)**2 // y = input * 100 + 10 ) ** .5 )(2) < 210 // Is the distance to the center less than 210? && e(2) > 200 // If not, shortcircuit, else is the distance to the center greater than 200 (border)? | ( // Else... Y > 210 // Is Y > 210 (Bottom half) & e(3) < 100 // And distance to center of lower circle less than 100 (Black circle on bottom) | X > 210 // Or X > 210 (Area on left) & e(1) > 100 // And distance to center of upper circle > 100 (Excluding white top circle) ) & e(3) > 25 // And distance to center of lower circle > 25 (Excluding white bottom circle) | e(1) < 25 // Or distance to center of upper circle < 25 (Including black top circle) ``` [Answer] # SVG (HTML 5) 172 bytes This is just an optimization of Neil's post, but he was warry of path minification. I think that just a bit silly (I hope you can excuse the expression), as there are at least two libraries in millionfold use that do just that. One is a default part of Adobe Illustrator's SVG export, the other is part of the [SVGO](https://www.npmjs.com/package/svgo) library. – Both would not fair well if used unaltered here, because they assume to work for standalone SVG files which need to be wellformed XML. The pivotal part of path optimization is that the [grammar](https://svgwg.org/svg2-draft/paths.html#PathDataBNF) expects a greedy parser and takes separation as optional: everything that can be legally interpreted as part of a token is read as a part of it, and the next token can start immediately. So ``` M 0,-20 a 40,40 0 0 1 0,80 ``` can be shortened to ``` M0-20a40,40,0,010,80 ``` * because the `-` cannot be interpreted as part of a preceding number * because command letters need no separation from numbers * because the fourth and fifth parameters to an `A`/`a` command, commonly called `large_arc` and `sweep`, are actually flags that can only take the values `0` or `1`. ``` <svg viewBox=-41,-21,82,82><path d=M0-20a40,40,0,010,80a20,20,0,010-40a20,20,0,000-40a40,40,0,000,80a40,40,0,010-80 stroke=#000 /><circle r=5 /><circle cy=40 r=5 fill=#fff> ``` [Answer] # PostScript, ~~139~~ 86 bytes ``` 00000000: 5b28 5b29 7b92 967d 2f63 7b30 8768 0192 [([){..}/c{0.h.. 00000010: 057d 285d 297b 6392 427d 3e3e 920d 2e30 .}(]){c.B}>>...0 00000020: 3492 9b88 4837 3292 8b39 7b34 7d92 8332 4...H72..9{4}..2 00000030: 2e30 3220 6392 a732 870e 0139 3092 0592 .02 c..2...90... 00000040: 4233 2031 5d5b 3520 315d 3320 2e32 5d30 B3 1][5 1]3 .2]0 00000050: 5b35 202e 325d [5 .2] ``` Before tokenization: ``` [([){setgray}/c{0 360 arc}(]){c fill}>>begin .04 setlinewidth 72 72 scale 9{4}repeat 2.02 c stroke 2 270 90 arc fill 3 1][5 1]3 .2]0[5 .2] ``` As rendered by Preview in OS X: [![As rendered by Preview in OS X](https://i.stack.imgur.com/k74b5.png)](https://i.stack.imgur.com/k74b5.png) Explanation: ``` % first some abbreviations [([){setgray}/c{0 360 arc}(]){c fill}>>begin .04 setlinewidth 72 72 scale 9{4}repeat % push 4s onto stack 2.02 c stroke % main stroked circle (r=2.02) 2 270 90 arc fill % black semicircle (r=2) 3 1] % black semicircle (r=1) [ % choose white 5 1] % white semicircle (r=1) 3 .2] % white semicircle (r=.2) 0[ % choose black 5 .2] % black semicircle (r=.2) ``` [Answer] # HTML, 267 bytes ``` <c style="border:1vw solid;background:linear-gradient(90deg,#fff 50%,#000 50%)"><c w style=top:0%><c></c></c><c style=top:50%><c w><style>c{position:absolute;padding:25%;border-radius:50%;top:25%;left:25%;background:#000}c c c{transform:scale(.5)}[w]{background:#fff} ``` Size of large ball is 52vw (50vw + border). Width of border is 1vw (1.92%). Size of small ball is 6.25vw (12.0%). [Answer] # SVG (HTML5), ~~199~~ 183 bytes ``` <svg viewBox=-41,0,82,82><path d=M0,1A40,40,0,0,1,0,81A20,20,0,0,1,0,41A20,20,0,0,0,0,1A40,40,0,0,0,0,81A40,40,0,0,1,0,1 stroke=#000 /><circle cy=21 r=5 /><circle cy=61 r=5 fill=#fff> ``` The path draws the main black body but also the outer border (it's golfier than a separate circle for some reason), but the two dots are separate circles. The border thickness is 1.25% of the overall diameter. The spot diameter is 12.5% of the overall diameter. The image scales to the viewing area. Edit: Saved 16 bytes thanks to @ccprog. ]
[Question] [ # Introduction Given an undirected graph G, we can construct a graph L(G) (called the line graph or conjugate graph) that represents the connections between edges in G. This is done by creating a new vertex in L(G) for every edge in G and connecting these vertices if the edges they represent have a vertex in common. Here's an example from [Wikipedia](https://en.wikipedia.org/wiki/Line_graph) showing the construction of a line graph (in green). [![The graph G](https://i.stack.imgur.com/rnhiD.png)](https://i.stack.imgur.com/rnhiD.png) [![New vertices representing each edge in G](https://i.stack.imgur.com/LCxoy.png)](https://i.stack.imgur.com/LCxoy.png) [![Vertices are connected when their edges in G are connected](https://i.stack.imgur.com/PEHto.png)](https://i.stack.imgur.com/PEHto.png) [![The line graph L(G)](https://i.stack.imgur.com/4ioEL.png)](https://i.stack.imgur.com/4ioEL.png) As another example, take this graph G with vertices A, B, C, and D. ``` A | | B---C---D---E ``` We create a new vertex for each edge in G. In this case, the edge between A and C is represented by a new vertex called AC. ``` AC BC CD DE ``` And connect vertices when the edges they represent have a vertex in common. In this case, the edges from A to C and from B to C have vertex C in common, so vertices AC and BC are connected. ``` AC / \ BC--CD--DE ``` This new graph is the line graph of G! [See Wikipedia for more information.](https://en.wikipedia.org/wiki/Line_graph) # Challenge Given the adjacency list for a graph G, your program should print or return the adjacency list for the line graph L(G). This is code-golf, so the answer with the fewest bytes wins! ### Input A list of pairs of strings representing the the edges of G. Each pair describes the vertices that are connected by that edge. * Each pair (X,Y) is guaranteed to be unique, meaning that that the list will not contain (Y,X) or a second (X,Y). For example: ``` [("1","2"),("1","3"),("1","4"),("2","5"),("3","4"),("4","5")] [("D","E"),("C","D"),("B","C"),("A","C")] ``` ### Output A list of pairs of strings representing the the edges of L(G). Each pair describes the vertices that are connected by that edge. * Each pair (X,Y) must be unique, meaning that that the list will not contain (Y,X) or a second (X,Y). * For any edge (X,Y) in G, the vertex it creates in L(G) must be named XY (the names are concatenated together in same order that they're specified in the input). For example: ``` [("12","13"),("12","14"),("12","25"),("13","14"),("13","34"),("14","34"),("14","45"),("25","45"),("34","45")] [("DE","CD"),("CD","CB"),("CD","CA"),("BC","AB")] ``` ### Test Cases ``` [] -> [] [("0","1")] -> [] [("0","1"),("1","2")] -> [("01","12")] [("a","b"),("b","c"),("c","a")] -> [("ab","bc"),("bc","ca"),("ca","ab")] [("1","2"),("1","3"),("1","4"),("2","5"),("3","4"),("4","5")] -> [("12","13"),("12","14"),("12","25"),("13","14"),("13","34"),("14","34"),("14","45"),("25","45"),("34","45")] ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` {⊇Ċ.c¬≠∧}ᶠcᵐ² ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/pRV/uRLr3kQ2sedS541LG89uG2BckPt044tOn//@hoJUMlHSUjpVgdCMsYzjIBs4yALFMwyxguZgIRi/0fBQA "Brachylog – Try It Online") [With all test cases](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp0A5Ha1H@nSSz605lHngkcdy2sfbluQDJQ4tOn//2iF6FgdhehoJQMlHSVDpVgUjk40kNRRMoIJJwI5SWDhJCArGcxKBrISYQqgqqH6jOEsEzDLCMgyBbOM4WImELFYhVgA) *(-1 byte replacing `l₂` with `Ċ`, thanks to @Fatalize.)* ``` {⊇Ċ.c¬≠∧}ᶠcᵐ² Full code { }ᶠ Find all outputs of this predicate: ⊇Ċ. A two-element subset of the input c which when its subarrays are concatenated ¬≠ does not have all different elements (i.e. some element is repeated) ∧ (no further constraint on output) cᵐ² Join vertex names in each subsubarray in that result ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~45 39 33 29 30 35~~ *and five years later:* 31 bytes ``` (*'<:')#(3=#'?',/')#+{x@!2##x}@ ``` [Try it online!](https://ngn.codeberg.page/k#eJxdj1FrgzAUhd/zK+7iwGQTnMa9JB3zfxShapNN2iokESyl++1LjLqyl/Ddc8+5hyhOXuIdj2lE2EcUf8ZJ6vj1NpVPeRRN9xIhw920m+6QmkFbpDgxpYlVSSFVgwYrje36rwQu9UmCGbUE+y1BSzOeLSg9XEBBZ8CH5RFZfnveX380VzCJw3AS5KDq7iwmcRWaVq7FHwQ19q3thh7ZPaGC0MpBQvAbFjjDq0AeBPcKnGNKEYA3+jFz8+Kr3djMvsZRO1PrqA4J/yPv8ssmbBu/buvg9HG3pOu5pWypZRsVM+WO3mdim1YE7aEs87Zsyc5c/HEe8hl70D2zhYt/XAS/i23MVp1Wv3IgcTM=) `{` `}@` apply a function with implicit argument `x` `#x` length `2#` repeat twice `!2##x` pairs of indices in `x` (the columns of a 2 by `#x` matrix) `x@` index into `x` `+` transpose `(` `)#` filter `(3=#'?',/')#` filter only those pairs whose concatenation (`,/`) has a count (`#`) of exactly 3 unique (`?`) elements This removes edges like `("ab";"ab")` and `("ab";"cd")` from the list. `(*'>:')#` filter only those pairs whose sort-descending permutation (`>`) starts with (`*`) a 1 (non-0 is boolean true) In our case, the sort-descending permutation could be `0 1` or `1 0`. [Answer] ## Ruby, 51 bytes ``` ->a{a.combination(2){|x,y|p [x*'',y*'']if(x&y)[0]}} ``` [Try it online!](https://tio.run/##VYvBDoIwDIbve4plJg7MJAh4MdG7Jx9g2WEDiRwcBCFhYTz7rBMw9tB@/f627ZVxJT67/UWOMsrrp6q07KpaB0k42oEZ22A@7ChlBpqoymDYmpDHYpocR1wwxDmJCSMHIv4WxqEzkixawqK8VkC5pxxILgfz9fyXrpR5SoCOntLVZV8nkIjuMn/gosZWtq1FGKrpuxcmVw3zhDcj@In8Anrru09CvSo5xGJN0V0X7g0) For each combination of two edges, if they have a vertex in common (i.e. if the first element of their intersection is non-`nil`), print an array containing the two edges to STDOUT. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Œcf/Ƈ ``` [Try it online!](https://tio.run/##y0rNyan8///opOQ0/WPt/w@3Zz1qWvOoYY7Co4a57v//R0crGSrpKBkpxepAWMZwlgmYZQRkmYJZxnAxE4hYLAA "Jelly – Try It Online") [Answer] ## JavaScript (Firefox 30-57), 77 bytes ``` a=>[for(x of a=a.map(x=>x.join``))for(y of a)if(x<y&&x.match(`[${y}]`))[x,y]] ``` Assumes all inputs are single letters (well, any single character other than `^` and `]`). [Answer] # [C (gcc)](https://gcc.gnu.org/), 173 bytes Input `i` and output `o` are flat, null-terminated arrays. Output names can be up to 998 characters long before this will break. ``` #define M(x)o[n]=malloc(999),sprintf(o[n++],"%s%s",x[0],x[1]) f(i,o,j,n,m)char**i,**j,**o;{for(n=0;*i;i+=2)for(j=i;*(j+=2);)for(m=4;m--;)strcmp(i[m/2],j[m%2])||(M(i),M(j));} ``` [Try it online!](https://tio.run/##fZLBjoIwEIbvPMWkG5IWahbRPZiGfQOfgO0BKqwlFgyYrFF5drYt4mLS9UDhn/lm/mmLWHwLMQxvu6KUdQFbfCZNWvNEZYdDI/BmsyG0O7ayPpVYJ8KQU@R3fofoOY24XpaceCWWtKEVrakiYp@1QSBpEFT6adi1bFpcJxELJJNhEhOjq0SyAFdGMhtQyZqpxYKR7tQKdcQyVe8xp1Wq/JiT2w1vsSR0iytCWD/oaaDbNz/YmsGxLSiMvpC1LYGrB3CfGZlRDUGYDmorwKZaQgIRM3QqOdMyTCAmmvgrxH5H/Y6ALh@x@xtC0HtmM4uvGmnde57prDJZ43GEcbos5drsantHeu3ZI5XPUijSRmiJqAsU/4LmA1DsLtvNyzID5lNZbpSYlDAqczcp5k2e3Ea1elLrScVGfUxq9ZRbz3MPu4fjJdW/nTWNpkSJMwoXe@r24tGnvZdZAExgJCyfO/j8BS8cvHjB7xz87gVfOPjCxffDLw "C (gcc) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` 2XN!"@Y:X&n?@ ``` [Try it online!](https://tio.run/##y00syfn/3yjCT1HJIdIqQi3P3uF/bKxahpKDmsv/6mh1Q3UdBXUj9VgdBSjbGMI2ArFNkcRNIGxjJLYJVE0tAA "MATL – Try It Online") Not as bad as I expected given cell array input. Basically the same idea as @Doorknob's [Ruby answer](https://codegolf.stackexchange.com/a/170697/8774). ``` 2XN % Get all combinations of 2 elements from the input ! % Transpose " % Iterate over the columns (combinations) @ % Push the current combination of edges Y: % Split it out as two separate vectors X&n % Get the number of intersecting elements between them ?@ % If that's non-zero, push the current combination on stack % Implicit loop end, valid combinations collect on the stack % and are implicitly output at the end ``` [Answer] # Mathematica 23 bytes ``` EdgeList[LineGraph[#]]& ``` Example: `g = Graph[{1 <-> 2, 2 <-> 3, 3 <-> 4, 2 <-> 4 }]` [![enter image description here](https://i.stack.imgur.com/mxlZE.png)](https://i.stack.imgur.com/mxlZE.png) ``` EdgeList@LineGraph[g] ``` (\* {2 <-> 1, 3 <-> 2, 4 <-> 1, 4 <-> 2, 4 <-> 3} \*) [Answer] # [Python 2](https://docs.python.org/2/), 109 bytes ``` lambda a:[(s,t)for Q in[[''.join(p)for p in a if x in p]for x in set(sum(a,()))]for s in Q for t in Q if s<t] ``` [Try it online!](https://tio.run/##bcyxDsIgEIDh3ae4sPRIiNG2LqY@RGdkoFUixlJSMNGnR6BNh8aFfPnvDvv1j9GUQV2u4SWH7iZBnjk65qkaJ2hBG86LYv8ctUGbm40NJGgFnyQrUsx0d4/uPaBkSCnN3aXeQqKfGe9c40WwkzYeFHJBd6uRHAgjR0L/RobxZaTcjmWMXR53UX1WHyW3i8v18k@1qs4qo05Z1drquQkawg8 "Python 2 – Try It Online") For each node `x` (discovered by making a set from the flattened list of edges), make a list of the pairs `p` that have `x` as a member; then, for each of those lists `Q`, find the unique, distinct pairings within `Q` (uniqueness/distinction is enforced via `if s<t`). [Answer] # [Scala](http://www.scala-lang.org/), 145 bytes Modified from [@Doorknob's Ruby answer](https://codegolf.stackexchange.com/a/170697/110802). --- Golfed version. [Try it online!](https://tio.run/##fZJBa4MwFMfvfopH8JCAyNZ2F8HCDjsMNnYoO4mHZ6Zdthq7JB0V6Wd3SWxrK2WBF/PL/@97TxPNcYN9U3yV3MArCgldAPBRVlBboKjWOoFHpbDNVkYJuc5ZAu9SGEih652vopisyp/Mx2DJWYoxb@pCSDSikZrOWFw1qkT@2XHUJbwIbeg@alm6FBXdx0KaUmnbA21ZLBv5VG9Ny7Y2m9lIqkkWdvu4/h7yU0LYIQq79nont9GDHb@4ASG3O@OqJL5WNk6nHnP7Bb6NAPzwaxZdkp/IHYmA3BP2nxYNm3ZpeXbbi04rRm/hmI/MHePtd095r@rMJ7wYeeb4YeT5RF8cdeZLscA/zv/sdFbQASoF6fLY0Hgez86aQGhlwiYqedsZp54Fe0OUmroGPgQuDkH/Bw) ``` def f(a:Seq[Seq[String]])=a.combinations(2).foreach{case List(x,y)=>if(x.intersect(y).nonEmpty)println(s"[${x.mkString("")},${y.mkString("")}]")} ``` Ungolfed version. [Try it online!](https://tio.run/##fVI9a8MwEN39Kw6RQQJj2iRdDCl06FBo6VA6hQxn1U7V2nKQlBJj/NtdyfJHHEKWQ0/v3Z3unjTHHNu2TH5SbuANhYQ6APhKMygsoKj2OoYnpbDafhgl5H7HYviUwsCmUwL8YQ5ZDK9Cm20Xet0ONo@DkuI1AXMKXwQAI14WiZBoRCk1XbIoK1WK/Btq4KjTLp@eQqhcWp8EIDKgp0hIkyptR6AVi2Qpn4uDsbqD7WNySTXZLupTVPz6zpQQ1oSwqKv51Y6wvm4T@DgOKOThaNwLzueYDWPH9U/sS3RnFp6jLpA7EgK5J@wWF/pLe7R4eV2LjksmbeIwnzB3GK/nDnVnfVYXeD3hpcMPE15d8Oue9/tjfm/jzs6cRKUm9yZ7Xpw0hoWlRw8GlrwfjWNHIrO/Ul2qWDD41gRN0Lb/) ``` object Main { def main(args: Array[String]): Unit = { val f: List[List[String]] => Unit = (a: List[List[String]]) => { a.combinations(2).foreach { case List(x, y) => if (x.intersect(y).nonEmpty) println(s"[${x.mkString("")}, ${y.mkString("")}]") } } val inputList: List[List[List[String]]] = List( List(), List(List("0", "1")), List(List("0", "1"), List("1", "2")), List(List("a", "b"), List("b", "c"), List("c", "a")), List(List("1", "2"), List("1", "3"), List("1", "4"), List("2", "5"), List("3", "4"), List("4", "5")) ) inputList.foreach { arr => println(s"Input: $arr") println("Output:") f(arr) println() } } } ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 8 bytes ``` S:đ∩z¿ᵐj ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FuuCrY5MfNSxsurQ_odbJ2QtKU5KLoZKLbjZFB3LFR2tZKCko2SoFIvM1okGkjpKRlDRRCA7CSyaBGQlg1nJQFYiVB6qFqrLGM4yAbOMgCxTMMsYLmYCEYuFOAUA) A port of [@Sundar R's Brachylog answer](https://codegolf.stackexchange.com/a/170723/9288) ``` S:đ∩z¿ᵐj S Find a subset of the input : ¿ Check that: đ the subset has exactly two elements ∩ and the intersection of the two elements z has exactly one element ᵐj Join each element of the subset ``` Nekomata will find all solutions, which are all the edges of the edge graph. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` @F#.cQ2 ``` [Try it here!](https://pyth.herokuapp.com/?code=%40F%23.cQ2&input=%5B%28%221%22%2C%222%22%29%2C%28%221%22%2C%223%22%29%2C%28%221%22%2C%224%22%29%2C%28%222%22%2C%225%22%29%2C%28%223%22%2C%224%22%29%2C%28%224%22%2C%225%22%29%5D&debug=0) ### If joining is necessary, 10 bytes ``` sMM@F#.cQ2 ``` [Try it here!](https://pyth.herokuapp.com/?code=sMM%40F%23.cQ2&input=%5B%28%221%22%2C%222%22%29%2C%28%221%22%2C%223%22%29%2C%28%221%22%2C%224%22%29%2C%28%222%22%2C%225%22%29%2C%28%223%22%2C%224%22%29%2C%28%224%22%2C%225%22%29%5D&debug=0) [Answer] # Wolfram Language ~~64~~ 53 bytes ``` ""<>#&/@#&/@Select[#~Subsets~{2},IntersectingQ@@#&]& ``` Finds all the input list's `Subset`s of length 2, `Select` those in which the nodes of one pair intersect with the nodes of another pair (indicating that the pairs share a node), and `StringJoin` the nodes for all selected pairs. The code is especially difficult to read because it employs 4 nested pure (*aka* "anonymous") functions. The code uses braces, "{}", as list delimiters, as is customary in Wolfram Language. 1 byte saved thanks to Mr. Xcoder. --- **Example** ``` ""<>#&/@#&/@Select[#~Subsets~{2},IntersectingQ@@#&]&[{{"1","2"},{"1","3"},{"1","4"},{"2","5"},{"3","4"},{"4","5"}}] (*{{"12", "13"}, {"12", "14"}, {"12", "25"}, {"13", "14"}, {"13", "34"}, {"14", "34"}, {"14", "45"}, {"25", "45"}, {"34", "45"}}*) ``` [Answer] # C# 233 bytes ``` static void c(List<(string a,string b)>i,List<(string,string)>o){for(int m=0;m<i.Count;m++){for(int n=m+1;n<i.Count;n++){if((i[n].a+i[n].b).Contains(i[m].a)||(i[n].a+i[n].b).Contains(i[m].b)){o.Add((i[m].a+i[m].b,i[n].a+i[n].b));}}}} ``` ## Example ``` using System; using System.Collections.Generic; namespace conjugateGraphGolf { class Program { static void Main() { List<(string a, string b)>[] inputs = new List<(string, string)>[] { new List<(string, string)>(), new List<(string, string)>() {("0", "1")}, new List<(string, string)>() {("0", "1"),("1", "2")}, new List<(string, string)>() {("a","b"),("b","c"),("c","a")}, new List<(string, string)>() {("1","2"),("1","3"),("1","4"),("2","5"),("3","4"),("4","5")} }; List<(string, string)> output = new List<(string, string)>(); for(int i = 0; i < inputs.Length; i++) { output.Clear(); c(inputs[i], output); WriteList(inputs[i]); Console.Write(" -> "); WriteList(output); Console.Write("\r\n\r\n"); } Console.ReadKey(true); } static void c(List<(string a,string b)>i,List<(string,string)>o){for(int m=0;m<i.Count;m++){for(int n=m+1;n<i.Count;n++){if((i[n].a+i[n].b).Contains(i[m].a)||(i[n].a+i[n].b).Contains(i[m].b)){o.Add((i[m].a+i[m].b,i[n].a+i[n].b));}}}} public static void WriteList(List<(string a, string b)> list) { Console.Write("["); for(int i = 0; i < list.Count; i++) { Console.Write($"(\"{list[i].a}\",\"{list[i].b}\"){(i == list.Count - 1 ? "" : ",")}"); } Console.Write("]"); } } } ``` ]
[Question] [ # Story I need to remember a lot of passwords and don't want to use the same one for multiple websites so I came up with a rule, but the rule shouldn't be transparent so what I do is: * Think of a long word or concept such as `breadpudding`. * Replace the first letter with the site we are logging into. If we are logging into `google`, our word becomes `greadpudding`. * Make the first letter uppercase. * Change the second letter to an `@` sign. * If the password starts with a non-consonant, add a certain number (such as `1234`); otherwise, add another number (such as `4321`). Ta da, you now have an adequate password. This process is arduous though so I need a program to generate this for me based on the following: # Problem Given input: * `a` : the initial word, which is a string and is always lowercase, and is guaranteed to be longer than 3 characters. * `b` : the site we are logging into, which is a string and is always lowercase, and is guaranteed to be non-empty. * `c` : the number for non-consonants, which is a positive integer that may have leading zeroes. * `d` : the number for consonants, which is a positive integer that may have leading zeroes. Output a string based on above criteria. # Test cases Input `a="volvo", b="gmail", c=5555, d="0001"` `G@lvo0001` Input `a="sherlock", b="9gag", c=31415926535, d=3` `9@erlock31415926535` Input `a="flourishing", b="+google", c=11111, d=2222` `+@ourishing11111` # Rules * `y` is a consonant. * If you decide `c` or `d` is an integer, you may parse it as such, and leading zeroes can be ignored (`0091` gets treated as `91`). * Trailing whitespace and newlines are allowed. * You may output the result to STDOUT or return the result in a function. * Characters allowed in `a` and `b` are `[a-z0-9!@#$%^&*()_+=-]`. * You may accept the 4 inputs in any consistent order. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins. [Answer] # [Python 3](https://docs.python.org/3/), 69 bytes ``` lambda a,b,*c:b[0].upper()+"@"+a[2:]+c[b[0]in"bcdfghjklmnpqrstvwxyz"] ``` [Try it online!](https://tio.run/##VYtNDoIwGET3nsJ0BUJMS8UEEhPvgSxahLZS2lp@FC9fPzYmzuZNMm/cOklraOgut6DZwO9sz1KeHpqSV7g@zs61PooTdEUJq7KyTppqG5RBvLl3Qj56PRj39OO0vN7rB9XBeWWmqIvQYvViUYrEwJQG5hAAxpigON79vFG2Xtumh60QTAAoOZG8yM453Q70z@60nb0apTKbmQhrhW6hkS3ADAKH8AU "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḣ©Œu;”@o;⁶⁵®eØC¤? ``` A full program, taking the arguments in the order `b`, `a`, `c`, `d`. **[Try it online!](https://tio.run/##AT0Awv9qZWxsef//4biiwqnFknU74oCdQG874oG24oG1wq5lw5hDwqQ/////Z21haWz/dm9sdm//NTU1Nf8wMDAx "Jelly – Try It Online")** ### How? The main link is dyadic, taking `b` and `a`, the program inputs are then `b`, `a`, `c`, and `d` (the 3rd through sixth command line arguments), so `c` and `d` are accessed as such. ``` Ḣ©Œu;”@o;⁶⁵®eØC¤? Main link: b, a e.g. "gmail", "volvo" (c="5555" and d="0001") Ḣ head b 'g' © copy to register and yield 'g' Œu convert to uppercase "G" ”@ literal '@' character '@' ; concatenate "G@" o logical or with a (vectorises) "G@lvo" ? if: ¤ nilad followed by link(s) as a nilad: ® recall value from register 'g' ØC yield consonants "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz" e exists in? 1 ⁶ ...then: 6th arg = 4th in = d "0001" ⁵ ...else: 5th arg = 3rd in = c "5555" ; concatenate "G@lvo0001" implicit print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ ~~20~~ 18 bytes ``` н©u'@I¦¦žN®åiI\}IJ ``` Input taken as `b,a,c,d` [Try it online!](https://tio.run/##AT8AwP8wNWFiMWX//zDDqMKpdSdAScKmwqbFvk7CrsOlaUlcfUlK//85Z2FnCnNoZXJsb2NrCjMxNDE1OTI2NTM1CjM "05AB1E – Try It Online") **Explanation** (outdated) ``` ¦ # remove the first char of a s # swap b to the top of the stack н© # push the head of b and store a copy in register uì # convert the head to upper case and prepend to a U # store in variable X žN®åi # if the head of b is a consonant \} # discard c X« # concatenate X with c or d '@1ǝ # insert an "@" at character position 1 ``` `0è` used in the link as `н` isn't pulled to TIO yet. [Answer] # Javascript ES6, 87 bytes ``` (a,b,c,d)=>b[0].toUpperCase()+'@'+a.slice(2)+(/[bcdfghjklmnpqrstvwxyz]/.test(b[0])?d:c) ``` ## Demo ``` f= (a,b,c,d)=>b[0].toUpperCase()+'@'+a.slice(2)+(/[bcdfghjklmnpqrstvwxyz]/.test(b[0])?d:c) console.log(f("volvo","gmail", 5555, "0001")); //G@lvo0001 console.log(f("sherlock","9gag", 31415926535, 3)); //9@erlock31415926535 console.log(f("flourishing","+google", 11111, "2222")); //+@ourishing11111 ``` [Answer] # C, 441 286 139 Bytes ``` #define o(c)*a[1]==0xc int main(int b,char** a){printf("%c@%s%s",*a[1],a[2]+2,(*a[1]>97&*a[1]<128) &!(o(65)|o(69)|o(6F)|o(75))?a[4]:a[3]);} ``` [Answer] # [R](https://www.r-project.org/), ~~105~~ 103 bytes ``` pryr::f({m=substr(b,0,1);paste0(toupper(m),'@',substring(a,3),'if'(grepl("[b-df-hj-np-tv-z]",m),d,c))}) ``` Anonymous function. Evaluates to ``` function (a, b, c, d) { m = substr(b, 0, 1) #first letter of website paste0(toupper(m), #concatenate that letter, capitalized, "@", #an '@', substring(a, 3), #the rest of the long string, if( #and grepl("[b-df-hj-np-tv-z]", m)), #if the first letter is a consonant, d #the consonant string/num, else c) #else the other one } ``` which is what's on TIO. Please help me golf that regex because I'm terrible at them. Saved 2 bytes from Giuseppe. [Try it online!](https://tio.run/##PY67bsQgEEV7fwVyAyiDBOs40hYr5T9WKfwATBYbBNjFRvl2Ak6UU0wx98zohpzVrUEFtW9TMm5DZAA0ApoAzRSd0dc5Kyu6obiPMQVSFA5I0P/MDzFJTpLbvZeBrBRQ@97Cn282XR93ZWuUtFESHaS3pL2PbFZs@WSbZ@lgz49yUm/nUoH@fv9uGkXw4ezhMGC9DsZi6AuAOecC0xrHRQbrpkcxrnrQGDrxKvrr5a3veuhORVm3BxOX0qVYL9o5bSUGUYFLgeacfwA "R – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), ~~80~~ 75 bytes ``` ^..(.*)¶(.).* $2@$1 ^([ -_aeiou].*)¶(.*)¶.* $1$2 (.*)¶.*¶(.*) $1$2 T`l`L`^. ``` [Try it online!](https://tio.run/##K0otycxL/P8/Tk9PQ09L89A2DT1NPS0uFSMHFUOuOI1oBd34xNTM/NJYqCSIBMkbqhhxwXgQcYhYSEJOgk9CnN7//2X5OWX5XOm5iZk5XKZAwGVgYGAIAA "Retina – Try It Online") Trying out a new language here, takes inputs in the order given in the question ### Explanation: ``` ^..(.*)¶(.).* $2@$1 ``` Create a word which is second word first letter, @ sign, first word from the 3rd character on. ``` ^([ -_aeiou].*)¶(.*)¶.* $1$2 ``` If the word starts with a non-consonant, append the first number ``` (.*)¶.*¶(.*) $1$2 ``` If there are still 3 lines left (no substitution in the last step, so it starts with a consonant), append the second number ``` T`l`L`^. ``` Uppercase the first letter [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 81 bytes ``` G=ucase$(_s;,1|)+@@`+_s;,3,_lC||~instr(@bcdfghjklmnpqrstvwxyz`,_sC,1|)|?G+;\?G+; ``` ## Explanation ``` Parameters are Website(A$), base word(C$), consonant-number(E$), and nonsonant-number(F$) G= SET G$ to ucase$( ) the upper-case version of (also works for '9gag', '+google') _s;,1| the first char of the website A$ read from cmd line +@@` plus a literal @ (B$) +_s;,3,_lC|| plus all characters from base word C$ from 3rd char onwards ~instr( IF the second arg to INSTR is in the first @bcdfghjklmnpqrstvwxyz`, with all consonants in the first arg _sC,1| and the first char of the base word C$ in the second ) |?G+; THEN print G$ plus the consonant addition \?G+; ELSE print G$ plus the other addition ``` Note that the last two lines appear the same, but the interpreter changes the behaviour slightly on each `;`: Whenever it sees the `;` instruction, it creates a new variable (in this case, the vars È$`and`F$` are the first available after reading all other literals and cmd line arguments) and assigns the first not-yet-assigned cmd line paraeter to that variable. [Answer] # JavaScript (ES6), 76 bytes ``` (a,b,c,d)=>b[0].toUpperCase()+'@'+a.slice(2)+(/[aeiou\d_\W]/.test(b[0])?c:d) ``` I would have added this as a suggestion as an improvement to [Weedoze's solution](https://codegolf.stackexchange.com/questions/127648/generating-an-adequate-password/127702#127702), but it seems like I can't comment on it since I mostly lurk [Answer] # [C#](https://docs.microsoft.com/en-us/dotnet/csharp/csharp), 111 bytes ``` (a,b,c,d)=>Char.ToUpper(b[0])+"@"+a.Substring(2)+(b.IndexOfAny("bcdfghjklmnpqrstvwxyz".ToCharArray()==0)?d:c); ``` Checking the consonant is particularly expensive with no direct regex capability on the `string` type. [Answer] # [F#](http://fsharp.org/), 157 bytes ``` let f(a:string)(b:string)c d=System.Char.ToUpper(b.[0]).ToString()+"@"+a.[2..]+(if((Seq.except['e';'i';'o';'u']['b'..'z'])|>Seq.contains b.[0])then d else c) ``` F# is still very new to me so there are probably better approaches to this. [Answer] # Java 8, ~~112~~ ~~99~~ ~~92~~ 87 bytes ``` (a,b,c,d)->b.toUpperCase().charAt(0)+"@"+a.substring(2)+(b.matches("[a-z&&[^aeiou]].*")?d:c) ``` -13 bytes by taking parameter `b` last instead of second. -1 byte by removing `y` -7 bytes thanks to *@OlivierGrégoire* (and parameters are in order again) -5 bytes thanks to *@PunPun1000* **Explanation:** [Try it here.](https://tio.run/##hU/LasMwELznKxadpNoRdtIU0tAXPTeX0lMoZS0rthJFMpZsKCXf7q6Dcyzdg2YW7czsHrDHuW@0O5THQVkMAd7QuJ8ZgHFRt3tUGrZjC/AeW@MqUHwimE6kuBJ1JaXYkOQ8oydEjEbBFhw8wMAxLVKVlmL@WMjoP5pGt68YNBdS1di@RJ6JhD2zBGXoinBx4wuR8EKeMKpaB852MP9CbXz3KW@YeFL3pRg2Y1TTFZaipsTemxJOdMy07@4TUEyXfIeoT9J3UTb0Fa3jTirOem97z1JWkcwSrqgIsizLmbic9Lc21Lq1Xh1pfl1hRbDMb/PVenG3Wo4my38d9tZ3rQk17UrzSeV9ZTWxfCzCBdVkcp6dh18) ``` (a,b,c,d)-> // Method with 4 String parameters and String return-type b.toUpperCase().charAt(0) // First character of B capitalized +"@" // + literal "@" +a.substring(2) // + A excluding first two characters +(b.matches("[ -_aeiou].*")? // If B starts with a consonant: d // + D : // Else: c) // + C // End of method (implicit / lambda with single return) ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 25 bytes ``` ldvjr@Ç^[aeiou]ü^Á/j DÍî ``` [Try it online!](https://tio.run/##K/v/PyelLKvI4XB7XHRiamZ@aezhPXGHG/WzuLhcDvceXvf/f2puYmYOV1l@Tlk@l4GBgSGXKRAAAA "V – Try It Online") Takes arguments in the buffer in order: ``` website word/phrase consonant number non-consonant number ``` [Answer] # [Bash 4](https://en.wikipedia.org/wiki/Bash_(Unix_shell)), 76 bytes ``` g(){ a=${2:0:1} c=$4 [[ "aeiou[0-9]" =~ .*$a.* ]]&&c=$3 p="${a^}@${1:2}$c" } ``` Works in Bash 4: ``` g volvo gmail 5555 0001; echo $p g sherlock 9gag 31415926535 3; echo $p g flourishing +google 11111 2222; echo $p ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 73 bytes ``` ->a,b,c,d{a.sub(/..(.*)/){b[0].upcase+"@#$1#{b[0]=~/[aeiou_\d\W]/?c:d}"}} ``` [Try it online!](https://tio.run/##HcjdCoIwGIDhW5HZgbO1tdTAwOouOpgjvv1okaA4F4TYrS/p6OV5R68@oanqsDsDUUQTMwN1XiWM0oSmmOFZib2kftDg7BZd4w2P/6v6MgH22ft7beqbZBd9MgtaljD4yUWNSO0buqS1k8MyCOQedux6/UIkQmUL7dqM57woD8ciK1bIHw "Ruby – Try It Online") [Answer] # JavaScript (ES6), 69 bytes ``` (a,b,c,d)=>e=a[0].toUpperCase()+"@"+a.slice(2)+/[AEIOU]/.test(e)?c:d ``` Pretty simple, probably can be golfed ]
[Question] [ [Read this if you're confused.](https://www.google.com/search?q=8675309&oq=8675309&aqs=chrome..69i57j5.2943j0j7&sourceid=chrome&ie=UTF-8) # Challenge: The goal of this code-golf is based around the number `8675309`... Your goal is to print out every prime number from 2 to 8675309, *starting with the number 2 and then skipping 8 prime numbers, then skipping 6, then skipping 7, etc.* In essence, skip a number of primes determined by the next number in the sequence `8675309`. Cycling over to 8 once it reaches 9. # Output: ``` 2 29 ``` (skipped 8 to get to the 10th prime) ``` 59 ``` (skipped 6 to get to the 17th prime) ``` 97 ``` (skipped 7 to get to the 25th prime) --- **Example: (PHP-like pseudo-code where `$prime` is an array containing all the prime numbers.)** ``` $tn=1; $c=1; $na=array(8,6,7,5,3,0,9); l: output($prime[$tn]); if ($prime[$tn]>=8675309) {exit(8675309)}; $c+=1; if ($c>=8) {$c=1}; $tn+=$na[$c]; goto l; ``` When I say *skip* 8 primes, I mean to go from the #1 prime, to the #10 prime (skipping the 8 in between). Each number must be on a new line. When you reach the `0` in `8675309`, just just print the next prime number without skipping any. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code (in-bytes) wins. [Answer] # Mathematica 67 bytes Doesn't hit 8675309 though - not sure of OP's intention on this. ``` Column@FoldList[NextPrime,2,Flatten@Array[{9,7,8,6,4,1,10}&,12937]] ``` [Answer] # [Wonder](https://github.com/wonderlang/wonder), 47 bytes ``` P\tk582161P;(_>@(os tk1P;P\dp +1#0P))cyc8675309 ``` Oh geez, this gets slower and slower as time goes on... # Explanation ``` P\tk582161P; ``` Takes 582161 (amount of primes <= 8675309) items from the infinite primes list `P` and redeclares result as `P`. ``` (_>@(...))cyc8675309 ``` Infinitely cycles the digits of 8675309 and performs a takewhile on the resulting list. ``` os tk1P;P\dp +1#0P ``` Output the first item in `P`, drop `cycle item + 1` elements from P, and redeclare result as `P`. This operation on `P` also acts as a truth value for takewhile; if the list is empty / falsy (meaning that we have reached 8675309), then we stop taking from the cycled list. # Faster implementation (for testing) ``` P\tk582161P;(_>@(os tk1P;P\dp +1#0P;#0))cyc8675309 ``` Still really slow, but noticeably faster. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23 29~~ 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) +6 bytes for a temporary patch to fulfil the requirement to print 8675309. -5 bytes moving to a golfier but slower approach to address that. ``` “⁹Ṁ:’©D‘ẋ“2Ṿ’R®ÆR¤ṁḢ€;®Y ``` Now too slow to run on TryItOnline, but it runs locally in a couple of minutes, producing the numbers shown below with line feeds in-between (# of primes skipped shown below in parentheses): ``` 2, 29, 59, 97, 127, 149, 151, 199, 257, 293, 349, 383, 409, 419, ... (8) (6) (7) (5) (3) (0) (9) (8) (6) (7) (5) (3) (0) ..., 8674537, 8674727, 8674867, 8675003, 8675053, 8675113, 8675137, 8675309 (8) (6) (7) (5) (3) (0) (4)* ``` \* the last is only an effective skip of 4, as it is simply appended to the list. **[Click here](http://jelly.tryitonline.net/#code=4oCcwr8w4oCZwqlE4oCY4bqL4oCcw5_igJlSwq7DhlLCpOG5geG4ouKCrDvCrlk&input=)** for a version using 3659 instead of 8675309, which has 19 sets of four skips (rather than 12937 sets of 7) and appends 3659 (which is an effective skip of 6). ### How? ``` “⁹Ṁ:’©D‘ẋ“2Ṿ’R®ÆR¤ṁḢ€;®Y - Main link: no arguments “⁹Ṁ:’ - base 250 number: 8675309 © - save in register D - convert to a decimal list: [8, 6, 7, 5, 3, 0, 9] ‘ - increment: [9,7,8,6,4,1,10] “2Ṿ’ - base 250 number: 12937 ẋ - repeat: [9,7,8,6,4,1,10,9,7,8,6,4,1,10, ... ,9,7,8,6,4,1,10] R - range (vectorises) [[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7], ...] ¤ - nilad followed by link(s) as a nilad ® - retrieve value from register: 8675309 ÆR - prime range [2,3,5,7, ... ,8675309] ṁ - mould the primes like the range list: [[2,3,5,7,11,13,17,19,23],[29,31,37,41,43,47,53],...] Ḣ€ - head €ach: [2,29,59,97,127,149,151,199, ..., 8675137] ® - retrieve value from register: 8675309 ; - concatenate: [2,29,59,97,127,149,151,199, ..., 8675137, 8675309] Y - join with line feeds - implicit print ``` [Answer] # Ruby, 121 bytes Trailing newline at end of file unnecessary and unscored. ``` P=[] (2..8675309).map{|c|s=1;P.map{|p|s*=c%p};P<<c if s!=0} S=[9,7,8,6,4,1,10]*P[-1] while y=P[0] p y P.shift S.shift end ``` Explanation: `P` is an array of primes. `c` is a candidate prime; `s` is the product of the residues modulo every smaller prime; if any such residue is zero (indicating that `c` is composite), `s` becomes (and stays) zero. The prime number generator is slow. It will take a looooong time to run. Testing was done by substituting a `P` array generated by more efficient means (specifically, short circuit on even division, and it also helps a *lot* to stop testing at the square root). [Answer] ## Haskell, 122 bytes This might be what is asked for: ``` s(a:b)=a:s[c|c<-b,c`mod`a>0] f(a:b)(s:t)=a:f(drop s b)t main=mapM print$takeWhile(<8675310)$f(s[2..])$cycle[8,6,7,5,3,0,9] ``` I could save a few bytes by precomputing how many number are needed, and replacing `takeWhile` with `take`. That would also allow to adapt to any decision about the last number to be output. It has already printed numbers up to 600000 using very few memory in my test, so I think it can go all the way. [Answer] # Haskell, 109 bytes ``` (p:z)%(x:r)=print p>>(drop x z)%r p%x=pure() [n|n<-[2..8675309],all((>0).mod n)[2..n-1]]%cycle[8,6,7,5,3,0,9] ``` [Try it online!](https://tio.run/nexus/haskell#HczRCoIwFADQ977ivggbzGFFZZJC9Bnig2wrB/PuctOy6N8tez5wfE@RB7hEHDgGfSYK3rSDfzhIU0DnrLNwjQw0soNn500H/g4egdiF0bo/3joDuc5mQcVbJmIqWJbEHgegqhKWI8EEP@EVJVO5VEKu@tZjWeMHT2m90TrfH3aNakMQosqk7qMFlAtgum6axLxMcHWu9uqgdmqrMnVs5vkL "Haskell – TIO Nexus") (truncated `8675309` to `8675`, otherwise it times out on *Try it online*) Usage: ``` *Main> [n|n0).mod n)[2..n-1]]%cycle[8,6,7,5,3,0,9] 2 29 59 97 127 149 151 199 257 293 349 383 409 419 467 541 587 631 661 691 701 769 829 881 941 983 1013 ... ``` [Answer] # [Perl 6](https://perl6.org), ~~65 73~~ 67 bytes ``` $_=8675309;.[0].put for (2..$_).grep(*.is-prime).rotor(1 X+.comb) ``` ( failed to print 8675137 because of missing `:partial` ) ``` $_=8675309;.[0].put for ^$_ .grep(*.is-prime).rotor((1 X+.comb),:partial) ``` ``` $_=8675309;.[0].put for ^($_+33) .grep(*.is-prime).rotor(1 X+.comb) ``` By shifting up the end of the Range, the `:partial` can be removed. [Try it](https://tio.run/nexus/perl6#DcxLCsIwEADQvacYsIvE4lAp9Yt3cCmIFq2jHUgyJRmpIp69dv3gTcGRJkhE0EoP/ho@wAo9Owdd5KDAAarRGwn3NDlE8ZwIOZjKorYUtvClN@tvyOr9ermqymKzw1Nxxu6l8JAIF5PVeVlawGekzsyQ03ycPVmMohLNAo45NuJvdhj@ "Perl 6 – TIO Nexus") ( 5 second limit added ) [See it finish](https://tio.run/nexus/perl6#Dc1NCsIwEEDhvacYsIvE4lAJrVXxDi4F0aJ1tAP5KclIFfHstdv3Ld4cLEmCRARdGMBd/QdYYGBroY/sBdhDOXkb/D3NDjE4ToTsValROvJb@NKb5Tdmzb6u1qUpNjs8FWfsXwKPEEFN1VS1QbyorMmN0RqfkXq1QE7L6eFIYwwSolrBMcc2uJsexz8 "Perl 6 – TIO Nexus") Initial example was timed at 52 minutes 41.464 seconds. ## Expanded: ``` $_ = 8675309; .[0] # get the first value out of inner list .put # print with trailing newline for # for every one of the following ^($_+33) # the Range ( add 33 so that 「.rotor」 doesn't need 「:partial」 ) .grep(*.is-prime) # the primes .rotor( 1 X+ .comb # (1 X+ (8,6,7,5,3,0,9)) eqv (9,7,8,6,4,1,10) ) ``` The result from the `rotor` call is the following sequence ``` ( ( 2 3 5 7 11 13 17 19 23) # 9 (8) ( 29 31 37 41 43 47 53) # 7 (6) ( 59 61 67 71 73 79 83 89) # 8 (7) ( 97 101 103 107 109 113) # 6 (5) (127 131 137 139) # 4 (3) (149) # 1 (0) (151 157 163 167 173 179 181 191 193 197) # 10 (9) (199 211 223 227 229 233 239 241 251) # 9 (8) (257 263 269 271 277 281 283) # 7 (6) (293 307 311 313 317 331 337 347) # 8 (7) (349 353 359 367 373 379) # 6 (5) (383 389 397 401) # 4 (3) (409) # 1 (0) (419 421 431 433 439 443 449 457 461 463) # 10 (9) ... ) ``` [Answer] # Befunge, 136 bytes ``` p2>:1>1+:"~"%55p:"~"/45p:*\`!v 1+^<+ 1<_:#!v#%+g55@#*"~"g54:_\:!#v_1-\ p00%7+1: ,+64g00.:_^#!`***"'(CS":$<^0-"/"g4 >5g#*^#"~"g5< 8675309 ``` [Try it online!](http://befunge.tryitonline.net/#code=cDI-OjE-MSs6In4iJTU1cDoifiIvNDVwOipcYCF2CjErXjwrIDE8XzojIXYjJStnNTVAIyoifiJnNTQ6X1w6ISN2XzEtXApwMDAlNysxOiAsKzY0ZzAwLjpfXiMhYCoqKiInKENTIjokPF4wLSIvImc0Cj41ZyMqXiMifiJnNTwKODY3NTMwOQ&input=), but be aware that it's going to time out long before it reaches the end. A compiled version on my local machine completes in under 10 seconds though. **Explanation** To test for primality we iterate over the range 2 to sqrt(*n*) and check if *n* is a multiple of any of those values - if not, it's a prime. This process is complicated by the fact that the iterated value needs to be stored in a temporary "variable", and since Befunge's memory cells are limited in size, that storage has to be split over two cells. To handle the skipped primes, we use a lookup "table" (which you can see on line 5) to keep track of the different ranges that need to be skipped. I'm not going to do a detailed analysis of the code, because there's quite a lot of interleaving code with commands shared across different code paths in order to save space. This makes things rather difficult to follow and I don't think it would be particularly interesting to anyone that wasn't already familiar with Befunge. **Sample Output** ``` 2 29 59 97 127 149 151 199 ... 8674397 8674537 8674727 8674867 8675003 8675053 8675113 8675137 ``` [Answer] # Bash (+coreutils), ~~98~~, 94 bytes EDITS: * Optimized row filter a bit, -4 bytes **Golfed** ``` seq 8675309|factor|grep -oP "^.*(?=: \S*$)"|sed 1b\;`printf '%d~45b;' {10,17,25,31,35,36,46}`d ``` **Test** ``` >seq 8675309|factor|grep -oP "^.*(?=: \S*$)"|sed 1b\;`printf '%d~45b;' {10,17,25,31,35,36,46}`d| head -25 2 29 59 97 127 149 151 199 257 293 349 383 409 419 467 541 587 631 661 691 701 769 829 881 941 ``` [Try It Online!](https://goo.gl/vKXXtd) (limited to N<1000, to make it run fast) The full version takes around ~15 seconds to complete on my machine. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/100852/edit). Closed 7 years ago. [Improve this question](/posts/100852/edit) Your task, if you choose to accept it, is simple. # Objective You must make a program that, when run, prints some (as many as you want) terms in a sequence that you choose. The sequence must be a valid [OEIS](http://oeis.org) sequence. The twist is that when you take the characters from your code that make up your sequence, string them together and run them *in the same language*, you should get the [formula for the nth of your sequence](http://www.bbc.co.uk/schools/gcsebitesize/maths/algebra/sequencesrev2.shtml) for your sequence. # Example Let's say I made this program: ``` abcdefghij ``` and chose the sequence of squares: <http://oeis.org/A000290> and I chose it to print the first 5 terms of the sequence, the output should be: ``` 1, 4, 9, 16, 25 ``` Note: the output is flexible, you can choose what delimiter you want separating the terms, but the delimiter should be noticeable so that each of the terms of the sequence can be differentiated. Now, the character at index 1 is `a`. The character at index 4 is `d`. The character at index 9 is `i`. So my new program would be: ``` adi ``` and it would have to print the formula for the nth term for my sequence, which is: ``` n^2 ``` Simple! ## Other things * You must print a minimum of 5 terms. * You may choose to 0- or 1-index. * Repeated numbers means repeated characters. * If your sequence isn't in order (e.g. it goes backwards), then your code still follows it (e.g. your code is written backwards). * You must use and only use the numbers in bounds of your answer, even if it has already gone out of bounds. You cannot use numbers from the same sequence you did not print. * If your sequence does not officially have a formula, you may use the first 3 letters of the name stated on the [OEIS](http://oeis.org/) website (e.g. the fibonacci sequence would print `fib` and the lucas-lehmer sequence would print `luc`). Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer, in bytes, wins! [Answer] # Python 2, 35 Bytes I decided to use the obvious sequence [A000027](http://oeis.org/A000027), which essentially has the formula `n` ;) If you run the following code: ``` #print'n' n=1 exec'print n;n+=1;'*8 ``` You get the output: ``` 1 2 3 4 5 6 7 8 ``` And if you take the 8 characters from my source code (0-indexed), you get this: ``` print'n' ``` Which simply prints `n`. --- If you were hoping for a more exciting answer, here's a Python 2 solution for `n^2`, i.e. [A000290](http://oeis.org/A000290): ``` #p r i n t ' n ^ 2 ' n=1 exec'print n*n;n+=1;'*10 ``` [Answer] # 05AB1E, ~~7~~ 6 bytes, [A000027](http://oeis.org/A000027) ``` 5L'n s ``` [Try it online!](http://05ab1e.tryitonline.net/#code=NUwnbiBz&input=) Explanation: ``` 5L # Push [1, 2, 3, 4, 5] 'n # Push "n" # Do nothing s # Swap (only in original program) # Implicit print ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 10 bytes, [A008585](https://oeis.org/A008585) This code outputs the first **11** elements of the sequence **3n**. ``` 3TÝ' §n*»J ``` [Try it online!](http://05ab1e.tryitonline.net/#code=M1TDnScgwqduKsK7Sg&input=) **Explanation** ``` 3 # push 3 # STACK: 3 TÝ # push range [0 ... 10] # STACK: 3, [0,1,2,3,4,5,6,7,8,9,10] ' § # push a space char converted to string # STACK: 3, [0,1,2,3,4,5,6,7,8,9,10], " " n # square the string # STACK: 3, [0,1,2,3,4,5,6,7,8,9,10] * # multiply the top 2 elements of the stack # STACK: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30] » # join by newlines J # join to string ``` Taking every *nth* item (0-indexed) gives: ``` 3'nJ ``` [which outputs 3n](http://05ab1e.tryitonline.net/#code=MyduSg&input=) [Answer] # Octave, 64 bytes [A000290](https://oeis.org/A000290) I went for the `n^2` one: ``` @()(1:5 ).^2 % ' n ^ 2 ' ``` Take the terms 1, 4, 9, 16, 25, 36, 49 and 64 to get: ``` @()'n^2' ``` which prints: ``` n^2 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~30~~ 28 bytes, [A000290](http://oeis.org/A000290) This is the sequence of squares ``` " n ^ 2 "5Ln ``` Outputs the first 5 terms of the sequence with the formula `n^2`: ``` [1, 4, 9, 16, 25] ``` [Try it online!](http://05ab1e.tryitonline.net/#code=IiAgbiAgICBeICAgICAgMiAgICAgICAgIjVMbg&input=) This is 1-indexed. So taking the characters from the code that make up the sequence, I get ``` "n^2" ``` Which outputs ``` n^2 ``` [Try it online!](http://05ab1e.tryitonline.net/#code=Im5eMiI&input=) ### Explanation ``` " n ^ 2 " # push this string 5 # push 5 L # push range [1, ..., 5] n # square it # implicit output ``` [Answer] # [Wonder](https://github.com/wonderlang/wonder), 16 bytes [A005843](http://oeis.org/A005843) ``` 0";2"tk 5gen *2 ``` This was once DASH, but has now been renamed to Wonder. Outputs the first 6 even numbers. Note the leading space. Keeping the indices 0, 2, 4, 6, and 8 yields: ``` "2t ``` Which prints `2t`. # Explanation ``` 0";2" ``` This is just a string and a number. ``` tk 5gen *2 ``` This generates an infinite list of even numbers starting from 0, then takes the first 5 items from that list. [Answer] # [MATL](http://github.com/lmendo/MATL), 8 bytes, [A000027](http://oeis.org/A000027) *Thanks to [Oliver](https://codegolf.stackexchange.com/users/12537/oliver) for a correction interpreting the challenge* ``` 'n' 5:& ``` The code prints `1 2 3 4 5`. Keeping only the first give chars it prints `n`. [Try it online!](http://matl.tryitonline.net/#code=J24nICA1OiY&input=) [Answer] # Octave, 49 bytes, [A109234](https://oeis.org/A109234) ``` @() 1 : 5 %'floor (n*sin h(1)) ';] ``` The sequence `floor(n*sinh(1))` are all numbers from `1` and up, except `6, 13, 20, 26, 33, 40, 46, _3, _0, _6 ...` So, the characters used to make `1 2 3 4 5` must be placed in those positions. The remaining positions are used for the string explaining the function. [Answer] # 05AB1E, 15 bytes, [A001477](https://oeis.org/A001477) ``` "n-1" žhSðý ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=Im4tMSIgICAgIMW-aFPDsMO9&input=) [Answer] # [Haystack](https://github.com/kade-robertson/haystack), ~~21~~ ~~10~~ 9 Bytes Haystack has had a lot of new features added in the past few days :) Of course, I am going to use [A000027](http://oeis.org/A000027). Here's the inital program: ``` <"n"o|OR4 ``` This will print out: ``` [1, 2, 3, 4, 5] ``` And if you take the characters 1-5, 0-indexed, you get: ``` "n"o| ``` Which prints `n`. --- If you want to have some more fun, here's a solution for [A000290](http://oeis.org/A000290): ``` ^"_(n\D2l^ 3keU02/:[W D5m"5s\ih_ Cr:OF]uAIe hWd>g|AkuH /6R>ud*O,\ )G:q$n|4y{ :|v\X:?dP/ ``` > > If you want to see only the necessary chars, click [here](https://gist.github.com/kade-robertson/8b3ad15a5e8fa0272943891f57a52491). > > > This will print the first 7 squares, and their corresponding chars in the above program, 0-indexed, are: ``` "n^2"O| ``` Which prints `n^2`. ]
[Question] [ According to [this page](http://www.datagenetics.com/blog/april12012/index.html), the best strategy to guess English hangman words is to calculate the odds of each letter in a word list that meet our conditions. But, as I'm really lazy, I don't really want to compute every word in the dictionary by myself. But, as I know that you are always here to help me, I'm sure you will be able to make me some king of a code that will do that for me. And, because my hard disk is nearly full, I'd like the smallest possible code. It means that **this is code-golf, and the submission with the lowest amount of bytes will win, but also the most accurate one !**. # Input/Output A random word from [this wordlist](https://gist.githubusercontent.com/paris-ci/a4f4c46acfb0ab63b88d/raw/b47403d451ce8492fe0da9095daf24a0f1c6cf08/wordlist.txt) will be taken. Your program should accept, in arguments, or by user input (popups, stdin, whatever), * Length of the word * Incorrect letter already found, or 0 if we just started the game, and you provided no incorrect letter. * Letters already found AND their position in the word Example : `./hangsolver 6 XBZ 1P 4P 2E 6E` Here, I picked the word "people". For clarity : P E \_ P \_ E (Wrong letters are X B and Z) That means, in one game, I'll have to launch your script many times! The output will be a single letter, your next try. # Rules * The one that will guess 10 words in less tries than the others will win. * In case of a tie, shortest code in bytes win. * If there is still a tie, the fastest program will win. * You may assume that there are only [these](https://gist.githubusercontent.com/paris-ci/a4f4c46acfb0ab63b88d/raw/b47403d451ce8492fe0da9095daf24a0f1c6cf08/wordlist.txt) words in the English language * I'll only try valid words from the wordlist. * I've got a good computer, CPU power won't be a problem ( but try to answer as fast as you can !) * You can't solve with an online solver, but you can download the wordlist, or have it passed as an argument. You can assume it will be named "wordlist.txt" and in the same directory as your script. * Your code must be able to run on a common OS. It could be windows, mac, or ubuntu/debian/CentOS or Redhat. * You can't use an external solver. * You can however shorten the URL to the wordlist. * This code-golf will end the first of September. * You MUST use the method described above. Good luck ! Wordlist found [here](https://codegolf.stackexchange.com/questions/25496/write-a-hangman-solver) on SE. [Answer] # Python3, 299 Bytes ``` import sys,collections as c;x,X,N,*Z=sys.argv;print([x for x in c.Counter(''.join([''.join(x)for x in map(set,filter(lambda l:len(l)==int(X)+1and all(x not in X.lower()for x in l)and all(l[int(x[0])-1]==x[1].lower()for x in Z),open('wordlist.txt')))]))if x not in ''.join(Z).lower()and x!='\n'][0]) ``` pretty sure this can be golfed further. Filters the wordlist for potential matches, builds a char frequency map, and selects the most often occuring character which is not yet picked. [Answer] # PowerShell, ~~248~~ ~~246~~ 241 bytes ``` $a=$args;$c=$a[0];$b=$a[2..$c];((gc wordlist.txt)-match"^$((1..$c|%{$e=,"[^$($a[1])]"*$c}{$e[$_-1]=(((@($b)-match"^$_\D")[0]-split$_)[-1],$e[$_-1]-ne'')[0]}{$e-join''}))$"-join''-split'\B'|?{!(@($b)-match$_).Count}|group|sort count)[-1].Name ``` ## Ungolfed Well, as much as I could without changing the way it works: ``` $a=$args $c=$a[0] $b=$a[2..$c] ( (gc wordlist.txt) -match "^$( ( 1..$c | ForEach-Object -Begin { $e = ,"[^$($a[1])]" * $c } -Process { $e[$_-1] = ( ( ( @($b) -match "^$_\D" )[0] -split $_ )[-1] , $e[$_-1] -ne '' )[0] } -End { $e-join'' } ) )$" -join '' -split'\B' | Where-Object { -not (@($b) -match $_).Count } | Group-Object | Sort-Object count )[-1].Name ``` ## Breakdown The approach I took here was to first generate a regular expression to get possible words out of the word list. Since I know the length of the word, and the letters that didn't work, I can make a regex out of that fairly easily. So in the PEOPLE example, 6 letters with XBZ not being part of the word, I would look to generate `^PE[^XBZ]P[^XBZ]E$`. I'm exploiting the fact that `Get-Content` (`gc`) returns an array of lines, and the `-match` operator when used with an array on the left side, returns an array of matches instead of a bool, so I can quickly get a list of just words that are candidates, once I have the regex. To generate the regex, I start with an array (`$e`) of the negative matching character class with `$c` elements (`$c` being the number of letters in the word). Iterating through the numbers 1 through `$c`, I check for a matched letter at that position, and if it exists, I replace the element in `$e` with that letter. Once I've iterated through all of the positions, the final array is `-join`ed (with empty string) and we have our regex. So now I've got an array of all the possible words it could be. A quick `-join` with empty string on that, gives me one big concatenated string of all the words, the I split on `\B` (not a word boundary, if I split on empty string I will get 2 extra blank elements), so now I have an array of every letter in every possible word. Piping that into `Where-Object` lets me filter out the letters that have already been matched. This part was a real pain. It had to deal with the list of matched letters (which include the position) being 1 element, more than 1 element, or 0 elements, hence forcing `$b` into an array first so that `-match` can operate on all them, but that (unfortunately in this case) returns an array, so we have to check `.Count`. Using `!(thing).Count` is a bit smaller than using `(thing).Count-gt0`. Moving on, now we've got an array of all the single characters (as `string`s not as `char`s) from all of the words it could possibly be, minus the letters that were already guessed correctly. Piping that into `Group-Object` gives me an object with the counts of each letter, so a quick pipe into `Sort-Object count` makes it easy to get the highest count. Rather than do `(thing|sort count -des)[0]` we can use `(thing|sort count)[-1]`. In PowerShell `[-1]` gets the last element. At this point we're still dealing with the objects that came from `Group-Object` so we get the `.Name` property which is the letter that appears the most. ## Notes * Should work with PowerShell v3+; almost certainly will choke on 2. * Remember when you call a PowerShell script, pass arguments with spaces, not commas. * Although I didn't see it in the rules, it looks like everyone is using the filename `wordlist.txt` otherwise that could shave a few bytes off. * Speed shouldn't be a problem. This appears to run instantly for me. The slowest run I could get it to do (`.\hangman.ps1 7 0`) runs in about 350ms. [Answer] # Java, 646 640 631 607 606 (short) 790 789 779 (fast) bytes ### ***SHORT*** ``` import java.util.*;class I{public static void main(String[]a)throws Exception{char[]w=a[1].toCharArray(),p,q;int l=Integer.parseInt(a[0]),i,z=w.length,j;q=new char[l];for(i=2;i<a.length;i++)q[Character.getNumericValue(a[i].charAt(0))-1]=(char)(a[i].charAt(1)+32);java.io.File u=new java.io.File("wordlist.txt");Scanner s=new Scanner(u);while(s.hasNextLine()){p=s.nextLine().toCharArray();if(p.length==l)for(i=0;i<l;i++)if(p[i]==q[i]||q[i]=='\0'){if(i==l-1)y:for(i=0;i<l;i++)for(j=0;j<z;j++)if(!(p[i]==w[j])){if(j==z-1){System.out.print(p[new String(q).indexOf('\0')]);return;}}else break y;}else{break;}}}} ``` ### ***FAST*** ``` import java.util.*;class I{public static void main(String[]a)throws Exception{char[]w=a[1].toCharArray(),p,q;int l=Integer.parseInt(a[0]),i,z=w.length,j,k,o,n[]=new int[255],r[];q=new char[l];for(i=2;i<a.length;i++)q[Character.getNumericValue(a[i].charAt(0))-1]=(char)(a[i].charAt(1)+32);String m=new String(q);java.io.File u=new java.io.File("wordlist.txt");Scanner s=new Scanner(u);while(s.hasNextLine()){p=s.nextLine().toCharArray();h:if(p.length==l)for(i=0;i<l;i++)if(p[i]==q[i]||q[i]=='\0'){if(i==l-1)y:for(i=0;i<l;i++)for(j=0;j<z;j++)if(p[i]!=w[j]){if(j==z-1){for(k=0;k<l-m.replace("\0","").length();k++)n[(int)p[new String(q).indexOf('\0',k)]]++;break h;}}else break y;}else{break;}}r=n.clone();Arrays.sort(n);for(o=0;o<255;o++)System.out.print(r[o]==n[254]?(char)o:"");}} ``` Put the wordlist file in the folder. Short version algorithm 1. Load Args 2. Construct the word we are trying to guess {'p','e','\0','p','\0','e'} 3. Load WordList 4. Go through each line of WordList 5. Stop when you find that the whole word matches this condition `p[i] == q[i] || q[i] == '\0'` where p is a word from the wordlist (char array), and q is the word we are trying to guess 6. Loop through wrong chars and compare to the word 7. Print the first missing character Long version algorithm 1. Short steps 1-7 2. Increment the character count in the n array for the missing chars 3. Loop until all the words come through 4. Print the character that had the highest count [Answer] # PHP, 346 bytes ``` <?php $a='array_shift';$p='preg_match';$a($v=&$argv);$w=array_fill(1,$a($v),'(.)');$c=$a($v);foreach($v as$q)$p('/(\d+)(\w)/',$q,$m)&&$w[$m[1]]=$m[2];foreach(file('wordlist.txt')as$y)if($p("/^".implode($w)."$/",$y=strtoupper(trim($y)),$m)&&(!$c||!$p("/[$c]/",$y)))for($i=0;$i++<count($m);)($v=@++$g[$m[$i].$i])&&$v>@$t&&$t=$v&&$l=$m[$i];echo @$l; ``` It works as follows: 1. Creates a regex pattern for matching the letters guessed so far 2. Iterates over each word from the file 3. If the word matches the regex, it makes sure that it doesn't contain one of the wrong letters 4. Increments a counter for each of the possible letters of that word (based on their position) 5. Outputs the letter with the highest counter Assumptions: * PHP `>=5.4` * There is a `wordlist.txt` file in the current folder [Answer] # Powershell, 153 bytes *Inspired by briantist's [answer](https://codegolf.stackexchange.com/a/55078/80745).* As other writers I used the filename `wordlist.txt`. Although it was possible to choose a shorter name. ``` param($l,$b,$c)((sls "^$(-join(1..$l|%{$p=$c|sls "$_."|% m* ("$p"[1],"[^$b$c]")[!$p]}))$" wordlist.txt|% l*e|% t*y|group|sort c*).Name-match"[^ $c]")[-1] ``` Less golfed test script: ``` $f = { param($length,$bad,$chars) $wordPattern=-join(1..$length|%{ # join all subpatterns for $_ from 1 to $length $c=$chars|sls "$_."|% Matches # find subpattern in char array ("$c"[1],"[^$bad$chars]")[!$c] # return a first char of subpattern if subpattern found, or bad characters }) # Note 1: The word subpattern is similar to 'PE[^XBZ1P 4P 2E 6E]P[^XBZ1P 4P 2E 6E]E' # Spaces and digits does not affect the search for letters, only letters are important. # # Note 2: The same applies to 0. [^0] matches any letter. # $matches=sls "^$wordPattern$" wordlist.txt|% Line # find matched words in file wordlist.txt and return matched string only $groups=$matches|% toCharArray|group|sort Count # group all chars in matched words by count $name=$groups.Name-match"[^ $chars]" # select property Name from all grouped elements (chars itself) and return not matched to $chars only $name[-1] # return last element in the sorted array (most frequently found char) # Note 3: The space is important in the regexp "[^ $chars]" # The space makes the regexp valid if the $chars array is empty } &$f 7 0 2o,5e,7t &$f 7 nl 2o,5e,7t &$f 6 XBZ 1P,4P,2E,6E ``` Output: ``` c r l ``` Variable values for `&$f 7 0 2o,5e,7t`: ``` $WordPattern: "[^02o 5e 7t]o[^02o 5e 7t][^02o 5e 7t]e[^02o 5e 7t]t" $Matches: concept collect comment correct connect convert consent concert $Groups: Count Name Group ----- ---- ----- 1 p {p} 1 v {v} 1 s {s} 2 m {m, m} 2 l {l, l} 4 r {r, r, r, r} 8 n {n, n, n, n...} 8 o {o, o, o, o...} 8 t {t, t, t, t...} 8 e {e, e, e, e...} 13 c {c, c, c, c...} $name: p v s m l r n c $name[-1]: c return: c ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/12693/edit). Closed 7 years ago. [Improve this question](/posts/12693/edit) I've never been able to wrap my head around the [Monty Hall problem](http://en.wikipedia.org/wiki/Monty_Hall_problem). Here's the premise: > > Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice? > > > Run 10,000 simulations. Output the win percentage of switching. For example: ``` > 66.66733% ``` [Answer] ## JavaScript 52 ``` for(i=s=0;i++<1e4;)s+=Math.random()<2/3;alert(s/100) ``` Doors are 1:[0,1/3), 2:[1/3,2/3), 3:[2/3, 1) Assume the prize is always in door 3. If the guest picks doors 1 or 2, which is range [0,2/3), and they switch, they've won the prize. [Answer] ## J: ~~17~~ 15 ``` 100%~+/2>?1e4$3 ``` It picks a random door—let's label these 0, 1, or 2 where 2 is the door with the car—and computes the benefit of switching based on this logic: * If the player picked door 0, the host will open door 1. Switching will earn the player a new car (`1`). * If the player picked door 1, the host will open door 0. Switching will earn the player a new car (`1`). * If the player picked door 2, the winning door, the host will open either door 0 or door 1. Either way, if the player switches, he or she will find a goat (`0`). It then computes the result as the sum of the previous array, divided by 100. I'm pretty shaky with J so I'm sure this could be improved further. [Answer] ## R ~~115~~ 100 The *pseudo-simulation* answer is 23 characters long: ``` sum(runif(1e4)>1/3)/100 ``` but here is an actual simulation: ``` D=1:3 S=function(x)x[sample(length(x),1)] sum(replicate(1e4,{ C=S(D) P=S(D) H=S(D[-c(C,P)]) F=D[-c(P,H)] C==F }))/100 ``` 1. `D` are the possible doors 2. `S` is a function to randomly select one item from a vector 3. `C` is the the door with the car (random among `D`) 4. `P` is the the door picked by the player (random among `D`) 5. `H` is the door picked by the host (random among `D` minus `C` and `P`) 6. `F` is the final door picked by the player (deterministic: `D` minus `P` and `H`) 7. success is measured by `C==F`. returns: [1] 66.731 **Edit** I can save a few characters by not assigning to variables and assuming without loss of generality that `C==1`: ``` D=1:3;S=function(x)x[sample(length(x),1)];sum(replicate(1e4,{P=S(D);1==D[-c(P,S(D[-c(1,P)]))]}))/100 ``` [Answer] ## Perl, ~~98~~ ~~89~~ ~~83~~ ~~75~~ ~~72~~ 71 characters Here's a serious answer that actually runs the simulation: ``` sub c{($==rand 2)-"@_"?$=:&c}$n+=$%==c c($%=rand 3)for 1..1e4;say$n/100 ``` In each loop iteration, the player's initial choice is always door #2. First the door with the car is stored in `$%`, then a different door is selected for Monty Hall to expose. If the remaining door is equal to `$%`, the round is won. (Perl puncutation variables `$%` and `$=` are used because they do integer truncation for free.) [Answer] ## Powershell - 168 131 125 115 **Golfed code:** ``` nal g Random;1..1e4|%{$C=g 3;$P=g 3;$T+=$C-eq(0..2|?{$_-ne$P-and$_-ne(0..2|?{$_-ne$P-and$_-ne$C}|g)})};"$($T/100)%" ``` > > **Changes from Original:** > > Trimmed 53 characters off the original script with some modifications. > > > * Removed spaces and parenthesis where PowerShell is forgiving of it. > * Used a `ForEach-Object` loop, via the `%` alias, instead of `while`. > * Used number ranges (e.g.: `0..2`) instead of explicitly defined arrays. > * Removed `write` from the last command - turns out I don't need it after all. > * Flipped the expression for the host's choice around to use the shorter pipelining syntax. > * Replaced 10000 with 1e4. > * Took [Joey's suggestion](https://codegolf.stackexchange.com/a/778/9387) and omitted `Get-` from `Get-Random`. (Note: This modification *significantly* bloats the run time. On my system it jumped from about 20 seconds to nearly a half-hour per run!) > * Used [Rynant's trick](https://codegolf.stackexchange.com/a/13044/9387) of doing `$T+=...` instead of `if(...){$T++}`. > > > **Some notes:** This script is intended to be as concise as possible, while also being as thorough a simulation of the Monty Hall scenario as possible. It makes no assumptions as to where the car will be, or which door the player will choose first. Assumptions are not even made for which specific door the host will choose in any given scenario. The only remaining assumptions are those which are actually stated in the Monty Hall problem: * The host will choose a door that the player did not pick first, which does not contain the car. + If the player picked the door with the car first, that means there are two possible choices for the host. * The player's final choice will be neither his initial choice nor the host's choice. --- **Ungolfed, with comments:** ``` # Setup a single-character alias for Random, to save characters later. # Note: Script will run a lot (about 500 times) faster if you use Get-Random here. # Seriously, as it currently is, this script will take about a half-hour or more to run. # With Get-Random, it'll take less than a minute. nal g Random; # Run a Monty Hall simulation for each number from 1 to 10,000 (1e4). 1..1e4|%{ # Set car location ($C) and player's first pick ($P) to random picks from a pool of 3. # Used in this way, Random chooses from 0..2. $C=g 3;$P=g 3; # Increment win total ($T) if the car is behind the door the player finally chooses. # (Player's final choice represented by nested script.) $T+=$C-eq( # Filter the doors (0..2) to determine player's final choice. 0..2|?{ # Player's final choice will be neither their original choice, nor the host's pick. # (Host's pick represented by nested script.) $_-ne$P-and$_-ne( # Filter the doors to determine host's pick. 0..2|?{ # Host picks from door(s) which do not contain the car and were not originally picked by the player. $_-ne$P-and$_-ne$C # Send filtered doors to Random for host's pick. }|g ) } ) }; # After all simulations are complete, output overall win percentage. "$($T/100)%" # Variable & alias cleanup. Not included in golfed script. rv C,P,T;ri alias:g ``` --- I've run this script several times and it consistently outputs results very near to two-thirds probability. Some samples: (As above) * 67.02% (Using `Get-Random` as the alias definition, instead of just `Random`) * 66.92% * 67.71% * 66.6% * 66.88% * 66.68% * 66.16% * 66.96% * 66.7% * 65.96% * 66.87% [Answer] # Ruby 48 40 38 My code doesn't make any assumptions about which door the prize will always be behind or which door the player will always open. Instead, I focused on what causes the player to lose. As per the [Wikipedia article](http://en.wikipedia.org/wiki/Monty_hall_problem): > > [...] 2/3 of the time, the initial choice of the player is a door hiding a goat. When that is the case, the host is forced to open the other goat door [...] "Switching" only fails to give the car when the player picks the "right" door (the door hiding the car) to begin with. > > > So to simulate this (instead of using fixed values), I modeled it as so: * the show randomly picks 1 of the 3 doors to hide the prize behind * the player then randomly picks 1 of the 3 doors as his first choice * the player always switches, so if his first choice was the same as the show's choice, he loses The code v1: ``` w=0;10000.times{w+=rand(3)==rand(3)?0:1};p w/1e2 ``` The code v3 (thanks to steenslag and Iszi!): ``` p (1..1e4).count{rand(3)!=rand(3)}/1e2 ``` Some sample return values: * 66.44 * 66.98 * 66.33 * 67.2 * 65.7 [Answer] # Mathematica 42 ``` Count[RandomReal[1,10^4],x_/;x>1/3]/100// N ``` > > 66.79 > > > [Answer] **PowerShell, 90** ``` $i=0 1..10000|%{$g=random 3;$n=0..2-ne$g;$g=($n,2)[!!($n-eq2)]|random;$i+=$g-eq2} $i/10000 ``` Commented: ``` # Winning door is always #2 $i=0 # Run simulation 1,000 times 1..10000|%{ # Guess a random door $g=random 3 # Get the doors Not guessed $n=0..2-ne$g # Of the doors not guessed, if either is the # winning door, switch to that door. # Else, switch to a random door. $g=($n,2)[!!($n-eq2)]|random # Increment $i if $i+=$g-eq2} # Result $i/10000 ``` [Answer] ## C, ~~101~~ 95 ``` float c,s,t,i;main(){for(;i<1e5;i++,c=rand()%3,s=rand()%3)i>5e4&c!=s?t++:t;printf("%f",t/5e4);} ``` That's for the actual simulation. For some cheaty rule-bending code, it's only ~~71~~ ~~65~~ 59: ``` p,i;main(){for(;i<1e5;rand()%5>1?i++:p++)printf("%f",p/1e5);} ``` I didn't do srand() because the rules didn't say I had to. Also, the cheaty version prints out about 30,000 extra numbers because it saves a character. I'm probably missing quite a few tricks, but I did the best I could. [Answer] **Python 2: 72 66 64** ``` from random import* i=10000 exec"i-=randint(0,2)&1;"*i print.01*i ``` Example output: 66.49 [Answer] **[Fish](http://esolangs.org/wiki/Fish) - ~~46~~ 43** This is using the same assumptions that Tristin made: ``` aa*v>1-:?v$aa*,n; v*a<$v+1$x! < >a*0^< $< ``` The down direction on `x` represents you initially picking the correct door, left and right are the cases that you picked a different door, and up is nothing, and will roll again. Originally, I initialized `10000` with `"dd"*`, but `"dd"` had to all be on the same line, and I wasted some whitespace. By snaking `aa*a*a*` I was able to remove a column, and ultimately 3 characters. There's a little bit of whitespace left that I haven't been able to get rid of, I think this is pretty good though! [Answer] **PHP 140** But i think that this is not working right. Any tip? I'm getting values from 49 to 50. ``` $v=0;//victorys for($i=0;$i<1e4;$i++){ //while the selection of the host ($r) equals the player selection or the car //h=removed by host, p=player, c=car while(in_array($h=rand(1,3),[$p=rand(1,3),$c=rand(1,3)])){} ($p!=$c)?$v+=1:0; //if the player changes the selection } echo ($v/1e4)*100; ``` [Answer] ## Game Maker Language, 19 (51 w/ loop) ``` show_message(200/3) ``` It outputs 66.67! This is the correct probability ;) --- The serious-mode code, **51** characters: ``` repeat(10000)p+=(random(1)<2/3);show_message(p/100) ``` Make sure to compile with treat all uninitialized variables as 0. --- The oldest code, **59** characters: ``` for(i=0;i<10000;i+=1)p+=(random(1)<2/3);show_message(p/100) ``` Again, make sure to compile with treat all uninitialized variables as 0. The output was `66.23` ]
[Question] [ **Problem** You are given a sequence of coloured balls (red `R` and green `G`). One such possible sequence is: ``` RGGGRRGGRGRRRGGGRGRRRG ``` In as few moves as possible, you must make it so that each ball is a different colour to its neighbours (i.e. the sequence alternates.) ``` RGRGRGRGRGRGRGRGRGRGRG ``` You should write a program that can convert an unordered sequence (in this case a string) with equal numbers of "R" and "G" into a sequence where the items alternate. One example session is below, for a naive algorithm (`<` is input to program, `>` is output. It isn't necessary to include the carets on the input or output.) ``` < RGGGRRGGRGRRRGGGRGRRRG > RGGRGRGGRGRRRGGGRGRRRG > RGRGGRGGRGRRRGGGRGRRRG > RGRGRGGGRGRRRGGGRGRRRG > RGRGRGGRGGRRRGGGRGRRRG > RGRGRGGRGRGRRGGGRGRRRG > RGRGRGGRGRGRGRGRGGRRRG > RGRGRGGRGRGRGRGRGRGRRG > RGRGRGGRGRGRGRGRGRGRGR > RGRGRGRGGRGRGRGRGRGRGR > RGRGRGRGRGGRGRGRGRGRGR > RGRGRGRGRGRGGRGRGRGRGR > RGRGRGRGRGRGRGGRGRGRGR > RGRGRGRGRGRGRGRGGRGRGR > RGRGRGRGRGRGRGRGRGGRGR > RGRGRGRGRGRGRGRGRGRGGR > RGRGRGRGRGRGRGRGRGRGRG (15 moves) ``` Another possibility is outputting "5,7" for example to indicate swapping of positions 5 and 7. You may position *either* Red or Green first, and you don't have to be consistent. Each sequence will be the same length as every other sequence. You may only swap any two letters in each move (they do not need to be adjacent.) **Winning Criteria** The program must show each step of the sort process. The program which makes the fewest *total* moves for all the below strings, wins. If there is a tie, the shortest code will win. **Input Strings** The following strings will be used to test the programs: ``` GGGGGGGGGGRRRRRRRRRR GGRRGGRRGGRRGGRRGGRR RRGGGGRRRRGGGGRRRRGG GRRGRGGGGRRRGGGGRRRR GRGGGRRRRGGGRGRRGGRR RGRGRGRGRGRGRGRGRGRG ``` The last sequence should result in zero moves. [Answer] ## Python, 140 122 119 115 ``` r=raw_input() f=lambda x:[i for i in range(x,len(r),2)if x-(r[i]!=max('RG',key=r[::2].count))] print zip(f(0),f(1)) ``` [Answer] ## APL 46 ``` ((2|y)/y←(i≠↑i)/n),[.1](~2|y)/y←(i=↑i)/n←⍳⍴i←⍞ ``` Running the given test cases yields: ``` GGGGGGGGGGRRRRRRRRRR 11 13 15 17 19 2 4 6 8 10 GGRRGGRRGGRRGGRRGGRR 3 7 11 15 19 2 6 10 14 18 RRGGGGRRRRGGGGRRRRGG 3 5 11 13 19 2 8 10 16 18 GRRGRGGGGRRRGGGGRRRR 3 5 11 17 19 4 6 8 14 16 GRGGGRRRRGGGRGRRGGRR 7 9 13 15 19 4 10 12 14 18 RGRGRGRGRGRGRGRGRGRG ``` The above solution uses index origin 1 with the swaps given in the columns of the results matrix. Two characters can be saved if the input vector i is initialised with the input string prior to execution rather than being input at the time of execution. [Answer] ## GolfScript (47 chars) ``` :S;4,{S,,{.S=1&3*\1&2*^1$=},\;}%2/{zip}%{,}$0=` ``` E.g. (using a [test case](http://golfscript.apphb.com/?c=OydSUkdHUkdSR1JHUkdSR1JHUkdSRycKOlM7NCx7Uywsey5TPTEmMypcMSYyKl4xJD19LFw7fSUyL3t6aXB9JXssfSQwPWA%3D) which is far easier to check for correctness than any of the suggested ones, which all have lots of correct answers): ``` < RRGGRGRGRGRGRGRGRGRG > [[1 2]] ``` Output is a list of zero-indexed pairs to swap. [Answer] ## Python, 213 chars ``` I=raw_input() def M(S,T): S=list(S);m=[] while S!=list(T):z=zip(S,T);x=z.index(('R','G'));y=z.index(('G','R'));m+=[(x,y)];S[x],S[y]='GR' return m N=len(I)/2 x=M(I,N*'RG') y=M(I,N*'GR') print[x,y][len(x)>len(y)] ``` `M` finds the moves required to convert `S` to `T`. It does this by repeatedly finding an `R` and a `G` out of position and swapping them. We then find the shorter move sequence to get to either `RGRG...RG` or `GRGR...GR`. Should find an optimal sequence of moves for every input. [Answer] # Mathematica 238 **Code** ``` f[x_] := With[{g = "GRGRGRGRGRGRGRGRGRGR", c = Characters, p = Position}, y = c[x]; s = c[g]; {v = Equal @@@ ({s, y}\[Transpose]), w = Not /@ v}; {vv = Thread[{y, v}], ww = Thread[{y, w}]}; ((Flatten /@ {p[#, {"R", False}], p[#, {"G", False}]}) &[If[Count[Equal @@@ ({s, y}\[Transpose]), False] < 10, vv, ww]])\[Transpose]] ``` N.B.: `\[Transpose]` is a single character, a superscripted "t", in *Mathematica*] **Examples** ``` f@"GGGGGGGGGGRRRRRRRRRR" f@"GGRRGGRRGGRRGGRRGGRR" f@"RRGGGGRRRRGGGGRRRRGG" f@"GRRGRGGGGRRRGGGGRRRR" f@"GRGGGRRRRGGGRGRRGGRR" f@"RGRGRGRGRGRGRGRGRGRG" f@"GRGRGRGRGRGRGRGRGRGR" ``` > > {{12, 1}, {14, 3}, {16, 5}, {18, 7}, {20, 9}} > > {{4, 1}, {8, 5}, {12, 9}, {16, 13}, {20, 17}} > > {{2, 3}, {8, 5}, {10, 11}, {16, 13}, {18, 19}} > > {{2, 1}, {10, 7}, {12, 9}, {18, 13}, {20, 15}} > > {{2, 1}, {6, 3}, {8, 5}, {16, 11}, {20, 17}} > > {} > > {} > > > [Answer] ## Mathematica 134 or 124 Depending on how you count "Transpose[]" which on Mathematica is just one char (no representation here). Spaces added for clarity ``` G = 0; R = 1; x_~ d ~ y__:= Transpose[Position[Symbol /@ Characters@x - PadLeft[{}, 20, {y}], #, 1] & /@ {1, -1}] f = SortBy[{d[#, 0, 1], d[#, 1, 0]}, Length][[1]] & ``` Sample: ``` f@"GGGGGGGGGGRRRRRRRRRR" f@"GGRRGGRRGGRRGGRRGGRR" f@"RRGGGGRRRRGGGGRRRRGG" f@"GRRGRGGGGRRRGGGGRRRR" f@"GRGGGRRRRGGGRGRRGGRR" f@"RGRGRGRGRGRGRGRGRGRG" f@"GRGRGRGRGRGRGRGRGRGR" ``` Output ``` {{{11}, {2}}, {{13}, {4}}, {{15}, {6}}, {{17}, {8}}, {{19}, {10}}} {{{3}, {2}}, {{7}, {6}}, {{11}, {10}}, {{15}, {14}}, {{19}, {18}}} {{{1}, {4}}, {{7}, {6}}, {{9}, {12}}, {{15}, {14}}, {{17}, {20}}} {{{2}, {1}}, {{10}, {7}}, {{12}, {9}}, {{18}, {13}}, {{20}, {15}}} {{{2}, {1}}, {{6}, {3}}, {{8}, {5}}, {{16}, {11}}, {{20}, {17}}} {} {} ``` [Answer] # Javascript - 173 characters ``` a=prompt(w=[[],[]]).split('');for(i=a.length,f=a[0];i--;)if(i%2<1&&a[i]!=f)w[0].push(i);else if(i%2>0&&a[i]==f)w[1].push(i);for(i=w[0].length;i--;)alert(w[0][i]+','+w[1][i]) ``` A great challenge, kept me busy for some time. Here the codes results for the test cases: ``` GGGGGGGGGGRRRRRRRRRR: [10, 1] [12, 3] [14, 5] [16, 7] [18, 9] GGRRGGRRGGRRGGRRGGRR: [ 2, 1] [ 6, 5] [10, 9] [14,13] [18,17] RRGGGGRRRRGGGGRRRRGG: [ 2, 1] [ 4, 7] [10, 9] [12,15] [18,17] GRRGRGGGGRRRGGGGRRRR: [ 2, 3] [ 4, 5] [10, 7] [16,13] [18,15] GRGGGRRRRGGGRGRRGGRR: [ 6, 3] [ 8, 9] [12,11] [14,13] [18,17] RGRGRGRGRGRGRGRGRGRG: ``` [Answer] # PHP - 34 moves - 193 characters ``` $l=strlen($a=$_GET["a"]);$n=$a[0]=="R"?"G":"R";while($i<$l){if($a[++$i]!=$n){echo$o." ";$o=$a=substr($a,0,$i).$n.preg_replace("/".$n."/",$n=="R"?"G":"R",substr($a,$i+1),1);}$n=$n=="R"?"G":"R";} ``` Might still try to improve this... ``` red_green.php?a=GGGGGGGGGGRRRRRRRRRR GRGGGGGGGGGRRRRRRRRR GRGRGGGGGGGGRRRRRRRR GRGRGRGGGGGGGRRRRRRR GRGRGRGRGGGGGGRRRRRR GRGRGRGRGRGGGGGRRRRR GRGRGRGRGRGRGGGGRRRR GRGRGRGRGRGRGRGGGRRR GRGRGRGRGRGRGRGRGGRR GRGRGRGRGRGRGRGRGRGR ``` ]
[Question] [ A rigid transformation of a square array is a mapping from square arrays of a certain size to square arrays of the same size, which rearranges the elements of the array such that the distance to each other element remains the same. If you printed out the matrix on a sheet of paper these are the transforms you could do to it without tearing or folding the paper. Just rotating or flipping it. For example on the array: \$ \begin{bmatrix} 1 & 2 \\ 4 & 3 \end{bmatrix} \$ There are 8 ways to rigidly transform it: \$ \begin{bmatrix} 1 & 2 \\ 4 & 3 \end{bmatrix} \begin{bmatrix} 2 & 3 \\ 1 & 4 \end{bmatrix} \begin{bmatrix} 3 & 4 \\ 2 & 1 \end{bmatrix} \begin{bmatrix} 4 & 1 \\ 3 & 2 \end{bmatrix} \begin{bmatrix} 3 & 2 \\ 4 & 1 \end{bmatrix} \begin{bmatrix} 4 & 3 \\ 1 & 2 \end{bmatrix} \begin{bmatrix} 1 & 4 \\ 2 & 3 \end{bmatrix} \begin{bmatrix} 2 & 1 \\ 3 & 4 \end{bmatrix} \$ The first \$4\$ are just rotations of the matrix and the second \$4\$ are rotations of it's mirror image. The following is *not* a rigid transform: \$ \begin{bmatrix} 2 & 1 \\ 4 & 3 \end{bmatrix} \$ Since the relative position of \$2\$ and \$3\$ has changed. \$2\$ used to be opposite \$4\$ and next to \$1\$ and \$3\$, but now it is opposite \$3\$ and next to \$1\$ and \$4\$. For some starting arrays "different" transforms will give the same array. For example if the starting array is all zeros, any transform of it will always be identical to the starting array. Similarly if we have \$ \begin{bmatrix} 1 & 0 \\ 1 & 0 \end{bmatrix} \$ The transforms which mirror it and rotate it a half turn, although they gave different results on the first example, give the same result in this example. There are never more than \$8\$ unique transforms, the \$4\$ rotations and \$4\$ mirror rotations. Even when we scale the matrix up. So the number of unique results is always less than or equal to 8. In fact a little bit of math can show that it is always 1, 2, 4, or 8. ## Task Take a non-empty square array of non-negative integers as input and return the number of unique ways to continuously transform it. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes. ## Test cases ``` 5 => 1 0 0 0 0 => 1 0 1 1 0 => 2 0 1 0 0 => 4 0 1 0 1 => 4 2 1 1 3 => 4 3 4 9 1 => 8 1 2 1 0 => 8 0 1 0 1 1 1 0 1 0 => 1 0 2 0 0 0 0 0 0 0 => 4 0 2 0 2 0 0 0 0 0 => 4 0 2 0 6 0 0 0 0 0 => 8 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` UZƭ7СQL ``` [Try it online!](https://tio.run/##y0rNyan8/z806tha88MTDi0M9Pl/uP1R05r//6O5FBSio01jY3XADAMdg1gdMAkXMAQKGKILGGAKGMIEjKBajGECxjomQAFLhApDHSMMQ8EWGwJpqGnIkkYwVyHRaJJG@CTN0CVjAQ "Jelly – Try It Online") `UZƭ` alternatively performs `U` (reverse each row) and `Z` (transpose). Doing this 7 times and collecting all intermediate results with `7С` gets all 8 transforms: {identity, `U`, `UZ`, `UZU`, … `UZUZUZU`}, and `QL` (unique+length) counts distinct ones. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 16 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` ≠∘⍷·⌽¨⊸∾⍉∘⌽⍟(↕4) ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4omg4oiY4o23wrfijL3CqOKKuOKIvuKNieKImOKMveKNnyjihpU0KQoK4o2JPuKLiOKfnEbCqCDin6gKMeKAvzHipYo1CjLigL8y4qWKMOKAvzDigL8w4oC/MAoy4oC/MuKlijDigL8x4oC/MeKAvzAKMuKAvzLipYow4oC/MeKAvzDigL8wCjLigL8y4qWKMOKAvzHigL8w4oC/MQoy4oC/MuKlijLigL8x4oC/MeKAvzMKMuKAvzLipYoz4oC/NOKAvznigL8xCjLigL8y4qWKMeKAvzLigL8x4oC/MAoz4oC/M+KlijDigL8x4oC/MOKAvzHigL8x4oC/MeKAvzDigL8x4oC/MAoz4oC/M+KlijDigL8y4oC/MOKAvzDigL8w4oC/MOKAvzDigL8w4oC/MAoz4oC/M+KlijDigL8y4oC/MOKAvzLigL8w4oC/MOKAvzDigL8w4oC/MAoz4oC/M+KlijDigL8y4oC/MOKAvzbigL8w4oC/MOKAvzDigL8w4oC/MArin6k=) `⍉∘⌽⍟(↕4)` Get the 4 rotations. `⌽¨⊸∾` Add the mirror image of each rotation. `≠∘⍷` Count the unique matrices. [Answer] # [R](https://www.r-project.org/), ~~97~~ ~~94~~ 83 bytes Or **[R](https://www.r-project.org/)>=4.1, 69 bytes** by replacing two `function` occurrences with `\`s. ``` function(m)length(unique(Map(function(i)m<<-t("if"(i%%2,m,t(m[ncol(m):1,]))),1:8))) ``` [Try it online!](https://tio.run/##lZDBCsIwDIbve4qiDFKI0HRTpmy@gTdv4kGG08JadXTg289aYWyyCl6aknzfT9qmq4quak1p1c2A5vXZXOwVWqMe7Rl2pzv0Q8V1ni8szFQ1AxXHEjVa0AdT3mpnbgiPnHOkTeZKV4E@2UY9YYnE@bzYMor6XgkCBUbu4CgR95MAYURjQI4BRu8INkLSSYSCiPQIIUuCSIIsxWj9lZINEedLnyKCiN@FCU9Rv5c3ktAPuFAmPm8cXoZGOmnIv43VDyPrXg "R – Try It Online") I'm happy with my discovery that `unique` works well on a list of matrices. **Explanation:** 1. Repeat 8 times a function returning alternating between: 1. transposition of previous matrix, 2. previous matrix with reversed rows. * Double transposition is needed for the size-1 edge case. 2. How many unique matrices? [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 4FDøDí})Ùg ``` [Try it online](https://tio.run/##yy9OTMpM/f/fxM3l8A6Xw2trNQ/PTP//PzraUMcoVifaWMckNhYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU3lotw6Xkn9pCYz/38TN5fAOl8NrazUPz0z/r3Nom/3/6OhoQx2jWJ1oYx2T2FgdhehoUwhloGMAFAWRUK4hkGuIyjVA5xpCuEZQxcYQLshonWhLmCzEPmSjwFYZAmmoKQgpI5grkGgUKSPcUmaoUrEA). **Explanation:** ``` 4F # Loop 4 times: D # Duplicate the current matrix # (which will be the implicit input-matrix the first iteration) ø # Zip/transpose; swapping rows/columns D # Duplicate again í # Reverse each row }) # After the loop: wrap all nine matrices into a list Ù # Uniquify this list of matrices g # Pop and push the length # (after which it is output implicitly as result) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` F⁴«⊞υθ⊞υ⮌θ≔EθE⮌θ§μλθ»I÷⁸№υθ ``` [Try it online!](https://tio.run/##RU09C8IwFJztr3jjCzwhiIPQqdSlg1BcQ4bQRhuoiU3SIoi/PbZa6C33BXdNp3zjVJ/SzXnAI4N3tqvH0OFIMLB8M1c9aR80DmxJixDM3eJFPXEgWGjrCYpY2Va/8EHQM8b@S5@s9sZGLFWIWNl4NpNpNZ4ISjfO@e9wRp6SEIITHAi4JBALr5KvUsq0n/ov "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⁴« ``` Repeat for each possible rotation. ``` ⊞υθ⊞υ⮌θ ``` Push the array and its vertical reflection to the predefined empty list. ``` ≔EθE⮌θ§μλθ ``` Rotate the array. ``` »I÷⁸№υθ ``` Count the number of times the array appears in the list. Each unique array in the list must appear that number of times. Divide that into `8` to give the number of unique arrays, and output the result. [Answer] # [Python](https://www.python.org), 58 bytes ``` lambda l:len({l:=(l[::-1],(*zip(*l),))[p]for p in(0,1)*4}) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVBBTsMwELznFaandeRWcVJQsGRuvCLkEJREteQ6qyYRAsRLuFRCcOQPPKO_YR0bJEQPXu3M7OzYfv3Ax2k3uONbr-_e56lflydlm_192zCrbOfg2SoNtlJqLWsB6ZNBSC0XnFdY98OBITMOMiF5un3hccPnw87YjsGotHE4T8D5hV7dunalEsYM06yCdN8gGDeJcTOiNX5G8Jrk_94qq8muFzPZNw1i51o4v4LT0EAJxMNYFarmMXKa0XZgPMSDV43oCYoh3vp4-rpM9A2TScay5UQgExlAvoCobCOQAeTLWBFAQec6KCWx-c-C0s9TK6nK2MeQPGT-1pjg6fw8ffWXLhP63_CSbw) Essentially a port of my [answer](https://codegolf.stackexchange.com/a/241592/107561) to a related (hexagonal) challenge, It generates all 8 symmetries from 2 reflections (up-down and transpose). [Answer] # JavaScript (ES6), ~~85~~ 81 bytes *Saved 4 bytes thanks to @l4m2* ``` f=m=>new Set([...f+1].map(c=>(m=m.map((_,y)=>m.map(r=>+c?r[y]:r.pop())))+0)).size ``` [Try it online!](https://tio.run/##dU5LTsMwEN3nFKNuYivFTVJApcjpCpZsumwrZBKnBOWH4wIFcQMkNizhHpynF@AIYep8KhaM5dG8z3zuxIOoQpWU@igvIlnXMc94kMtHmEtNFoyx2PFWLBMlCXlAMp6ZmlwPt5QHDVA8cMKZWmxXU8XKoiQUw3EpZVXyLGsl7zeJksSOK5syJUV0maRyvs1D4lKmi7lWSb4m6C7TRJPBMl/mA8riQl2I8JZUwAN4sQBSqUEAh@pgHNAhCvuQT6UMtYxQd0RzBN6msX@0jJxR78vQIMzVZm4/CwbUsFeb7EYq2vuVRB/EJKPnFlJhkVdFKllarMlecsDG54ABnB/OmIH98/2@@/zAbMMU7N3Xm01xyCutTyzc7FmWC675HfIsr0F@g1rtuENei3zjHLdojOms0SYW8n43ZWL6sPYwe23d7fKb3X3u9ux5/x/@9C8/@QU "JavaScript (Node.js) – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 48 bytes ``` a->#Set([a=if(i%2,Mat(Vecrev(a)),a~)|i<-[1..8]]) ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P1HXTjk4tUQjOtE2M00jU9VIxzexRCMsNbkotUwjUVNTJ7FOsybTRjfaUE/PIjZW839iQUFOpUaigq6dQkFRZl4JkKkE4igppIHVK0SDDDAFMQx0DKyBOBbMNLQ2RDANkJmGIKYRWIExiGmsY2JtCRE11DFC0gY0zhBIgvXABI0gdsBIhKARNkEzJEGgXwA "Pari/GP – Try It Online") A port of [@loopy walt's Python answer](https://codegolf.stackexchange.com/a/241751/9288). ]
[Question] [ Note: This is an attempt at recycling [guest271314's permutation question(s)](https://codegolf.stackexchange.com/q/175677/76162) There's an interesting pattern that forms when you find the differences between lexographically sorted permutations of base 10 numbers with ascending unique digits. For example, `123` has permutations: ``` 123 132 213 231 312 321 ``` When you find the differences between these, you get the sequence ``` 9 81 18 81 9 ``` Which are all divisible by nine (because of the digit sum of base 10 numbers), as well as being palindromic. Notably, if we use the next number up, `1234`, we get the sequence ``` 9 81 18 81 9 702 9 171 27 72 18 693 18 72 27 171 9 702 9 81 18 81 9 ``` Which extends the previous sequence while remaining palindromic around \$693\$. This pattern always holds, even when you start using more that `10` numbers, though the length of the sequence is \$n!-1\$ for \$n\$ numbers. Note that to use numbers above `0 to 9`, we don't change to a different base, we just multiply the number by \$10^x\$, e.g. \$ [1,12,11]\_{10} = 1\*10^2 + 12\*10^1 + 11\*10^0 = 231\$. Your goal is to implement this sequence, by returning each element as a multiple of nine. For example, the first 23 elements of this sequence are: ``` 1 9 2 9 1 78 1 19 3 8 2 77 2 8 3 19 1 78 1 9 2 9 1 ``` Some other test cases (0 indexed): ``` 23 => 657 119 => 5336 719 => 41015 5039 => 286694 40319 => 1632373 362879 => 3978052 100 => 1 1000 => 4 10000 => 3 100000 => 3 ``` ### Rules: * The submission can be any of: + A program/function that takes a number and returns the number at that index, either 0 or 1 indexed. + A program/function that takes a number \$n\$ and returns up to the \$n\$th index, either 0 or 1 indexed. + A program/function that outputs/returns the sequence infinitely. * The program should be capable of theoretically handling up to the \$11!-1\$th element and beyond, though I understand if time/memory constraints make this fail. In particular, this means you cannot concatenate the digits and evaluate as base 10, since something like \$012345678910\$ would be wrong. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest implementation for each language wins! ### Notes: * This is [OEIS A217626](https://oeis.org/A217626) * I am offering a bounty of 500 for a solution that works out the elements directly without calculating the actual permutations. * The sequence works for any contiguous digits. For example, the differences between the permutations of \$ [1,2,3,4]\_{10} \$ are the same as for \$[-4,-3,-2,-1]\_{10}\$. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ,‘œ?ŻḌI÷9 ``` [Try it online!](https://tio.run/##ARsA5P9qZWxsef//LOKAmMWTP8W74biMScO3Of///zc "Jelly – Try It Online") (print the n'th element) [Try it online!](https://tio.run/#%23ASEA3v9qZWxsef//LOKAmMWTP8W74biMScO3Of8yMFLDh@KCrP8 "Jelly – Try It Online") (20 first elements) Explanation: ``` I÷9 Compute the difference divided by 9 between ‘ the (n+1)th œ? permutation , and the (n)th œ? permutation Ż of [0,1,2,...n] Ḍ converted to decimal. ``` (Jelly has the builtin `œ?` which computes the `n`th permutation of a list in approximately linear time. Quite useful.) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 71 bytes ``` ≔⟦N⊕θ⟧ηW⌈η≧÷L⊞OυEη﹪κ⊕Lυη≔⁰δF²«≔Eυλζ≔⟦⟧ηF⮌Eυ§κι«⊞η§ζκ≔Φζ⁻μκζ»≦⁻↨ηχδ»I÷δ⁹ ``` [Try it online!](https://tio.run/##VZDLTsMwEEXXyVd4OZaMVMoKdVVASJEaqLqtWJh6Glt1nOBHqIr67cHOA1FvLM/cOfd6DpLbQ8N136@dU5WBfWHa4N9C/YkWKCOFOVis0XgU8EU/GJF0lX9LpZFAyc@qDjVISknJ25GwU5X0UBj/ojolkJENmspL2AYn31u03DcWAksDIOPViKAbON06TTOBDmc0nQIuGBHxdWwsgSUlP3k2NRIwcnWUX6JgLu@nzNkwscMOrcNZvPaFEXhO9io5JVyWkqZoc/PCyIkmwox8VdrH7cR6qUxwUA@CyfaaZ3@72ODRw6Bh5IlH20i9X9DxB9d8a5Xx8Mzdv32BYOQxJln1/fKhv@v0Lw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⟦N⊕θ⟧η ``` Get a list containing the input and one more than the input. ``` W⌈η ``` Repeat until both values are zero. ``` ≧÷L⊞OυEη﹪κ⊕Lυη ``` Perform factorial base conversion on both values. This is the first time I've actually used `≧` on a list! ``` ≔⁰δ ``` Clear the result. ``` F²« ``` Loop over each factorial base number. ``` ≔Eυλζ ``` Make a list of the digits from 0 to length - 1. ``` ≔⟦⟧η ``` Initialise the result to an empty list. ``` F⮌Eυ§κι« ``` Loop over the digits of the factorial base number. ``` ⊞η§ζκ ``` Add the next permutation digit to the result. ``` ≔Φζ⁻μκζ» ``` Remove that digit from the list. ``` ≦⁻↨ηχδ» ``` Convert the permutation as a base 10 number and subtract the result so far from it. ``` I÷δ⁹ ``` Divide the final result by 9 and cast to string. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 82 bytes *-2 bytes thanks to Jo King* ``` ->\n{([-] map {$/=[^n];:10[map {|splice $/,$_,1},[R,] .polymod(1..n-2)]},n+1,n)/9} ``` [Try it online!](https://tio.run/##LcjfCoIwFIDxVzkXIxwd3Y7rDxb2EN2uJZIKwZxDr8T27Culmx98n29He4r9DLsOypjeHm5JdGqgrz0sTJT66cz1QlJv4zN5@361wASyCimgvqOBzA927ocmoSxzac5NQLcndFwUIU71DF3CKg7dMEKuEIgKhPPKUaqfB6nWICk3/sr4BQ "Perl 6 – Try It Online") 0-indexed. Doesn't enumerate all permutations. Should theoretically work for all n, but bails out for n > 65536 with "Too many arguments in flattening array". The following **80 byte** version works for n up to 98!-2 and is a lot faster: ``` {([-] map {$/=[^99];:10[map {|splice $/,$_,1},[R,] .polymod(1..97)]},$_+1,$_)/9} ``` [Try it online!](https://tio.run/##NY1BDoIwFESv8hfEFC3QTxWohku4baohQhOTNjSwapCz10J0815mZjFumEwVrIeDhjYsRGYKbOdgSYpWPoRQtysyuTef2Zn3a4CkoMmT4krlnSrI3Wi8HXuCeS7qVK1xPGFEWog1zJ0HTWIAPU5QcgqIgkK94cJ45JnxLfCqbOpoZGzHj39FE3lUsJ00aVaGLw "Perl 6 – Try It Online") The following **53 byte** version should theoretically work for all n, but bails out for n >= 20 with "refusing to permutate more than 20 elements". ``` {[-](map {:10[$_]},permutations(1..$_+1)[$_,$_-1])/9} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Olo3ViM3sUCh2srQIFolPrZWpyC1KLe0JLEkMz@vWMNQT08lXttQEyiloxKvaxirqW9Z@784sVIhTUMlXlMhLb9IAajGyOA/AA "Perl 6 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 134 bytes ``` n=>(F=_=>f>n?((G=(n,z=0,x=f,y=l,b=[...a])=>y?G(n%(x/=y),+b.splice(n/x,1)+z*10,x,y-1,b):z)(n--)-G(n))/9:F(a.push(++l),f*=l))(a=[l=f=1]) ``` [Try it online!](https://tio.run/##VYvBboMwEETv/YpeKu3Gi7FD0pTQJbck/xChyFBoXbkGQRsBP09BzaWHeRpp5n2am@mK1jbfga/fyunMk@cUjnzltEr9AeDE4GlkRT1XNLCjnC9SSpMhp8PhBP4J@pAHJJHLrnG2KMGHPWkU40rPFg2Bphz3I4IPAgxmAzGM90cwsvnpPkAIh1St2CGC4YvjinWGU3JZR6R1TLs5WxXFtFHRXKPn9csuJq3Ukj/cqe5jnMkv04DltKh9V7tSuvodrNB0XoiID0lVt3Az7aNlndhX3qqNSqwQ@M9Y/vN5@gU "JavaScript (Node.js) – Try It Online") 1-indexed. @guest271314's opinion is right. Direct permutation computation is shorter... ### Explanation ``` n=>( // Function - F=_=> // Helper func to calculate length needed f>n? // If f > n (meaning the length is enough) - ( ( G=( // Helper func to calculate permutation value - n, z=0, // Initial values x=f, // Made as copies because we need to alter y=l, // these values and the function will be b=[...a] // called twice )=> y? // If still elements remaining - G( n%(x/=y), // Get next element +b.splice(n/x,1)+z*10, // And add to the temporary result x, y-1, // Reduce length b // Remaining elements ) :z // Otherwise return the permutation value )(n--)-G(n) // Calculate G(n) - G(n - 1) )/9 // ... the whole divided by 9 :F( a.push(++l), // Otherwise l = l + 1, push l into the array f*=l // ... and calculate l! ) )( a=[l=f=1] // Initial values ) ``` ## Original solution (159 bytes) ``` n=>(x=l=t=0n,P=(a,b=[])=>n?""+a?a.map(z=>P(a.filter(y=>y-z),[...b,z])):(v=b.reduce((u,y)=>u=u*10n+y),x?--n?0:t=v-x:0,x=v):0)([...Array(n+1))].map(_=>++l))&&t/9n ``` [Try it online!](https://tio.run/##LY3NboMwEITvfYwcot16ce3QNIVqjfoAlXJHqDKEplTERMQg4OUp@TnMp5FG@ubP9vZStNXZB645lPORZ8cGBq7Zs3K0Z7CUc5ohG5esVsImVp7sGSY2e7Dyp6p92cLIZgwmpFRKmdOUIcbQcy7b8tAVJUBH4yLouHvWyokRaUiCwCUq9twHQ6xo4B5jhXAVfLatHeHL@l95qhw4oUlvEbPb7zcbIWrE9dq/RG7@eEo3IWkd0W7JVoURvapwqeHb5n0XkVbqmjseVI8xuhsrNkXjLk1dyro5QrXc3YiI8z8 "JavaScript (Node.js) – Try It Online") Link is to a longer version made for performance. `Array(n+1)` becomes `Array(Math.min(n+1,15))` in order to make demo work. Theoretically works up to infinity (up to stack limit in practice). ### Explanation I mean there's too much to explain. ``` n=>( // Function x=l=t=0n, // Initialization P=( // Function to determine the permutation - a, // remaining items b=[] // storage )=> n? // if we haven't reached the required permutation yet - ""+a? // if we haven't the last layer of loop - a.map( // loop over the entries - z=> P( // recurse - a.filter(y=>y-z), // pick out the selected number [...b,z] // append to next ) ) :( // if we are at the last layer - v=b.reduce((u,y)=>u=u*10n+y), // calculate the value of the permutation x? // if not the first number - --n? // if not the last - 0 // do nothing :t=v-x // else calculate difference :0, // else do nothing x=v // record ot anyway ) :0 // else do nothing ) ( [...Array(n+1)].map(_=>++l) // the list of numbers to permute )&&t/9n // last difference divided by 9 ``` [Answer] # Pyth, ~~15~~ 14 bytes ``` .+m/i.PdSQT9,h ``` Returns the nth term. Try it [here](http://pyth.herokuapp.com/?code=.%2Bm%2Fi.PdSQT9h&input=23+%2B+1&debug=0). ``` .+ Find the differences between adjacent elements of m mapping lambda d: .PdSQ the dth permutation of input, i T converted to base 10 / 9 divided by 9 , over [Q+1,Q] h Q Q ``` [Answer] # [J](http://jsoftware.com/), ~~44~~, 41 bytes ``` (9%~[:(2-~/\])i.(10#.1+A.)[:i.@>.!inv)@>: ``` [Try it online!](https://tio.run/##VY9Na8JAEIbv@RWvFTFLkzUT7U6yUPEDPEkPvWovDQndUhJJbC8F/3ocI0ocmBeedz5257t90uMCrxZjBIhgJUON9ft20/rp6LSzfhyeJvsP5bRP0VDT81KrnXV6MdcDV/6pxdy2ypPIs68KfgFSCC0CS3eHubMIKWJJAicilGKKRBxmkUSA7rVbo3nhHlFXi1PMwNJujPiUCNFljeH@UjMzD8j9SWIjykJx98rDBy6TPfS8t5VGVtV1nh0DfP4e8VM1eYODGK5xVXm989@iwIAitGc "J – Try It Online") Note: works even for 10! test case, but loses some precision there... ## original explanation ``` (9 %~ [: (2 -~&(10&#.)/\ ]) 1 + i. A. i.@>.@(!inv))@>: ( )@>: NB. add one to input NB. since n-1 deltas NB. gives n results NB. call that "n" ( i. ) NB. take the first n ( A. ) NB. lexicographically NB. sorted items of ( i.@ ) NB. 0 up to... ( >.@ ) NB. the ceil of... ( (!inv)) NB. the inverse of NB. the factorial ( 1 + ) NB. add 1 so our NB. lists start at 1 NB. instead of 0 ( [: ( ) ) NB. apply what's in NB. parens to that NB. list of lists ( (2 -~ /\ ]) ) NB. take successive NB. differences BUT ( ( &(10&#.) ) ) NB. convert each list NB. to a base 10 NB. number first (9 %~ ) NB. and divide every NB. items of the NB. result by 9 ``` [Answer] # JavaScript (ES6), 112 bytes Very similar to [Shieru Asakoto's algorithm](https://codegolf.stackexchange.com/a/175745/58563). ``` n=>(g=N=>(h=a=>k>n?(F=r=>--i?F(+a.splice(N/(k/=i),1)+r*10,N%=k):r/9)``:h([i+1,...a],k*=i++))([i=k=1]))(n++)-g(n) ``` [Try it online!](https://tio.run/##bc7faoMwFAbw@z2FN4Okav54NJrCsXe99AVGoeKszSKx6Njru0A72bLm4pDk93H4Ptqvdulmc/tM3fTerxdcHdZkwMbPK7ZY29odyBFnrNPUHI4kbtlyG03Xk4YTy9HQRNJ43kmRNK9o6X7mmp7P@yt5M7FMGGPtKbE7NHFMqf9Di/Lkb86/04E4unaTW6axZ@M0kAvJIPKH0ojzSBXly1@VUm9aAKiAy1@cSyGLwAsB@sezSimdB4FcgF9xD0gFGZQQJEBlVanvCdBlJYos7CjEVkL@N7EVfGLiYfDMxMPWbw "JavaScript (Node.js) – Try It Online") ]
[Question] [ **Requirement:** Write a program (in any language) that counts the number of lines of code in files matching `*.sh` in the directory tree starting from the directory that the program is executed in, excluding lines that are empty, only contain whitespace, or are just single-line comments (a line which the first character that is not a whitespace character is `#`). Files will only contain printable ASCII characters. **Output:** A single integer representing the total count (can be followed by a newline too). Here is an expanded solution in Python: ``` import os, sys def recurse(dir = './'): count = 0 for file in os.listdir(dir): if not os.path.isfile(dir + file): count += recurse(dir + file + '/') elif file.endswith('.sh'): with open(dir + file, 'r') as f: for line in f.read().split('\n'): if (not line.strip().startswith('#')) and (not line.strip() == ''): count += 1 return count sys.stdout.write(recurse()) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~47~~ 46 bytes ``` ls *.sh -r|gc|%{$o+=!($_-match'^\s*(#|$)')};$o ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/P6dYQUuvOENBt6gmPblGtVolX9tWUUMlXjc3sSQ5Qz0uplhLQ7lGRVNds9ZaJf//fwA "PowerShell – Try It Online") (will always return `0` since there aren't any files) [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvlJafn5BXklpckpCnnJyfm5uaV6JkBxTUK874n1OsoAWkFXSLatKTa1SrVfK1bRU1VOJ1cxNLkjPU42KKtTSUa1Q01TVrrVXy//8HAA "PowerShell – Try It Online") (here's a link that populates a dummy file so you can see the process) *-1 byte thanks to Neil* `ls` is alias for `Get-ChildItem`, specifying `*.sh` with the `-r`ecurse parameter, then we `g`et-`c`ontent of files. For each of those lines `|%{...}`, we accumulate into our `$o`utput a one if the Boolean `!(...)` statement is truthy. Inside the statement is a simple regex `-match` against the whitespace-only/comment/blank lines. Finally we leave `$o` on the pipeline. ~~The implicit `Write-Output` that happens at program completion adds a trailing newline, but that shouldn't matter in this case because the variable `$o` itself doesn't have a trailing newline nor does the actual return variable. It's a quirk of the shell, not a quirk of the program. For example, saving this to a script and executing that script in a pipeline will not have a newline.~~ [Answer] # Powershell 3+, 40 byte ``` (ls *.sh -r|sls '^\s*(#|$)' -a -n).Count ``` `ls *.sh -r` gets a file names from the directory tree. `sls` (alias for [Select-String](https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Select-String)) gets all strings (`-a` is shortcut for `-AllMatches`) that not mathces (`-n` is alias for `-NotMatch`) to the pattern `'^\s*(#|$)'`. [Answer] # Linux Shell, ~~30~~ 60 bytes confirmed in `dash` ``` cat `find . -name \*.sh`|tr -d " \t"|grep .|grep -v ^#|wc -l ``` 1. `find . -name \*.sh`: find files matching the pattern, list with path 2. `cat ''`: list contents of these files 3. `tr -d " \t"`: trim tabs and spaces 4. `grep .`: remove empty lines 5. `grep -v ^#`: remove comments 6. `wc -l`: count lines of output [Answer] ## Haskell, ~~211~~ 210 bytes ``` import System.Directory f x=listDirectory x>>=fmap sum.mapM(\d->doesFileExist d>>=(#d)).map((x++"/")++) p#d|p=do c<-readFile d;pure$sum[1|take 3(reverse d)=="hs.",(q:_):_<-map words$lines c,q/='#']|1<2=f d f"." ``` Oh dear, without shell glob and regex you have to do all the work by yourself. Maybe there's somewhere a module for it. Also, IO code in Haskell requires some overhead to get the types right. ``` f x = -- main function, expects a directory 'x' listDirectory x >>= -- read content of directory (without "." and "..") map((x++"/")++) -- for each entry: prepend current directory 'x' and a slash mapM(\d->doesFileExist d>>=(#d)) -- for each entry: call function '#' with -- first parameter: a boolean, True if it's a regular file, False if it's a directory -- second parameter: the filename itself -- '#' returns a list of valid lines for each file fmap sum -- sum this list p#d |p -- if 'p' is True (i.e. 'd' is regular file) do c<-readFile d; -- read the content 'c' of file 'd' and pure$sum[1| ] -- return the number of lines take 3(reverse d)=="hs." -- (only if the file end with .sh) (q:_):_<-map words$lines c,q/='#' -- where the first word doesn't start with a hash sign -- (function 'words' strips leading whitespace) |1<2 -- else ('d' is a directory) =f d -- examine d f"." -- start with current directory ``` [Answer] # [R](https://www.r-project.org/), ~~70~~ 64 bytes ``` sum(!grepl("^(#|$)",unlist(lapply(dir(,".sh$",r=T),readLines)))) ``` Explanation: The `dir` function has the `recursive` flag set. `readLines` returns the lines of a file in a vector, which are then flattened with `unlist`. [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 55 ``` find . -name \*.sh -exec cat {} +|grep -Evc '^\s*(#|$)' ``` [Try it online!](https://tio.run/##BcGBCYAgFAXAVR4UWIY6RVtIYF/LwCy0Iqhmt7vRZF/IQp05qbCRCWVaooWEiGZ10FxmD@FuRyBz4PnQvXNyO0R/EdigM2@qt25ZKT8 "Bash – Try It Online") [Answer] ## Batch + Internal tools, ~~80~~ 76 Bytes ``` @for /F %%F IN ('findstr/SV "^\s*# ^\s*$" *.sh^|find/C":"')DO @set/P=%%F<NUL ``` Uses the builtin `findstr` to fetch the lines, then counts these line using `find /C`. This however produces output with a newline, so we need to convert that into an output without. This is done by using `for /F` to fetch the output and then use `<NUL set /P` to output without the trailing newline. [Answer] # [Ruby](https://www.ruby-lang.org/), 61 bytes ``` p Dir.glob("**/*.sh").sum{|x|open(x).grep(/^\s*[^#\s]/).size} ``` [Try it online!](https://tio.run/##HcuxDoIwGATg/X@KQodCY9qFsW4@gomDSAKmQCMK6Q@xSnn2WrkbbvnOLs0nuKNSBZx7g2CQ1DBrnIHEACWxQOilr@@PBPahCRQA46RfGftLgT07sDfLV9/6Vim3hYmcjBXdMDZZyrnkkaS5wOW5euf3p8tFZ/WUyapEfq1oiTcZhfnqLYQf "Ruby – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~149~~ ~~146~~ ~~144~~ ~~140~~ ~~149~~ ~~146~~ 116 bytes ``` import os print sum(l.strip()[:1]not in'#'for a,b,c in os.walk(".")for n in c for l in open(a+"/"+n)if'.sh'==n[-3:]) ``` [Try it online!](https://tio.run/##pZDBboMwDIbvPIVHD05UGgS9IfVJSg@BhpEV7CjJhLaXZ0m1w9TrfLH9O/Znx33Fmand7erYR@BQFBzU@rhbL1DVE3ONsig2G2dgZyiLg/YqzFgBbihBB5iaroBkU6M2b6MR2BOqD7YkBGqs8ADEcbb0DpEhGAOz8SbpqWd8S76PfYTk7yjlKy2vMOjvF2L7S2z/TazQZOqfH3DeUoTwuYpFheitE/LaNbc0ECzhASf2oKuhGlOa3qtNLw9RqlLmAmVxhBwuz3o@Qx/LujyStBPmOy4Xup7O3U3u@w8 "Python 2 – Try It Online") ~~Reports 0 on TIO but works locally. Probably not any `.sh` files in whatever is the current directory.~~ I think it now works correctly on TIO and fixed a bug for +6, both thanks to @JonathanAllen -30 with thanks to @ovs Alternative for **139 bytes** but only works on Windows. ``` import os os.system('dir/s/b *.sh>f') print sum(sum((0,1)[x.strip()>''and'#'!=x.strip()[0]]for x in open(l[2:].strip()))for l in open("f")) ``` Creates a temporary file `f` to store the results for the `dir` command. [Answer] # [Röda](https://github.com/fergusq/roda) + find, 98 bytes ``` {bufferedExec"find",".","-name","*.sh"|{|x|try readLines x}_|{|x|x~=`\s|#.*`,"";[1]if[#x>0]}_|sum} ``` [Try it online!](https://tio.run/##K8pPSfyfm5iZp1D9vzqpNC0ttSg1xbUiNVkpLTMvRUlHSQ@IdfMSc1OBtJZecYZSTXVNRU1JUaVCUWpiik9mXmqxQkVtPFi0os42Iaa4RllPK0FHSck62jA2My1aucLOIBaooLg0t/Z/7X8A "Röda – Try It Online") # Pure Röda, 129 bytes ``` {["."]|[_]if isFile(_1)else unpull(x)for x in[ls(_1)]|{|x|try readLines x if[x=~`.*\.sh`]}_|{|l|l~=`\s|#.*`,"";[1]if[#l>0]}_|sum} ``` [Try it online!](https://tio.run/##Fc3RCoMgFIDhVxG7qRiyrke73NXewESDjAknG54Eh6de3dX1/8Ef1mksy@g8yyVLLrgiqZWbmcOXA1vrrrGAlkX/jQB1auY1sMScl4BXVJQp0RZ@LNhxejtv8cqzTP1hRDsI/Bi161MBwdGbAakSrblx/pDd@ZEVPO8XwLjsZS9/ "Röda – Try It Online") Explanation: ``` { ["."]| /* Push "." to the stream */ /* For each _1 in the stream: */ [_]if isFile(_1) /* If _1 is a file, push it to the output stream */ else /* Else (if _1 is a directory): */ unpull(x)for x in[ls(_1)]| /* Push each file/dir in _1 to the *input stream* */ {|x| /* For each x in the stream: */ try readLines x /* Push lines of x to the stream ignoring errors */ if[x=~`.*\.sh`] /* if x ends in .sh */ }_| {|l| /* For each l in the stream: */ l~=`\s|#.*`,""; /* Remove whitespace and comments from l */ [1]if[#l>0] /* Push 1 to the stream if l is not empty */ }_| sum /* Sum all numbers in the stream */ } ``` [Answer] # PHP, ~~105 140 174 186 184~~ 172 bytes ``` function f($d){foreach(glob("$d/*")as$n)$n[strlen($d)+1]^_^A&&$s+=!is_dir($n)?fnmatch("*.sh",$n)?preg_match_all("/^\s*[^#]/m",join(file($n))):0:f($n);return$s;}echo f("."); ``` skips hidden directories and files (name starts with a dot). Run with `-nr`. ## breakdown ``` function f($d) { # loop through directory entries foreach(glob("$d/*")as$n) # if name does not start with a dot $n[strlen($d)+1]^_^A # then increase sum: &&$s+= # not a directory? !is_dir($n) # filename matches pattern? ?fnmatch("*.sh",$n) # count lines that are neither empty nor begin with a "#" ?preg_match_all("/^\s*[^#]/m",join(file($n))) # else 0 :0 # is a directory: recurse :f($n) ; return$s; } echo f("."); ``` --- I could save two more bytes with `fnmatch()*preg_match_all()` instead of `fnmatch()?preg_match_all():0`; and then another one with `is_dir()?B:A` instead of `!is_dir()?A:B`; but that could make it insanely slow. [Answer] # [C (clang)](http://clang.llvm.org/), ~~248~~ 209 bytes ``` #import <regex.h> *l,i,j;*k;regex_t r;f(n,s,t){if(fnmatch("*.sh",n,0))return 0;k=fopen(n,"r");for(regcomp(&r,"^\\s*(#|$)",1);i=getline(&l,&i,k)>0;)regexec(&r,l,0,0,0)&&j++;}main(){ftw(".",f,1);printf("%d",j);} ``` [Try it online!](https://tio.run/##HY3BboMwEETv/Qq0Sa1dskX0vE2@JEqFXBsMZkHGVSOl@XYSormN5r2xHzY22q7rLozzlHLxlVzrrlV3eisjB@6lHORVfeciiUflhTPdgkevY5Nth1BWSwesXBMll3@TFrUMRz/NTp9zSEDip4RPi53GGU1iuJzPS4m7/z0Bf5KEY@tyDOrQRDaBBzrVQq9bZzcgcr2FjOkPB7mPTVCkm89/CBWw3xxzCpo9wvsPcE9yX9cH "C (clang) – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 57 bytes ``` for f (**/*.sh(D))a+=(${${(f)"$(<$f)"//[ ]}%%#*}) <<<$#a ``` [Try it online!](https://tio.run/##RU1BasMwEDxHr5hGSiy7xIKcVZ@aXvuAtoe1I2ORWDKWoCEhb3eXtrQLwywzuzPXNCzj6ehn7CbUZFojXDdEqCIPbnYgRv6M7@Hsg0sFmp@jmuo0iAYtE6xFcXh9KYR8MK0Phh2JLo6jC1ngdyTSRJ1LYiWRqWWdl9Ff3FGEmNmmvxcJn76F/xSOX/o4o4euKlNxq34uS3p80uqmbrov10pbxWTMG1Yf981GVvdSWGuVpGWafcjYnaEIzXa/fAE "Zsh – Try It Online") Almost beat bash+coreutils with native zsh constructs. ``` for f (**/*.sh(D)) # the (D) flag enables globdots a+=(${${(f)"$(<$f)"//[ ]}%%#*}) # ${(f)"$(<$f)" } # read in file, split on newlines # ${ //[ ]} # remove all spaces and tabs # ${ %%#*} # remove longest trailing #comment # a+=( ) # if append non-empty lines to array <<<$#a # print array length ``` --- ## [Zsh](https://www.zsh.org/) `-oextendedglob -oglobstarshort -oglobdots`, 51 bytes ``` for f (**.sh)a+=(${${(f)"$(<$f)"}/[ ]#\#*}) <<<$#a ``` [Try it online!](https://tio.run/##RU7LTsQwDDxvvmIgEX2gbSTOoTe48gEsh7R1txFtUiWWWLHaby9hQWDJHnvGHvkzTdvyPriI/YrG6k4L6qcAVfBEkWBz8kc4@Nl5SgXan6XGNmkSLboMMAbF08tzIeSN7pzXWZHow7KQZ4HfkEir7SmJnQTbLvO5WdyJBuEDZ9n@nUi4dCX@XbK9EIk4rAw6MfmBhuMcOnyXxDamKUS@TkPgtI0hYkRZ1/m/yt4/luqszuVY3arSqAwX/YrdmzzI@lIJY4ySdluj84z9DGXR3j1sXw "Zsh – Try It Online") globstarshort allows `**.sh`, globdots removes the `(D)` flag, and extendedglob makes `[ \t]#` work like the regex `[ \t]*`. Sidenote: I think some answers here don't match hidden files. If they can be safely ignored, then `-oglobdots` or `(D)` is not needed. [Answer] # [Nim](http://nim-lang.org/), 114 bytes ``` import os,re var c=0 for f in walkDirRec".": if f=~re".*\.sh$": for l in f.lines:c+=int l=~re"\s*[^#\s]" echo c ``` ]
[Question] [ ### Introduction You must create a function to convert Greek numerals into Arabic numerals. The input will be a Greek numeral less than `1000` and more than `0`. This is the reverse of my [previous challenge](https://codegolf.stackexchange.com/questions/78222/greek-conversion-golf). ### Algorithm 1. Split input into letters (e.g. `ΡΚΓ` -> `Ρ`, `Κ`, `Γ`) 2. Take each letter, and change to character found in table below, for letter symbol, (e.g. `ΡΚΓ` -> `Ρ`, `Κ`, `Γ` -> `100`, `20`, `3`). 3. Add (e.g. `ΡΚΓ` -> `Ρ`, `Κ`, `Γ` -> `100`, `20`, `3` -> `123`) ### Specifications * No built-in number-system conversion * Input will be capitalized as in example. * Output must be in base 10. * `ΡΡΡΡ` will never happen. It will be `Υ`. ### Test Cases ``` ΡΚΓ -> 123 Η -> 8 ΨΟΖ -> 777 Ρ -> 100 ΧϜ -> 606 ΡϘ -> 190 ΜΒ -> 42 Ν -> 50 ``` ### Table ``` Α = 1 = Alpha = 913 UTF-8 Β = 2 = Beta = 914 UTF-8 Γ = 3 = Gamma = 915 UTF-8 Δ = 4 = Delta = 916 UTF-8 Ε = 5 = Epsilon = 917 UTF-8 Ϝ = 6 = DiGamma = 988 UTF-8 Ζ = 7 = Zeta = 918 UTF-8 Η = 8 = Eta = 919 UTF-8 Θ = 9 = Theta = 920 UTF-8 Ι = 10 = Iota = 921 UTF-8 Κ = 20 = Kappa = 922 UTF-8 Λ = 30 = Lambda = 923 UTF-8 Μ = 40 = Mu = 924 UTF-8 Ν = 50 = Nu = 925 UTF-8 Ξ = 60 = Xi = 926 UTF-8 Ο = 70 = Omicron = 927 UTF-8 Π = 80 = Pi = 928 UTF-8 Ϙ = 90 = Koppa = 984 UTF-8 Ρ = 100 = Rho = 929 UTF-8 Σ = 200 = Sigma = 931 UTF-8 Τ = 300 = Tau = 932 UTF-8 Υ = 400 = Upsilon = 933 UTF-8 Φ = 500 = Phi = 934 UTF-8 Χ = 600 = Chi = 935 UTF-8 Ψ = 700 = Psi = 936 UTF-8 Ω = 800 = Omega = 937 UTF-8 Ϡ = 900 = SamPi = 992 UTF-8 ``` [Answer] # Python 3, 112 Saved 4 bytes thanks to vaultah. Booyah, beating JS! ``` lambda x,z="ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ".find:sum((z(c)%9+1)*10**(z(c)//9)for c in x) ``` With test cases: ``` assert(f("ΡΚΓ")==123) assert(f("Η")==8) assert(f("ΨΟΖ")==777) assert(f("Ρ")==100) assert(f("ΧϜ")==606) ``` Loops through the string and uses its index in the list of potentials chars to calculate how much it's worth. [Answer] # JavaScript (ES7), 115 bytes ``` s=>[...s].map(c=>n+=((i="ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ".search(c))%9+1)*10**(i/9|0),n=0)|n ``` [Answer] ## Haskell, ~~116~~ 113 bytes ``` f x=sum[v|d<-x,(l,v)<-zip"ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ"$(*)<$>[1,10,100]<*>[1..9],d==l] ``` Usage example: `map f ["ΡΚΓ","Η","ΨΟΖ","Ρ","ΧϜ","ΡϘ","ΜΒ","Ν"]` -> `[123,8,777,100,606,190,42,50]`. Lookup the value of the greek letter from a list of pairs `(letter, value)` and sum. The list of values is build by `(*)<$>[1,10,100]<*>[1..9]`, where `(*)<$>[1,10,100]` builds a list of functions `[(*1),(*10),(*100)]` (multiply by 1, 10 and 100) which are applied separately to the elements of `[1..9]` and concatenated into a single list. Edit: 3 bytes with thanks to @xnor. [Answer] # Julia, ~~82~~ 70 bytes ``` x->10.^((t=findin([1:5;76;6:16;72;17;19:25;80]+912,x)-1)÷9)⋅(t%9+1) ``` [Try it online!](http://julia.tryitonline.net/#code=ZiA9IHgtPjEwLl4oKHQ9ZmluZGluKFsxOjU7NzY7NjoxNjs3MjsxNzsxOToyNTs4MF0rOTEyLHgpLTEpw7c5KeKLhSh0JTkrMSkKCmZvciB4IGluICgizqHOms6TIiwgIs6XIiwgIs6ozp_OliIsICLOoSIsICLOp8-cIiwgIs6hz5giLCAizpzOkiIsICLOnSIpCiAgICBwcmludGxuKGYoeCkpCmVuZA&input=) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~47~~ 45 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁵*ב} “#'nn(2jj33556;r”Or2/F+878Ọ ¢iЀ’d9ñ/€S ``` [Try it online!](http://jelly.tryitonline.net/#code=4oG1KsOX4oCYfQrigJwjJ25uKDJqajMzNTU2O3LigJ1PcjIvRis4Nzjhu4wKwqJpw5DigqzigJlkOcOxL-KCrFM&input=&args=zqHOms6T) or [verify all test cases](http://jelly.tryitonline.net/#code=4oG1KsOX4oCYfQrigJwjJ25uKDJqajMzNTU2O3LigJ1PcjIvRis4Nzjhu4wKwqJpw5DigqzigJlkOcOxL-KCrFPCteKCrA&input=&args=J86hzprOkycsICfOlycsICfOqM6fzpYnLCAnzqEnLCAnzqfPnCcsICfOoc-YJywgJ86czpInLCAnzp0n). [Answer] ## JavaScript (ES6), 116 bytes ``` s=>[...s].map(c=>n+=+((i="ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ".search(c))%9+1+"e"+(i/9|0)),n=0)|n ``` Only 1 byte longer than ES7! [Answer] ## Python 3, 188 Bytes ``` def f(x,l=list,z=0): r=l(range(1,10));R=[a*10for a in r] for a,b in l(zip(l("ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ"),r+R+[a*10for a in R])): z+=(0,b)[a in x] return z ``` [Try it out!](https://repl.it/CIdI/1) (Test cases included) [Answer] # [Retina](https://github.com/mbuettner/retina), 72 bytes ``` T`_Ι-ΠϘ0ΡΣ-ΩϠ`dl [a-j] $0aa \d $&0 T`_Α-ΕϜΖ-Θl`dd \d+ $* 1 ``` [Try it online.](http://retina.tryitonline.net/#code=JShHYApUYF_OmS3OoM-YMM6hzqMtzqnPoGBkbApbYS1qXQokMGFhIApcZAokJjAgClRgX86RLc6Vz5zOli3OmGxgZGQKXGQrCiQqCjE&input=zqHOms6TCs6XCs6ozp_OlgrOoQrOp8-cCs6hz5gKzpzOkgrOnQ) ### Explanation Basically - replace every Greek symbol with the number that it represents, then return the sum of all the resulting numbers: Transliterate `10`s digits to Arabic and `100`s digits to the Latin alphabet (`0`-`9` => `a`-`j`): ``` T`_Ι-ΠϘ0ΡΣ-ΩϠ`dl ``` Append "aa " to any `100`s digits: ``` [a-j] $0aa ``` Append "0 " to any `10`s digits: ``` \d $&0 ``` Transliterate `1`'s digits and Latin alphabet to Arabic: ``` T`_Α-ΕϜΖ-Θl`dd ``` Convert all space-separated decimal numbers to unary: ``` \d+ $* ``` Count the total number of unary `1`s: ``` 1 ``` ]
[Question] [ Shrink each word in a string of group of strings to single letters delineated by spaces or punctuation. ### Example ``` I'm a little teapot, short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout! Tip me over and pour me out. ``` becomes ``` I' a l t, s a s. H i m h, h i m s. W I g a s u - h m s! T m o a p m o. ``` Edit - if there are multiple spaces, preserve only one space. All punctuation should be preserved, I missed the apostrophe. Yes this is code golf :-). [Answer] # CJam, 13 bytes ``` r{(\'A,f&Sr}h ``` Works if I can consider only the common punctuation characters, and the output can have trailing spaces. (Thanks to Dennis.) This question needs much more clarification... # CJam, 17 16 bytes ``` r{(\eu_elf&Sr}h& ``` [Try it online](http://cjam.aditsu.net/#code=r%7B%28%5Ceu_elf%26Sr%7Dh%26&input=I%27m%20a%20little%20teapot%2C%20%20short%20and%20stout.%20Here%20is%20my%20handle%2C%20here%20is%20my%20spout.%20When%20I%20get%20all%20steamed%20up%20-%20hear%20me%20shout!%20%20%20Tip%20me%20over%20and%20pour%20me%20out.%20). ### Explanation ``` r e# Read one word from input. { e# While it is not EOF: (\ e# Extract the first character. eu e# Convert the rest to uppercase. _el e# And lowercase. f& e# Delete characters in the first string if not in the second string. S e# Append a space. r e# Read the next word. }h & e# Discard the last space by intersecting with empty string. ``` [Answer] # Pyth, 14 bytes ``` jdm+hd-rtd0Gcz ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=jdm%2Bhd-rtd0Gcz&input=I%27m+a+little+teapot%2C++short+and+stout.+Here+is+my+handle%2C+here+is+my+spout.+When+I+get+all+steamed+up+-+hear+me+shout!+++Tip+me+over+and+pour+me+out.+&debug=0) ### Explanation: ``` implicit: z = input string cz split z by spaces m map each word d to: hd first letter of d + + rtd0 (lowercase of d[1:] - G but remove all chars of "abc...xyz") jd join resulting list by spaces and print ``` [Answer] # Python 3.4, ~~94~~ ~~92~~ ~~82~~ 77 bytes ``` print(*[w[0]+''.join(c[c.isalpha():]for c in w[1:])for w in input().split()]) ``` I'm new to code golfing but I thought I'd give it a try! This one's not a winner, but it was fun. This just splits the string, taking the first character of each word along with any punctuation in the rest of the word. \*edited with changes by FryAmTheEggman, DLosc [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` Ḣ;ḟØB$ Ḳ¬ÐfÇ€K ``` [Try it online!](https://tio.run/##RY2hDsIwGIQ9T3EkJJjBC@BQLFgSdJP90JF2bdp/S2YxWCSOBD2FmmZPMl6kdDXIu3z33YWUakMY@9dm7J/DY7uYjf370w3303D7Xrt9CCFfagioklkRmIQ1nAFeGscQVQHPpuY1duQIpYduIWOtKIP8V94m6CipQo4zxalScUpCU4HaYhVp4aBpMtc8B3Ao7ZRNQy4dRUUCkukH "Jelly – Try It Online") Solution done with *Mr. Xcoder* and *caird coinheringaahing* in [Jelly Hypertraining chat room](https://chat.stackexchange.com/transcript/message/40638992#40638992). Alternative 14 bytes: [Try it online!](https://tio.run/##RY0xCsIwGIWv8gTBpXoBNyeLq@Ac6K@pJE1I/gpdPYGjm@DsJBTq2p6kXiSmWRzf43vfO5NSTQhj9@4/w@3Yt2P3XI/dY7hv5n37vb52IYR8oSGgSmZFYBLWcAZ4aRxDVAU8m5pX2JIjlB66gYy1ogzyX3mboIOkCjlOFKdKxSkJTQVqi2WkhYOmyVzzDMC@tFM2F3LpKCoSkEw/ "Jelly – Try It Online") [Answer] # sed (39 chars) Just a couple of regular expressions: ``` sed 's+\<\(.\)[A-Za-z]*+\1+g;s+ *+ +g' ``` [Answer] # Lua - 126 characters Lua isn't much of a code golfing language, but I gave it a shot: ``` a=''for b in string.gmatch( c, '%S+%s?' )do d=(b:match('%w')or''):sub(1,1)e=b:match('[^%s%w]')or''a=a..d..e..' 'end print( a ) ``` This assumes that `c` is the string. Here it is cleaned up for readability: ``` local string = [[I'm a little teapot, short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout! Tip me over and pour me out.]] local final = '' for word in string.gmatch( string, '%S+%s?' ) do local first = ( word:match( '%w' ) or '' ):sub( 1, 1 ) local second = word:match( '[^%s%w]' ) or '' final = final .. first .. second .. ' ' end print( final ) ``` You can test it [here](http://www.lua.org/cgi-bin/demo) (copy and paste it. For the first on you also have to do `c = "I'm a little ...`.) For some reason the online demo of Lua won't let you input variables using `io.read`... [Answer] ## PowerShell, 56 bytes ``` %{($_-split' '|%{$_[0]+($_-replace'[a-z]','')})-join' '} ``` [Answer] # Javascript (*ES6*) 72 68 bytes ``` f=x=>x.split(/\s+/).map(x=>x.replace(/^(.)|[a-z]/gi,'$1')).join(' ') ``` ``` <input id="input" value="I'm a little teapot, short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout! Tip me over and pour me out. " /> <button onclick="output.innerHTML=f(input.value)">Run</button> <br /><pre id="output"></pre> ``` **Commented:** ``` f=x=> x.split(/\s+/). // split input string by 1 or more spaces map(x=> // map function to resulting array x.replace(/^(.)|[a-z]/gi, '$1') // capture group to get the first character // replace all other letters with empty string ). join(' ') // join array with single spaces ``` [Answer] ## C99 - ~~170~~ 169 bytes ``` main(_,a)char**a;{for(char*b=a[1],*c=b,*e,*d;*c++=*b;){for(e=b;*++b&&*b-32;);for(*b=0,d=strpbrk(e,"!',-."),d&&d-e?*c++=*d:0;b[1]==32;++b);++b;*c++=32;*c=0;}puts(a[1]);} ``` Ungolfed: ``` main(int argc, char**a) { char*b=a[1],*c=b,*e,*d; while(*c++=*b){ for(e=b;*++b&&*b-32;); //scan for first space or end of word *b=0; //mark end of word for(;b[1]==32;++b); //skip following spaces d=strpbrk(e,"!',-."); //find punctuation if(d&&d-e) //append punctuation if any, and it's not the word itself *c++=*d; *c++=32; //append space b++; } *c=0; //mark end of line puts(a[1]); } ``` Usage: ``` gcc -std=c99 test.c -o test ./test "I'm a little teapot, short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout! Tip me over and pour me out." ``` Output: ``` I' a l t, s a s. H i m h, h i m s. W I g a s u - h m s! T m o a p m o. ``` [Answer] # Java 8, 87 bytes ``` s->{for(String x:s.split(" +"))System.out.print(x.replaceAll("^(.)|[a-z]+","$1")+" ");} ``` **Explanation:** [Try it here.](https://tio.run/##RZDBasMwEETv/YqpKNQisaHXhhZ6aw7NJYUeQgqqvYmVypKQ5JA09be7ayclIB12mJ037E7tVe482V313ZdGxYg3pe3pBtA2UdiokrAYRmDvdIUyW6ag7RZRzljt@POLSSVdYgGLJ/Qxfz5tXPh3Hh5jEb3RKROYCCmXx5ioKVybCs@GlB2KQN4w6cWYTHxmhfxdqfxnPRFTcfcg5ERAyFnXz84w334Zhl2YY6uGO19wqzWUPBe2RZmJ@X0DBaYnQ0ikvEtTLly7kKBsxTFDEbxSIOiI5oiaZUNT1Fcp@tH0UZPFHFviVWN4lVRDFVqPnN0qoKEhuU23TH/XfpjdnsII4ojRMCaJy/W6/g8) ``` s->{ // Method with String parameter and no return-type for(String x:s.split(" +")) // Split the input on one or multiple spaces // And loop over the substrings System.out.print( // Print: x.replaceAll("^(.)|[a-z]+","$1")// Regex to get the first letter + all non-letters +" "); // + a space delimiter // End of loop (implicit / single-line body) } // End of method ``` **Regex explanation:** ``` x.replaceAll("^(.)|[a-z]+","$1") x.replaceAll(" "," ") # Replace the match of String1 with String2, in String `x` " " # Regex to match: ^(.) # The first character of String `x` |[a-z]+ # Or any one or multiple lowercase letters " " # Replace with: $1 # The match of the capture group (the first character) ``` So it basically removes all lowercase letters of a String, except the very first one. [Answer] # [Perl 5](https://www.perl.org/), 34 bytes **33 bytes code + 1 for `-p`.** ``` s!\S\K\S+| \K +!$&=~s/\w| //gr!ge ``` [Try it online!](https://tio.run/##RY2xCsIwGIRf5QqiQ1s7ObpbOlZwyRLoTxNImpD8VYTioxvTLI53fPedp2AuKcVKjGIQY71BDKirw/H6iZ14bei6OVQzpdSfLCSMZjYEJukdN0BULjDkMiGyW/mMGwWCjrBvqFwbaqD@VfQFeiha0GOmPDUmT0lamrB6tJmWAZZ288oVgLv2e3ZPCuUoKwpQTF/nWbslptb/AA "Perl 5 – Try It Online") [Answer] # R, ~~46~~ 45 bytes ``` cat(gsub("^\\w\\W*\\K\\w*","",scan(,""),T,T)) ``` This reads a line from STDIN and prints to STDOUT. It uses a regular expression to remove all characters after the first letter followed by any amount of punctuation. Ungolfed + explanation: ``` # Read a string from STDIN and convert it to a character vector, # splitting at spaces input <- scan(what = "") # Replace stuff with nothing using a regex. # ^ start position anchor # \w single "word" character # \W* any amount of non-word (i.e. punctuation) characters # \K move the match position forward # \w* any number of word characters replaced <- gsub("^\\w\\W*\\K\\w*", "", input, ignore.case = TRUE, perl = TRUE) # Print the vector elements to STDOUT, separated by a space cat(replaced, sep = " ") ``` Example: ``` > cat(gsub("^\\w\\W*\\K\\w*","",scan(,""),T,T)) 1: I'm a little teapot, short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout! Tip me over and pour me out. I' a l t, s a s. H i m h, h i m s. W I g a s u - h m s! T m o a p m o. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` #õKεćsDáмJ}ðý ``` [Try it online!](https://tio.run/##RY0hDgIxFESvMgSBWQgIboBgwW6CLtkf2qTdNu1fEgSac3ADzDpQRRNuVLo1yJm8ebNci@OKUprGYf8Z3rewiffvc3eNj/hKqZ4ZCGjFrAlMwlmugCCtZ4iuRWDb8wJb8gQVYC6QudZUQf6r4Ap0kNShxonyVOs8JWGoRe8wz7TwMDSae54AaJQbsz2TL0dZUYBi@gE "05AB1E – Try It Online") **Explanation:** ``` #õKεćsDáмJ}ðý Full program # Split on spaces õK Remove empty strings from the list ε For each... ć push a[1:], a[0] s Swap D Duplicate á Push only letters of a м pop a,b => push a.remove(all elements of b) J Join } End for each ðý Join with spaces ``` [Answer] **VBA (Excel), ~~141~~ 133 Bytes** Using VBA Immediate Window, [A1] as Inputted Strings. ``` z=" "&[A1]:for a=2 to len(z):c=mid(z,a,1):[A2]=[A2]&IIF(mid(z,a-1,1)=" ",c,IIF(asc(lcase(c))>96 and asc(lcase(c))<123,"",c)):next:?[TRIM(A2)] ``` ``` z=" "&[a1]:for a=2 to len(z):c=mid(z,a,1):e=asc(lcase(c)):[a2]=[a2]&iif(mid(z,a-1,1)=" ",c,IIF((e>96)*(e<123),"",c)):next:?[TRIM(A2)] ``` [Answer] # [Perl 6](https://perl6.org), 15 bytes ``` s:g/(\w)\w+/$0/ ``` [Try it online!](https://tio.run/##zY7NCsIwEIRfZYSCf7X15MHi3V48CV4KEujSFJImJBtLnz6mufgKHnf45pu15NQlFm/cUBzaR@VVcLaJ/jrUu27ed/OxLs51bFB5scR2qyGgRmZFYBLWcAl4aRxDTD08m8AV7uQIo4deIFOsqIT8Rd5m6CVpQouBUlWpVCWhqUewOCVaOGhazYE3AJ6jXW/zIZeHkiID2fSnb30B "Perl 6 – Try It Online") ]
[Question] [ The goal is to write a function or program which takes a set of integer arrays and returns a set of all possible arrays which meet the following criteria: * A valid array must contain at least one number from each of the input arrays. * A valid array cannot contain more than one number from a single input array. * A valid array cannot contain duplicate values. **Additional rules:** * Order of the output does not matter. * Input/Output can be in any format you wish. * If no valid arrays exist, the result should be an empty array or blank string. **Examples:** ``` input: [[1,2], [2,1,0], [0,3,1]] output: [[2,3], [1]] ``` ``` input: [[1,3,4,7], [1,2,5,6], [3,4,8], [8,9]] output: [[6,7,8], [5,7,8], [2,7,8], [4,6,9], [4,5,9], [2,4,9], [3,6,9], [3,5,9], [2,3,9], [1,8]] ``` ``` input: [[1,2,3], [2,3,4], [1,4]] output: [] ``` [Answer] ### GolfScript, 36 characters ``` :I[[]]\{{{|$}+1$/}%|}/{I{1$&,(},!*}, ``` Input/output is standard GolfScript arrays, see in [this example](http://golfscript.apphb.com/?c=W1sxIDMgNCA3XSBbMSAyIDUgNl0gWzMgNCA4XSBbOCA5XV0KCjpJW1tdXVx7e3t8JH0rMSQvfSV8fS97SXsxJCYsKH0sISp9LAoKcA%3D%3D&run=true). ``` :I # save input to variable I # part 1: generate all possible sets with zero or one numbers from each array # (zero or one is one char shorter than exactly one which would work also) [[]]\ # push the set with an empty set { # iterate over all input sets { # iterate over the numbers in the current set {|$}+1$/ # add this number to any set in the result }% | # join with the result set }/ # part 2: filter for valid sets (i.e. exactly one number from each array) { # start of filter block I{ # filter the input array of sets 1$& # calculate overlap of the current set with the input set ,( # remove if length is equal to one }, ! # is the list empty? (i.e. all input matched the filter criterion) * # get rid of the second item on the stack }, # end of filter block ``` [Answer] # CJam, 35 bytes ``` q~:Q{m*{(+$_&}%}*_&{Q{1$&,(},,*!},p ``` Input is a list of list like: ``` [[1 3 4 7] [1 2 5 6] [3 4 8] [8 9]] ``` and output is the list of unique lists that match all conditions, like for above input, ``` [[1 8] [2 3 9] [3 5 9] [3 6 9] [2 4 9] [4 5 9] [4 6 9] [2 7 8] [5 7 8] [6 7 8]] ``` How it works: ``` q~:Q "Evaluate the input and store it in Q"; { }* "Run this block for each adjacent pair in the array"; m* "Calculate Cartesian product of the pair"; { }% "Map each cartesian product with the code block"; (+$ "Flatten the array and sort it"; _& "Make the array unique"; _& "Only take unique cartesian products"; { }, "Filter the cartesian products based on the code block"; Q{ }, "Put Q on stack and run it through this filter"; 1$& "Take ∩ of the input array with the cartesian product"; ,( "Check that length of the ∩ should be greater than 1"; ,*! "Now we have all the lists from the input list of list" "which matched more than 1 element from this cartesian" "product. So if this list is non empty, discard this" "cartesian product"; p "Print the filtered out valid unique arrays"; ``` [Try it online here](http://cjam.aditsu.net/) [Answer] ## Mathematica, ~~135~~ ~~84~~ 72 bytes ``` f=Cases[Union/@Tuples@#,l_/;!MemberQ[#,k_/;Length@Intersection[k,l]>1]]& ``` Less golf: ``` f = Cases[ Union /@ Tuples@#, l_ /; ! MemberQ[#, k_ /; Length@Intersection[k, l] > 1] ] & ``` This defines a function `f` that expects the input as a plain Mathematica list of lists, e.g. ``` f[{{1, 2}, {2, 1, 0}, {0, 3, 1}}] ``` Basically, I'm creating a list of all lists that fulfil conditions 1 and 3, and then I'm filtering out those that violate conditions 2. ~~There might be a shortcut for one of the two, which I'll have to think about in more depth tomorrow.~~ Found that shortcut! [Answer] # ruby, ~~143~~ 114 Now shorter thanks to @Ventero. ``` h={};i=eval$*[0];v=i.flatten.uniq loop{h[a=v.sample(1+rand(v.size)).sort]||=h[a]||i.any?{|o|(o&a).size!=1}?1:p(a)} ``` Usage: ``` ruby uniq_arr.rb '[[1,3,4,7],[1,2,5,6],[3,4,8],[8,9]]' [2, 3, 9] [6, 7, 8] [3, 5, 9] [1, 8] [2, 7, 8] [4, 6, 9] [5, 7, 8] [2, 4, 9] [3, 6, 9] [4, 5, 9] ``` Making it stop (eventually) is easy, but requires some code. It stops one h contains 2\*\*l-1 elements, l being the number of unique elements in i, i.flatten.uniq.size <http://ideone.com/zTlXZw> [Answer] ### Ruby — ~~80~~ 73 characters @Howard knocks off 7 characters: ``` f=->a{a[0].product(*a).map(&:uniq).uniq.select{|l|a.all?{|x|(l&x).one?}}} ``` Some sample input: ``` a = [[1, 2], [2, 1, 0], [0, 3, 1]] b = [[1,3,4,7], [1,2,5,6], [3,4,8], [8,9]] c = [[1,2,3], [2,3,4], [1,4]] d = [[]] e = [[1,2]] ``` Output: ``` f[a] # => [[1], [2, 3]] f[b] # => [[1, 8], [3, 2, 9], [3, 5, 9], [3, 6, 9], [4, 2, 9], [4, 5, 9], [4, 6, 9], [7, 2, 8], [7, 5, 8], [7, 6, 8]] f[c] # => [] f[d] # => [] f[e] # => [[1], [2]] ``` ### Haskell — 90 characters I'm just learning Haskell, so I imagine this can be vastly improved. Same basic strategy as my Ruby solution. ``` import Data.List f a=[l|l<-nub.map nub$sequence a,all(\x->length x==1)(map(intersect l)a)] ``` [Answer] # Python, 157 characters This is a straightforward brute-force implementation. ``` from itertools import* a=input() v=set(chain(*a)) print[x for x in chain(*[combinations(v,r)for r in range(len(v))])if all(1==len(set(x)&set(y))for y in a)] ``` ]
[Question] [ The challenge is to, given a list of points, sort in a way that, when they are connected in this order, they never intersect. Input format (read from stdin): ``` X Y 1 2 3 4 5 6 ... ``` Output should be the same as input, but sorted. Rules: * You can start from any point. * The last point must be same as first one, making a close circuit. * It should be done considering the Cartesian grid. * You may assume that the input points do not all lie on a single line. * The endpoints of each line do not count as intersecting. For further help: [![diagram](https://i.stack.imgur.com/3mJ11.png)](http://prntscr.com/3ayjys) [Answer] ## Mathematica - ~~20~~ 30 chars Just the sorting part ``` SortBy[%, ArcTan @@ # &] ``` Whole testing code, that consists of generating 100 random points and plotting the line ``` RandomReal[{-10, 10}, {100, 2}]; SortBy[%, ArcTan @@ # &]; ListPlot@% /. Point[p_] :> {EdgeForm[Dashed], FaceForm[White], Polygon[p], PointSize -> Large, Point[p]} ``` # +26 chars If you demand proper input/ouput, then ``` "0 0 4 4 0 4 4 0"; Grid@SortBy[%~ImportString~"Table", ArcTan @@ # &] ``` # +2 chars Just adding `N@` ``` Grid@SortBy[%~ImportString~"Table", ArcTan @@ N @ # &] ``` because above code works only on real numbers and not on integers due to Mathematica's weird behavior when sorting symbolic expressions ``` N@Sort[{ArcTan[1], ArcTan[-2]}] Sort[N@{ArcTan[1], ArcTan[-2]}] {0.785398, -1.10715} {-1.10715, 0.785398} ``` **EDIT** I just realized if the points are not around the origin it won't work, so it also requires shift to the center of points ``` SortBy[%, ArcTan @@ N[# - Mean@%] &] ``` ![enter image description here](https://i.stack.imgur.com/fcOaR.png) [Answer] The question has changed, thus this answer contains different versions, with and without a closed path. ## Perl, open path, 69 bytes ``` print"@$_$/"for sort{$$a[0]<=>$$b[0]||$$a[1]<=>$$b[1]}map{[/\S+/g]}<> ``` Each point is expected in STDIN as line, with the coordinates separated by white space. *Any* number format is supported that Perl interprets as number (including floating point numbers). **Example:** ``` 0 0 4 4 0 4 4 0 -2 1 2 -2 2 4 3.21 .56 .035e2 -7.8 0 2 ``` **Output:** ``` -2 1 0 0 0 2 0 4 2 -2 2 4 3.21 .56 .035e2 -7.8 4 0 4 4 ``` ![Result](https://i.stack.imgur.com/rWHf4.png) **Ungolfed:** ``` print "@$_$/" for # print output line sort { # sort function for two points $a and $b $$a[0] <=> $$b[0] # compare x part || $$a[1] <=> $$b[1] # compare y part, if x parts are identical } map { [/\S+/g] } # convert input line to point as array reference <> # read input lines ``` # Circuit variants In the first question version, there was a connection between the last and first point to make a circuit. ## Center is not existing point, 253 bytes This variant can fail, if the center is one of the points, see example 3. **Edits:** * In his [answer](https://codegolf.stackexchange.com/a/26007/16143) swish noticed, that the points should be centered around the origin to ensure a cross-free circuit: + Sorting needs transformed coordinates. + The original string representation of the numbers need to be kept for the output. * Bug fix: the special case for the negative x-axis had included the positive x-axis. ``` print"$$_[2] $$_[3]$/"for sort{($X,$Y)=@$a;($x,$y)=@$b;(!$X&&!$Y?-1:0)||!$x&&!$y||!$Y&&!$y&&$X<0&&$x<0&&$X<=>$x||atan2($Y,$X)<=>atan2($y,$x)||$X**2+$Y**2<=>$x**2+$y**2}map{[$$_[0]-$M/$n,$$_[1]-$N/$n,@$_]}map{$n++;$M+=$$_[0];$N+=$$_[1];$_}map{[/\S+/g]}<> ``` **Example 1:** ``` 4 4 -2 0 2 0 1 1 4 0 -2 -2 -3 -1 1 -2 3 0 2 -4 0 0 -1 -2 3 3 -3 0 2 3 -5 1 -6 -1 ``` **Output 1:** ``` 0 0 -6 -1 -3 -1 -2 -2 -1 -2 1 -2 2 -4 2 0 3 0 4 0 1 1 3 3 4 4 2 3 -5 1 -3 0 -2 0 ``` ![Result circuit 1](https://i.stack.imgur.com/bCdz0.png) **Example 2:** Testing number representation and coordinate transformation. ``` .9e1 9 7 7.0 8.5 06 7.77 9.45 ``` **Output 2:** ``` 7 7.0 8.5 06 .9e1 9 7.77 9.45 ``` ![Result circuit 2](https://i.stack.imgur.com/UGAhA.png) **Ungolfed:** ``` print "$$_[2] $$_[3]$/" for sort { # print sorted points ($X, $Y) = @$a; # ($X, $Y) is first point $a ($x, $y) = @$b; # ($x, $y) is second point $b (!$X && !$Y ? -1 : 0) || # origin comes first, test for $a !$x && !$y || # origin comes first, test for $b !$Y && !$y && $X < 0 && $x < 0 && $X <=> $x || # points on the negative x-axis are sorted in reverse order atan2($Y, $X) <=> atan2($y, $x) || # sort by angles; the slope y/x would be an alternative, # then the x-axis needs special treatment $X**2 + $Y**2 <=> $x**2 + $y**2 # the (quadratic) length is the final sort criteria } map { [ # make tuple with transformed and original coordinates # the center ($M/$n, $N/$n) is the new origin $$_[0] - $M/$n, # transformed x value $$_[1] - $N/$n, # transformed y value @$_ # original coordinates ] } map { $n++; # $n is number of points $M += $$_[0]; # $M is sum of x values $N += $$_[1]; # $N is sum of y values $_ # pass orignal coordinates through } map { # make tuple with point coordinates [ /\S+/g ] # from non-whitespace in input line } <> # read input lines ``` ## Without restriction, 325 bytes ``` print"$$_[2] $$_[3]$/"for sort{($X,$Y)=@$a;($x,$y)=@$b;atan2($Y,$X)<=>atan2($y,$x)||$X**2+$Y**2<=>$x**2+$y**2}map{[$$_[0]-$O/9,$$_[1]-$P/9,$$_[2],$$_[3]]}map{$O=$$_[0]if$$_[0]>0&&($O>$$_[0]||!$O);$P=$$_[1]if$$_[1]>0&&($P>$$_[1]||!$P);[@$_]}map{[$$_[0]-$M/$n,$$_[1]-$N/$n,@$_]}map{$n++;$M+=$$_[0];$N+=$$_[1];$_}map{[/\S+/g]}<> ``` In the previous version, the center is put at the begin and the last points on the negative axis are sorted in reverse order to get cross-free to the center again. However, this is not enough, because the last points could lie on a different line. Thus the following example 3 would fail. This is fixed by moving the centered origin a little to the top and right. Because of centering, there must be at least one point with positive x value and a point with positive y value. Thus the minimums of the positive x and y values are taken and reduced to a ninth (a half or third could be enough). This point cannot be one of the existing points and is made the new origin. The special treatments of the origin and the negative x-axis can be removed, because there is any point that lies on the new origin. **Example 3:** ``` -2 -2 -1 -1 -2 2 -1 1 2 -2 1 -1 2 2 1 1 0 0 ``` **Output 3:** ``` 0 0 -1 -1 -2 -2 1 -1 2 -2 1 1 2 2 -2 2 -1 1 ``` ![Result 3](https://i.stack.imgur.com/OiQP6.png) **Example 1** is now differently sorted: ![Result 1](https://i.stack.imgur.com/GghNR.png) **Ungolfed:** ``` print "$$_[2] $$_[3]$/" for sort { # print sorted points ($X, $Y) = @$a; # ($X, $Y) is first point $a ($x, $y) = @$b; # ($x, $y) is second point $b atan2($Y, $X) <=> atan2($y, $x) || # sort by angles; the slope y/x would be an alternative, # then the x-axis needs special treatment $X**2 + $Y**2 <=> $x**2 + $y**2 # the (quadratic) length is the final sort criteria } map { [ # make tuple with transformed coordinates $$_[0] - $O/9, $$_[1] - $P/9, # new transformed coordinate $$_[2], $$_[3] # keep original coordinate ] } map { # get the minimum positive x and y values $O = $$_[0] if $$_[0] > 0 && ($O > $$_[0] || !$O); $P = $$_[1] if $$_[1] > 0 && ($P > $$_[1] || !$P); [ @$_ ] # pass tuple through } map { [ # make tuple with transformed and original coordinates # the center ($M/$n, $N/$n) is the new origin $$_[0] - $M/$n, # transformed x value $$_[1] - $N/$n, # transformed y value @$_ # original coordinates ] } map { $n++; # $n is number of points $M += $$_[0]; # $M is sum of x values $N += $$_[1]; # $N is sum of y values $_ # pass orignal coordinates through } map { # make tuple with point coordinates [ /\S+/g ] # from non-whitespace in input line } <> # read input lines ``` [Answer] # GolfScript, 6 / 13 chars (open path; 49 chars for closed path) > > Note: This solution is for the [current version of the challenge](https://codegolf.stackexchange.com/revisions/26001/3) as edited by Rusher. It is *not* a valid solution to the [original challenge](https://codegolf.stackexchange.com/revisions/26001/2), which required that the line from last point back to the first also should not intersect the other lines. The 49-char solution below is valid for the original challenge too. > > > ``` ~]2/$` ``` The code above assumes that the output can be in any reasonable format. If the output format has to match the input, the following 13-character version will do: ``` ~]2/${" "*n}/ ``` Explanation: * `~` evaluates the input, turning it into a list of numbers; `]` gathers these numbers into an array, and `2/` splits this array into two-number blocks, each representing one point. * `$` sorts the points in lexicographic order, i.e. first by the x-coordinate and then, if there are ties, by the y-coordinate. It is easy to show that this will guarantee that the lines drawn between the points do not intersect, *as long as* the path does not need to loop back to the beginning. * In the 5-character version, ``` stringifies the sorted array, producing the native string representation of it (e.g. `[[0 0] [0 4] [4 0] [4 4]]`). In the longer version, `{" "*n}/` joins the coordinates of each point by a space, and appends a newline. Online demo: [short version](http://golfscript.apphb.com/?c=IyBDYW5uZWQgaW5wdXQ6CjsiCjAgMAo0IDQKMCA0CjQgMAoiCgojIFByb2dyYW06Cn5dMi8kYA%3D%3D) / [long version](http://golfscript.apphb.com/?c=IyBDYW5uZWQgaW5wdXQ6CjsiCjAgMAo0IDQKMCA0CjQgMAoiCgojIFByb2dyYW06Cn5dMi8keyIgIipufS8%3D). --- Ps. Here's a 49-char solution to the original problem, where the path is required to be closed: ``` ~]2/$.0=~:y;:x;{~y-\x-.+.@9.?*@(/\.!@@]}${" "*n}/ ``` It works in a similar manner as [Heiko Oberdiek's Perl solution](https://codegolf.stackexchange.com/a/26002), except that, instead of using trig functions, this code sorts the points by the slope (*y* − *y*0) / (*x* − *x*0), where (*x*0, *y*0) is the point with the lowest *x*-coordinate (and lowest *y*-coordinate, if several points are tied for lowest *x*). Since GolfScript doesn't support floating point, the slopes are multiplied by the fixed constant 99 = 387420489. (If that's not enough precision, you can replace the `9` with `99` to turn the multiplier into 9999 ≈ 3.7 × 10197.) There's also some extra code to break ties (by the *x* coordinate) and to ensure that, as in Heiko's solution, points with *x* = *x*0 are sorted last, in decreasing order by *y* coordinate. Again, [here's an online demo](http://golfscript.apphb.com/?c=IyBDYW5uZWQgaW5wdXQ6CjsiCjAgMAo0IDQKMCA0CjQgMAoiCgojIFByb2dyYW06Cn5dMi8kLjA9fjp5Ozp4O3t%2BeS1ceC0uKy5AOS4%2FKkAoL1wuIUBAXX0keyIgIipufS8KCg%3D%3D). [Answer] # Mathematica, 35 This works for ANY list of unique points. ``` s=StringSplit;Grid@Sort@s@s[%,"\n"] ``` You say "read from stdin", so for Mathematica, I'm assuming "read from last output". ## Input (last output): ``` "0 0 4 4 0 4 4 0" ``` ## Output: ``` 0 0 0 4 4 0 4 4 ``` If input and output needn't be in the "newlines" format, this can shrink to **6** characters: ``` Sort@% ``` taking the last output as input, assuming the last output is a 2-dimensional array. Input (last output): ``` {{0,0},{4,4},{0,4},{4,0}} ``` Ouput: ``` {{0,0},{0,4},{4,0},{4,4}} ``` [Answer] # PHP (~~175~~ ~~109~~ 100 chars) ``` while(fscanf(STDIN,'%d%d',$a,$b))$r[]=sprintf('%1$04d %2$04d',$a,$b);sort($r);echo implode(' ',$r); ``` OK, I admit, PHP isn't the best golfing language, but I gave it a try. Here's some sample output: ``` 0000 0000 0000 0004 0004 0000 0004 0004 ``` What is does is it puts the information into a string formatted with previous zeroes. Then it just sorts the points textually. P.S. It fails on numbers above `9999`. [Answer] # Python 2.7, 42B ``` import sys print''.join(sorted(sys.stdin)) ``` Couldn't really be simpler; read STDIN, sort lines, print lines. NB I've respected the exact I/O requirements of the question, but if you're manually populating STDIN you need to press `CTRL+d` to end input. ]
[Question] [ Inspired by the following XKCD comic: ![enter image description here](https://i.stack.imgur.com/cntL5.png) In Missy Elliot's "Work It", part of the chorus goes as follows: `Is it worth it, let me work it` `I put my thing down, flip it and reverse it` Bearing that in mind, I propose the following code golf challenge: Create code that does, in order: 1. Takes 8-bit ASCII input from STDIN; e.g `n` (Hex 6E, or Bin 01101110) 2. Shifts each byte's 8 bits down 1 bit level (I believe it's called a bitwise shift down), e.g `01101110` becomes `00110111` ("put my thing down"); 3. Inverts each byte's bits, e.g `00110111` becomes `11001000` ("flip it"); 4. Reverses the bits for each byte, e.g `11001000` becomes `00010011` ("reverse it"); 5. If a byte's value is less than 32, then perform `(95 + [byte value])`, or in other words, `(126-(31-[byte value]))`, on the byte before converting back to ASCII... If the byte value is still less than 32, repeat step 5 6. If a byte's value is greater than 126, then perform `([byte value] - 95)`, or in other words, `(32+([byte value]-127))`, on the byte before converting back to ASCII... IF the value is still greater than 126, repeat step 6. 7. Display the newly converted string as ASCII. **An example of this code in action:** (The input, is it worth it?) `workit missy` ("missy" being the input, "workit" is the function) *Now behind the scenes...* (let me work it... Into binary) `01101101 01101001 01110011 01110011 01111001` (Put my thing down... Bitwise) `00110110 00110100 00111001 00111001 00111100` (...Flip it...) `11001001 11001011 11000110 11000110 11000011` (... And reverse it!) `10010011 11010011 01100011 01100011 11000011` (Converted back to Decimal) `147 211 99 99 195` (Perform the necessary math) `147-95 211-95 99 99 195-95 => 52 116 99 99 100` (Convert back to ASCII and display, the output) `4tccd` **Rules** 1. Shortest code wins... simple as that... 2. Input can be via function, by prompt or whatever works for you, so long as you can make Rule 1 "work it" for you... ;) 3. I am not after reversibility, so long as you can make the code do what I have asked it to do, I'll be happy... Best of luck! [Answer] ## APL ~~50~~ 45 ``` ⎕UCS n+95ׯ1++⌿126 31∘.≥n←2⊥⊖~(8/2)⊤⌊.5×⎕UCS⍞ ``` Takes input on the keyboard, e.g.: ``` ⎕UCS n+95ׯ1++⌿126 31∘.≥n←2⊥⊖~(8/2)⊤⌊.5×⎕UCS⍞ missy 4tccd ``` [Answer] ## GolfScript ~~43~~ ~~38~~ 35 ``` {2/~512+2base(;-1%2base-32+95%32+}% ``` Explanation: For each character in the string, we will do the following: ``` 2/ # "Put your thing down": do integer division (accomplishing a bit shift). ~ # "Flip it": negate the bits of the integer. 512+ #make sure the binary form will have sufficient initial 0s (the extra initial 1 will be removed). 2base #convert string to value in base 2 (as an array) (; #remove the initial 1 added by the 512 addition -1% # "Reverse it": reverse the array 2base #convert back to base 10 -32+95%32+ #this does the equivalent of the subtraction/addition logic ``` Usage: ``` echo 'missy' | ruby golfscript.rb workit.gs > 4tccd ``` Thanks to help from PeterTaylor. [Answer] # K, 68 58 ``` {"c"${$[a<32;95;a>126;-95;0]+a:6h$0b/:|~8#0b,0b\:x}'4h$'x} ``` . ``` k){"c"${$[a<32;95;a>126;-95;0]+a:6h$0b/:|~8#0b,0b\:x}'4h$'x}"missy" "4tccd" ``` [Answer] # J - 61 ``` u:-&95^:(>&126)"0+&95^:(<&32)"0#.|."1(1-0,0,}:)"1#:3&u:1!:1[1 missy 4tccd ``` [Answer] # J, 55 54 characters ``` u:+/(*126&>*.32&<)_95 0 95+/#.|."1#:255-<.-:a.i.1!:1[1 ``` [Answer] ## Ruby, 115 This entry is uncompetitively long. So I'll go with, "but you can read it!" :-P ``` $><<gets.chars.map{|c|c=(c.ord.to_s(2)[0..-2].tr('01','10').reverse+'11').to_i(2) (c+(c<32?95:c>126?-95:0)).chr}*'' ``` Reads from `stdin`: ``` missy 4tccd ``` [Answer] ## Python 2.7, 106 Another rather long answer, but hey it's my first try: ``` for c in raw_input():x=sum(1<<7-i for i in range(8)if~ord(c)>>1+i&1);print'\b%c'%(x+95*((x<32)-(x>126))), ``` Modified based off of Darren Stone and grc's comments below... [Answer] ## Python 2.7 - 73 ~~86~~ Thanks to the change in rules I found a much simpler way to do this all using binary and integer manipulation. This saves space over Quirlioms by not needing a temporary variable: ``` for i in input():print chr((int(bin(ord(i)>>1^255)[:1:-1],2)-32)%95+32), > python workit.py "missy" 4 t c c d > python workit.py "P Diddy" - 9 \ t T T d ``` And in explanation form: ``` for i in input(): # Take an input, better quote it # Is it worth it? Let me work it print chr( int(bin( ord(i)>>1 # Put my thing down by bitshifting it ^255 # XOR it with 255 to flip the bits and pad to 8 bits )[:1:-1] # Then reverse it (but don't take the cruft # python puts at the start of binary strings) ,2) )-32)%95+32 # This pulls everything into the 32-126 range ), ``` ]
[Question] [ Given a series of numbers for events X and Y, calculate Pearson's correlation coefficient. The probability of each event is equal, so expected values can be calculated by simply summing each series and dividing by the number of trials. ## Input ``` 1 6.86 2 5.92 3 6.08 4 8.34 5 8.7 6 8.16 7 8.22 8 7.68 9 12.04 10 8.6 11 10.96 ``` ## Output ``` 0.769 ``` Shortest code wins. Input can be by stdin or arg. Output will be by stdout. Edit: Builtin functions should not be allowed (ie calculated expected value, variance, deviation, etc) to allow more diversity in solutions. However, feel free to demonstrate a language that is well suited for the task using builtins (for exhibition). Based on David's idea for input for Mathematica (86 char using builtin mean) ``` m=Mean;x=d[[All,1]];y=d[[All,2]];(m@(x*y)-m@x*m@y)/Sqrt[(m@(x^2)-m@x^2)(m@(y^2)-m@y^2)] m = Mean; x = d[[All,1]]; y = d[[All,2]]; (m@(x*y) - m@x*m@y)/((m@(x^2) - m@x^2)(m@(y^2) - m@y^2))^.5 ``` Skirting by using our own mean (101 char) ``` m=Total[#]/Length[#]&;x=d[[All,1]];y=d[[All,2]];(m@(x*y)-m@x*m@y)/((m@(x^2)-m@x^2)(m@(y^2)-m@y^2))^.5 m = Total[#]/Length[#]&; x = d[[All,1]]; y = d[[All,2]]; (m@(x*y)-m@x*m@y)/((m@(x^2)-m@x^2)(m@(y^2)-m@y^2))^.5 ``` [Answer] # Mathematica 34 bytes Here are a few ways to obtain the Pearson product moment correlation. They all produce the same result. From Dr. belisarius: 34 bytes ``` Dot@@Normalize/@(#-Mean@#&)/@{x,y} ``` --- **Built-in Correlation function I**: 15 chars This assumes that `x` and `y` are lists corresponding to each variable. ``` x~Correlation~y ``` > > 0.76909 > > > --- **Built-in Correlation function II**: 31 chars This assumes d is a list of ordered pairs. ``` d[[;;,1]]~Correlation~d[[;;,2]] ``` > > 0.76909 > > > The use of `;;` for `All` thanks to A Simmons. --- **Relying on the Standard Deviation function**: ~~118~~ 115 chars The correlation can be determined by: ``` s=StandardDeviation; m=Mean; n=Length@d; x=d[[;;,1]]; y=d[[;;,2]]; Sum[((x[[i]]-m@x)/s@x)((y[[i]]-m@y)/s@y),{i,n}]/(n-1) ``` > > 0.76909 > > > --- **Hand-rolled Correlation**: 119 chars Assuming `x` and `y` are lists... ``` s=Sum;n=Length@d;m@p_:=Tr@p/n; (s[(x[[i]]-m@x)(y[[i]]-m@y),{i,n}]/Sqrt@(s[(x[[i]]-m@x)^2,{i,n}] s[(y[[i]] - m@y)^2,{i,n}])) ``` > > 0.76909 > > > [Answer] ## PHP 144 bytes ``` <? for(;fscanf(STDIN,'%f%f',$$n,${-$n});$f+=${-$n++})$e+=$$n; for(;$$i;$z+=$$i*$a=${-$i++}-=$f/$n,$y+=$a*$a)$x+=$$i*$$i-=$e/$n; echo$z/sqrt($x*$y); ``` Takes the input from STDIN, in the format provided in the original post. Result: > > 0.76909044055492 > > > Using the vector dot product: ![](https://chart.googleapis.com/chart?cht=tx&chl=%5Crho_%7Bxy%7D%3D%5Cfrac%7Bx%27%5Ccdot+y%27%7D%7B%7C%7Cx%27%7C%7C%5C%2C%7C%7Cy%27%7C%7C%7D) where ![](https://chart.googleapis.com/chart?cht=tx&chl=x%27%2C%5C%2Cy%27) are the input vectors ![](https://chart.googleapis.com/chart?cht=tx&chl=x%2C%5C%2Cy) adjusted downwards by ![](https://chart.googleapis.com/chart?cht=tx&chl=E%28x%29) and ![](https://chart.googleapis.com/chart?cht=tx&chl=E%28y%29) respectively. ## Perl 112 bytes ``` / /,$e+=$`,$f+=$',@v=($',@v)for@u=<>; $x+=($_-=$e/$.)*$_,$y+=($;=$f/$.-pop@v)*$;,$z-=$_*$;for@u; print$z/sqrt$x*$y ``` > > 0.76909044055492 > > > Same alg, different language. In both cases, new lines have been added for 'readability', and are not required. The only notable difference in length is the first line: the parsing of input. [Answer] # Q Assuming builtins are allowed and x,y data are seperate vectors (7 chars): ``` x cor y ``` If data are stored as orderded pairs, as indicated by David Carraher, we get (for 12 characters): ``` {(cor).(+)x} ``` [Answer] # MATLAB/Octave For the purpose of demonstrating built-ins only: ``` octave:1> corr(X,Y) ans = 0.76909 octave:2> ``` [Answer] ## APL 57 Using the dot product approach: ``` a←1 2 3 4 5 6 7 8 9 10 11 b←6.86 5.92 6.08 8.34 8.7 8.16 8.22 7.68 12.04 8.6 10.96 (a+.×b)÷((+/(a←a-(+/a)÷⍴a)*2)*.5)×(+/(b←b-(+/b)÷⍴b)*2)*.5 0.7690904406 ``` [Answer] # J, ~~30~~ 27 bytes ``` ([:+/*%*&(+/)&.:*:)&(-+/%#) ``` This time as a function taking two arguments. Uses the vector formula for calculating it. ## Usage ``` f =: ([:+/*%*&(+/)&.:*:)&(-+/%#) (1 2 3 4 5 6 7 8 9 10 11) f (6.86 5.92 6.08 8.34 8.7 8.16 8.22 7.68 12.04 8.6 10.96) 0.76909 ``` ## Explanation Takes two lists *a* and *b* as separate arguments. ``` ([:+/*%*&(+/)&.:*:)&(-+/%#) Input: a on LHS, b on RHS &( ) For a and b # Get the count +/ Reduce using addition to get the sum % Divide the sum by the count to get the average - Subtract the initial value from the average Now a and b have both been shifted by their average For both a and b *: Square each value (+/)&.: Reduce the values using addition to get the sum Apply in the inverse of squaring to take the square root of the sum to get the norm *& Multiply norm(a) by norm(b) * Multiply a and b elementwise % Divide a*b by norm(a)*norm(b) elementwise [:+/ Reduce using addition to the sum which is the correlation coefficient and return it ``` [Answer] ## Python 3, 140 bytes ``` E=lambda x:sum(x)/len(x) S=lambda x:(sum((E(x)-X)**2for X in x)/len(x))**.5 lambda x,y:E([(X-E(x))*(Y-E(y))for X,Y in zip(x,y)])/S(x)/S(y) ``` 2 helper functions (`E` and `S`, for expected value and standard deviation, respectively) are defined. Input is expected as 2 iterables (lists, tuples, etc). [Try it online](http://ideone.com/fork/t4RfXd). [Answer] # Oracle SQL 11.2, 152 bytes (for exhibition) ``` SELECT CORR(a,b)FROM(SELECT REGEXP_SUBSTR(:1,'[^ ]+',1,2*LEVEL-1)a,REGEXP_SUBSTR(:1,'[^ ]+',1,2*LEVEL)b FROM DUAL CONNECT BY INSTR(:1,' ',2,LEVEL-1)>0); ``` Un-golfed ``` SELECT CORR(a,b) FROM ( SELECT REGEXP_SUBSTR(:1, '[^ ]+', 1, 2*LEVEL-1)a, REGEXP_SUBSTR(:1, '[^ ]+', 1, 2*LEVEL)b FROM DUAL CONNECT BY INSTR(:1, ' ', 2, LEVEL - 1) > 0 ) ``` Input string should use the same decimal separator as the database. [Answer] # Python 3 with SciPy, 52 bytes (for exhibition) ``` from scipy.stats import* lambda x,y:pearsonr(x,y)[0] ``` An anonymous function that takes input of the two data sets as lists `x` and `y`, and returns the correlation coefficient. **How it works** There's not a lot going on here; SciPy has a builtin that returns both the coefficient and the p-value for testing non-correlation, so the function simply passes the data sets to this and returns the first element of the `(coefficient, p-value)` tuple returned by the builtin. [Try it on Ideone](https://ideone.com/UqghSC) ]
[Question] [ *This challenge was originally [posted on codidact](https://codegolf.codidact.com/posts/288943).* --- Given a number \$n \geq 3\$ as input output the smallest number \$k\$ such that the modular residues of \$k\$ by the first \$n\$ primes is exactly \$\{-1,0,1\}\$. That is, there are three primes in the first \$n\$ primes, so that prime 1 divides \$k\$, prime 2 divides \$k+1\$ and prime 3 divides \$k-1\$, *and* every prime in the first \$n\$ primes divides one of those three values. For example if \$n=5\$, the first \$5\$ primes are \$2, 3, 5, 7, 11\$ the value must be at least \$10\$ since with anything smaller \$11\$ is an issue. So we start with \$10\$: $$ 10 \equiv 0 \mod 2 $$ $$ 10 \equiv 1 \mod 3 $$ $$ 10 \equiv 0 \mod 5 $$ $$ 10 \equiv 3 \mod 7 $$ Since \$10 \mod 7 \equiv 3\$, \$10\$ is not a solution so we try the next number. * \$11 \equiv 4\mod 7\$ so we try the next number. * \$12 \equiv 2\mod 5\$, so we try the next number. * \$13 \equiv 3\mod 5\$, so we try the next number. * \$14 \equiv 3\mod 11\$, so we try the next number. * \$15 \equiv 4\mod 11\$, so we try the next number. * \$16 \equiv 2\mod 7\$, so we try the next number. * \$17 \equiv 2\mod 5\$, so we try the next number. * \$18 \equiv 3\mod 5\$, so we try the next number. * \$19 \equiv 5\mod 7\$, so we try the next number. * \$20 \equiv 9\mod 11\$, so we try the next number. $$ 21 \equiv 1 \mod 2 $$ $$ 21 \equiv 0 \mod 3 $$ $$ 21 \equiv 1 \mod 5 $$ $$ 21 \equiv 0 \mod 7 $$ $$ 21 \equiv -1 \mod 11 $$ 21 satisfies the property so its the answer. ## Task Take as input \$n \geq 3\$ and give as output the smallest number satisfying. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The goal is to minimize the size of your source code as measured in bytes ## Test cases ``` 3 -> 4 4 -> 6 5 -> 21 6 -> 155 7 -> 441 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` Nθ→W‹Lυθ«→¿⬤υ﹪ⅈκ⊞υⅈ»W›⌈﹪ⅈυ²M→I⊖ⅈ ``` [Try it online!](https://tio.run/##VY0/C8IwEMXn9lNkvEBdHBzsJAoiWClOrrE9m2D@2DSpgvjZ43UQ7A0P7u733muk8I0TOqWDfcRwiuaKHnpe5pUbEdZn1clA21MqjQyOOAwktgsSIi9Yzzl759mczdSNwUZriAWrXBu1gwsQfOdE13GQ04MuhH5@wXuPIlBzJV7KRAP/vshJluSd19Re2QBbMQTYYePRoA3YThaaMqVVWoz6Cw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @UnrelatedString's Jelly answer. ``` Nθ ``` Input `n`. ``` →W‹Lυθ«→¿⬤υ﹪ⅈκ⊞υⅈ» ``` Generate the first `n` primes. ``` W›⌈﹪ⅈυ²M→ ``` Continue counting up while the number's greatest residue modulo those `n` primes exceeds 2. ``` I⊖ⅈ ``` Decrement to produce the final result. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` %Ṁ=2ʋ1#ÆN€’ ``` [Try it online!](https://tio.run/##y0rNyan8/1/14c4GW6NT3YbKh9v8HjWtedQw879x0eF2IDPy/39zAA "Jelly – Try It Online") ``` 1# Find the first integer starting from n for which Ṁ its greatest % ʋ ÆN€ residue modulo the first n primes =2 is 2. ’ Decrement. ``` If \$k\$ has residues \$ \{-1,0,1\} \$, \$k + 1\$ has residues \$\{0, 1, 2\}\$. On reflection, I'm... not entirely sure this program is valid, since 1. it might erroneously reject a \$k\$ with its only \$1\$ residue from \$2\$, and 2. while every integer necessarily has \$0\$ and \$1\$ as residues from *some* primes, it's not clear that there's no \$n\$ for which some erroneous \$k\$ with a maximum minimal-positive residue of \$2\$ mod the first \$n\$ primes but not \$0\$ and \$1\$ mod *one of the first \$n\$* primes is less than the real least \$k\$. However, it does pass the test cases, and it seems plausible that it is in fact correct. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 80 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 10 bytes ``` ?ʁǎ%G2=)2ȯ‹ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJHPSIsIiIsIj/KgceOJUcyPSkyyK/igLkiLCIiLCI3Il0=) A little goofy port of Jelly. ## Explained ``` ?ʁǎ%G2=)2ȯ‹­⁡​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁢⁣​‎‏​⁢⁠⁡‌­ )2ȯ # ‎⁡First two integers where G # ‎⁢ The maximum of ?ʁǎ% # ‎⁣ [k % x for x in first n primes] 2= # ‎⁤ Equals 2 2ȯ # ‎⁢⁡The first two integers is because 1 is considered to pass the test, meaning that it needs to be accounted for. This could otherwise just be a single byte if there was something that started from n ‹ # ‎⁢⁢Decrement # ‎⁢⁣The G flag gets the biggest item (which is the number in the list that _isn't_ 1) 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `t`, 12 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` 2Ƙ$LÆP%G2=;⁻ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPTIlQzYlOTglMjRMJUMzJTg2UCUyNUcyJTNEJTNCJUUyJTgxJUJCJmZvb3Rlcj0maW5wdXQ9NSZmbGFncz10) Port of Unrelated String's Jelly answer. #### Explanation ``` 2Ƙ$LÆP%G2=;⁻ # Implicit input 2Ƙ ; # First 2 positive integers where: $LÆP # List of the first (input) primes % # The current number mod this G2= # Maximum equals 2 ⁻ # Decrement both # Implicit output of last item ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 95 bytes ``` f=(n,k)=>(y=L=[],g=n=>(P=i=>y%i--?P(i):i)(y++)?n&&g(n):L[-~k%y]=g(n-1))(n)+',0,0'==L?k:f(n,-~k) ``` [Try it online!](https://tio.run/##Zcy9CoMwFIbhvfehnkOSYukvwjE3kMFdHMSakCpJqaWQpbeeZi0Z34eP7zF@xm162edbOH@fY9QEji9ILQRS1A/ckEvRkaU2FFYI2YHFxiIExlC6sjTgsFG9@C5FGCiVOCAmYxWveV0RKbk0Or2mBcbJu82v8371BjQcEXf/csrknMklk2smtyTxBw "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 115 bytes ``` f=lambda n,i=1,p=1:n*[0]and p%i*[i]+f(n-p%i,i+1,p*i*i) x=3;q=f(input()) while max(x%y for y in q)>2:x+=1 print(x-1) ``` [Try it online!](https://tio.run/##DcpLCoMwEADQfU4xGyE/obF0YxkvIi5SbHBAxygpJqdP3b3FiyUtO3e1Blz99pk9sCV0NqLrWY@PyfMMsSE90mSC5Pa2JXMHTZqUyPh8HxgkcfwlqZS4Flq/sPksc1Mg7CcUIIZDDV2fDToRT@Ikc@tUra8/ "Python 2 – Try It Online") Uses [Lynn's function to get the first n primes](https://codegolf.stackexchange.com/a/152433/114446). Port of Unrelated String's Jelly answer. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 89 bytes ``` r`\d*$ ¶__ "$&"}+`\b(_+)(¶_+)*¶\1+$ $&_ $ ¶$%` +`(?>\b(_+)(¶_+)*¶\1*)(?!_?_?$) $&_ G`$ \B ``` [Try it online!](https://tio.run/##K0otycxLNPyvqqHhnvC/KCEmRUuF69C2@HguJRU1pVrthJgkjXhtTQ2gkLam1qFtMYbaKlwqavFcIFUqqglc2gka9nYYirQ0NewV4@3j7VU0wardE1S4Ypz@/zfmMuEy5TLjMgcA "Retina – Try It Online") Link includes test cases. Explanation: ``` r`\d*$ ¶__ ``` Append `2` in unary to the buffer, deleting any input number. This awkward approach is fortunately the same length as the more straightforward approach of deleting the input number before starting the loop, as that version then requires history, which prevents more than one test case from being run at once. ``` \b(_+)(¶_+)*¶\1+$ $&_ ``` If the last value in the buffer is divisible by any of the previous values then increment it. ``` +` ``` Repeat until it becomes prime. ``` "$&"}` ``` Repeat until `n` primes have been generated. ``` $ ¶$%` ``` Make a copy of the `n`th prime. ``` (?>\b(_+)(¶_+)*¶\1*)(?!_?_?$) $&_ ``` If there is a prime for which the copy does not have a residue of no more than `2` then increment it. The atomic group `(?>...)` ensures that the regex doesn't try to add the prime to the residue to increase it to more than `2`, or worse, divide one of the primes by one of the other primes. ``` +` ``` Repeat until no residue is greater than `2`. ``` G`$ ``` Keep only the final result. ``` \B ``` Subtract `1` and convert it to decimal. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞+.Δ>IÅp%à< ``` Port of [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/263736/52210). [Try it online](https://tio.run/##yy9OTMpM/f//Ucc8bb1zU@w8D7cWqB5eYPP/vykA) or [verify all test cases](https://tio.run/##ATAAz/9vc2FiaWX/MyA3xbh2eT8iIOKGkiAiP3nCqf/iiJ4rLs6UPsKuw4VwJcOgPP99LP8). **Explanation:** ``` ∞ # Push an infinite positive list: [1,2,3,...] + # Add the (implicit) input-integer to each: [n+1,n+2,n+3,...] .Δ # Find the first integer that's truthy for: > # Increase the current value by 1: [n+2,n+3,n+4,...] IÅp # Push a list of the first input amount of primes % # Modulo the current value+1 by each of these primes à # Pop and push the maximum remainder < # Verify that it's equal to 2, by decreasing it by 1 (since only 1 is # truthy in 05AB1E) # (after which the found result is output implicitly) ``` ]
[Question] [ **This question already has answers here**: [Biggest Irreducible Hello World](/questions/196824/biggest-irreducible-hello-world) (19 answers) Closed 3 years ago. I guess you could call this the next challenge in the "Irreducible series". * [Hello World](https://codegolf.stackexchange.com/questions/196824/biggest-irreducible-hello-world) # Challenge Create a [cat](https://esolangs.org/wiki/Cat_program#:%7E:text=The%20cat%20program%20is%20a,every%20program%20is%20a%20quine.) subject to the constraint that it is *irreducible*. A cat program `C` is considered *irreducible* if there does not exist a cat (in the same programming language as `C`) that can be constructed by removing characters from `C`. For example ``` console.log(prompt.call()); ``` can have the the bracketed characters removed ``` console.log(prompt[.call]())[;] -> console.log(prompt()) ``` And it will still be a cat. Therefore `console.log(prompt.call());` is not irreducible. The winner will be the program with the longest source code. # Extras A big shout out to [@acupoftea](https://codegolf.stackexchange.com/users/90124/acupoftea) for [showing](https://codegolf.stackexchange.com/questions/196824/biggest-irreducible-hello-world#comment483918_196824) that, for any given language, there is actually a maximum score. Otherwise you could construct an infinite set that would break [Higman's lemma](https://en.wikipedia.org/wiki/Higman%27s_lemma)!. [Answer] # [C (gcc)](https://gcc.gnu.org/) with `-trigraphs`, ~~327~~ ~~357~~ 413 bytes Some creative uses of the language: * Very important `typedef`s for pointers to types * Constants that are then decremented using the super-experimental [tadpole operator](https://devblogs.microsoft.com/oldnewthing/20150525-00/?p=45044) * Dynamic allocation of the character buffer, for reasons * Use of `fread` to read in a character * Use of `fprintf` to print a character as a fixed single-byte string * The essential use of trigraphs in case you are typing on a keyboard from the 1800s * Using `iso646.h` because the ISO said so :-) ``` ??=include <stdio.h> ??=include <stdlib.h> ??=include <iso646.h> typedef unsigned*v;struct g??<v c;??>;typedef struct g*h;h c;main()??<c=calloc(sizeof(struct g),-??-EXIT_SUCCESS);c->c=calloc(sizeof(unsigned),-??-EXIT_SUCCESS);do??<fread(c->c,-??-EXIT_SUCCESS,-??-EXIT_SUCCESS,stdin);if(feof(stdin)==EXIT_FAILURE xor EXIT_FAILURE)fprintf(stdout,"%.1s",c->c);??>while(feof(stdin)==EXIT_FAILURE xor EXIT_FAILURE);??> ``` [Try it online!](https://tio.run/##lZDPS8MwFIDv/hVhIDSjHQiyS9YGGRUHnqwDb1JfkvZBTEqSbuofb20mBel28fi@972fkDUAw8B5jgZ0LyTZ@CDQrtriagY1vs0peru@XUcaPjsppCK98dgYKZYH5oPrIZCG882BAOO8YJM1pZYta8fUe40moaMHOdRaW0g8fkmrksmjacZ5Vr7snl@r/XZbVhVlkBVzfRp@SRd27K@crEUSK8@McxD/YChDlajfXWKY5yfn/m73uH8qyYd15C@gqnNowsm2fUgX16sbv0jjRBo/cGxRy//0i0XD8CDHM8nROi2@Qem68UMWHDau7lr/Aw "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly) `u`, \$4\times10^{41}\$ bytes ``` “...”WẈbØ%ỌV ``` Except instead of `...` its \$133390687877217192365177139021057049493695\$ `Ɱ` characters More specifically, a score of \$400172063631651577095531417063171148481103\$ ## How it works The standard cat program in Jelly is ``` ƈȮøL¿ ``` [Try it online!](https://tio.run/##y0rNyan8//9Yx4l1h3f4HNr//39uaU5JJldOZl4qV2ZeQWkJAA "Jelly – Try It Online") If we convert each of these characters to their Unicode code point we get ``` [392, 558, 248, 76, 191] ``` Treat this a base \$4294967296 = 2^{32}\$ number and convert it back to decimal to get \$133390687877217192365177139021057049493695\$ The above program has a string consisting of \$133390687877217192365177139021057049493695\$ `Ɱ` characters. We then take its length, convert it to base \$4294967296\$, convert back to characters and run as Jelly code. By forcing Jelly to encode the source as UTF-8 rather than using the Jelly code page, multi byte characters are counted as multiple bytes rather than just 1. This is 100% irreducible. The cat program it encodes is optimal for Jelly, so there's no way to remove any of the `Ɱ` characters and still create a cat program, and all of the other characters are necessary to correctly convert the string to a program and execute it. More specifically: * Removing either `“` or `”` will cause syntax errors * Removing the `W` will cause `Ẉ` to return a list of lists of \$1\$s rather than the code points in base \$4294967296\$ * Removing the `Ẉ` will mean the program won't ever convert the string to the code points in base \$4294967296\$ * Removing any of `bØ%` will prevent the base conversion happening * Removing `Ọ` or `V` will stop the program from converting to characters and running the program Furthermore, I believe this is the longest you can get using the method of "long string's length in a high base" in Jelly. The base being used must meet the following criteria: * The number isn't "constructed" via commands to be larger, as these commands can be removed and the long string adjusted for the lower base * The number doesn't have digits in it, as characters can be removed to just isolate the lowest digit and the long string can then be adjusted to match this new base `Ø%` is the largest constant Jelly has which meets these criteria at \$2^{32}\$, so, as a higher base leads to a longer string, an answer in Jelly cannot beat this one. [Answer] # JavaScript (ES7), 10346554967051525 bytes The string `-~[]` is actually repeated \$2586638741762875\$ times. ``` Infinity=>eval((-~[]-~[]-~[]-~[]…-~[])**20+'') ``` You can [Try this version online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@98zLy0zL7Ok0tYutSwxR0PDyNTCzMzYwtzE0NzMyMLcQLcuOhYda2ppGRloq6tr/k/OzyvOz0nVy8lP10jTUPJIzcnJV1TS1PwPAA), where all but the last 5 `-~[]` have been replaced with a hard-coded integer. ### How? The characters in the name of the input variable `Infinity` are not used anywhere else, so we can't simplify the code by shortening it. The only way to get its content is that the expression in `eval()` evaluates to the string `"Infinity"`. We do it by computing: $$2586638741762875^{20}$$ where \$2586638741762875\$: * is less than [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) and can therefore be generated by adding \$1\$ repeatedly * becomes higher than [`Number.MAX_VALUE`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE) when raised to the power of \$20\$ We can probably make it longer by using a more convoluted expression. For instance, I think it should still be irreducible if we use `-~RegExp` instead of `-~[]`. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~11~~ ~~12~~ 15 bytes ``` \A`[^\\](?<=\\) ``` [Try it online!](https://tio.run/##VY0xDsIwDEV3TvE3YEEcAIS4AisB1bSGRqQxil0Kpw8pLHS1338vsflIObt9dTw7d1rsNlvnljkfuJOnjzdYy7j6pAaHRljj3DBIuuPCNfXKX0B6e/Tl7kNAS08GRfDLEiHyEHzk1Wwi3EMSqqmP9F9FYaC3jhHpWLH@E0jBEuqWEtXGSX9ZsgLrOAwyQMsKY7hIpTzQcGDjZvUB "Retina 0.8.2 – Try It Online") Explanation: The `\` suppresses the trailing newline, without which the program fails to be a cat program. The `A`` is required to identify the stage as an AntiGrep rather than a Match stage (which would just output the count of something). For the output to match the input, the pattern must fail to match; this is done by matching any non-`\` and then ensuring that the character was actually a `\`; this character was chosen because it needs to be quoted, making the pattern longer. I also looked into the other stage types Retina has to see what the best I could do for them was. * Deduplicate - best I could do was `\D`()` (5 bytes) deduplicate all empty strings * Grep - best I could do was `\G`` (3 bytes) keep everything * Match - best I could do was `\!`(.|[^.])+` (12 bytes) match everything * Sort - best I could do was `\O$`` or `\O`$` or similar (4 bytes) sort in original order or sort nothing * Replace - best I could do was a single newline (1 byte) replace nothing with nothing - this means that all Retina cat programs that contain a newline can be reduced to 1 byte * Split - best I could do was `\S`\n` (5 bytes) split on newlines and join with newlines * Transliteration - best I could do was `\T`` (3 bytes) translate nothing [Answer] # [Japt](https://github.com/ETHproductions/japt), 125 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) I'm very far from sure that this is valid but I am somewhat sure it can be beaten! ``` Ov"11111111111111111111111111111111111111111111111111111"n2 a"11111111111111111111111111111111111111111111110110001"n2 d qR ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=T3YiMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEibjIgYSIxMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMDExMDAwMSJuMiAgZCAgcVI&input=MQoyCjMKNA) [Answer] # [Python 3](https://docs.python.org/3/), ~~8+(10\*(85+(10\*749535276648396287585636512750330369605831039396714237143337)))~~ infinite bytes ``` exec("\U0000006e\U0000003d\U00000030\U0000003b\U00000063\U0000003d\U00000022\U00000030\U00000030\U00000030\U00000030\U0000002e\U0000002e\U0000002e\U0000002e\U0000002e\U00000022\U0000000a\U00000066\U0000006f\U00000072\U00000020\U0000005f\U00000020\U00000069\U0000006e\U00000020\U00000063\U0000003a\U0000006e\U0000002b\U0000003d\U00000031\U0000000a\U00000073\U0000003d\U00000062\U00000079\U00000074\U00000065\U00000061\U00000072\U00000072\U00000061\U00000079\U00000028\U00000029\U0000000a\U00000077\U00000068\U00000069\U0000006c\U00000065\U00000020\U0000006e\U0000003a\U00000073\U0000002e\U00000061\U00000070\U00000070\U00000065\U0000006e\U00000064\U00000028\U0000006e\U00000026\U00000032\U00000035\U00000035\U00000029\U0000003b\U0000006e\U0000003e\U0000003e\U0000003d\U00000038\U0000000a\U00000065\U00000078\U00000065\U00000063\U00000028\U00000073\U0000002e\U00000064\U00000065\U00000063\U0000006f\U00000064\U00000065\U00000028\U00000029\U00000029") ``` The `exec("")` adds 8 characters, and unicode-escapes multiply the count by 10. Decoded: ``` n=0;c="\U00000030\U00000030\U00000030\U00000030....." for _ in c:n+=1 s=bytearray() while n:s.append(n&255);n>>=8 exec(s.decode()) ``` This decoding routine adds the 85 characters. The string inside `c` is the actual code, encoded in unary, with a unicode-escaped `0` character per unary digit. This is too large to fit in the observable universe (approximately $$7.5 \times 10 ^ {60}$$ characters long), hence no TIO link. The unary is then decoded and executed, to get a `cat` program: ``` while True:print(input()) ``` I'm pretty sure you could recursively repeat these steps *ad infinitum* and it would still be irreducible (so I win by default), but I thought I'd keep my answer as an example finite. ]
[Question] [ According to Alexa rankings, the top 10 websites are: ``` google.com youtube.com facebook.com baidu.com yahoo.com wikipedia.org amazon.com twitter.com qq.com google.co.in ``` Being the top 10 visited websites, these are probably also the top 10 misspelled websites [Citation Needed]. # Your task Your goal is to write a program or function that accepts a string containing a misspelled domain name, and outputs all domain names on the top 10 list that are spelled similarly. ## Rules * Each input may be up to three characters off from a correct website. A changed character may a substitution (cat -> cot), addition (cat -> cant), or removal (cat -> at). * Moving a letter counts as two characters changed (the deletion of one character and the addition of another) * The input will only include the characters a-z, period, and dash * The name of a website does not include the `http(s)://` or the `www.` The websites are exactly as listed above. * The program must print out all websites that match the input. * Case doesn't matter. The test cases will be presented as lower case, but if your program requires upper case, that's fine too. * As always, no standard loopholes. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! # Some test cases (Input followed by outputs) ``` yahoo.com yahoo.com (no change for correct spelling) goggle.com google.com wikipedia.organ wikipedia.org bidua.cm baidu.com .om qq.com google.co.i google.com and google.co.in google.com google.com and google.co.in twipper.com twitter.com yahoo.org yahoo.com amazing.com amazon.com factbook.co facebook.com ki-pedia.org wikipedia.org google.co.india google.co.in goo.com google.com aol.com qq.com qqzon.com qq.com and amazon.com ``` ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=87174,OVERRIDE_USER=41505;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Mathematica, ~~167~~ 166 bytes *Saved one byte thanks to Martin Ender* ``` iSelect[{"google.com","youtube.com","facebook.com","baidu.com","yahoo.com","wikipedia.org","amazon.com","twitter.com","qq.com","google.co.in"},#~EditDistance~i<4&] ``` Defines a pure function that returns a list of urls. The `` is [this](http://reference.wolfram.com/language/ref/character/Function.html) This answer uses the same method as my NodeJS answer. [Answer] # [Nim](http://nim-lang.org/), ~~229~~ ~~205~~ ~~185~~ 174 bytes ``` import strutils,sequtils,future s=>"googlexyoutubexfacebookxbaiduxyahooxwikipedia.org amazonxtwitterxqqxgoogle.co.in".replace("x",".com ").split.filterIt it.editDistance(s)<4 ``` Yep, Nim has a builtin for Levenshtein distance (although it requires an `import`), which is what the question described. Defines an anonymous procedure, which must be passed to a testing procedure to be used. An testing program is provided below: ``` import strutils,sequtils,future proc test(d: string -> seq[string]) = echo d #[Your input here]# test(s=>"googlexyoutubexfacebookxbaiduxyahooxwikipedia.org amazonxtwitterxqqxgoogle.co.in".replace("x",".com ").split.filterIt it.editDistance(s)<4) ``` [Answer] ## JavaScript (ES6), 240 bytes ``` f= s=>`google.com,youtube.com,facebook.com,baidu.com,yahoo.com,wikipedia.org,amazon.com,twitter.com,qq.com,google.co.in`.split`,`.filter(t=>[...s].map((u,i)=>(q=p=i+1,w=w.map((v,j)=>p=Math.min(++p,q-(u==t[j]),q=++v))),w=[...[...t].keys()])|p<4) ; ``` ``` <input oninput=o.textContent=f(this.value).join`\n`><pre id=o> ``` [Answer] # Python, ~~216~~ ~~200~~ ~~193~~ 183 bytes ``` import editdistance as e i=raw_input() print[n for n in"googlexyoutubexfacebookxbaiduxyahooxamazonxtwitterxqqxgoogle.co.in wikipedia.org".replace('x','.com ').split()if e.eval(i,n)<4] ``` The module editdistance calculates the Levenshtein distance, which is the straightforward implementation of what the challenge was asking for. EDIT: Saved 3 bytes thanks to @shooqie EDIT 2: Saved another 10 bytes thanks to @shooqie and @Frank [Answer] # NodeJS, ~~163~~ ~~161~~ 151 bytes *10 bytes saved thanks to Copper's Nim solution* ``` x=>"google youtube facebook baidu yahoo wikipedia.org,amazon twitter qq google.co.in".replace(/ /g,".com,").split`,`.filter(y=>require("leven")(x,y)<4) ``` [Try it on Tonic](http://tonicdev.com/dinod123/nearesturl) Defines an anonymous function that returns an array of urls. This solution uses Levenshtein distance, which happens to be exactly what was described by the rules. This answer just selects the urls from an array based on if their Levenshtein distance is small enough. ]
[Question] [ Given an integer `N`, output the `N`th positive number `K` with the following property in decimal base: For each digit `I` at position `P` of `K`, the number formed from `K` by removing the `P`th digit (i.e. `I`) is divisible by `I`. ### Example and remarks `324` is such a number: * `3` divides `24` * `2` divides `34` * `4` divides `32` **Note 1:** we assume that the empty number is divisible by anything, like `0`. Therefore `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8` and `9` are valid. **Note 2:** `K` cannot contain the digit `0`, since you cannot divide by `0`. ### Inputs and outputs * You may take the input as a function argument, through `STDIN`, etc. * You may return the output from a function, through `STDOUT`, etc. * You may index those numbers starting from `0` (in which case `N >= 0`) or from `1` (in which case `N > 0`), whichever suits you more. ### Test cases Those examples are indexed from `0`, so if you indexed from `1`, then add `1` to the numbers in the `N` column. ``` N Output 0 1 4 5 8 9 15 77 16 88 23 155 42 742 47 1113 121 4244 144 6888 164 9999 ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~21~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` DLR©œ^€®ịDḌḍ@DPȧµ#Ṫ ``` Input is 1-indexed. [Try it online!](http://jelly.tryitonline.net/#code=RExSwqnFk17igqzCruG7i0ThuIzhuI1ARFDIp8K1I-G5qg&input=MTIy) ### How it works ``` DLR©œ^€®ịDḌḍ@DPȧµ#Ṫ Main link. No arguments. µ Convert the chain to the left into a link. # Read n from STDIN and execute the link to the left for k = 0, 1, 2, ... until n value return a truthy value. D Convert D to base 10 (digit array). LR Construct the range from 1 to the length of the digit array. © Copy the range to the register. ® Yield the value of the register. œ^€ Take the multiset difference of each element of the range and the range itself. ịD Index into the digit array. Ḍ Convert each list of digits to integer. This yields all numbers with one suppressed digit. ḍ@D Test each of these numbers for divisibility by the suppressed digit from the digit array. P Take the product of the resulting Booleans. ȧ Logical AND with k (k would return 1). Ṫ Tail; extract the last (nth) element. ``` [Answer] # Pyth, 20 ``` e.f!s.e.x%s.D`Zksb1` ``` [Try it here](http://pyth.herokuapp.com/?code=e.f%21s.e.x%25s.D%60Zksb1%60&input=15&debug=0) or run the [Test Suite](http://pyth.herokuapp.com/?code=e.f%21s.e.x%25s.D%60Zksb1%60&input=15&test_suite=1&test_suite_input=1%0A5%0A9%0A16%0A17%0A24%0A43%0A48%0A122%0A145%0A165&debug=0) N is 1-indexed for this answer. Uses largely the same logic as my python script. Notable differences are using `.D` to delete the digit from the string during the test and using exception handling to deal with zero digits. [Answer] # Pyth, 26 bytes ``` e.f&!/J`Z\0!s%VsM.DLJUJjZT ``` [Test suite.](http://pyth.herokuapp.com/?code=e.f%26%21%2FJ%60Z%5C0%21s%25VsM.DLJUJjZT&test_suite=1&test_suite_input=1%0A5%0A9%0A16%0A17%0A24%0A43%0A48%0A122%0A145%0A165&debug=0) ``` e.f&!/J`Z\0!s%VsM.DLJUJjZT e.f The n-th number (Z) where: !/J`Z\0 Z does not contain "0" & and !s the following does not contain zero: sM.DLJUJ generate the set of the digits removed jZT all the digits %V modulus in parallel if Z is 324, the first set would be [24,34,32] the second set would be [3,2,4] the third set would be [24%3, 34%2, 32%4] ``` [Answer] # Python 2, 93 bytes ``` n=input();r=0 while n:r+=1;k=t=1;exec't&=(r/k/10*k+r%k)%(r/k%10or r)<1;k*=10;'*r;n-=t print r ``` *Very* inefficient. Input is 1-indexed. Test it on [Ideone](http://ideone.com/p7mOWN). ### Alternate version, 100 bytes The above code performs roughly **10x** divisibility tests where only **x** are required. At the cost of only **7 extra bytes**, efficiency can be improved dramatically, either by replacing `*r` with `*len(`r`)` or by refactoring the code as follows. ``` n=input();r=0 while n: r+=1;k=t=1 for _ in`r`:t&=(r/k/10*k+r%k)%(r/k%10or r)<1;k*=10 n-=t print r ``` This handles all test cases with ease, even on [Ideone](http://ideone.com/iqf7Nr). [Answer] ## JavaScript (ES6), ~~82~~ ~~78~~ 76 bytes ``` f=(n,k=0)=>n?f(n-!eval(/0/.test(++k)+`${k}`.replace(/./g,"|'$`$''%$&")),k):k ``` Input is 1-indexed. Works by building up a string of the form `false|'24'%3|'34'%2|'32'%4` and evaluating it. Strings are used because they are still syntactically valid in the single-digit case. The recursion limits this to about n=119. Iterative version for ~~88~~ ~~84~~ 82 bytes: ``` n=>{for(k=0;n;n-=!eval(/0/.test(++k)+`${k}`.replace(/./g,"|'$`$''%$&")));return l} ``` Edit: Saved 2 bytes thanks to @Dennis♦. [Answer] # Ruby, 90 ``` f=->n,s=?0{0while s.next![?0]||s[1]&&/t/=~s.gsub(/\d/){eval"#$`#$'%#$&>0"};n<1?s:f[n-1,s]} ``` Similar approach to Neil's Javascript answer, but significantly longer due to a lack of implicit type conversion (except that booleans do get converted into strings by `gsub`, which is nice). [Answer] # Ruby, 109 bytes ``` ->n{i=s=1;n.times{s=?0;s="#{i+=1}"while s[?0]||(0...x=s.size).any?{|i|(s[0,i]+s[i+1,x]).to_i%s[i].to_i>0}};s} ``` [Answer] ## [Hoon](https://github.com/urbit/urbit), 246 bytes ``` =+ x=0 |= n/@ =+ k=<x> =+ %+ levy %+ turn (gulf 0 (dec (lent k))) |= a/@ =+ (trim +(a) k) =+ (rash (snag a p) dit) ?: =(- 0) | =(0 (mod (fall (rust (weld (scag a p) q) dem) x) -)) (curr test &) ?: =(- &) ?: =(0 n) x $(n (dec n), x +(x)) $(x +(x)) ``` Ungolfed: ``` =+ x=0 |= n/@ =+ k=<x> =+ %+ levy %+ turn (gulf 0 (dec (lent k))) |= a/@ =+ (trim +(a) k) =+ (rash (snag a p) dit) ?: =(- 0) | =(0 (mod (fall (rust (weld (scag a p) q) dem) x) -)) (curr test &) ?: =(- &) ?: =(0 n) x $(n (dec n), x +(x)) $(x +(x)) ``` This...is really terrible. I feel dirty for posting this. Set `k` to the string form of the current number, map over the list `[0...(length k)-1]` splitting the string at that index (`a`). Get the `a` character, parse it to a number, and if it's `0` return no. Get the prefix of `a` and weld it to the other half of the split, parse to a number, check if the index divides it evenly. `++levy` returns yes iff calling the function on all the elements of the list is also yes. In this case, the function `++test` curried with yes, so it checks that all of the characters in `k` work. If we're at the 0th value, we return the current number, or else we recurse with n decremented (and increment `x`) [Answer] # [Lua](https://www.lua.org/), 199 bytes ``` n,m=1,...function e(n)for i=1,#n do x=n:sub(1,i-1)..n:sub(i+1)s=n:sub(i,i)if x==""or s=="0"or x%s~=0 then return x==""end end return true end while m+0>0 do n=n+1 m=m-(e(""..n)and 1 or 0)end print(n) ``` [Try it online!](https://tio.run/##LU7tCsIwDHyVUBFa1pUWBEGo7zJdxwIuk37gfvnqNXX7EZK73OXyKkOtpBfvtDFmKvTMuBIESWpaIyDzJ4Jxhc3TLZWHdBp7p4zZEXZOpWODGhVOLPRCsDVxt23YzunrLeQ5EMSQS6RdE2iEVgeXYwl//JnxFWDp7N22YPLUOVj80ssgheBkNbDKAZ@2qhneESnzw7XWy/UH "Lua – Try It Online") ]
[Question] [ Let's get right in to it. Your challenge is to make a program that does these things depending on its input: 1. If the input is a number, output "Prime" if the number is a prime number and "Not prime" if the number isn't a prime number. You can assume the number is > 1. 2. If the input is two numbers, output every single prime number between the first number (inclusive) and the second number (exclusive). You can assume the first number is smaller than the second. 3. Here comes the real challenge: if there's no input, the program should output a shorter version of itself that does exactly the same things as the original program. The program is not allowed to read from any file or from the web. The new program should also be able to do this. It should work for at least 5 generations. **The new program doesn't have to be in the same language as the first.** # Scoring: Your score is equal to the sum of the number of bytes in the first five generations of your submission (the submission itself being generation one). If the new code is hard-coded in to the first program, multiply the score by 1.5. **Lowest score wins.** (If you find some kind of flaw in the scoring system, please let me know in the comments) [Answer] # CJam, 66 + 65 + 64 + 63 + 62 = 320 ~~325~~ ~~355~~ bytes The following 5 lines are the first 5 generations: ``` { `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~ { `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~ { `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~ { `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~ { `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~ ``` The last one produces ``` {`(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~ ``` which still performs the prime tasks correctly. [Test it here.](http://cjam.aditsu.net/#code=%7B%20%20%20%20%20%60(%5C1%3E%2Bq~%5D(%5C_%2C%5B%22_~%22a%7B~mp'P%22Not%20p%22%3F%22rime%22%40%3B%7D%7B~%2C%3E%7Bmp%7D%2Cp%3B%7D%5D%3D~%7D_~&input=5%2013) ## Explanation The basic CJam quine is ``` {"_~"}_~ ``` which can be extended very easily to a generalised quine. For an explanation of this [see my answer here](https://codegolf.stackexchange.com/a/42122/8478). The basic ideas for this answer are: * Start the quine with a bunch of spaces and remove one of these when quining. * Get an array with all input numbers (0, 1 or 2) and choose some code to run depending on the length (by using it to index into an array). Here is a breakdown of the code inside the quine: ``` "Remove a space from the block's string representation:"; `(\1>+ ` "Get the string representation of the block."; (\ "Slice off the leading '{' and pull the remaining string back up."; 1> "Remove the first character, i.e. a space."; + "Prepend the '{' to the string again."; "Get the array of inputs and choose the code:"; q~](\_,[...]=~ q~ "Read and eval the input."; ] "Wrap everything (including the string for the block) in an array."; (\ "Shift off the string and swap it with the rest of the array."; _, "Duplicate the input array and get its length."; [...]= "Use it to index into this array."; ~ "If there are no inputs there will now be an array on the top of the stack, which ~ will unwrap. Otherwise there will be a block which ~ will evaluate."; "If there is no input, push the string needed for the quine and put it in an array for ~ to unwrap:"; "_~"a "If there is one input, test for primality:"; ~mp'P"Not p"?"rime"@; ~mp "Unwrap the input array and test for primality."; 'P"Not p"? "Choose either 'P' or 'Not p' depending on the result."; "rime" "Push the common part of the string."; @; "Pull up the quine string and discard it."; "If there are two inputs, print an array with all the primes in the range:"; ~,>{mp},p; ~ "Unwrap the array leaving N and M on the stack."; , "Get a range [0 1 .. N-1]."; > "Drop the first M elements, giving [M M+1 .. N-1]."; {mp}, "Filter to keep only the primes."; p "Pretty-print the array."; ; "Discard the quine string."; ``` [Answer] # C, Score: 553 + 552 + 551 + 550 + 549 = 2755, # Original Length: 553, Avg: 551 # EDIT: Only 5 generations, not 6! Looks like Martin beat me both in time and in score (by nearly an order of magnitude!). Ah, well. The original program is as follows: ``` char*c="char*c=%c%s%c;k=%d,a;p(c,v,d){for(v=2;v<c;v++)d+=!(c%cv);return!d;}int main(int C,char**V){if(C==1){printf(c,34,c,34,k/10,37,34,34,34,34,34,37,34);return 0;}a=atoi(V[1]);if(C==2)printf(p(a,0,0)?%cPrime%c:%cNot prime%c);if(C==3)for(;a<atoi(V[2]);a++)if(p(a,0,0))printf(%c%cd %c,a);}";k=10000,a;p(c,v,d){for(v=2;v<c;v++)d+=!(c%v);return!d;}int main(int C,char**V){if(C==1){printf(c,34,c,34,k/10,37,34,34,34,34,34,37,34);return 0;}a=atoi(V[1]);if(C==2)printf(p(a,0,0)?"Prime":"Not prime");if(C==3)for(;a<atoi(V[2]);a++)if(p(a,0,0))printf("%d ",a);} ``` I'll unravel it a little bit for better understanding, but for it to work properly the new lines are NOT part of the program. ``` char*c="char*c=%c%s%c;k=%d,a;p(c,v,d){for(v=2;v<c;v++)d+=!(c%cv);return!d;}int main(int C,char**V){if(C==1){printf(c,34,c,34,k/10,37,34,34,34,34,34,37,34);return 0;}a=atoi(V[1]);if(C==2)printf(p(a,0,0)?%cPrime%c:%cNot prime%c);if(C==3)for(;a<atoi(V[2]);a++)if(p(a,0,0))printf(%c%cd %c,a);}"; k=10000,a; p(c,v,d){ for(v=2;v<c;v++) d+=!(c%v); return!d; } int main(int C,char**V){ if(C==1){ printf(c,34,c,34,k/10,37,34,34,34,34,34,37,34); return 0; } a=atoi(V[1]); if(C==2) printf(p(a,0,0)?"Prime":"Not prime"); if(C==3) for(;a<atoi(V[2]);a++) if(p(a,0,0)) printf("%d ",a); } ``` The only thing that changes from program to program is the value of `k`, which loses exactly one digit every iteration. Interestingly, after the 5th generation, k becomes zero and stays there, so you can iterate ad infinitum and always have valid output. [Answer] # Tcl 253 + 252 + 251 + 250 + 249 = 1255 bytes ``` eval [set x { proc q a\ b {incr b;expr $a%$b?\[q $a $b]:$a==$b} proc 1 a {if [q $a 1] puts\ Prime {puts Not\ Prime}} proc 2 a\ b {while $b-\$a {if [q $a 1] puts\ $a;incr a}} proc 0 {} {puts "eval \[set x {[string ra $::x 1 end]}]"} $argc {*}$argv}] ``` The code needs to end with a newline. Explanation: ``` eval [set x {...}] ``` Write the code into x, then execute it. ``` $argc {*}$argv ``` Execute the command which name is the argument length, passing the arguments along. ``` proc q a\ b {incr b;expr $a%$b?\[q $a $b]:$a==$b} ``` Returns 1 when a is prime, 0 else. Uses recursion; the second backslash prevents command substitution from the interpreter and enables the one from `expr` (which is lazy). ``` proc 1 a {if [q $a 1] puts\ Prime {puts Not\ Prime}} proc 2 a\ b {while $b-\$a {if [q $a 1] puts\ $a;incr a}} ``` Straightforward implementation of the requirements. ``` proc 0 {} {puts "eval \[set x {[string ra $::x 1 end]}]"} ``` This is the quine, stripping a space from the beginning each time. ]
[Question] [ ## Input The name of a file in the raster graphics format of your choice. The chosen format must support at least 8 bits per channel and 3 channels. ## Output A file in the same format, with the same dimensions and pixels as the first, but whose pixels are grouped in descending order of the number of times they occur, sorted from left-to-right, top-to-bottom. * If certain colours of pixels appear the same number of times, their order is unspecified. * You must not overwrite the input file (use a different file name for the output). * Any and all third-party image processing libraries are permitted. ## Example ![panda](https://i.stack.imgur.com/Uj69P.png) Will give output similar to: ![sorted pixels from panda image](https://i.stack.imgur.com/lDgk4.png) Especially in the lower parts of the image some variation may occur, due to different tie breaking between colours of equal frequency. [Answer] # Mathematica, ~~125~~ 123 bytes ``` Export["a"<>#,i=ImageData@Import@#;Image@ArrayReshape[Join@@ConstantArray@@@SortBy[Tally[Join@@i],-Last@#&],Dimensions@i]]& ``` This defines an unnamed function which takes the file name in any common image format and writes the result to the a file with the same name but prepended with `a`. The result looks a bit different from the OP's, since Mathematica's `SortBy` breaks ties by default sort order, so the bottom bits where loads of ties occur look a bit neater: ![Not a panda.](https://i.stack.imgur.com/TvmiZ.png) The implementation itself is really straightforward: * `ImageData` to get a grid of colour values. * `Join` to flatten the array. * `Tally` to count the occurrence of each colour. * `SortBy[...,-Last@#&]` to sort by frequencies from highest to lowest. * `ConstantArray` and `Join` to expand the tallies again. * `ArrayReshape` to recover the original image shape (obtained with `Dimensions`). * `Image` to convert the data back to an image object. FYI, 22 bytes are used on file I/O. An equivalent version that takes and returns an image object comes in at 103 bytes: ``` (i=ImageData@#;Image@ArrayReshape[Join@@ConstantArray@@@SortBy[Tally[Join@@i],-Last@#&],Dimensions@i])& ``` [Answer] # J, ~~94~~ 81 bytes A function taking the name of a PNG file (with no transparency channel) and writing the result in the input filename prepended by "o". ``` f=.3 :0 load'graphics/png' (($a)$#/|:\:~(#,{.)/.~,a=.readpng y)writepng'o',y ) ``` ![input](https://i.stack.imgur.com/PTduA.png) ![output](https://i.stack.imgur.com/yTack.png) ## Method * Create a list of every color-number and the number of it's appearances * Sort list by number of it's appearances * Multiplicate every color-number equal it's appearances * Reshape the new list to the shape of the original image [Answer] # Python2/PIL, ~~244~~ ~~226~~ ~~225~~ ~~223~~ ~~222~~ ~~202~~ ~~186~~ ~~182~~ ~~170~~ 159 ``` from PIL.Image import* s=raw_input();i=open(s);g=list(i.getdata());i.putdata(sum([[c[1]]*-c[0]for c in sorted((-g.count(r),r)for r in set(g))],[]));i.save(2*s) ``` ### Changelog ``` <p><b>Edit 1:</b> saved 18 bytes with new algorithm.</p> <p><b>Edit 2:</b> saved 1 byte with remembering that Python 2 has int division without <code>from __future__ import division</code>. Whoops.</p> <p><b>Edit 3:</b> saved 2 bytes by swapping <code>cmp</code> for <code>key</code>.</p> <p><b>Edit 4:</b> saved 1 byte by clever unpacking. <code>w=i.size[0]</code> -> <code>w,h=i.size</code></p> <p><b>Edit 5:</b> moved <code>list()</code> to an earlier position, drastically improving runtime. No length change.</p> <p><b>Edit 6:</b> saved 20 bytes by remembering that there is also sequence sorting in Python. Probably slower, but also produces images more like the the Mathematica one.</p> <p><b>Edit 7:</b> saved 16 bytes by changing <code>putpixel</code> to a list and <code>putdata</code>. Under 200!</p> <p><b>Edit 8:</b> saved 4 bytes by changing <code>range(...)</code> to <code>...*[0]</code> since we don't need the values.</p> <p><b>Edit 9:</b> saved 12 bytes by converting the <code>for</code> loop to a <code>sum</code>.</p> <p><b>Edit 10:</b> saved 11 bytes by noticing that the image size doesn't matter anymore (since edit 7). Whoops v2.0.</p> ``` ## Shorter version by [stokastic](https://codegolf.stackexchange.com/users/30701/stokastic), 123 ``` from PIL.Image import* s=raw_input();i=open(s);d=list(i.getdata());i.putdata(sorted(d,key=lambda D:d.count(D)));i.save(2*s) ``` Well, let's at least try, even though it's already beaten. It's extremely slow, Panda processed for several minutes on my laptop. Saves with a filename with the original filename repeated twice. ![panda](https://i.stack.imgur.com/yMNJU.png) [Answer] # Python, 1197 bytes ``` # -*- coding: utf-8 -*- from __future__ import division from collections import Counter import png from sys import argv,exit script,file_name,output_file_name=argv def group(s,n): return zip(*[iter(s)]*n) def flatten(list_of_lists): result=[] for lst in list_of_lists: result.extend(lst) return result def group_list(old_list,tuples_per_list): new_list=[] i=1 appended_row=[] for item in old_list: appended_row.extend(flatten([item])) if i==tuples_per_list: new_list.append(appended_row) i=1 appended_row=[] else: i+=1 return new_list input_image=png.Reader(file_name) image_data=input_image.read() width=image_data[0] height=image_data[1] pixels=list(image_data[2]) if image_data[3]["alpha"]: ints_per_colour=4 elif image_data[3]["greyscale"]: ints_per_colour=2 else: ints_per_colour=3 colours=Counter(colour for row in pixels for colour in group(row,ints_per_colour)).most_common() pixel_list=flatten([element]*count for element,count in colours) ordered_rows=group_list(pixel_list,width) f=open(output_file_name,"wb") png_object=png.Writer(width,height,greyscale=image_data[3]["greyscale"],alpha=image_data[3]["alpha"]) png_object.write(f,ordered_rows) f.close() ``` [The `png` module I used](https://pypi.python.org/pypi/pypng). [Answer] # C# 413 Complete program. Pass the file name on command line, the output is saved in the same format as file "o". Not using some neat features of linq, like SelectMany and Enumerable.Range, as the program would be cleaner but longer. ``` using System.Collections.Generic;using System.Linq;using System.Drawing; class P{ static void Main(string[]a){ var d=new Dictionary<Color,int>();var b=new Bitmap(a[0]); int n,x,y,w=b.Width,h=b.Height; for (x=w;x-->0;)for(y=h;y-->0;){var p=b.GetPixel(x,y);d[p]=d.ContainsKey(p)?d[p]+1:1;} y=h;foreach(var q in d.OrderBy(v=>v.Value)){for(n=q.Value;n-->0;){ if(x<=0){x=w;--y;}b.SetPixel(--x, y, q.Key);}}b.Save("o"); }} ``` **Readable** formatting courtesy of VS2010 ``` using System.Collections.Generic; using System.Linq; using System.Drawing; class P { static void Main(string[] a) { var d = new Dictionary<Color, int>(); var b = new Bitmap(a[0]); int n,x,y,w = b.Width, h=b.Height; for (x = w; x-- > 0;) for (y = h; y-- > 0;) { var p = b.GetPixel(x, y); d[p] = d.ContainsKey(p) ? d[p]+1 : 1; } y = h; foreach (var q in d.OrderBy(v => v.Value)) { for (n = q.Value; n-- > 0; ) { if (x <= 0) { x = w; --y; } b.SetPixel(--x, y, q.Key); } } b.Save(a[0]+"."); } } ``` [Answer] # Python 2 : 191 bytes Here's my attempt. I figured I might be able to save some space by using `Counter`, but it didn't end up as small as Pietu1998's answer. ``` from collections import Counter from PIL import Image i=Image.open(raw_input()) s=reduce(lambda x,y:x+y,map(lambda(a,b):[a]*b,Counter(i.getdata()).most_common())) i.putdata(s) i.save("o.png") ``` ## Output from Panda ![Output from Panda](https://i.stack.imgur.com/QjhRk.png) ]
[Question] [ **Input:** you are given 2 integers, `n` and `k`. `n` is a positive (>= 1) integer, and `k` an integer, which is the number of times you are allowed to use `n`. **Output:** output all of the non-negative integers that can be formed using at most `k` `n`'s using these mathematical operations: `+`, `-`, `*`, `/`, and parentheses. **Edit: if your language supports removing elements from an array/set/etc., the requirement of non-negative integers is required. If not, then it is not required.** The only numerical value that can exist in the expression is n (however many times). If the value of the expression exceeds the maximum value of whatever data storage you have (such as `int` or `long`, etc.), you have to compensate for it (there is no maximum value that can be given for `n`). Speed is not important, but shortest code wins! **Bonuses:** * -50: include exponentiation in the list of mathematical operations. Exponentiation is defined to be that the base is some expression of n, not e = 2.71828... * -50: include the floor (or ceiling) functions if a given possible operation is not an integer. Examples ``` > 2 2 0 1 4 > 4 3 3 4 5 12 20 64 ... ``` (Sample inputs/outputs do not necessarily include bonuses) [Answer] # Javascript (E6) 215 (315 - 2\*50 bonus) ~~252~~ **Edit** Simplified. Correct bug of 0 missing Defined as a function, then counting 10 more byte for output using `alert()` *Important* Really this one is not valid according to the rules, because javascript can not handle big numbers. For instance with parameters 2,5 it can't find 2^2^2^2^2 (ie 2^65536). A number this big is 'Infinity' in javascript. **Golfed** ``` F=(n,k,g={})=>{k+=k-1;for (l=i=1;x=i.toString(6),l+=!!x[l],l<k;i++)if(x.split(0).length*2==l+1){for(s=[n,n],p=l;o=x[--p];) if(-o)b=s.pop(),a=s.pop(),s.push(o<2?a+b:o<3?a-b:o<4?a*b:o<5?a/b:Math.pow(a,b));else s.push(x[p]=n); r=Math.floor(s.pop());r>=0&isFinite(r)&!isNaN(r)&!g[r]&&(g[r]=x)}return Object.keys(g)}; ``` ~~To be golfed.~~ I have an idea I want to share: use a postfix notation. In postfix any type of expression is made just of values and operators - no parentheses needed. The postfix notation can be translated to usual algebraic infix notation - but that's out of scope in this challenge. **Usage** ``` alert(F(4,3)) ``` Output `1,2,3,4,5,8,12,16,20,32,64,252,256,260,1024,4096,65536,4294967296,1.3407807929942597e+154` **Ungolfed** ``` F=(n, k, g={})=>{ k += k - 1; // Count in base 6 - '0' means Value, '1'..'5' means operators // A valid expression starts with Value twice, then n operators intermixed with n-1 Values // x: Coded expression, l: Expression length, k Expression limit length from param for (l = i = 1; x = i.toString(6), l += !!x[l], l<k; i++) if (x.split(0).length*2 == l+1) // check balancing values/operators { for (s = [n,n], p = l; o = x[--p];) // Calc stack starts with N,N if (-o) // If not '0' b=s.pop(),a=s.pop(), // Do calc s.push(o<2 ? a+b : o<3 ? a-b : o<4 ? a*b : o<5 ? a/b : Math.pow(a,b)) else // Push value s.push(n) // r = Math.floor(s.pop()); // Last result in stack r >= 0 & isFinite(r) & !isNaN(r) & !g[r] && (g[r]=x) // Put in hashtable avoiding duplicates } // Uncomment this to see the postfix expression list // for (i in g) console.log(i, [n,n,...[...g[i]].reverse().map(v=>v>0?'x+-*/^'[v]:n)]) return Object.keys(g) // Retust list of hashtable keys } ``` **First version** this is more complicated but maybe easier to follow Display the postfix expression for each number ``` F=(n,k)=> { var i,l,s; var cmd; var op='n+-*/^' var bag = {} function Calc(val,pos,stack) { while (c = cmd[pos]) { if (c == 0) { stack.push(n); cmd[pos] = n pos++ } else { var b=stack.pop(), a=stack.pop(); stack.push(c < 2 ? a+b : c < 3 ? a-b : c < 4 ? a*b : c < 5 ? a/b : Math.pow(a,b)) cmd[pos]=op[c] pos++ } } var res = Math.floor(stack.pop()) if (res > 0 && isFinite(res) && !isNaN(res) && !bag[res]) { bag[res] = cmd } } k=k+k-3; for (i=1;s=i.toString(6), !s[k]; i++) { l=s.split(0).length; if (l+l-1==s.length) { var cmd = (s+'00').split('').reverse() Calc(n, 0, [], cmd.map(c=>op[c]).join(' ')) } } for (i in bag) { console.log(bag[i],'=', i) } } ``` **Usage** ``` F(4,3) ``` Output ``` [4, 4, "/"] = 1 [4, 4, "+", 4, "/"] = 2 [4, 4, 4, "/", "-"] = 3 [4, 4, "-", 4, "+"] = 4 [4, 4, "/", 4, "+"] = 5 [4, 4, "+"] = 8 [4, 4, "+", 4, "+"] = 12 [4, 4, "*"] = 16 [4, 4, "*", 4, "+"] = 20 [4, 4, "+", 4, "*"] = 32 [4, 4, "*", 4, "*"] = 64 [4, 4, "^", 4, "-"] = 252 [4, 4, "^"] = 256 [4, 4, "^", 4, "+"] = 260 [4, 4, "^", 4, "*"] = 1024 [4, 4, "+", 4, "^"] = 4096 [4, 4, "*", 4, "^"] = 65536 [4, 4, "^", 4, "^"] = 4294967296 [4, 4, 4, "^", "^"] = 1.3407807929942597e+154 ``` [Answer] # Python 2, 249 characters - 50 bonus = 199 ``` from operator import* n,k=input() def g(a): if len(a)==1:yield a[0] else: for i in range(1,len(a)): for l in g(a[:i]): for r in g(a[i:]): for o in[add,sub,mul,pow]: yield o(l,r) if r:yield l/r print set(map(abs,g([n]*k))) ``` Sample runs: ``` 2,2 set([0, 1, 4]) 4,3 set([32, 65536, 2, 3, 4, 5, 0, 1, 64, 252, 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096L, 12, 1024, 4096, 20, 4294967296L, -252, -12, -4, -3, 260]) ``` This claims the exponentiation bonus of -50 points. Allowing exponentiation can give some staggeringly large results for small inputs (remove `pow` from the list of operators to try without exponentiation). [Answer] ## Mathematica, 105 bytes - 100 bonus = 5 **Note:** This does not currently support parentheses. Fixing once the OP clarifies the challenge. If negative integers are okay, too, this scores **1** instead. ``` f[n_,k_]:=Union@Abs@Floor@ToExpression[ToString@n&~Array~k~Riffle~#<>""&/@Tuples[Characters@"*+/-^",k-1]] ``` Somewhat ungolfed: ``` f[n_, k_] := Union@Abs@Floor@ ToExpression[ ToString@n &~Array~k~Riffle~# <> "" & /@ Tuples[Characters@"*+/-^", k - 1] ] ``` I'm claiming both bonuses for including exponentiation and flooring non-integer results. Examples: ``` f[2, 2] f[4, 3] Out[1] = {0, 1, 4} Out[2] = {0, 3, 4, 5, 12, 20, 64, 252, 260, 1024, 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096} ``` [Answer] # Python 2.x: 32 (`132-(50+50)`) ``` from itertools import* l=list("+-*/")+["**"] f=lambda n,k:{abs(eval(j)) for j in(`k`+`k`.join(i)+`k`for i in product(l,repeat=n-1))} ``` I'll claim both bonuses: `x/y` behaves like you would expect `floor(x/y)` to behave, and it does support powers. Demo: ``` from itertools import* l=list("+-*/")+["**"] f=lambda n,k:{abs(eval(j)) for j in(`k`+`k`.join(i)+`k`for i in product(l,repeat=n-2))} f(2,2) Out[2]: {0, 1, 2, 3, 6, 8, 16} f(2,3) Out[3]: {0, 2, 3, 4, 6, 9, 12, 24, 27, 30, 81, 7625597484987L} f(3,2) Out[4]: {0, 1, 2, 3, 4, 5, 6, 8, 10, 14, 16, 18, 32, 65536} f(4,2) Out[5]: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 17, 18, 20, 30, 32, 34, 64, 32768, 65534, 65538, 131072, 2003529930406846464979072351560255750447825475569751419265016973710894059556311453089506130880933348101038234342907263181822949382118812668869506364761547029165041871916351587966347219442930927982084309104855990570159318959639524863372367203002916969592156108764948889254090805911457037675208500206671563702366126359747144807111774815880914135742720967190151836282560618091458852699826141425030123391108273603843767876449043205960379124490905707560314035076162562476031863793126484703743782954975613770981604614413308692118102485959152380195331030292162800160568670105651646750568038741529463842244845292537361442533614373729088303794601274724958414864915930647252015155693922628180691650796381064132275307267143998158508811292628901134237782705567421080070065283963322155077831214288551675554073345107213112427399562982719769150054883905223804357045848197956393157853510018992000024141963706813559840464039472194016069517690156119726982337890017641517190051133466306898140219383481435426387306539552969691388024158161859561100640362119796101859534802787167200122604642492385111393400464351623867567078745259464670903886547743483217897012764455529409092021959585751622973333576159552394885297579954028471943529913543763705986928913757153740001986394332464890052543106629669165243419174691389632476560289415199775477703138064781342309596190960654591300890188887588084733625956065444888501447335706058817090162108499714529568344061979690565469813631162053579369791403236328496233046421066136200220175787851857409162050489711781820400187282939943446186224328009837323764931814789848119452713007440220765680910376203999203492023906626264491909167985461515778839060397720759279378852241294301017458086862263369284725851403039615558564330385450688652213114813638408384778263790459607186876728509763471271988890680478243230394718650525660978150729861141430305816927924971409161059417185352275887504477592218301158780701975535722241400019548102005661773589781499532325208589753463547007786690406429016763808161740550405117670093673202804549339027992491867306539931640720492238474815280619166900933805732120816350707634351669869625020969023162859350071874190579161241536897514808261904847946571736601005892476655445840838334790544144817684255327207315586349347605137419779525190365032198020108764738368682531025183377533908861426184800374008082238104076468878471647552945326947661700424461063311238021134588694532200116564076327023074292426051582811070387018345324567635625951430032037432740780879056283663406965030844225855967039271869461158513793386475699748568670079823960604393478850861649260304945061743412365828352144806726676841807083754862211408236579802961200027441324438432402331257403545019352428776430880232850855886089962774458164680857875115807014743763867976955049991643998284357290415378143438847303484261903388841494031366139854257635577105335580206622185577060082551288893332226436281984838613239570676191409638533832374343758830859233722284644287996245605476932428998432652677378373173288063210753211238680604674708428051166488709084770291208161104912555598322366244868556651402684641209694982590565519216188104341226838996283071654868525536914850299539675503954938371853405900096187489473992880432496373165753803673586710175783994818471798498246948060532081996066183434012476096639519778021441199752546704080608499344178256285092726523709898651539462193004607364507926212975917698293892367015170992091531567814439791248475706237804600009918293321306880570046591458387208088016887445835557926258465124763087148566313528934166117490617526671492672176128330845273936469244582892571388877839056300482483799839692029222215486145902373478222682521639957440801727144146179559226175083889020074169926238300282286249284182671243405751424188569994272331606998712986882771820617214453142574944015066139463169197629181506579745526236191224848063890033669074365989226349564114665503062965960199720636202603521917776740668777463549375318899587866282125469797102065747232721372918144666659421872003474508942830911535189271114287108376159222380276605327823351661555149369375778466670145717971901227117812780450240026384758788339396817962950690798817121690686929538248529830023476068454114178139110648560236549754227497231007615131870024053910510913817843721791422528587432098524957878034683703337818421444017138688124249984418618129271198533315382567321870421530631197748535214670955334626336610864667332292409879849256691109516143618601548909740241913509623043612196128165950518666022030715613684732364660868905014263913906515063908199378852318365059897299125404479443425166774299659811849233151555272883274028352688442408752811283289980625912673699546247341543333500147231430612750390307397135252069338173843322950701049061867539433130784798015655130384758155685236218010419650255596181934986315913233036096461905990236112681196023441843363334594927631946101716652913823717182394299216272538461776065694542297877071383198817036964588689811863210976900355735884624464835706291453052757101278872027965364479724025405448132748391794128826423835171949197209797145936887537198729130831738033911016128547415377377715951728084111627597186384924222802373441925469991983672192131287035585307966942713416391033882754318613643490100943197409047331014476299861725424423355612237435715825933382804986243892498222780715951762757847109475119033482241412025182688713728193104253478196128440176479531505057110722974314569915223451643121848657575786528197564843508958384722923534559464521215831657751471298708225909292655638836651120681943836904116252668710044560243704200663709001941185557160472044643696932850060046928140507119069261393993902735534545567470314903886022024639948260501762431969305640666366626090207048887438898907498152865444381862917382901051820869936382661868303915273264581286782806601337500096593364625146091723180312930347877421234679118454791311109897794648216922505629399956793483801699157439700537542134485874586856047286751065423341893839099110586465595113646061055156838541217459801807133163612573079611168343863767667307354583494789788316330129240800836356825939157113130978030516441716682518346573675934198084958947940983292500086389778563494693212473426103062713745077286156922596628573857905533240641849018451328284632709269753830867308409142247659474439973348130810986399417379789657010687026734161967196591599588537834822988270125605842365589539690306474965584147981310997157542043256395776070485100881578291408250777738559790129129407309462785944505859412273194812753225152324801503466519048228961406646890305102510916237770448486230229488966711380555607956620732449373374027836767300203011615227008921843515652121379215748206859356920790214502277133099987729459596952817044582181956080965811702798062669891205061560742325686842271306295009864421853470810407128917646906550836129916694778023822502789667843489199409657361704586786242554006942516693979292624714524945408858422726153755260071904336329196375777502176005195800693847635789586878489536872122898557806826518192703632099480155874455575175312736471421295536494084385586615208012115079075068553344489258693283859653013272046970694571546959353658571788894862333292465202735853188533370948455403336565356988172582528918056635488363743793348411845580168331827676834646291995605513470039147876808640322629616641560667508153710646723108461964247537490553744805318226002710216400980584497526023035640038083472053149941172965736785066421400842696497103241919182121213206939769143923368374709228267738708132236680086924703491586840991153098315412063566123187504305467536983230827966457417620806593177265685841681837966106144963432544111706941700222657817358351259821080769101961052229263879745049019254311900620561906577452416191913187533984049343976823310298465893318373015809592522829206820862230332585280119266496314441316442773003237792274712330696417149945532261035475145631290668854345426869788447742981777493710117614651624183616680254815296335308490849943006763654806102940094693750609845588558043970485914449584445079978497045583550685408745163316464118083123079704389849190506587586425810738422420591191941674182490452700288263983057950057341711487031187142834184499153456702915280104485145176055306971441761368582384102787659324662689978418319620312262421177391477208004883578333569204533935953254564897028558589735505751235129536540502842081022785248776603574246366673148680279486052445782673626230852978265057114624846595914210278122788941448163994973881884622768244851622051817076722169863265701654316919742651230041757329904473537672536845792754365412826553581858046840069367718605020070547247548400805530424951854495267247261347318174742180078574693465447136036975884118029408039616746946288540679172138601225419503819704538417268006398820656328792839582708510919958839448297775647152026132871089526163417707151642899487953564854553553148754978134009964854498635824847690590033116961303766127923464323129706628411307427046202032013368350385425360313636763575212604707425311209233402837482949453104727418969287275572027615272268283376741393425652653283068469997597097750005560889932685025049212884068274139881631540456490350775871680074055685724021758685439053228133770707415830756269628316955687424060527726485853050611356384851965918968649596335568216975437621430778665934730450164822432964891270709898076676625671517269062058815549666382573829274182082278960684488222983394816670984039024283514306813767253460126007269262969468672750794346190439996618979611928750519442356402644303271737341591281496056168353988188569484045342311424613559925272330064881627466723523751234311893442118885085079358163848994487544756331689213869675574302737953785262542329024881047181939037220666894702204258836895840939998453560948869946833852579675161882159410981624918741813364726965123980677561947912557957446471427868624053750576104204267149366084980238274680575982591331006919941904651906531171908926077949119217946407355129633864523035673345588033313197080365457184791550432654899559705862888286866606618021882248602144999973122164138170653480175510438406624412822803616648904257377640956326482825258407669045608439490325290526337532316509087681336614242398309530806549661879381949120033919489494065132398816642080088395554942237096734840072642705701165089075196155370186264797456381187856175457113400473810762763014953309735174180655479112660938034311378532532883533352024934365979129341284854970946826329075830193072665337782559314331110963848053940859283988907796210479847919686876539987477095912788727475874439806779824968278272200926449944559380414608770641941810440758269805688038949654616587983904660587645341810289907194293021774519976104495043196841503455514044820928933378657363052830619990077748726922998608279053171691876578860908941817057993404890218441559791092676862796597583952483926734883634745651687016166240642424241228961118010615682342539392180052483454723779219911228595914191877491793823340010078128326506710281781396029120914720100947878752551263372884222353869490067927664511634758101193875319657242121476038284774774571704578610417385747911301908583877890152334343013005282797038580359815182929600305682612091950943737325454171056383887047528950563961029843641360935641632589408137981511693338619797339821670761004607980096016024823096943043806956620123213650140549586250615282588033022908385812478469315720323233601899469437647726721879376826431828382603564520699468630216048874528424363593558622333506235945002890558581611275341783750455936126130852640828051213873177490200249552738734585956405160830583053770732533971552620444705429573538361113677523169972740292941674204423248113875075631319078272188864053374694213842169928862940479635305150560788126366206497231257579019598873041195626227343728900516561111094111745277965482790471250581999077498063821559376885546498822938985408291325129076478386322494781016753491693489288104203015610283386143827378160946341335383578340765314321417150655877547820252454780657301342277470616744241968952613164274104695474621483756288299771804186785084546965619150908695874251184435837306590951460980451247409411373899927822492983367796011015387096129749705566301637307202750734759922943792393824427421186158236161317886392553095117188421298508307238259729144142251579403883011359083331651858234967221259621812507058113759495525022747274674369887131926670769299199084467161228738858457584622726573330753735572823951616964175198675012681745429323738294143824814377139861906716657572945807804820559511881687188075212971832636442155336787751274766940790117057509819575084563565217389544179875074523854455200133572033332379895074393905312918212255259833790909463630202185353848854825062897715616963860712382771725621313460549401770413581731931763370136332252819127547191443450920711848838366818174263342949611870091503049165339464763717766439120798347494627397822171502090670190302469762151278521956142070806461631373236517853976292092025500288962012970141379640038055734949269073535145961208674796547733692958773628635660143767964038430796864138563447801328261284589184898528048048844180821639423974014362903481665458114454366460032490618763039502356402044530748210241366895196644221339200757479128683805175150634662569391937740283512075666260829890491877287833852178522792045771846965855278790447562192663992008409302075673925363735628390829817577902153202106409617373283598494066652141198183810884515459772895164572131897797907491941013148368544639616904607030107596818933741217575988165127000761262789169510406315857637534787420070222051070891257612361658026806815858499852631465878086616800733264676830206391697203064894405628195406190685242003053463156621891327309069687353181641094514288036605995220248248886711554429104721929134248346438705368508648749099178812670565665387191049721820042371492740164460943459845392536706132210616533085662021188968234005752675486101476993688738209584552211571923479686888160853631615862880150395949418529489227074410828207169303387818084936204018255222271010985653444817207470756019245915599431072949578197878590578940052540122867517142511184356437184053563024181225473266093302710397968091064939272722683035410467632591355279683837705019855234621222858410557119921731717969804339317707750755627056047831779844447637560254637033369247114220815519973691371975163241302748712199863404548248524570118553342675264715978310731245663429805221455494156252724028915333354349341217862037007260315279870771872491234494477147909520734761385425485311552773301030342476835865496093722324007154518129732692081058424090557725645803681462234493189708138897143299831347617799679712453782310703739151473878692119187566700319321281896803322696594459286210607438827416919465162267632540665070881071030394178860564893769816734159025925194611823642945652669372203155504700213598846292758012527715422016629954863130324912311029627923723899766416803497141226527931907636326136814145516376656559839788489381733082668779901962886932296597379951931621187215455287394170243669885593888793316744533363119541518404088283815193421234122820030950313341050704760159987985472529190665222479319715440331794836837373220821885773341623856441380700541913530245943913502554531886454796252260251762928374330465102361057583514550739443339610216229675461415781127197001738611494279501411253280621254775810512972088465263158094806633687670147310733540717710876615935856814098212967730759197382973441445256688770855324570888958320993823432102718224114763732791357568615421252849657903335093152776925505845644010552192644505312073756287744998163646332835816140330175813967359427327690448920361880386754955751806890058532927201493923500525845146706982628548257883267398735220457228239290207144822219885587102896991935873074277815159757620764023951243860202032596596250212578349957710085626386118233813318509014686577064010676278617583772772895892746039403930337271873850536912957126715066896688493880885142943609962012966759079225082275313812849851526902931700263136328942095797577959327635531162066753488651317323872438748063513314512644889967589828812925480076425186586490241111127301357197181381602583178506932244007998656635371544088454866393181708395735780799059730839094881804060935959190907473960904410150516321749681412100765719177483767355751000733616922386537429079457803200042337452807566153042929014495780629634138383551783599764708851349004856973697965238695845994595592090709058956891451141412684505462117945026611750166928260250950770778211950432617383223562437601776799362796099368975191394965033358507155418436456852616674243688920371037495328425927131610537834980740739158633817967658425258036737206469351248652238481341663808061505704829059890696451936440018597120425723007316410009916987524260377362177763430621616744884930810929901009517974541564251204822086714586849255132444266777127863728211331536224301091824391243380214046242223349153559516890816288487989988273630445372432174280215755777967021666317047969728172483392841015642274507271779269399929740308072770395013581545142494049026536105825409373114653104943382484379718606937214444600826798002471229489405761853892203425608302697052876621377373594394224114707074072902725461307358541745691419446487624357682397065703184168467540733466346293673983620004041400714054277632480132742202685393698869787607009590048684650626771363070979821006557285101306601010780633743344773073478653881742681230743766066643312775356466578603715192922768440458273283243808212841218776132042460464900801054731426749260826922155637405486241717031027919996942645620955619816454547662045022411449404749349832206807191352767986747813458203859570413466177937228534940031631599544093684089572533438702986717829770373332806801764639502090023941931499115009105276821119510999063166150311585582835582607179410052528583611369961303442790173811787412061288182062023263849861515656451230047792967563618345768105043341769543067538041113928553792529241347339481050532025708728186307291158911335942014761872664291564036371927602306283840650425441742335464549987055318726887926424102147363698625463747159744354943443899730051742525110877357886390946812096673428152585919924857640488055071329814299359911463239919113959926752576359007446572810191805841807342227734721397723218231771716916400108826112549093361186780575722391018186168549108500885272274374212086524852372456248697662245384819298671129452945515497030585919307198497105414181636968976131126744027009648667545934567059936995464500558921628047976365686133316563907395703272034389175415267500915011198856872708848195531676931681272892143031376818016445477367518353497857924276463354162433601125960252109501612264110346083465648235597934274056868849224458745493776752120324703803035491157544831295275891939893680876327685438769557694881422844311998595700727521393176837831770339130423060958999137314684569010422095161967070506420256733873446115655276175992727151877660010238944760539789516945708802728736225121076224091810066700883474737605156285533943565843756271241244457651663064085939507947550920463932245202535463634444791755661725962187199279186575490857852950012840229035061514937310107009446151011613712423761426722541732055959202782129325725947146417224977321316381845326555279604270541871496236585252458648933254145062642337885651464670604298564781968461593663288954299780722542264790400616019751975007460545150060291806638271497016110987951336633771378434416194053121445291855180136575558667615019373029691932076120009255065081583275508499340768797252369987023567931026804136745718956641431852679054717169962990363015545645090044802789055701968328313630718997699153166679208958768572290600915472919636381673596673959975710326015571920237348580521128117458610065152598883843114511894880552129145775699146577530041384717124577965048175856395072895337539755822087777506072339445587895905719156736L} ``` [Answer] # J: -23 (77-50\*2) This doesn't work for `n<=2` yet, not sure why. I'll look into fixing this, but if anyone knows an anwer, please say so in the comments. ``` ~.>.|"."1 k,~"1 k,"1((,~(,&k=:'x',~":k))~)/"1((5^n),n)$;{;/(n=:n-1)#,:'*%+-^' ``` [Answer] # Haskell, 35 I'm not sure whether a function is enough or an actual program is required, so I'm posting two versions, both with 100 bonus. As a program, score of 80: ``` import Data.List d x=[flip x,x] n#1=[n] n#k=[(+),(-),(*),(/),(**)]>>=d>>=($n#(k-1)).map.($n) g[n,k]=filter(>0)$[1..read k::Int]>>=map floor.(read n#) main=interact$show.nub.g.words ``` or as a function, score of 35: ``` import Data.List d x=[flip x,x] n#1=[n] n#k=[(+),(-),(*),(/),(**)]>>=d>>=($n#(k-1)).map.($n) n%k=nub.filter(>0)$[1..k]>>=map floor.(n#) ``` sample output, for `(4%3)` or `echo 4 3|codegolf.exe`, sorted for your conveneince: ``` [1,2,3,4,5,8,12,16,20,32,64,252,256,260,1024,4096,65536,4294967296,13407807929942597099574024998205846127479365820592393 377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096,17976931348623159 077293051907890247336179769789423065727343008115773267580550096313270847732240753602112011387987139335765878976881441662 249284743063947412437776789342486548527630221960124609411945308295208500576883815068234246288147391311054082723716335051 0684586298239947245938479716304835356329624224137216] ``` The only thing that is a little weird about this is that the floating-point number `Infinity` floors to a humongous integer, but I hope this doesn't matter too much. [Answer] # J, -43 (53-2\*50) ``` [:~.[:<.[:|[:;(#~&x:)4 :'y/x'L:1[:([:{(<<"0'-+%*^')#~<:)] ``` This doesn't always work, because J tries to prevent calculations with numbers that are too large. If we are allowed to use (machine) floats, which simply get set to infinity on an overflow, we get the following, slightly shorter, for a score of 52-100 = -48: ``` [:~.[:<.[:|[:;#~4 :'y/x'L:1[:([:{(<<"0'-+%*^')#~<:)] ``` This is a version not in any way shape or from inspired by my previous J answer, so I'm posting it as a separate answer. Trivia: this might be the first time I've had to use an explicit function in a J answer. Usage (Yes, the little boxes are actual data structures in J, and are actually displayed like this.): ``` f =: [:~.[:<.[:|[:;(#~&x:)4 :'y/x'L:1[:([:{(<<"0'-+%*^')#~<:)] g =: [:~.[:<.[:|[:;#~4 :'y/x'L:1[:([:{(<<"0'-+%*^')#~<:)] test =: (/:~ L: 0) @: (g ; f) f. NB. Make a list of the result of both functions, and sort the answers. 5!:4 <'f' ┌─ [: ├─ ~. │ ┌─ [: ──┤ ├─ <. │ │ ┌─ [: └────┤ ├─ | │ │ ┌─ [: └────┤ ├─ ; │ │ ┌─ ~ ─── # │ │ ┌─ & ──┴─ x: └────┤ │ ┌─ 4 │ │ ┌─ : ─┴─ ,:'y/x' │ ├─ L: ─┴─ 1 └────┤ │ ┌─ [: │ │ ┌─ [: │ │ ├─ { └──────┼─────┤ ┌─ <'-';'+';'%';'*';'^' │ └─────────┼─ ~ ──────────────────── # │ └─ <: └─ ] 2 test 2 ┌─────┬─────┐ │0 1 4│0 1 4│ └─────┴─────┘ 4 test 3 ┌────────────────────────────────────────────────────────────────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────... │0 1 3 4 5 12 20 32 64 252 260 1024 65536 4.29497e9 1.34078e154 _│0 1 3 4 5 12 20 32 64 252 260 1024 65536 4294967296 134078079299425970995740249982058461274793658205923933777235614437217640300735469768018742981669034276900318581864860508537538828119465699... └────────────────────────────────────────────────────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────... /:~ 4 g 4 NB. _ is infinity in J. 0 1 2 3 4 5 7 8 9 12 16 20 24 28 36 48 60 64 68 80 128 248 256 264 1008 1020 1024 1028 1040 4096 65532 65540 262144 1.67772e7 4.29497e9 4.29497e9 1.71799e10 1.09951e12 1.84467e19 3.40282e38 1.34078e154 5.36312e154 3.4324e156 _ 4 f 4 |limit error | y/x ``` [Answer] # Python 2 - 212 bytes (262-50) Second ever code golf! ``` a,c,j=raw_input(),['+','-','*','/','**'],set() def e(f): for g in c: h=f.replace('.',g,1) if '.' in h:e(h) else: i=eval(h) if i>=0:j.add(i) for d in range(1,input()+1):e(((a+'.')*d)[:d*2-1]) print(j) ``` EDIT: Ok with brackets is gets a little larger: # With brackets - 354 bytes (404-50) ``` a,c,j=raw_input(),['+','-','*','/','**','+(','-(','*(','/(','**(',')+',')-',')*',')/',')**',')+(',')-(',')*(',')/(',')**(','(',')'],set() def e(f): for g in c: h=f.replace('.',g,1) if '.' in h:e(h) else: try: i=eval(h) if i>=0:j.add(i) except:pass for d in range(1,input()+1):e(((a+'.')*d)[:d*2-1]) print(j) ``` [Answer] # Haskell - 235 bytes - 100 bonus = 135 ``` import Control.Monad import Data.List (nub,sort) r(l:h:_)=filter(>=0)$sort$nub$map(floor.foldr(\op m->n`op`m)n)$replicateM(k-1)[(+),(-),(*),(/),(**)] where n=fromIntegral l;k=fromIntegral h main=interact(\s->show$r$map read$words s) ``` Tested with ``` $ printf "4 3" | ./pi [0,1,3,4,5,12,20,32,64,260,1024,65536,4294967296,13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096,179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216] ``` This result is achieved using `replicateM`. If we use the input `4 3`, `replicateM` will give us the following arrays of functions : `[[(+),(+)],[(+),(-)],[(+),(*)],[(+),(/)],[(+),(**)],[(-),(+)],[(-),(-)],[(-),(*)],[(-),(/)],[(-),(**)],[(*),(+)],[(*),(-)],[(*),(*)],[(*),(/)],[(*),(**)],[(/),(+)],[(/),(-)],[(/),(*)],[(/),(/)],[(/),(**)],[(**),(+)],[(**),(-)],[(**),(*)],[(**),(/)],[(**),(**)]]`, or more simply, `[[a->a->a]]`. Each array is then folded from the right using `n` as input : `[(+),(+)] = 4+(4+4) = 12`. Note that there is no operator precedence here : `[(*),(+)] = 4*(4+4) != (4*4)+4`. The given numbers are then floored, nubed, sorted and filtered for numbers less than 0. [Answer] # C, dc & bash utils – 259 (source) + 21 (to run) - 100 bonuses = 180 Save as `calc.c`: ``` #include <stdio.h> #define X printf int main(int c,char*v[]){int n,k,l,t,i,j;char*O="+-*/^";if(c!=3)return 0;n=atoi(v[1]);k=atoi(v[2]);for(l=1,t=k;t>1;t--)l*=5;for(i=0;i<l;i++){t=i;X("%d ",n);for(j=1;j<k;j++){X("%d%c",n,O[t%5]);t/=5;}X("d*vp\n");}return 1;} ``` Compile: ``` gcc -o calc calc.c ``` This will output permutations of `dc` compatible input. `dc` is a unlimited precision calculator, so can generate large numbers, it also has exponentiation. `dc` in default mode uses integer arithmetic so that's `floor` builtin, and the common commands `d*v` near the end effectively take the absolute value to increase the number of possible valid outputs. Running alone just generates a lot of output, e.g. ``` $ ./calc 6 2 6 6+d*vp 6 6-d*vp 6 6*d*vp 6 6/d*vp 6 6^d*vp ``` So to get the results, tie this into `dc | sort -n | uniq | xargs` to get the desired output, e.g. ``` $ ./calc 2 2 |dc|sort -n|uniq|xargs 0 1 4 $ ./calc 2 3 |dc|sort -n|uniq|xargs 0 1 2 3 6 8 16 $ ./calc 2 4 |dc|sort -n|uniq|xargs 0 1 2 3 4 5 6 8 9 10 12 14 16 18 32 36 64 256 $ ./calc 3 3 |dc|sort -n|uniq|xargs 0 1 2 3 4 6 9 12 18 24 27 30 81 216 729 19683 ``` The highest k it can handle is 13, but then you'll be waiting a long time for the results! ``` $ ./calc 2 8 |dc|sort -n|uniq|xargs 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 87 88 92 94 95 96 97 98 99 100 101 102 104 106 108 110 112 114 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 136 138 140 142 143 144 145 146 148 150 152 154 156 158 159 160 161 162 163 164 165 166 167 168 169 170 171 180 190 192 194 195 196 197 198 199 200 201 202 204 206 208 223 224 225 227 238 240 242 244 246 248 250 252 253 254 255 256 257 258 259 260 262 264 266 268 272 280 282 284 286 287 288 289 290 291 292 294 296 304 310 311 312 313 314 316 318 320 322 323 324 325 326 328 330 332 338 359 361 363 364 384 386 388 390 391 392 393 394 396 398 400 402 404 408 441 448 449 450 451 452 480 482 484 486 496 500 502 504 506 508 509 510 511 512 513 514 515 516 518 520 522 524 527 528 529 531 544 568 572 574 576 577 578 579 580 584 621 623 624 625 627 629 640 642 644 645 646 647 648 649 650 651 652 654 656 674 676 678 720 721 722 723 724 727 729 731 776 780 782 784 786 788 792 796 798 800 802 804 841 896 898 900 902 904 959 961 963 968 1008 1012 1014 1016 1018 1020 1022 1023 1024 1025 1026 1028 1030 1032 1034 1036 1040 1058 1087 1089 1091 1148 1150 1152 1154 1156 1158 1160 1200 1225 1246 1248 1250 1252 1254 1288 1290 1292 1294 1295 1296 1297 1298 1300 1302 1304 1352 1369 1440 1442 1444 1446 1448 1458 1521 1564 1566 1568 1570 1572 1598 1600 1602 1640 1681 1764 1796 1798 1800 1802 1804 1920 1921 1922 1923 1924 1936 2032 2040 2042 2044 2045 2046 2047 2048 2049 2050 2051 2052 2054 2056 2064 2116 2176 2177 2178 2179 2180 2209 2302 2304 2306 2308 2310 2312 2314 2316 2399 2401 2403 2450 2498 2500 2502 2584 2586 2588 2590 2591 2592 2593 2594 2596 2598 2600 2601 2704 2738 2884 2886 2888 2890 2892 2916 3120 3134 3136 3138 3200 3278 3279 3280 3281 3282 3364 3444 3598 3600 3602 3840 3842 3844 3846 3848 3969 4088 4090 4092 4094 4095 4096 4097 4098 4100 4102 4104 4225 4352 4354 4356 4358 4360 4608 4622 4624 4626 4802 4898 4900 4902 4998 4999 5000 5001 5002 5041 5176 5180 5182 5184 5186 5188 5192 5202 5329 5474 5476 5478 5774 5776 5778 5929 6084 6239 6241 6243 6272 6400 6557 6559 6560 6561 6563 6565 6887 6889 6891 7200 7225 7320 7684 7686 7688 7690 7692 7938 8064 8184 8186 8188 8190 8191 8192 8193 8194 8196 8198 8200 8320 8450 8708 8710 8712 8714 8716 9216 9248 9409 9602 9604 9606 9800 9801 9996 9998 10000 10002 10004 10082 10364 10366 10367 10368 10369 10370 10372 10402 10404 10406 10658 10816 10952 11552 12482 12544 13118 13120 13122 13124 13126 13778 14161 14400 14639 14641 14643 14884 15129 15374 15376 15378 15625 15874 15876 15878 16127 16129 16131 16376 16380 16382 16383 16384 16385 16386 16388 16392 16639 16641 16643 16898 16900 16902 17161 17422 17424 17426 17956 18496 18818 19206 19207 19208 19209 19210 19600 19602 19996 19998 20000 20002 20004 20162 20164 20166 20732 20734 20736 20738 20740 20808 21314 21316 21318 21904 23104 24964 25600 25921 26242 26244 26246 26569 26896 27556 28561 29282 30752 31752 32256 32257 32258 32259 32260 32764 32765 32766 32767 32768 32769 32770 32771 32772 33280 33281 33282 33283 33284 33800 34848 36864 37634 37636 37638 38412 38414 38416 38418 38420 39202 39204 39206 39998 40000 40002 40328 40804 41468 41470 41472 41474 41476 41616 42632 50625 51842 52486 52487 52488 52489 52490 53138 58564 61504 62500 63502 63504 63506 64512 64514 64516 64518 64520 65025 65530 65532 65534 65535 65536 65537 65538 65540 65542 66049 66560 66562 66564 66566 66568 67598 67600 67602 68644 69696 75272 76828 76830 76832 76834 76836 78408 80000 80656 81796 82942 82944 82946 83521 84100 85264 97344 102400 103682 103684 103686 104972 104974 104976 104978 104980 106274 106276 106278 107584 127008 129028 129030 129032 129034 129036 130050 130321 131064 131066 131068 131070 131071 131072 131073 131074 131076 131078 131080 132098 133124 133126 133128 133130 133132 135200 150544 152100 153662 153664 153666 155236 156816 158404 159998 160000 160002 161604 165888 195312 202500 207368 209948 209950 209952 209954 209956 212552 234256 254016 256036 258062 258064 258066 260098 260100 260102 261121 262136 262140 262142 262144 262146 262148 262152 263169 264194 264196 264198 266254 266256 266258 268324 270400 279841 307328 320000 329476 331774 331776 331778 334084 388129 390623 390625 390627 393129 405000 414736 417316 418609 419902 419904 419906 421201 422500 425104 456976 516128 520200 521284 522242 524284 524286 524287 524288 524289 524290 524292 526338 528392 531441 532512 611524 614654 614656 614658 617796 640000 663552 668168 781250 806404 809998 810000 810002 813604 837218 839806 839807 839808 839809 839810 842402 923521 1032256 1040400 1042568 1044482 1044484 1044486 1048572 1048574 1048576 1048578 1048580 1052674 1052676 1052678 1056784 1065024 1185921 1229312 1327104 1331716 1336334 1336336 1336338 1340964 1562500 1620000 1669264 1674434 1674436 1674438 1679612 1679614 1679616 1679618 1679620 1684802 1684804 1684806 1690000 2079364 2085134 2085136 2085138 2088968 2090916 2097148 2097150 2097152 2097154 2097156 2105352 2458624 2560000 2672672 3240000 3348872 3359228 3359230 3359232 3359234 3359236 3369608 3694084 4170272 4177936 4186116 4190209 4194302 4194304 4194306 4198401 4202500 4210704 4743684 5308416 5345344 5764801 6250000 6697744 6708100 6718462 6718464 6718466 6728836 6739216 7388168 8340544 8380418 8388606 8388607 8388608 8388609 8388610 8396802 9487368 9834496 10758400 12960000 13436928 14760964 14776334 14776336 14776338 14791716 16744464 16760834 16760836 16760838 16777212 16777214 16777216 16777218 16777220 16793602 16793604 16793606 16810000 18957316 18974734 18974736 18974738 18992164 21381376 21523360 24010000 25000000 26853124 26873854 26873856 26873858 26894596 29552672 29986576 33362176 33521672 33554428 33554430 33554432 33554434 33554436 33587208 37949472 38950081 43020481 43046719 43046721 43046723 43072969 47458321 50000000 53747712 59105344 67043344 67076100 67108862 67108864 67108866 67141636 67174416 75898944 86093442 92236816 99960004 99999998 100000000 100000002 100040004 107495424 108243216 134217728 172186884 200000000 214358881 214990848 236421376 252047376 260144641 268369924 268435454 268435456 268435458 268500996 276922881 285610000 303595776 368947264 400000000 406586896 429898756 429981694 429981696 429981698 430064644 454371856 536870912 688747536 737894528 859963392 1040578564 1073610756 1073676289 1073741822 1073741824 1073741826 1073807361 1073872900 1107691524 1416468496 1475635396 1475789054 1475789056 1475789058 1475942724 1536953616 1600000000 1719926784 2081157128 2147352578 2147483646 2147483647 2147483648 2147483649 2147483650 2147614722 2215383048 2754990144 2951578112 4032758016 4162056196 4162314254 4162314256 4162314258 4162572324 4294443024 4294705154 4294705156 4294705158 4294967292 4294967294 4294967296 4294967298 4294967300 4295229442 4295229444 4295229446 4295491600 4430499844 4430766094 4430766096 4430766098 4431032356 4569760000 5509980288 5903156224 6879707136 8324628512 8589410312 8589934588 8589934590 8589934592 8589934594 8589934596 8590458888 8861532192 10750371856 11019540676 11019960574 11019960576 11019960578 11020380484 11294588176 16649257024 17178820624 17179344900 17179869182 17179869184 17179869186 17180393476 17180917776 17723064384 22039921152 23612624896 25600000000 34359738368 44079842304 66597028096 67652010000 68718428164 68719476734 68719476736 68719476738 68720525316 69799526416 70892257536 110075314176 137438953472 152587890625 176319369216 274877906944 377801998336 549755813888 656100000000 705277476864 1090946826256 1099507433476 1099511627774 1099511627776 1099511627778 1099515822084 1108126760976 1410554953728 1785793904896 2199023255552 2803735918096 2821103188996 2821109907454 2821109907456 2821109907458 2821116625924 2838564518416 4347792138496 4398046511104 5642219814912 11284439629824 17592186044416 45137758519296 70368744177664 140737488355328 218340105584896 280925623418896 281474909601796 281474976710654 281474976710656 281474976710658 281475043819524 282025135308816 360040606269696 562949953421312 722204136308736 1125899906842624 1853020188851841 4503599627370496 10000000000000000 72057594037927936 184884258895036416 1152921504606846976 2177953337809371136 4611686018427387904 9223372036854775808 17324859965700833536 18444492376972984336 18446744056529682436 18446744073709551614 18446744073709551616 18446744073709551618 18446744090889420804 18448995976604549136 19631688197463081216 36893488147419103232 73786976294838206464 121439531096594251776 295147905179352825856 4722366482869645213696 1208925819614629174706176 7958661109946400884391936 79228162514264337593543950336 340282366920938463463374607431768211456 ``` Right now, it follows a strict `# # op # op # op ...` pattern, but you can get more numbers by switching the pattern around, e.g.: ``` (2 * 2 * 2) / (2 + 2) → 2 2 * 2 * 2 2 + / ``` The way this could be done is to treat the numbers and operators as symbols and permute them alike. You would get a lot of sequences not legal in `dc`, but let `dc` figure that out. Results pending... [Answer] **HASKELL 98 (198-100 bonus)** **edit:** I'd comment, but I can't, I'd suggest to treat unlimited range as a bonus It seems to me that a few answer miss a point: `using at most k n`. This means that f(4,3) can generate (4/4) = 1 or (4\*4)=16. Anyway that's my answer. I assume int/int to behave as floor. Exponentiation is included. ``` import Data.List f=[(+),(-),div,(*),(^)] a y f=f y o n x=filter(>0).map(a n.a x)$f++map flip f t[n,k]=(0:).nub.concat.take(fromInteger k)$iterate(>>=o n)[n] main=interact$show.sort.t.map read.words ``` --- ***HASKELL 111 (211-100 bonus)*** ``` import Data.List f=[(+),(-),div,(*),(^)] c=concatMap a y f=f y o n x=map(a n.a x)$f++map flip f l 1 _ s=0:s l k o s=c(l(k-1)o.filter(>0))[c o s,s] t[n,k]=l k(o n)[n] main=interact$show.sort.nub.t.map read.words ``` [Answer] # Ruby 181 - 50 - 50 = 81 ``` def p(k,n);k<=1?[n]:(1...k).reduce([]){|a,s|a+[:+,:-,:*,:/,:**].reduce([]){|a,o|b=p(s,n);b+a+b.product(p(k-s,n)).map{|a|a.reduce(&o) rescue nil}.compact}}.uniq.find_all{|k|k>=0};end ``` ]
[Question] [ # Challenge I'm sure you read the title, and came in to farm your rep, thinking its kids' stuff, but think again! You have to challenge each other in the *shortest* code to count the occurences of a string in another. For example, given the following input: > > aaaabbbbsssffhd > > > as a string, and the string > > s > > > should output > > 3 > > > # Rules Just before you smile and say, "Hey, I'll use ----," read this: * No use of external libraries, or your language's API. You have to implement it manually. Which means you can't use your language's built-in function or method for counting occurences * No file I/O * No connecting with a server, website, et cetera * In a case of `ababa`, where it starts with `aba` and if you read the last 3 letters it's also `aba`, you only count one**\*** *Thank you @ProgramFOX for that (the last rule)!* \***Hint**: When you count occurences, you can remove the ones you counted to avoid disobeying this rule I think the last 2 rules are just for rule benders! # Winning Criterion As previously stated the winner is the code with the less bytes used. The winner will be announced five days later (15 June 2014) # My Small Answer Here's my C++ answer, where it assumes that the `li` variable holds the string to check occurences in, and `l` is the string to look for in `f`: ### Ungolfed ``` int c = 0; while (li.find(lf) != string::npos) { int p = li.find(lf); int l = p + lf.length() - 1; for (p = p; p <= l; p++) { li[p] = static_cast<char>(8); } ++c; } ``` Of course, to use `std::string`, you have to include the string header file! ### Golfed ``` int c=0;while(li.find(lf)!=string::npos){int p=li.find(lf);int l=p+lf.length()-1;for(p=p;p<=l;p++){li[p]=static_cast<char>(8);}++c;} ``` ### Result The variable `c` is going to be the value of how many times the string was found --- ###                                                                           Enjoy! # Winner After a long wait [@Dennis](https://codegolf.stackexchange.com/a/31507/19785) answer wins with only 3 bytes, written in GolfScript [Answer] # GolfScript, 3 bytes ``` /,( ``` Assumes string and substring are on the stack. [Try it online.](http://golfscript.apphb.com/?c=ImFhYWFiYmJic3NzZmZoZCIicyIvLCg%3D) ### How it works ``` / # Split the string around occurrences of the substring. , # Get the length of the split array. ( # Subtract 1. ``` [Answer] ## JavaScript 32 Nothing really interesting here... ``` (p=prompt)().split(p()).length-1 ``` `split` main purpose is to create an array from a string using the delimiter in argument. [Answer] # J (7) `No use of external libraries` Check! `, or your language's API.` Check...? I don't know what an language API is. `You have to implement it manually` Check! `No file I/O` Check! `No connecting with a server, website, et cetera` Check! ``` +/a E.b ``` How it works: `E.` is `WindowedMatch`: the J Refsheet gives `'re' E. 'reread'` as example. This gives `1 0 1 0 0 0`. Then, the only thing left to do is simply adding this with `+/` (basically `sum`). I don't think this counts as using `your language's built-in function or method for counting occurences`, but that's disputable. EDIT: Just to be clear: ``` +/'aba'E.'ababa' 2 ``` [Answer] # C# - 73 ``` //a = "aba"; //b = "ababa"; Console.Write(b.Split(new string[]{a},StringSplitOptions.None).Length-1); // output = "1" ``` [Answer] # Python 2.x - 49 23 22 bytes This is assuming variable input is okay. Both strings can be of any length. Shortened @avall. ``` a='s' b='aaaabbbbsssffhd' print~-len(b.split(a)) ``` 49 bytes version, counts every instance of the substring ('aba' is in 'ababa' twice). ``` a='s' b='aaaabbbbsssffhd' print sum(a==b[i:i+len(a)]for i in range(len(b))) ``` [Answer] # Powershell 32 ``` ($args[0]-split$args[1]).count-1 ``` Works like this: ``` PS C:\MyFolder> .\ocurrences.ps1 ababa aba 1 ``` **Explanation:** Uses `-split` to separate the first argument by the second one, returns the size of the array resulting from the split (minus 1) [Answer] # Applescript, 106 bytes Applescript is a fun, but silly language to golf in. ``` on run a set AppleScript's text item delimiters to (a's item 1) (count of (a's item 2)'s text items)-1 end ``` Run with `osascript`: ``` $ osascript instr.scpt s aaaabbbbsssffhd 3 $ ``` [Answer] # C# - 66 Bytes ``` //s = "aba" //t = "ababa" Console.Write(t.Split(new[]{s},StringSplitOptions.None).Length-1); //Output: 1 ``` [Answer] # C ~~130~~ 120 Note: will probably crash if called with incorrect arguments. ``` r;main(int c,char**a){char*p=*++a,*q,*t;while(*p){for(q=a[1],t=p;*q&&*q==*t;q++)t++;*q?p++:(p=t,r++);}printf("%d\n",r);} ``` Ungolfed (kinda): ``` int main(int argc, char *argv[]) { int result = 0; char *ptr = argv[1]; while (*ptr) { char *tmp, *tmp2 = ptr; // str(n)cmp for (tmp = argv[2]; *tmp; tmp++, tmp2++) if (*tmp != *tmp2) break; if (*tmp) { ptr++; } else { result++; ptr += tmp; } } printf("%d\n", result); } ``` Old version with `strstr` and `strlen`: 103 ``` l;main(int c,char**a){char*p=a[1];l=strlen(a[2]);while(c++,p>l)p=strstr(p,a[2])+l;printf("%d\n",c-5);} ``` [Answer] # Delphi XE3 (113) Takes 2 strings, removes substring from string and substracts new length from old length followed by a division of the substring length. ``` function c(a,b:string):integer;begin c:=(Length(a)-Length(StringReplace(a,b,'',[rfReplaceAll])))div Length(b)end; ``` Testing: > > c('aaaabbbbsssffhd','s') = 3 > > c('aaaabbbbsssffhd','a') = 4 > > > > [Answer] # Lua (48) So i thought I could just submit another answer, this time in lua. Its very possible this could be improved a lot, im very new to this. ``` print((a.len(a)-a.len(a.gsub(a,b,"")))/b.len(b)) ``` [Answer] # Fortran 90: 101 Standard abuse of implicit typing, works for any length arrays `a` and `b`, though one should expect that `len(a) < len(b)`. ``` function i();i=0;k=len(trim(b))-1;do j=1,len(trim(a))-k;if(a(j:j+k)==b(1:1+k))i=i+1;enddo;endfunction ``` This function must be `contain`ed within a full program to work. `a` and `b` are received from stdin and can be entered either on the same line (either comma or space separated) or on different lines. Compile via `gfortran -o main main.f90` and execute as you would any other compiled program. ``` program main character(len=256)::a,b read*,a,b print*,i() contains function i() i=0 k=len(trim(b))-1 do j=1,len(trim(a))-k if(a(j:j+k)==b(1:1+k))i=i+1 end do end function end program main ``` Tests: ``` >ababa aba 2 ``` I could make the above return 1 if I add 4 characters (`,k+1`) for the `do` loop ``` > aaaabbbbbsssffhd s 3 ``` [Answer] # Mathematica ~~26~~ 23 Works like Dennis' algorithm, but wordier: ``` Length@StringCases[a,b] ``` Three chars shaved off by Szabolics. [Answer] ## C++ 225 ``` int n,k,m; int main() { string s1,s2; cin>>s1; cin>>s2; int x=s1.size(),y=s2.size(); if(x>=y) { for(int i=0;i<x;i++) { k=0,m=0; for(int j=0;j<y;j++) { if(s2[j]==s1[i+m]) { k++,m++; } else break; } if(k==y) { n++; i+=(y-1); } } } cout<<n<<endl; return 0; } ``` [Answer] ## Java (38) ``` System.out.print(a.split(b).length-1); ``` (The question did not require a complete program or function.) [Answer] # Cobra - 25 ``` print a.split(b).length-1 ``` [Answer] # [K/Kona](https://github.com/kevinlawler/kona) 6 ``` +/y~'x ``` where `x` is the string and `y` the substring. `~` is the negate operator, with `'`, it is applied to every element in `x`; it will return `0` if it does not match and `1` if it does match. Since it is applied element-wise, the result of `y~'x` is a vector, the `+/` then sums the result giving the total number of occurrences. Unfortunately, this method requires that `y` is only one character, otherwise we will be comparing a multi-character string to a single character string, resulting in a `length error`. ]
[Question] [ Let us call a prime \$p\$ an \$(m,k)\$-distant prime \$(m \ge 0, k \ge 1, m,k \in\mathbb{Z})\$ if there exists a power of \$k\$, say \$k^x (x \ge 0, x \in\mathbb{Z})\$, such that \$|k^x-p| = m. \$ For example, \$23\$ is a \$(9,2)\$-distant prime as \$|2^5 - 23| = 9\$. In other words, any prime which is at a distance of \$m\$ from some non-negative power of \$k\$ is an \$(m,k)\$-distant prime. For this challenge, you can either: * Take input three integers \$n, m, k\; (n,k \ge1, m \ge0)\$ and print the \$n^{th}\$ \$(m,k)\$-distant prime. You do not need to handle inputs where answer does not exist. You can take \$n\$ as zero-indexed if you want. * Take \$n, m, k\$ as input and print the first \$n\$ \$(m,k)\$-distant primes. * Or, take only \$m\$ and \$k\$ as input and print all \$(m,k)\$-distant primes. It is fine if your program runs infinitely and does not terminate if there aren't any \$(m,k)\$-distant primes, or all such primes have already been printed. # Examples ``` m,k -> (m,k)-distant primes 1,1 -> 2 0,2 -> 2 1,2 -> 2, 3, 5, 7, 17, 31, 127, 257, 8191, 65537, 131071, 524287, ... 2,2 -> 2, 3 2,3 -> 3, 5, 7, 11, 29, 79, 83, 241, 727, 6563, 19681, 59051 3,2 -> 5, 7, 11, 13, 19, 29, 61, 67, 131, 509, 1021, 4093, 4099, 16381, 32771, 65539, 262147, ... 20,2 -> None 33,6 -> 3 37,2 -> 41, 53, 101, 293, 1061, 2011, 4133, 16421, ... 20,3 -> 7, 23, 29, 47, 61, 101, 223, 263, 709, 2207, 6581, 59029, 59069, 177127, 177167 20,7 -> 29, 2381, 16787 110,89 -> 199, 705079 ``` # Rules * Standard loopholes are forbidden. * You may choose to write functions instead of programs. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (in bytes) wins. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` ^ᵗ↙X≜ℕ₁ᵗ~ȧʰ+ṗ ``` [Try it online!](https://tio.run/##AT4Awf9icmFjaHlsb2cy/3vihrDigoLhuol94bag/17htZfihplY4omc4oSV4oKB4bWXfsinyrAr4bmX//9bMywyXQ "Brachylog – Try It Online") ``` ^ᵗ↙X≜ℕ₁ᵗ~ȧʰ+ṗ Given input [A,B] ^ᵗ↙X≜ Try every X: [A, B^X] ℕ₁ᵗ B^X ≥ 1 ~ȧʰ Try [A, B^X] and [-A, B^X] + Sum of A + B^X or -A + B^X ṗ is a prime. ``` [Answer] # JavaScript (ES6), 103 bytes Expects `(m)(k)(n)` and returns the \$n\$-th \$(m,k)\$-distant prime (1-indexed). ``` m=>k=>F=(n,p)=>(g=d=>p%--d?g(d):d^1)(p)|(g=(n,K=1)=>K>n||K<n&k>1&&g(n,K*k))(p+m)*g(p-m)||--n?F(n,-~p):p ``` [Try it online!](https://tio.run/##ZVHbTtwwEH3fr/BLFxuc4LFjO4EmqA/lZSV@YBtQtGFTCLloQZWqbvvry4yzF1Af7IzPnDkzZ/Jc/apeV5un8S3qh/pxt853XV60eXGb816OIi94k9d5MX6Jovqm4bW4qu9B8FFsMYGURQ5IWhT9drv42s/bAubzhvDzViDtohPnDR@jTmy3UdTf3GIq@jeKq3F3vZwxtgTJGB4oJbu8ZFHBNKEKUf0fChPqT6hkRjKLEHLxGFLSGGiLVwoZvp21htIGlMen1YlO8R3HMUnqSVJ/kjwkUDs9Jk6NUEVnGOJJEdUJAp66OuvwDZlLqVGmLJCSCS1AHZVOMhDok5yjWadBsVghAkpjmKjMhJsQZ0jaaO/3zqjYaUhOjgyy3cfVBTu0ArRkjygNbam9CnZCRCNoRYMlQDLgEprgsCpF2/7ggyTNNDz1p@pJLaC0Ck82tFZhN/ulEB0/juygDe2nr/OHHv7T7yCBYBoZaeAAKJlmEkq25wCtxiurfDYrZ/F62HyvVj85X3aStZLdlYLlBfuDtauhfx1eHuOXoTlkl@ju22ZT/eZ3ooy7auT8QbI@lKx5J3greM8uGAhMPw9PPT/78XYmxPXsr9i9Aw "JavaScript (Node.js) – Try It Online") ### Commented ``` m => k => // outer functions taking m and k F = (n, p) => // inner recursive function taking n ( // and using p = current prime candidate g = d => // g is a recursive function taking a divisor d p % --d ? g(d) // decrement d until it divides p : d ^ 1 // return a truthy value if p is composite )(p) | // initial call to g with d = p ( // g = (n, // g is a recursive function taking n = p + m or p - m K = 1) => // and K = k ** x K > n || // if K is greater than n K < n & k > 1 && // or K is less than n and k is greater than 1: g(n, K * k) // do a recursive call with k raised to the next exponent )(p + m) * // unless the above function is truthy for p + m ... g(p - m) // ... and for p - m (meaning that we don't have |k**x-p|=m) // or p was composite: || --n // decrement n ? // if all of the above is truthy: F(n, -~p) // try again with p + 1 : // else: p // success: return p ``` [Answer] # [Haskell](https://www.haskell.org/), ~~96~~ ~~88~~ 70 bytes * Saved 8 bytes thanks to @ovs! * Saved 18 bytes thanks to @Delfad0r! ``` m!k=[p|p<-[2..],all((>0).mod p)[2..p-1],elem m[abs$k^i-p|i<-[0..m+p]]] ``` [Try it online!](https://tio.run/##dc@9CoMwFAXg3ae4AQelJuQHapXavVMfQFJIqdBgoqE6@u422qGg6Xbz5YRz81JD2xgzzxa1Ve0md8Y1J0RmypgkudCU2P4JLl3QYSazxjQWbK0eQ9zeNXaT9i8oIfbgpJSzVbqDsoTrDZI0Wk8VPPsIwL11N0IMo2obYH5giIWYIr7lYk3vmPuBh9MciRALn8b4d8EDZcsOQqDj1vPF8z91dN/Hv54Hv84oOhXzBw "Haskell – Try It Online") ``` m!k= -- The function's called with m!k [p| -- Yield every p when p <- [2..], -- p is an integer >= 2 all((>0).mod p)[2..p-1], -- p is prime all -- For all [2..p-1] -- possible divisors of p, mod p -- p mod that number >0 -- is greater than 0 elem m[abs$k^i-p|i<-[0..m+p]] -- Make sure it's (m, k)-distant ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 bytes ``` 2Ẓȧ+,_ɗ⁴æḟƑƇɗɗ# ``` [Try it online!](https://tio.run/##ASwA0/9qZWxsef//MuG6ksinKyxfyZfigbTDpuG4n8aRxofJl8mXI////zL/M/8xMA "Jelly – Try It Online") Takes three command line arguments \$k\$, \$m\$, \$n\$. Produces the first \$n\$ \$(m, k)\$-distant primes. ## Explanation ``` 2Ẓȧ+,_ɗ⁴æḟƑƇɗɗ# Main dyadic link 2 Starting with 2 # Find the first n numbers p such that ɗ ( Ẓ p is prime ȧ and ɗ ( +,_ɗ⁴ p ± m Ƈ Filter items that Ƒ don't change when æḟ rounded down to the nearest power of k ɗ ) ɗ ) ``` [Answer] # [R](https://www.r-project.org/), 79 bytes ``` function(m,k)repeat{while(sum(!(T=T+1)%%2:T)>1|all(abs(k^(0:T)-T)-m))1;show(T)} ``` [Try it online!](https://tio.run/##K/qfmx1fUJSZm1ps@z@tNC@5JDM/TyNXJ1uzKLUgNbGkujwjMydVo7g0V0NRI8Q2RNtQU1XVyCpE086wJjEnRyMxqVgjO07DACiiC0S5mpqG1sUZ@eUaIZq1CKM1jHSMNf8DAA "R – Try It Online") Prints all (m,k)-distant primes. [Answer] # [JavaScript (V8)](https://v8.dev/), 91 bytes ``` m=>k=>{for(i=1;;(g=v=>!v+!~-k+v%k?~-v:g(v/k))(i-m)*g(i+m)+~-j||print(i))for(j=++i;i%--j;);} ``` [Try it online!](https://tio.run/##bczRCoIwFMbx@55CL4RzGqPNQVpr9iwSKGdiicluMl99KUEk8@Lc/Pifz5aufN566gbucl8Z35qiMcWrevRARmq6SCGEhto4U8SOxRNvmEua68TduQZ3aBCBeIv7Goi1yCZux7Hr6T4AIS4z1jBGmhLOrUb99hVEkUSYT3873C0kZkrXJENKt0mtSQVVGs6rpTquKdt@VCFl/yTlTPnpR/4D "JavaScript (V8) – Try It Online") (`i<1000` is added so you can test it with multiple testcases.) This function takes only \$m\$ and \$k\$ as input, and prints all \$\left(m,k\right)\$-distant primes (in language supported integer range). ]
[Question] [ **This question already has answers here**: [I double the source, you double the output!](/questions/132558/i-double-the-source-you-double-the-output) (162 answers) Closed 6 years ago. Related: [I double the source, you double the output!](/q/132558/71806) --- When *Steve Jobs* launched the iPhone 3G, the slogan said > > Twice as fast, half the price > > > I changed the word *fast* to *long* to better represent this challenge. ### Objective Write a program that outputs a non-zero, **even** integer. If the source code is doubled, the value of the output must be cut off by half. To double the source in a Unix shell (with Core Utilites): ``` cat source.txt source.txt > doubled-source.txt ``` ### Rules & Requirements Now the requirement has changed and the task has been even more challenging! * You must build **a full program**. * The initial source is **no longer required** to be at least 1 byte long. An empty program qualifies as long as the output is correct. * Both the integers must be in base 10 (outputting them in any other base or with scientific notation is forbidden), and must **not** be zero. The integer is no longer required to be positive, so if you like a negative number, it's OK. * Your program must not take input (or have an unused, empty input) and must not throw any error (compiler warnings are not considered errors). Exit code must be zero. * Outputting the integers with trailing / leading spaces / newlines is allowed, as long as only one integer is output. * You can't assume a newline between copies of your source. If you need one, **clarify it**. See the Unix shell command above. * [Standard loopholes are forbidden.](https://codegolf.meta.stackexchange.com/questions/1061) Because this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest (original, undoubled) code in each language wins! ### Extras Please give description / explanation to your code if possible. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 12 bytes ``` (()()[][{}]) ``` Outputs 2. [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0NDU0MzOja6ujZW8/9/AA "Brain-Flak – Try It Online") The doubled program outputs 1. [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0NDU0MzOja6ujZWE5n9/z8A "Brain-Flak – Try It Online") ### Explanation This code pushes 2 + stack height - top of stack. Initially, this is 2 + 0 - (implicit) 0 = 2. When this code is run again, it pops the existing 2 and pushes 2 + 1 - 2 = 1. [Answer] # [Python 2](https://docs.python.org/2/), 35 34 bytes Uses a concept similar to that of [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard) in the [double challenge](https://codegolf.stackexchange.com/a/132565/72350) with an [improvement](https://codegolf.stackexchange.com/a/140886/72350) I found to his original code. Here I use the fact that the length of the file is 34 bytes long. Meaning it is equal to 4 modulo 6. (`34%6 = 4`). The double source code would have a length of 68. And `68%6 = 2`, which is exactly what we want. ``` print open(__file__,"a").tell()%6# ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EIb8gNU8jPj4tMyc1Pl5HKVFJU68kNSdHQ1PVTPn/fwA) [Double source code](https://tio.run/##K6gsycjPM/r/v6AoM69EIb8gNU8jPj4tMyc1Pl5HKVFJU68kNSdHQ1PVTJmwiv//AQ) # Explanation This opens the source code file in append mode ``` open(__file__,"a") ``` We then find the current position in the file, this will be at the end of the file due to opening in append mode ``` open(__file__,"a").tell() ``` We print this length modulo 6 ``` print open(__file__,"a").tell()%6 ``` And add a comment, so that doubling the source code does not execute more code ``` print open(__file__,"a").tell()%6# ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ¬‘ ``` Outputs 2, **[Try it online!](https://tio.run/##y0rNyan8///QmkcNM/7/BwA "Jelly – Try It Online")** While ``` ¬‘¬‘ ``` Outputs 1, **[Try it online!](https://tio.run/##y0rNyan8///QmkcNM8DE//8A "Jelly – Try It Online")** ### How? The default input to a monadic chain is zero... ``` ¬‘ - Main link: no arguments ¬ - logical not -- not the implicit input of 0 to yield 1 ‘ - increment -- increment 1 to yield 2 - implicit print if this is the end of the program, otherwise... ... ¬‘ - continues the monadic chain: ¬ - logical not -- not the 2 to yield 0 ‘ - increment -- increment 0 to yield 1 - implicit print if this is the end of the program ``` --- The two byters: ``` Ị‘ - insignificant (abs(z)<=1); increment Ṇ‘ - non-vectorising logical not; increment ``` would work too. [Answer] # [Ly](https://github.com/LyricLy/Ly), 7 bytes ``` 2y1-+-N ``` [Try it online!](https://tio.run/##y6n8/9@o0lBXW9fv/38A "Ly – Try It Online") Simple port of the [Brain-Flak answer](https://codegolf.stackexchange.com/a/140881/70424). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes Outputs **4** ``` 6rÍ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/frOhw7///AA "05AB1E – Try It Online") **Doubled Source** Outputs **2** ``` 6rÍ6rÍ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/frOhwLwj//w8A "05AB1E – Try It Online") **Explanation** ``` 6 # push 6 r # reverse the stack (does nothing) Í # subtract 2 ``` With the doubled source we continue with ``` 6 # push 6 r # reverse the stack (puts 4 on top) Í # subtract 2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ®‘!İ©Ḥµ ``` [Try it online!](https://tio.run/##ARgA5/9qZWxsef//wq7igJghxLDCqeG4pMK1//8 "Jelly – Try It Online") Outputs 2. Duplicated Source: ``` ®‘!İ©Ḥµ®‘!İ©Ḥµ ``` [Try it online!](https://tio.run/##y0rNyan8///QukcNMxSPbDi08uGOJYe2onH//wcA "Jelly – Try It Online") Outputs 1. [Answer] # sh, 50 bytes ``` #!/bin/sh expr 200 / `wc -c $0 | cut -c 1-3` exit ``` ]
[Question] [ Write a program or function that given a string (or your language's equivalent), determine if the string is a word, or not, and output a truthy or falsy value. *(This is not a duplicate of [Is this even a word?](https://codegolf.stackexchange.com/questions/45295/is-this-even-a-word) The incorrect words are generated in a very different way that I believe makes this a completely different challenge)* The words will all be lowercase, between 5 and 10 characters, and have no apostrophes. The correct words are a randomly selected subset of the SCOWL English words list (size 50). The incorrect words are generated via two methods: swapping and substitution. The "swapping" words are generated using a modified [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) on the letters of randomly selected (real) words. Instead of swapping the letters every time, a letter may or may not be swapped (the probability varies, so some words will be more realistic than others). If the new word matches an existing word, the result is discarded and it generates another word. The "substitution" words are generated using a similar method, but instead of swapping the letter with another letter, each letter has a chance of being replaced with another random letter. Each method is used to generate 50% of the fake words. ## Scoring Your function must be less than **150 bytes**. The scoring is determined as follows: ``` percentage of answers correct + ((150 - length of program) / 10) ``` ## Rules Since this deals with a large number of test cases (each wordlist is 1000 words), an automated testing program is fine. The automated tester does not count towards the length of the program; however, it should be posted so that others are able to test it. * No loopholes. * No spelling/dictionary related built-ins. ## Resources **List of words:** <http://pastebin.com/Leb6rUvt> **List of not words (updated)**: <http://pastebin.com/rEyWdV7S> **Other resources** (SCOWL wordlist and the code used to generate the random words): <https://www.dropbox.com/sh/46k13ekm0zvm19z/AAAFL25Z8ogLvXWTDmRwVdiGa?dl=0> [Answer] # PHP, 64.9 (50%, 1 byte) Well, I'm not really sure if this is an acceptable answer, but here goes: ``` 1 ``` Run like this: ``` echo '1' | php -- word ``` Obviously, for an equally large list of correct and incorrect words, this results in 50% false positives and 0% false negatives, so 50% correct. As the program is 1 byte though, you're getting the maximum possible length bonus (zero-length answers notwithstanding). [Answer] ## CJam, 78.6 (78.5%, 149 bytes) ``` l2b0"(1»\]ÁûKëá*ßð%äp`Ï_5ÚY÷:Ä$î ëQXV)­JKÆ¿-(ivHì?{'à\ßÐiCæz°P0ãª/îÏèÄ)WCÅH±Ø^2Ô¥? î'jJ#OAõ~×cA$[8,ô#~¬#7>"255b2b+= ``` Matches 696 real words and doesn't match 874 non-words, giving `1570/2000 = 0.785`. Tested on the online interpreter in Chrome - I'm not sure if the permalink will work in Firefox. In case it doesn't, the string, which contains unprintables, can be obtained by ``` [24 40 5 49 25 187 92 93 193 251 158 131 75 235 131 225 42 129 223 240 14 37 228 112 96 207 95 53 218 89 247 58 3 196 3 36 1 238 143 32 235 139 81 15 88 86 41 20 173 74 75 198 191 45 40 105 118 72 236 63 123 39 224 15 15 92 223 208 16 147 105 140 67 16 230 122 176 80 26 48 133 227 148 144 170 47 238 207 232 136 24 196 41 87 132 67 197 72 177 216 94 24 50 212 165 63 10 238 39 106 74 35 79 65 245 126 215 136 6 99 65 36 91 56 44 143 155 150 244 35 126 172 35 55 62]:c ``` The program merely hashes the input and performs a lookup based on 1077 possible buckets. I tried regex golfing this, but the non-words were too close to real words for it to be useful. [Try it online!](http://cjam.aditsu.net/#code=l2b0%22%18(%051%19%C2%BB%5C%5D%C3%81%C3%BB%C2%9E%C2%83K%C3%AB%C2%83%C3%A1*%C2%81%C3%9F%C3%B0%0E%25%C3%A4p%60%C3%8F_5%C3%9AY%C3%B7%3A%03%C3%84%03%24%01%C3%AE%C2%8F%20%C3%AB%C2%8BQ%0FXV)%14%C2%ADJK%C3%86%C2%BF-(ivH%C3%AC%3F%7B'%C3%A0%0F%0F%5C%C3%9F%C3%90%10%C2%93i%C2%8CC%10%C3%A6z%C2%B0P%1A0%C2%85%C3%A3%C2%94%C2%90%C2%AA%2F%C3%AE%C3%8F%C3%A8%C2%88%18%C3%84)W%C2%84C%C3%85H%C2%B1%C3%98%5E%182%C3%94%C2%A5%3F%0A%C3%AE'jJ%23OA%C3%B5~%C3%97%C2%88%06cA%24%5B8%2C%C2%8F%C2%9B%C2%96%C3%B4%23~%C2%AC%237%3E%22255b2b%2B%3D&input=teactivare) | [Test suite](http://cjam.aditsu.net/#code=qN%2F%7B%0A%0A2b0%22%18(%051%19%C2%BB%5C%5D%C3%81%C3%BB%C2%9E%C2%83K%C3%AB%C2%83%C3%A1*%C2%81%C3%9F%C3%B0%0E%25%C3%A4p%60%C3%8F_5%C3%9AY%C3%B7%3A%03%C3%84%03%24%01%C3%AE%C2%8F%20%C3%AB%C2%8BQ%0FXV)%14%C2%ADJK%C3%86%C2%BF-(ivH%C3%AC%3F%7B'%C3%A0%0F%0F%5C%C3%9F%C3%90%10%C2%93i%C2%8CC%10%C3%A6z%C2%B0P%1A0%C2%85%C3%A3%C2%94%C2%90%C2%AA%2F%C3%AE%C3%8F%C3%A8%C2%88%18%C3%84)W%C2%84C%C3%85H%C2%B1%C3%98%5E%182%C3%94%C2%A5%3F%0A%C3%AE'jJ%23OA%C3%B5~%C3%97%C2%88%06cA%24%5B8%2C%C2%8F%C2%9B%C2%96%C3%B4%23~%C2%AC%237%3E%22255b2b%2B%3D%0A%0A%7D%25%3A%2B&input=pupal%0Aunderplays%0Abanjoist%0Abackbitten) (paste full word list to count number of matches) [Answer] # Mathematica, 69.35 (69.35%, 150 bytes) ``` StringContainsQ[" "|##&@@"seaeiislaanreuaooesrtnlneimdiuuosnlrlggtwtwnsdjexexavsvnuvtxsgokcmairlzlzeyatgpnlfiyhtcdxrvmuqtqtmsfohnk"~StringPartition~2] ``` --- **Explanation** The function will check whether the word contains certain letter pairs that rarely occur in real words. If so, the function will return `True`, indicating that the word is probably not a real word. For example, pair `"ii"` occurs 21 times in the list of not words, while does not occur in the list of words. **Correct rate** ``` Words: 85.4% Not words: 53.3% ``` [Answer] ## CSharp, 69.85 (57.45%, 26 bytes) ``` "hoeiaunrt".Contains(s[1]) ``` I check if second letter of the word is on the list most popular second letters in english ([from this site](http://letterfrequency.org/)). **Automated test:** ``` static void Main(string[] args) { string[] good = System.IO.File.ReadAllLines( @"PATH_GOOD.txt"); string[] bad = System.IO.File.ReadAllLines(@"PATH_BAD.txt"); int counter_good = 0; int counter_bad = 0; foreach (string s in good) { if ("hoeiaunrt".Contains(s[1])) counter_good++; } foreach (string s in bad) { if (!("hoeiaunrt".Contains(s[1]))) counter_bad++; } Console.WriteLine(counter_good); Console.WriteLine(counter_bad); Console.ReadLine(); } ``` **Result:** ``` 828 321 ``` **Calculation:** ``` (828+321)/20 + 124/10 = 57.45 + 12.4 = 69.85 ``` [Answer] # ES6, 76 (67.4%, 64 bytes) A more serious answer this time. This is a pretty simple algorithm. It returns a truthy value when the second character of a word is one of `aeinoru`. It does not yield a significantly better success ratio than just `1`, but it is still very short. ``` w=>/^[^qxy][aehil-prux]/.test(w)>/[^aeiouy]{3}|[fiopq]$/.test(w) ``` [Test here.](https://jsfiddle.net/u8ska9p7/6/) * +2.7 by adding a regex to find words with 3 or more consecutive consonants and rule them "non-word" * +0.1 by replacing `&!` with `>` * +1.95 by excluding the most uncommon first characters `qxy`, adding more valid (common) second characters to compensate for false negatives, getting rid of the redundant comma in regex * +0.05 by excluding words ending with the unlikely ending characters `fiopq` ]
[Question] [ Instead of normal binary, you must count from 1 to an input in **negabinary concatenated to negaquaternary**. Here's an example, put in the form of an array: ``` [11, 1102, 1113, 100130, 101131, 11010132, 11011133, 11000120, 11001121, 11110122, 11111123, 11100110, 11101111, 10010112, 10011113, 10000100, 10001101, 10110102, 10111103, 10100230, 10101231, 1101010232, 1101011233, 1101000220, 1101001221, 1101110222, 1101111223, 1101100210, 1101101211, 1100010212, 1100011213, 1100000200, 1100001201, 1100110202, 1100111203, 1100100330, 1100101331, 1111010332, 1111011333, 1111000320, 1111001321, 1111110322, 1111111323, 1111100310, 1111101311, 1110010312, 1110011313, 1110000300, 1110001301, 1110110302, 1110111303, 111010013030, 111010113031, 100101013032, 100101113033, 100100013020, 100100113021, 100111013022, 100111113023, 100110013010, 100110113011, 100001013012, 100001113013, 100000013000, 100000113001, 100011013002, 100011113003, 100010013130, 100010113131, 101101013132, 101101113133, 101100013120, 101100113121, 101111013122, 101111113123, 101110013110, 101110113111, 101001013112, 101001113113, 101000013100, 101000113101, 101011013102, 101011113103, 101010013230, 101010113231, 11010101013232, 11010101113233, 11010100013220, 11010100113221, 11010111013222, 11010111113223, 11010110013210, 11010110113211, 11010001013212, 11010001113213, 11010000013200, 11010000113201, 11010011013202, 11010011113203, 11010010013330] ``` Your program must produce those numbers in any of these forms: * spaced apart * in an array * on new lines ### How do I get those numbers? Integer `n` will be used as an example of input. ``` for i := 1 to n print "i in base -2" + "i in base -4" ``` ### Rules: * You can submit a function or a whole program * You can go from 0 or 1 to the input * Builtins are allowed [Answer] ## Python - 83 bytes ``` f=lambda i,k:i and f(-i/k,k)+`-i%k`or'' i=0;exec"i-=1;print f(i,2)+f(i,4);"*input() ``` `f` is a function that converts (the negation of) an integer *i* to a negative base *2 ≤ k ≤ 10*. Input is taken from stdin. --- **Sample Usage** ``` $ echo 30 | python nega2+4.py 11 1102 1113 100130 101131 11010132 11011133 11000120 11001121 11110122 11111123 11100110 11101111 10010112 10011113 10000100 10001101 10110102 10111103 10100230 10101231 1101010232 1101011233 1101000220 1101001221 1101110222 1101111223 1101100210 1101101211 1100010212 ``` [Answer] # Julia, ~~124~~ ~~81~~ 73 bytes ``` n->(a=2863311530;b=3435973836;[base(2,(i+a)$a)*base(4,(i+b)$b)for i=1:n]) ``` This creates an unnamed function that accepts an integer and returns an array. Each element of the array is a successive number between 1 and *n* in negabinary concatenated to itself in negaquaternary. The negabinary representation of an integer can be computed using Schroppel's shortcut: ``` base(2, (i + 2863311530) $ 2863311530) ``` For an integer *i*, this is *i* + 2863311530, XOR 2863311530, encoded in base 2. The negaquaternary shortcut is similar: ``` base(4, (i + 3435973836) $ 3435973836) ``` [Answer] # [O](http://o.readthedocs.org/), 18 bytes ``` j){n.2_bo4_bo' o}d ``` Just my own take on this. Prints numbers with a space between them. [Try it online](http://o-lang.herokuapp.com/link/code=j)%7Bn.2_bo4_bo%27+o%7Dd&input=7) Explanaiton: ``` j) Increment input by 1 { }d Do this (input+1) times n.2_bo Convert n to base -2 and output 4_bo Convert n to base -4 and output ' o Output a space ``` [Answer] # Pyth - 31 30 29 27 bytes Uses [Forumla by D. Librik (Szudzik)](https://en.wikipedia.org/wiki/Negative_base#Calculation) (look at negabinary and quaternary sections). Can probably be golfed a bit. ``` VQjksjVmx+NKi*8d16K"AC",2 4 ``` Prints from zero on separate lines. ``` VQ For i in 0-Q jk Join by empty string s Sum of two arrays jV Vectorized base conversion m "AC" Map of A and C x Bitwise xor +NK Sum of loop var and constant inline assigned i 16 To base 10 from 16 *8 String repetition times 8 d Map var K Xnor of constant ,2 4 Bases 2 and 4 ``` [Try it here online](http://pyth.herokuapp.com/?code=VQjksjVmx%2BNKi*8d16K%22AC%22%2C2+4&input=10&debug=1). [Answer] # CJam, ~~34~~ ~~33~~ 32 bytes I think this can be golfed further. Counts from 0. ``` li),{_[CA]{:Ba8*Gb_@+^B8-b\}/N}/ ``` [Try it online](http://cjam.aditsu.net/#code=li)%2C%7B_%5BCA%5D%7B%3ABa8*Gb_%40%2B%5EB8-b%5C%7D%2FN%7D%2F&input=10). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` bF¥€Ø½ḤN¤Ḍ ``` [Try it online!](https://tio.run/##ASEA3v9qZWxsef//YkbCpeKCrMOYwr3huKROwqThuIz///8xMDA "Jelly – Try It Online") ## How it works ``` bF¥€Ø½ḤN¤Ḍ - Main link. Takes an integer as left argument ؽḤN¤ - Yield the list [-2, -4]: ¤ - Group the previous commands into a constant: ؽ - Start with [1, 2] (builtin constant) Ḥ - Double [2, 4] N - Negate [-2, -4] ¥€ - Generate the range 1...n and do the following to each: b - Convert to bases -2 and -4 - For example, 5b[-2, -4] => [[1, 0, 1], [1, 3, 1]] F - Flatten the lists [1, 0, 1, 1, 3, 1] Ḍ - Convert to a number 101131 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Output is an array of digit arrays. ``` õìJÑ)ícUõì4n ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9exK0SntY1X17DRu&input=MTAKLVE) ]
[Question] [ Write a program (the body of the function is enough) that accepts a string of alphanumeric characters and validates it according to ISO 13616:2007. The algorithm for validation is (source: wikipedia article on IBAN <http://en.wikipedia.org/wiki/International_Bank_Account_Number>): > > Validating the IBAN An IBAN is validated by converting it into an > integer and performing a basic mod-97 operation (as described in ISO > 7064) on it. If the IBAN is valid, the remainder equals 1.The > algorithm of IBAN validation is as follows: > > > * Check that the total IBAN length is correct as per the country. If not, the IBAN is invalid. The correct IBAN lengths can be found here: <http://pastebin.com/kp4eECVk> (can also be found below), ordered by the length of the IBAN number. the first 2 characters of each number is the country code. All other characters (lowercase letters on the pastebin, but can be any case in the actual IBAN) behind the first 2 can be any alphanumeric character. > * Move the four initial characters to the end of the string. > * Replace each letter in the string with two digits,thereby expanding the string, where A = 10, B = 11, ..., Z = 35. > * Interpret the string as a decimal integer and compute the remainder of that number on division by 97 > > > If the remainder is 1, the check digit test is passed and the IBAN might be valid. > > > Example (fictitious United Kingdom bank, sort code 12-34-56, account number 98765432): > > > > ``` > - IBAN: GB82 WEST 1234 5698 7654 32 > - Rearrange: W E S T12345698765432 G B82 > - Convert to integer: 3214282912345698765432161182 > - Compute remainder: 3214282912345698765432161182 mod 97 = 1 > > ``` > > The algorithm moest return true (or a truthy value) if the number is valid, and false (or a falsy value) if the number is invalid according to the algorithm. You do not need to check if the number actually exists, only if it's valid. The algorithm has to work for each of the different approved IBAN numbers mentioned in the wikipedia article above. The algorithm should be compatible with numbers both with or without separator characters between 2 alphanumeric characters. The separator character can either be periods, spaces or dashes and one number can contain different types of separators. Usual loopholes apply: no external resources, no built-in functions or methods. Puzzle type is code golf. Shortest code in bytecount wins. Standard boilerplate needed to execute the program (e.g. namespace, class, function declaration in OOP) is not included in the bytecount. Bonus: if you can return the properly formatted IBAN number (according to the national format on wikipedia) instead of true in the case of a valid number, you get a 25% reduction in your score. If the number is invalid, you return a literal string with the value "Invalid". --- Copy of the IBAN lengths in case the pastebin ever is removed: ``` Country;Chars;IBAN Fields Norway;15;NOkk bbbb cccc ccx Belgium;16;BEkk bbbc cccc ccxx Burundi;16;BIkk nnnn nnnn nnnn Denmark;18;DKkk bbbb cccc cccc cc Faroe Islands;18;FOkk bbbb cccc cccc cx Finland;18;FIkk bbbb bbcc cccc cx Greenland;18;GLkk bbbb cccc cccc cc Netherlands;18;NLkk bbbb cccc cccc cc Macedonia;19;MKkk bbbc cccc cccc cxx Slovenia;19;SIkk bbss sccc cccc cxx Austria;20;ATkk bbbb bccc cccc cccc Bosnia and Herzegovina;20;BAkk bbbs sscc cccc ccxx Estonia;20;EEkk bbss cccc cccc cccx Kazakhstan;20;KZkk bbbc cccc cccc cccc Lithuania;20;LTkk bbbb bccc cccc cccc Luxembourg;20;LUkk bbbc cccc cccc cccc Costa Rica;21;CRkk bbbc cccc cccc cccc c Croatia;21;HRkk bbbb bbbc cccc cccc c Latvia;21;LVkk bbbb cccc cccc cccc c Liechtenstein;21;LIkk bbbb bccc cccc cccc c Switzerland;21;CHkk bbbb bccc cccc cccc c Bahrain;22;BHkk bbbb cccc cccc cccc cc Bulgaria;22;BGkk bbbb ssss ddcc cccc cc Georgia;22;GEkk bbcc cccc cccc cccc cc Germany;22;DEkk bbbb bbbb cccc cccc cc Ireland;22;IEkk aaaa bbbb bbcc cccc cc Montenegro;22;MEkk bbbc cccc cccc cccc xx Serbia;22;RSkk bbbc cccc cccc cccc xx United Kingdom;22;GBkk bbbb ssss sscc cccc cc Gibraltar;23;GIkk bbbb cccc cccc cccc ccc Israel;23;ILkk bbbn nncc cccc cccc ccc United Arab Emirates;23;AEkk bbbc cccc cccc cccc ccc Andorra;24;ADkk bbbb ssss cccc cccc cccc Czech Republic;24;CZkk bbbb ssss sscc cccc cccc Moldova;24;MDkk bbcc cccc cccc cccc cccc Pakistan;24;PKkk bbbb cccc cccc cccc cccc Romania;24;ROkk bbbb cccc cccc cccc cccc Saudi Arabia;24;SAkk bbcc cccc cccc cccc cccc Slovakia;24;SKkk bbbb ssss sscc cccc cccc Spain;24;ESkk bbbb gggg xxcc cccc cccc Sweden;24;SEkk bbbc cccc cccc cccc cccx Tunisia;24;TNkk bbss sccc cccc cccc cccc Virgin Islands;24;VGkk bbbb cccc cccc cccc cccc Algeria;24;DZkk nnnn nnnn nnnn nnnn nnnn Portugal;25;PTkk bbbb ssss cccc cccc cccx x Angola;25;AOkk nnnn nnnn nnnn nnnn nnnn n Cape Verde;25;CVkk nnnn nnnn nnnn nnnn nnnn n Mozambique;25;MZkk nnnn nnnn nnnn nnnn nnnn n Iceland;26;ISkk bbbb sscc cccc iiii iiii ii Turkey;26;TRkk bbbb bxcc cccc cccc cccc cc Iran;26;IRkk nnnn nnnn nnnn nnnn nnnn nn France;27;FRkk bbbb bggg ggcc cccc cccc cxx Greece;27;GRkk bbbs sssc cccc cccc cccc ccc Italy;27;ITkk xaaa aabb bbbc cccc cccc ccc Mauritania;27;MRkk bbbb bsss sscc cccc cccc cxx Monaco;27;MCkk bbbb bsss sscc cccc cccc cxx San Marino;27;SMkk xaaa aabb bbbc cccc cccc ccc Burkina Faso;27;BFkk nnnn nnnn nnnn nnnn nnnn nnn Cameroon;27;CMkk nnnn nnnn nnnn nnnn nnnn nnn Madagascar;27;MGkk nnnn nnnn nnnn nnnn nnnn nnn Albania;28;ALkk bbbs sssx cccc cccc cccc cccc Azerbaijan;28;AZkk bbbb cccc cccc cccc cccc cccc Cyprus;28;CYkk bbbs ssss cccc cccc cccc cccc Dominican Republic;28;DOkk bbbb cccc cccc cccc cccc cccc Guatemala;28;GTkk bbbb cccc cccc cccc cccc cccc Hungary;28;HUkk bbbs sssk cccc cccc cccc cccx Lebanon;28;LBkk bbbb cccc cccc cccc cccc cccc Poland;28;PLkk bbbs sssx cccc cccc cccc cccc Benin;28;BJkk annn nnnn nnnn nnnn nnnn nnnn Ivory Coast;28;CIkk annn nnnn nnnn nnnn nnnn nnnn Mali;28;MLkk annn nnnn nnnn nnnn nnnn nnnn Senegal;28;SNkk annn nnnn nnnn nnnn nnnn nnnn Brazil;29;BRkk bbbb bbbb ssss sccc cccc ccct n Palestinian;29;PSkk bbbb xxxx xxxx xccc cccc cccc c Qatar;29;QAkk bbbb cccc cccc cccc cccc cccc c Ukraine;29;UAkk bbbb bbcc cccc cccc cccc cccc c Jordan;30;JOkk bbbb nnnn cccc cccc cccc cccc cc Kuwait;30;KWkk bbbb cccc cccc cccc cccc cccc cc Mauritius;30;MUkk bbbb bbss cccc cccc cccc cccc cc Malta;31;MTkk bbbb ssss sccc cccc cccc cccc ccc ``` [Answer] ## J (294 - 73.5 = 220.5) I've not counted the function definition (`f=:3 :0`...`)`) because it can be considered boilerplate, counting the whole block gives a score of **304 - 76 = 228**. ``` f=:3 :0 >((1=97|1".'x',~' '-.~":48-~k-7*64<k=.3&u:4|.b)*(#b)=15+1 i.~+/"1(2{.b)&E.;.2'NO.BEBI..DKFOFIGLNL.MKSI.ATBAEEKZLTLU.CRHRLVLICH.BHBGGEDEIEMERSGB.GIILAE.ADCZMDPKROSASKESSETNVGDZ.PTAOCVMZ.ISTRIR.FRGRITMRMCSMBFCMMG.ALAZCYDOGTHULBPLBJCIMLSN.BRPSQAUA.JOKWMU.MT.'){'Invalid';1}.;' '&,&.>_4<\b=.y-.' -.' ) ``` Tests: ``` NB. invalid numbers f '' Invalid f 'GB82 WEST 1234 5698 7654 31' Invalid f 'NL82 WEST 1234 5698 7654 32' Invalid NB. different separators and formatting f 'GB82.WEST.1234.5698.7654.32' GB82 WEST 1234 5698 7654 32 f 'GB82-WEST-1234-5698-7654-32' GB82 WEST 1234 5698 7654 32 f 'GB82WEST12345698765432' GB82 WEST 1234 5698 7654 32 f 'GB82 WEST 1234 5698 7654 32' GB82 WEST 1234 5698 7654 32 f 'GB.82-WE ST-12.345698.76-5432' GB82 WEST 1234 5698 7654 32 NB. wikipedia examples f 'GR16 0110 1250 0000 0001 2300 695' GR16 0110 1250 0000 0001 2300 695 f 'CH93 0076 2011 6238 5295 7' CH93 0076 2011 6238 5295 7 f 'SA03 8000 0000 6080 1016 7519' SA03 8000 0000 6080 1016 7519 f 'GB29 NWBK 6016 1331 9268 19' GB29 NWBK 6016 1331 9268 19 ``` Explanation: * `b=.y-.' -.'`: remove any separators from the argument and store the result in `b`. * `1}.;' '&,&.>_4<\b`: split `b` up in groups of four, add a space in front of every group, join the groups and remove the leading space. If `y` contained a valid IBAN number, this is its canonical representation (i.e. groups of four, separated by spaces, with the last group maybe having less than four elements). * `(`...`){'Invalid';`: create an array with the string `Invalid` as element 0 and the formatted IBAN number as element 1. Select the right one based on whether the IBAN number is valid: + Check the length: - `'NO.BEBI.---.JOKWU.MT.'`: a list of all the country codes for each length, separated by dots - `+/"1(2{.b)&E.;.2`: group the string by the dots, and see which one contains the given country code (the first 2 elements of `b`). - `15+1 i.~`: find the index of the matching one and add `15` to find the length. - `(#b)=`: check it against the actual length of `b`. + Check the number: - `4|.b`: rotate `b` to the left by 4 (rearrange) - `k=.3&u:`: find the ASCII value for each number - `48-~k-7*64<k`: subtract 7 from each letter, then subtract 48 from all, giving the values - `1".'x',~' '-.~":`: format, remove spaces, add an 'x' at the end (for high-precision mode, which is necessary for large numbers), and turn it back into a number - `1=97|`: check if the number mod 97 equals 1. * `>`: unbox the resulting string [Answer] # CJam, ~~151.5~~ 141.75 points ``` 0000000: 6c22 202e 2d22 2d3a 512c 220f a86e 5136 l" .-"-:Q,"..nQ6 0000010: 1bff 75f6 e8e4 0b35 5dab f190 0d85 59c4 ..u....5].....Y. 0000020: 1938 4366 3d29 5eaa e879 024a 77d9 8baf .8Cf=)^..y.Jw... 0000030: 5c16 3258 a4d2 4e6c 1a60 429f affa b8f4 \.2X..Nl.`B..... 0000040: 435d e706 457b 89a9 16b8 1d4b 08f7 9970 C]..E{.....K...p 0000050: eeb9 7467 f8e9 c935 33be 2467 3dd4 1afb ..tg...53.$g=... 0000060: e2ec 20cc 99e4 2783 cb96 512d f9f8 7e75 .. ...'...Q-..~u 0000070: 7066 4307 2232 3536 6232 3762 2740 662b pfC."256b27b'@f+ 0000080: 2740 2f7b 5132 3c23 3126 217d 235f 573e '@/{Q2<#1&!}#_W> 0000090: 462a 2b3d 5134 6d3c 412c 7327 5b2c 3635 F*+=Q4m<A,s'[,65 00000a0: 3e2b 6623 737e 3937 2531 3d5d 312d 2249 >+f#s~97%1=]1-"I 00000b0: 6e76 616c 6964 2251 342f 532a 3f nvalid"Q4/S*? ``` The above program is 189 bytes long and qualifies for the bonus. At the cost of 26 more bytes – for a total score of 161.25 – we can avoid unprintable characters: ``` l" .-"-:Q,",YER,moTd$V6nH\-Mh/I-z(]k!uw()=j9_[C3n&As0(F;TAn$eB-r%:p+^b,1Y.j;thavi@!d,Dt7M_x-5V:#o/m_CKj-c*Imy~IjXPBCo?aM#lrN:[[email protected]](/cdn-cgi/l/email-protection)"33f-94b27b'@f+'@/{Q2<#1&!}#_W>F*+=Q4m<A,s'[,65>+f#s~97%1=]1-"Invalid"Q4/S*? ``` You can test this version in the [CJam interpreter](http://cjam.aditsu.net/). ### Example run ``` $ cat gen.cjam "l\" .-\"-:Q,"[32,15>{[ "NO"15"BE"16"BI"16"DK"18"FO"18"FI"18"GL"18"NL"18"MK"19"SI"19 "AT"20"BA"20"EE"20"KZ"20"LT"20"LU"20"CR"21"HR"21"LV"21"LI"21 "CH"21"BH"22"BG"22"GE"22"DE"22"IE"22"ME"22"RS"22"GB"22"GI"23 "IL"23"AE"23"AD"24"CZ"24"MD"24"PK"24"RO"24"SA"24"SK"24"ES"24 "SE"24"TN"24"VG"24"DZ"24"PT"25"AO"25"CV"25"MZ"25"IS"26"TR"26 "IR"26"FR"27"GR"27"IT"27"MR"27"MC"27"SM"27"BF"27"CM"27"MG"27 "AL"28"AZ"28"CY"28"DO"28"GT"28"HU"28"LB"28"PL"28"BJ"28"CI"28 "ML"28"SN"28"BR"29"PS"29"QA"29"UA"29"JO"30"KW"30"MU"30"MT"31 ]2/{1=L=},0f=_!!{:+}*}fL]"@"*'@f-27b256b:c`"\\\\"/"\\"* "256b27b'@f+'@/{Q2<#1&!}#_W>F*+=Q4m<A,s'[,65>+f#s~97%1=]1-\"Invalid\"Q4/S*?" $ LANG=en_US cjam gen.cjam | tee >(cksum) > iban.cjam 770150303 189 $ LANG=en_US cjam iban.cjam <<< GB82WEST12345698765432; echo GB82 WEST 1234 5698 7654 32 ``` ### How it works ``` "…"256b27b'@f+" ``` converts the string `"…"` into an integer by considering it a base-256 number, then into an array of integers by considering it a base 27-number, adds the character code of `@` to each digit and casts to Character in the process. As a result, the following code gets executed: ``` " Read one line from STDIN, remove allowed separators, store the result in variable “Q” and push its length (“,”). "; l" .-"-:Q, " Push the string from above. The correct number of characters for country code “NO” is 15. The correct number of characters for country codes “BE” and “BI” is 16. The number of characters should never be 17. ⋮ "; "NO@BEBI@@DKFOFIGLNL@MKSI@ATBAEEKZLTLU@CRHRLVLICH@BHBGGEDEIEMERSGB@" "GIILAE@ADCZMDPKROSASKESSETNVGDZ@PTAOCVMZ@ISTRIR@FRGRITMRMCSMBFCMMG@" "ALAZCYDOGTHULBPLBJCIMLSN@BRPSQAUA@JOKWMU@MT"++ " Split the above string at the at signs (“@”). "; '@/ " Find the index of the (first) substring such that the index of the country code (“Q2<”) in the substring is even. "; {Q2<#1&!}# " If the country code is invalid, the index will be -1. If the index is greater than -1 (“W>”), add 15 to it; if it isn't, leave -1 on the stack. "; _W>F*+ " Compare the result to the length of the IBAN. Push 1 if they match and 0 otherwise. "; = " Push the IBAN rotated to the left by four characters. "; Q4m< " “A,s'[,65>+” pushes “0123456789ABCDEFGHIJKLMNOPQRSTUVXYZ”. For each character of the IBAN, push its index in that string (-1 if not present). "; A,s'[,65>+f# " Stringify (“s”) the result, interpret the string (“~”) and compute the residue of the (topmost) resulting integer modulo 97. "; s97% " Push 1 if the residue is 1; otherwise, push 0 "; 1= " Wrap the entire stack in an array and remove the integer 1 from it. If the IBAN is valid, the array will be empty. " If the result is falsy, the IBAN is valid; split it into substrings of length 4 and join them using spaces (“S”). Otherwise, the IBAN is invalid; say so. "; "Invalid"Q4/S*? ``` [Answer] # Bash, ~~738 519 444 434~~ 427 Here's something to start us off, I wrote it (and saved 317 characters, mostly in the country code storage bit) while the question was in the sandbox. Let me know if there are any issues. The function reads from stdin, which is quite common in Bash (the question says "accepts a string of alphanumeric characters", it doesn't require this to be via arguments). It returns 0 if the IBAN is valid and a non-zero value if it is invalid. An IBAN containing any characters other than the delimiters `. -` and `A-Z0-9` is invalid ``` t=return v=`tr -d .\ -` [ "`tr -dc A-Z0-9<<<$v`" = $v ]||$t ((${#v}>9))||$t r=`grep -oE "[0-9]+[A-Z]{2}*${v:0:2}"<<<15NO16BEBI18DKFIFOGLNL19MKSI20ATBAEEKZLTLU21CHCRHRLILV22BGBHDEGBGEIEMERS23AEGIIL24ADCZDZESMDPKROSASESKTNVG25AOCVMZPT26IRISTR27BFCMFRGRITMCMGMRSM28BJCICYDOGTHULBMLPLSNAZ29BRPSQAUA30JOKWMU31MT` [ "${r:0:2}" = ${#v} ]||$t v=${v:4:99}${v:0:4} d=({A..Z}) for a in {10..35};{ v=${v//${d[a-10]}/$a} } $t `bc<<<$v%97-1` ``` ## Explanation ``` t=return # Alias return to $t v=`tr -d .\ -` # Remove delimiters from STDIN and save to a variable $v. # If you want the function to take the IBAN as an argument, insert <<<$1 just before the last ` in the line above # Check that the number now contains no characters other than A-Z0-9 (i.e. if all other characters are removed, the string should remain the same because there aren't any of them) # If not, return. By default, return uses the exit status of the previous command, which will be 1 [ "`tr -dc A-Z0-9<<<$v`" = $v ]||$t # Check that $v is long enough to have a country code at the start, return if not # I could have put 2 instead of 9, but the character count is the same ((${#v}>9))||$t # give grep the country code data string, which is of the format <length1><country><country><length2><country><country><country>... # for example, this tells you that EE has an IBAN length of 20 # grep searches for a number ([0-9]+), followed by any number including zero of country codes ([A-Z]{2}*), followed by the first two characters of the input IBAN, i.e. its country code (${v:0:2}) # -o makes grep only output the match, not the line containing it; -E enables extended regexes # The result is saved to the variable $r r=`grep -oE "[0-9]+[A-Z]{2}*${v:0:2}"<<<15NO16BEBI18DKFIFOGLNL19MKSI20ATBAEEKZLTLU21CHCRHRLILV22BGBHDEGBGEIEMERS23AEGIIL24ADCZDZESMDPKROSASESKTNVG25AOCVMZPT26IRISTR27BFCMFRGRITMCMGMRSM28BJCICYDOGTHULBMLPLSNAZ29BRPSQAUA30JOKWMU31MT` # Check that the length specified by the country code, the first two chars of $r, is equal to the actual IBAN's length ${#v}. return 1 if not. [ "${r:0:2}" = ${#v} ]||$t v=${v:4:99}${v:0:4} # Put the first 4 chars to the back d=({A..Z}) # Make an array of letters A to Z # Loop for each number from 10 to 35 for a in {10..35};{ # in the IBAN, replace letters A to Z by the corresponding number from 10 to 35 v=${v//${d[a-10]}/$a} } # $v is now an integer # note: I used bc here because Bash's built-in arithmetic couldn't handle big numbers # find the remainder of dividing $v by 97, subtract 1, and return the value # if the remainder is 1, then the IBAN is valid and 1-1=0 is returned. $t `bc<<<$v%97-1` ``` ## Examples ``` ibanfn<<<'-GB82-WEST-1234 5698.7654.32 ' #returns 0, valid ibanfn<<<'-GB82-WEST-1234 5698.7654.33 ' #returns 27, invalid, fails remainder test ibanfn<<<'GB82 WEST 1234 5698 7654 32a' #returns 1, invalid, contains invalid character a ibanfn<<<'YY82 WEST 1234 5698 7654 32' #returns 1, invalid, country code does not exist ibanfn<<<'GB82 WEST 1234 5698 7654 3210' #returns 1, invalid, wrong length ``` [Answer] ## Python 3 - (483 - 25%) 362 ``` import re def c(i): i=re.sub('\W','',i);q,s='NOBEBIDKFOFIGLNLMKSIATBAEEKZLTLUCRHRLVLICHBHBGGEDEIEMERSGBGIILAEADCZMDPKROSASKESSETNVGDZPTAOCVMZISTRIRFRGRITMRMCSMBFCMMGALAZCYDOGTHULBPLBJCIMLSNBRPSQAUAJOKWMUMT',i for m in b" !!#####$$%%%%%%&&&&&''''''''((())))))))))))****+++,,,,,,,,,------------....///0": if(i[:2],len(i)+17)==(q[:2],m): i=i[4:]+i[:4] for z in range(26):i=re.sub(chr(65+z),str(z+10),i) return(int(i)%97==1)and re.findall('.{,4}',s)or 0 q=q[2:] return 0 ``` [Answer] # Perl (356+2 \* 75% = 268.5) the code is so confusing that even SE's syntax highlighting gets lost in it :) ``` #!perl -ln use bignum;s/\W//g;$_=$T=uc;$q=15;/\w/?$H{$_}=$q:$q++for'NO,BEBI,,NLGLDKFOFI,SIMK,KZEEATLTLUBA,HRCHLVCRLI,RSIEGEDEBGBHGBME,GIAEIL,SASESKESCZMDTNPKADDZVGRO,PTMZCVAO,TRISIR,CMMGMRSMITFRGRBFMC,ALAZPLCIGTHUSNCYDOBJLBML,UABRQAPS,KWMUJO,MT'=~/,|../g;/../;$q=$H{$&}==y///c;/..../;$_=$'.$&;s/[A-Z]/ord($&)-55/ge;print+(Invalid,join' ',($T=~/.{1,4}/g))[1==$_%97*$q] ``` ## Explanation ``` #!perl -nl ``` `-n` means read stdin line by line; `-l` adds newlines to print ``` use bignum; ``` required for modulo operation later to return correct value. ``` s/\W//g; ``` remove everything that's not \w from IBAN. ``` $_=$T=uc; ``` convert the iban number to upper case, also save it to $T - will be used for pretty-printing later. ``` $q=15; ``` set the temporary variable to 15, it will be used to build a hash table with country code to iban length mapping. ``` /\w/ ? $H{$_}=$q : $q++ for 'NO,BEBI,,NLGLDKFOFI,SIMK,KZEEATLTLUBA,HRCHLVCRLI,RSIEGEDEBGBHGBME,GIAEIL,SASESKESCZMDTNPKADDZVGRO,PTMZCVAO,TRISIR,CMMGMRSMITFRGRBFMC,ALAZPLCIGTHUSNCYDOBJLBML,UABRQAPS,KWMUJO,MT' =~ /,|../g; ``` split the large string into an array of commas or two-letter country codes, iterate over it. if the element starts with a letter, it's a country code - save it in the hash with a value of $q; otherwise, a comma means to increment $q. so, NO will get the value of 15, BE and BI will be 16, and so on. ``` /../; ``` match first two characters from IBAN (the country code) ``` $q=$H{$&}==y///c; ``` check if IBAN has correct length for the country code, save result in $q ``` /..../;$_=$'.$&; ``` move first four characters to the end of IBAN ``` s/[A-Z]/ord($&)-55/ge; ``` replace all letters with corresponding numbers, starting with A = 10 ``` print+(Invalid,join' ',($T=~/.{1,4}/g))[1==$_%97*$q] ``` print either "Invalid" or the pretty-printed IBAN. `1==$_%97*$q` will only equal `1` for an IBAN with a correct length and correct remainder. [Answer] ## Perl 6 - 354 chars - (not sure of bonus) ``` my $r = slurp 'ir'; my @cs = $r.comb(/(\D)+/);my @ns = $r.comb(/(\d)+/); my %h; for @ns Z @cs -> $n, $c {%h{$n}=[$c.comb(/\w**2/)]}; for my @ =lines() { my $o=$_; my $y=$_.substr(0,2); $_=s:g/\s|\-|\.//.uc.comb.rotate(4).join; my $l=$_.chars ; $_.=trans(['A'..'Z'] => ['10'..'35']); next if $y !~~ %h{$l}.any; say $_%97==1??"$o ok"!!"Invalid"; } ``` Reading input from `IBANS.txt` on `STDIN` and slurping the rules from the file `ir` (I left the rules out of the total in case they were boilerplate - the rules file is 191 characters so the total would be 545. ``` perl6 ibanvalidate.p6 IBANS.txt ``` `IBANS.txt` is as follows: ``` GB82 WEST 1234 5698 7654 32 GB82-WEST-1234-5698-7654-32 gb82-west-1234-5698-7654-32 GB82WEST12345698765432 GB82.WEST.1234.5698.7654.32 GR16 0110 1250 0000 0001 2300 695 GB82 WEST 1234 5698 7654 31 NL82 WEST 1234 5698 7654 32 GB29 NWBK 6016 1331 9268 19 Whee perl6 CANADA 000 Banks 007 911 ``` **Notes** * validates country code and length and outputs as below * Character count from: `wc -m ibanvalidate.p6` * Currently not much error checking validation of input is done. * Whitespace is signficant in Perl6 (or more significant than Perl 5) so is counted. Typical output: ``` GB82 WEST 1234 5698 7654 32 ok GB82-WEST-1234-5698-7654-32 ok GB82WEST12345698765432 ok GB82.WEST.1234.5698.7654.32 ok GR16 0110 1250 0000 0001 2300 695 ok Invalid GB29 NWBK 6016 1331 9268 19 ok ``` This is not typical Perl6 code (especially the `comb` - lines a friendly and influential Perl developper mentioned this in passing): I'm a beginner. Once the contest is done I will add/change and make any modifications suggested by Perl6-ers. Thanks for playing and being nice :-) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 311 bytes, score 233.25 ``` {/:i^(..)<[A..Z0..9]>+$/&&'NobeBIdkfofiglNlmkSiatbaeekzltLucrhrlvliChbhbggedeiemersGbgiilAeadczmdpkrosaskessetnvgDzptaocvMzistrIrfrgritmrmcsmbfcmMgalazcydogthulbplbjcimlSnbrpsqaUajokwMumt'~~/^:i(..)*$($0)/&&.comb==$0.comb(/<:Lu>/)+15&&[.comb].rotate(4)>>.&{:36($_)}.join%97==1&&~.comb(4)||'Invalid'}o{TR/\ .-//} ``` [Try it online!](https://tio.run/##fY7bTsIwAIbveYolzh1EOs4nGYmoMSTAhWBMRDDt1pWyls62YBiHp/FNfDAEvOfuz//9X/InWLLqga8NKzL8w8Zr0qkDgNsa3wPwngegMWlnTc@y7IFAuNMN40hElLAB4/GQQo0gxnHKdG8ZyJlkK0YfZmiGCMEhpphjqZ4RoZTdYxgGKQ@TWAoFVYyVwnqxIo9poqEIVv2UKi27MpJEUs0lDxRHUcD7BDKYButQED1bMpQwNA8oZ8MFkon6gq9wLuLv/pJre7/3pk16On9jOmbePZ4GgeDI9838OTheq9lbtj03W6hY1vjcTYAUGmrslN12G1ibZqnqmJ/uDswFXVw3ar5fsKz9v152t1u7u1hBRkN7JzajF@/DADnP2x2ujFKxllFwbUQn3YiEzNikUy8ab09qZBSKpXKuUm3UQa1aKR@39u0lfJn@/lzmBfvu8Ac "Perl 6 – Try It Online") I'm not sure * where separator characters are allowed exactly. I simply remove all of them. * whether the final formatted output should be uppercase. ### Explanation ``` { / # Match against regex :i # ignore case ^ # start of string (..) # country code (stored in $0) <[A..Z0..9]>+ # alphanumeric characters $ # end of string / && 'NobeBIdk...' # Country code string with uppercase letter # for each length increase ~~ # match against / # regex :i # ignore case ^ # start of string (..)* # series of two characters (stored in $0) $($0) # country code / && .comb== # IBAN length equals $0.comb(/<:Lu>/) # number of uppercase characters +15 # plus 15 && [.comb] # Split IBAN into characters .rotate(4) # Rotate by four >>.&{:36($_)} # Convert each from base-36 .join # Join %97==1 # Modulo 97 check && ~.comb(4) # Add space after every four characters || 'Invalid' # Return 'Invalid' if any of the checks failed } o # Function composition { TR/\ .-// # Remove space, dot, dash } ``` [Answer] **Python3.x (539 chars - 25% = 404.25)** (To be said first: I'm a bit confused what HAS to be counted by your rules so I just counted my whole function) 539 characters - Including `import` and `def IBAN(i):` (tabs at the beginning of the line are counted anyway in python so they don't matter) Bonus applied as stated in the rules. ``` def IBAN(i): import re i=re.sub(r'[^\w]','',i).upper() k=len(i) z=i[:2]in re.search(r'%s([A-Z ]*)'%k,'15NO16BE BI18DK FO FI GL NL19MK SI20AT BA ES KZ LT LU21CR HR LV LI CH22BH BG GE DE IE MK RS GB23GI IL AE24MD PK RO SA SK ES SE TN VG DZ25CV MZ26IS TR IR FR GR IT MR MC SM BF CM MG28AL AZ CY DO GT HU LB PL BJ CI ML SN29BR PS QA UA30JO KW MU31MT').group(1)or None if int(''.join([c if c.isdigit()else str(ord(c)-55)for c in i[4:]+i[:4]]))%97!=1 or z is None:return('Invalid') return(' '.join([i[0+j:4+j]for j in range(0,k,4)])) ``` Code with comments (not completed yet... I'm way too tired to write the remaining part of the comments... I'll do that tomorrow) ``` def IBAN(i): import re # Remove all non word characters (including space) and change to uppercase # as0098-7*46.76A -> AS009874676A i=re.sub(r'[^\w]','',i).upper() # Get the length of it because I need it later multiple times k=len(i) # r'%s([A-Z ]*)'%k = Replace %s with the length of i # re.search( ,'15NO16BE BI18DK FO FI GL NL19MK SI20AT BA ES KZ LT LU21CR HR LV LI CH22BH BG GE DE IE MK RS GB23GI IL AE24MD PK RO SA SK ES SE TN VG DZ25CV MZ26IS TR IR FR GR IT MR MC SM BF CM MG28AL AZ CY DO GT HU LB PL BJ CI ML SN29BR PS QA UA30JO KW MU31MT') # = search (with regexp) in this string (which are the lengths and countrycodes seperated by space) # Return the first found match (scroll to the right to see) .group(1) # i[:2]in or None # = The first two characters in the returned string (in the same order and same case) z=i[:2]in re.search(r'%s([A-Z ]*)'%k,'15NO16BE BI18DK FO FI GL NL19MK SI20AT BA ES KZ LT LU21CR HR LV LI CH22BH BG GE DE IE MK RS GB23GI IL AE24MD PK RO SA SK ES SE TN VG DZ25CV MZ26IS TR IR FR GR IT MR MC SM BF CM MG28AL AZ CY DO GT HU LB PL BJ CI ML SN29BR PS QA UA30JO KW MU31MT').group(1)or None if int(''.join([c if c.isdigit()else str(ord(c)-55)for c in i[4:]+i[:4]]))%97!=1 or z is None:return('Invalid') return(' '.join([i[0+j:4+j]for j in range(0,k,4)])) ``` [Answer] # Perl (535) Not really golfed yet - no idea if I qualify for the bonus ;-) I will add some @professorfish type explanations. ``` #!perl -ln $r="15NO16BEBI18DKFIFOGLNL19MKSI20ATBAEEKZLTLU21CHCRHRLILV22BGBHDEGBGEIEMERS23AEGIIL24ADCZDZESMDPKROSASESKTNVG25AOCVMZPT26IRISTR27BFCMFRGRITMCMGMRSM28BJCICYDOGTHULBMLPLSNAZ29BRPSQAUA30JOKWMU31MT"; $c{$1} = [unpack("(A2)*", $2)] while($r) =~/(\d{2})(\D{2,})/g; @h{("A".."Z")}=(10..35); chomp;$o=$_;$_=uc$_; s/[ -.]//g; $l=y///c; ($m)=($_=~m/^.{2}/g); ($n=$_) =~s/^(....)(.*)/$2$1/dg; $n=~s/([A-Z])/$h{$1}/g; print $m ~~ @{$c{$l}} ? "length valid for $m":"invalid length"; use bignum; print $n%97==1 ? "$o ok":"$o Invalid"; ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 372 bytes \* .75 = 279 ``` s=>(s=s[R="replace"](/[^A-Z0-9]/g,"")).length-14-"NO|BEBI||DKFOFIGLNL|MKSI|BATEEKZLTLU|CRCHRLVLI|GBHBGEDEIEMERS|GILAE|SADCZMDZPKROSASKESETNVG|PTAOCVMZ|ISTRIR|BFRGRITSMRMCMG|ALBJAZCYDOGTHUPLCIMLSN|BRPSQAUA|JOKWMU|MT".match(eval(`/.*${s.slice(0,2)}/i`))[0].split`|`.length||BigInt((s.slice(4)+s.slice(0,4))[R](/\w/g,x=>parseInt(x,36)))%97n-1n?"Invalid":s[R](/(.{4})/g,"$1 ") ``` [Try it online!](https://tio.run/##pZFrb5swFIa/91dYqJNgKw6XQEKndAJCCAVCBqTV0nUKSpyUjRIU04tU97dndtdpUi5dq/IBIes5z3v88jO7zfB0lVe1WC5naD3vrHHnhMcdfBF3uBWqimyKuEu@cfHDFMeSaFw2FkccJwiwQOWivhLlpsgNImI5lkdI1@9FPc8NBgEJ/cQjlpk6jj8O0mBE7Njux8FZ4BHX6luu03U8J3TihLheYDokMbv2OOyOh34cJWbiO4mTDs5cMkzNyD4Lx8RL0tiLidWL3dhLkzAO7dAlZmCdmmP7Wzdy0/5oGNheGCQDYsXD5Ks5Mslp5J@HIxKmHLzO6ukVj26zgp804MfDBwxxkU8RLx0pwmMjnwjChXQJcVXk9YRMni9IiJUvvLLm@b94U/j0b7JJh2Jaz/c72st956TKVhgx/P5I1QVB@GC0SlEuv3BeSYPzGXeMn3gePjQfBdbloQw4Yf15uizxskCwWC74Oc8aPmg0QHRTVzf1MXiePjjY5FyrrYBzJ0mBrKhNoOlGG7R0rQlU@bWKQbBPoexT0LNZPp@jFSprgBG9dFYvVxhk5QzMlyvadJ2Xi93bQhYFWRRkUZBFwa2o/fdSdmtFBosMFhksMlh8v5axDGUkA99vfF3Vb9TCpwLAUwPwz7a0WPGt@1LuLv@VV2iWZwDdZ9dVgfCOvFjWgSTLEnVoEpDow14yUFT6pRvaZub/@O0Iu2@olGnpQKGDQFfUNtAUQwOtDfd@cFuamJIK2s/pNFhq040kultLk40N74vsrl@gGGBwbvmUpJCsqjIwFL0NtsQvkOvf "JavaScript (Node.js) – Try It Online") Test cases borrowed from @marinus 's J answer. ]
[Question] [ Given equation of two lines in the format Ax+By=C, determine their intersection point. If they are parallel print 'parallel' without quotes. For input/output format refer sample input/output. ``` Input 1x+1y=1 1x-1y=1 Output (1.00,0.00) Input 0x+1y=0 1x+0y=0 Output (0.00,0.00) ``` 1. -1000000 <= A,B,C <= 1000000. 2. Note their intersection point may not be integer. Print upto two decimal places. 3. Shortest solution wins. [Answer] ## Ruby - 119 chars ``` a,b,c,d,e,f=(gets+gets).scan(/-?\d+/).map &:to_f puts (t=a*e-b*d)==0?'parallel':"(%.2f,%.2f)"%[(e*c-b*f)/t,(a*f-c*d)/t] ``` [Answer] ## Python, 148 146 chars ``` import re I=raw_input a,b,p,c,d,q=eval(re.sub('x|y=','.,',I()+','+I())) D=a*d-b*c print'(%.2f,%.2f)'%((p*d-q*b)/D,(a*p-c*q)/D)if D else'parallel' ``` [Answer] ## [sage](http://sagemath.org/) - 162 chars ``` x,y=var('x,y') e=lambda:eval(raw_input().replace('x','*x').replace('y','*y=')) try:r=solve([e(),e()],[x,y])[0];print`r[0].rhs(),r[1].rhs()` except:print'parallel' ``` [Answer] ## Python+sympy - 161 chars ``` from sympy import* x,y=symbols('xy') e=lambda:eval(raw_input().replace('x','*x').replace('y=','*y-')) r=solve([e(),e()],[x,y]) print r and`r[x],r[y]`or'parallel' ``` **Python+sympy - 143 chars (different output format)** ``` from sympy import* x,y=symbols('xy') e=lambda:eval(raw_input().replace('x','*x').replace('y=','*y-')) print solve([e(),e()],[x,y])or'parallel' ``` output format for 143 char version is slightly different from the spec ``` In: 1x+1y=1 1x-1y=1 Out: {x: 1, y: 0} In: 0x+1y=0 1x+0y=0 Out: {x: 0, y: 0} ``` [Answer] ## J, 146 132 134 124 ``` echo'parallel'"_`(1|.')(',[:(,',',])&(0j2&":)/[:,,.@{:%.}:)@.([:*@|[:-/ .*}:)|:".>{.`(<@}:@;@(1 2&{))`{:(`:0)"1;:;._2(1!:1)3 ``` Parsing this is awful. **Edit**: Realized that my output is basically broken, although it works for the examples given and parallels... **Edit**: Posting the shorter version I already had. **Edit**: Fixed without too much pain... **Edit**: Fixed a weird issue where the program was spread across multiple lines. Somewhat ungolfed version: ``` words =: ;:;._2(1!:1)3 NB. Leverage J's parser itself to split each line into e.g. ax + by = c lines =: ".>{.`(<@}:@;@(1 2&{))`{:(`:0)"1 words NB. Use a 3-part gerund (`) to get boxed strings 'ax';'b';'c', unbox and parse calc_and_format =: 1|.')(',[:(,',',])&(0j2&":)/[:,,.@{:%.}: NB. %. (matrix multiply) first two rows (a d/b e) by third row turned (c/f) NB. And then format laboriously. 0j2&": formats numbers with 2 decimals. det_nonzero =: [:*@|[:-/ .*}: NB. 1 if determinant (-/ .*) of (a b/d e) is nonzero (*@|) echo'parallel'"_`[[email protected]](/cdn-cgi/l/email-protection)_nonzero|: lines NB. transpose parsed input to get (a d/b e/c f). NB. If det_nonzero, call calc_and_format, otherwise constant 'parallel' NB. Print ``` [Answer] # OCaml + Batteries, 163 characters As straightforward as it gets: ``` Scanf.scanf"%fx%fy=%f\n%fx%fy=%f\n"Float.(fun a b c d e f->Printf.(fun u->if u=0.then printf"parallel"else printf"(%.2f,%.2f)"((b*f-c*e)/u)((d*c-a*f)/u))(b*d-a*e)) ``` **Edit:** * Initial version, 169 * Use Batteries for delimited overloading of operators, 164 * Lambda binding of `u`, 163 [Answer] ## C-149 bytes Not much of golfing just the basics. ``` float a,b,c,d,m,n,t;main(){scanf("%fx%fy=%f%fx%fy=%f",&a,&b,&m,&c,&d,&n);t=b*c-a*d;t?printf("(%.2f,%.2f)",(b*n-d*m)/t,(c*m-a*n)/t):puts("parallel");} ``` [Here](http://ideone.com/68538) is the ideone link for testing. Instead of printing 'parallel' an alternative could be to print the orthogonal distance between the lines when they are parallel. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` ∆Q:[vt|`ċ₃ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiIZROlt2dHxgxIvigoMiLCIiLCIxeCsxeT0xXG4xeC0xeT0xIl0=) [8 if the format can be `⟨ ⟨ `x` | xval ⟩ | ⟨ `y` | yval ⟩ ⟩`](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiIZROsKsw59gxIvigoMiLCIiLCIxeCsxeT0xXG4xeC0xeT0xIl0=). Returns fraction representation of all numbers if not integer. ## Explained ``` ∆Q:[vt|`ċ₃ ∆Q # Solve the two input equations simultaneously :[ # If there's a solution vt # get the last values of each two item tuple |`ċ₃ # else, push the string "parallel" ``` ]
[Question] [ *This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge, the cops' thread is [here](https://codegolf.stackexchange.com/questions/241485/from-code-to-golf-cops-thread)* You can change the word `code` into `golf` by changing a letter at a time in four steps: ``` CODE [COLE](https://en.wiktionary.org/wiki/cole#English) COLD GOLD GOLF ``` Today, we’ll be doing the same thing with programs. Your challenge is to crack an answer on the cops' thread. Cops will create a series of programs in which the first prints `code`, the last prints `golf` and the rest print distinct English words such that each program can be derived from the previous by changing a single character of its code. For example, if the program `abcde` outputs `code` in a certain language, and the program `abcdf` outputs `potato`, then changing that `e` to an `f` is a valid step. And if the program `aqcdf` outputs `golf`, then `abcde` -> `abcdf` -> `aqcdf` is a valid chain in which you change a character twice. The cops will only share the `code` program and the number of changes, your challenge is to figure out the rest. Once you discover their whole program chain, their answer is cracked. Cops may output in any casing - `coDe`, `Code`, `CODe` etc. The dictionary used is `/dict/words`, which I've put in a [gist](https://gist.github.com/chunkybanana/08d7f8c3bd773ea546d641a9f3051e22) for convenience. ## Scoring The user with the most cracks wins the cops challenge. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), cracks [emanresu A’s answer](https://codegolf.stackexchange.com/a/241505/101522) ``` «ƛ↔ƒ `ƛ↔ƒ `ƛ₅ƒ `»₅ƒ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCq8ab4oaUxpLCqyxcbmDGm+KGlMaSYCxcbmDGm+KChcaSYCxcbmDCu+KChcaSYCwiLCIiLCIiXQ==) Note: The final two characters in each line in the linked program is just so that each one can be ran alongside one another; they aren’t required for the individual programs. The first change is changing the first character, which changes the compressed string into a dictionary compressed string. From this point on, because of the way that dictionary compression works in Vyxal, the final character in the string is ignored. The next two changes are simply changing to the dictionary entry for `golf`. What’s convenient about using the dictionary is that most of it is made up of English words, so I didn’t have to worry much about how I changed those two characters, as long as I changed them to the correct characters. I’m guessing the intended solution was probably more clever than just switching to dictionary compression, but I saw that the option was available and decided to take advantage of it. [Answer] # Python 2, [cracks Fmbalbuena's cop](https://codegolf.stackexchange.com/a/241748/106710) in two steps, not including start and end [Start for reference] ``` golf="code" goof="cold" print golf ``` Step 1 ``` golf="code" golf="cold" print golf ``` Step 2 ``` golf="code" golf="gold" print golf ``` [End] ``` golf="code" golf="golf" print golf ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), cracks [alephalpha's answer](https://codegolf.stackexchange.com/a/241503/100563) Well someone has to do it... One step:remove the comma. ``` go="co";lf="de";print(go,lf) go="co";lf="de";print(go lf) ``` [Try it online!](https://tio.run/##K0gsytRNL/j/Pz3fVik5X8k6J81WKSVVybqgKDOvRCM9XyEnTfP/fwA "Pari/GP – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 2 steps, cracks [alephalpha's second answer](https://codegolf.stackexchange.com/a/241509/100563) first spacify the first comma to output gode ``` g=c;f=e;l=d;print(g o,l,f) ``` then the last for golf ``` g=c;f=e;l=d;print(g o,l f) ``` [Try it online!](https://tio.run/##K0gsytRNL/j/P9022TrNNtU6xzbFuqAoM69EI10hXydHIU3z/38A "Pari/GP – Try It Online") [Answer] # [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), 3 steps, cracks [@Fmbalbuena's answer](https://codegolf.stackexchange.com/a/241569/9365) Using the list provided in the question: * `3130<202(^+@)`: [code](https://tio.run/##S03OSylITkzMKcop@P/f2NDYwMbIwEgjTttB8/9/AA) * `3138<202(^+@)`: [cole](https://tio.run/##S03OSylITkzMKcop@P/f2NDYwsbIwEgjTttB8/9/AA) * `2138<202(^+@)`: [cold](https://tio.run/##S03OSylITkzMKcop@P/fyNDYwsbIwEgjTttB8/9/AA) * `2138<242(^+@)`: [gold](https://tio.run/##S03OSylITkzMKcop@P/fyNDYwsbIxEgjTttB8/9/AA) * `2338<242(^+@)`: [golf](https://tio.run/##S03OSylITkzMKcop@P/fyNjYwsbIxEgjTttB8/9/AA) [Answer] # [JavaScript (Node.js)](https://nodejs.org), cracks [@Arnauld's answer](https://codegolf.stackexchange.com/a/241524/9365) Didn't include `~` in my search originally which meant I got it in 7 programs... ``` _=>(0x63044+185882).toString(36), // coda _=>(0xd3044+185882).toString(36), // mice _=>(0xd3044+~85882).toString(36), // gond _=>(0xd3004+~85882).toString(36), // golf ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/R/NFW9rp2FQYWZsYGKibWhhamFhpqlXkh9cUpSZl65hbKapo6Cvr5AMUouh0gi7ykSomSn4VeZmJqeiqKzDpTI9Py8FodIAr8qcnP8YKi2wq0zjitVLyy9yTUzO0NBI01SwtQO6Pq84PydVLyc/XSNNQ1NT8z8A "JavaScript (Node.js) – Try It Online") Used [this program](https://tio.run/##hZFhb9owEIY/J7/iJjFiL8aJCaSppvRb/8D2kbWra0yaysRtHKp2jP51dpBkggo2S2fZuudev3d@lC/Sqbp8akaVnevtduYHP/MrEr@mSTyZhCKbZllKeWO/N3VZFSRJacAgikAhfoIdn2Flz87/wy5LpY/Z97NsYav5ARv/mzXmBJudYRf@DV/Y@lqqB0JsXRZlJU3LUcivYO17ylaugT73TbuVaSAHol@k@VhCCf3q@95swmDKIGVwwSBjcMlAxBgCY4yRYCAikBEICaQEYmPkkvjAUNl78Gac8wBiMU4m0/QiuxyF0Rf@@Xb4W96ruV5U9vU9OCis9ZORSi911fyV8Jr6rT10Lbm9Z2zluAnuVveYImgY3w/hQAtvp9kSM4KyvbhXH4/IHY0GV7kA0jJ8KRu0G93O5OjXTTiIKAyH0NV/yvMPU6ed/b1/azQ3tiB3wWDdPrFpf3Ww7sQ74yT64cKoWDoGAQR0c4c@diIbv9/UzgW67fQBF@q455U26qGnNruy3Yax3f4B) combined with `grep`ing the dictionary to refine the results and then guesswork on which paths felt more likely to head towards `golf`! [Answer] # Charcoal, Cracks [@Neil's answer](https://codegolf.stackexchange.com/a/241531/9365) * [`⍘⍘$zPγβ`](https://tio.run/##S85ILErOT8z5//9R7wwgUqkKOLf53Kb//wE "Charcoal – Try It Online") - `code` * [`⍘⍘$zZγβ`](https://tio.run/##S85ILErOT8z5//9R7wwgUqmKOrf53Kb//wE "Charcoal – Try It Online") - `codo` * [`⍘⍘#zZγβ`](https://tio.run/##S85ILErOT8z5//9R7wwgUq6KOrf53Kb//wE "Charcoal – Try It Online") - `caul` * [`⍘⍘#xZγβ`](https://tio.run/##S85ILErOT8z5//9R7wwgUq6IOrf53Kb//wE "Charcoal – Try It Online") - `cand` * [`⍘⍘#xjγβ`](https://tio.run/##S85ILErOT8z5//9R7wwgUq7IOrf53Kb//wE "Charcoal – Try It Online") - `cant` * [`⍘⍘9xjγβ`](https://tio.run/##S85ILErOT8z5//9R7wwgsqzIOrf53Kb//wE "Charcoal – Try It Online") - `nigh` * [`⍘⍘9?jγβ`](https://tio.run/##S85ILErOT8z5//9R7wwgsrTPOrf53Kb//wE "Charcoal – Try It Online") - `naga` * [`⍘⍘,?jγβ`](https://tio.run/##S85ILErOT8z5//9R7wwg0rHPOrf53Kb//wE "Charcoal – Try It Online") - `girn` * [`⍘⍘,hjγβ`](https://tio.run/##S85ILErOT8z5//9R7wwg0slIP7f53Kb//wE "Charcoal – Try It Online") - `goli` * [`⍘⍘,hgγβ`](https://tio.run/##S85ILErOT8z5//9R7wwg0slIP7f53Kb//wE "Charcoal – Try It Online") - `golf` [Answer] # Python 3, cracks [Fmbalbuena's answer](https://codegolf.stackexchange.com/a/241877/101522) ``` golf="code" try:exec("print( golf )") except:print("a") ``` ``` golf="code" try:exec("print( golf')") except:print("a") ``` ``` golf="code" try:exec("print('golf')") except:print("a") ``` Adding the first `'` causes the `exec` to error, which goes to the except and prints `a`. After that, you can add the second `'`, which changes the contents of the `exec` to `print('golf')`, which outputs the target. ]
[Question] [ In this challenge, the task is to write a program or function which simulates a number of people walking. Input will be some representation of the people's positions on a 2d grid, and one of four directions (or none) for each. The movement follows a few rules: * No person can walk into a space occupied by a person who is not moving * No two or more people can walk into the same space (none of them move) * No two adjacent people can swap positions If a person would not collide with another, they will move one space in the specified direction. You can choose how directions are represented. All coordinates are pairs of integers. No two people will start in the same position. ### Test cases: Inputs are represented as pairs of coordinates (`[x, y]`), followed by a direction. Outputs are only the resulting coordinates. All of these have four people for simplicity, but inputs can consist of any (non-zero) number of people. **Input 1:** ``` [[[0, 0], +y], [[-1, 0], +x], [[-2, 0], +x], [[1, 0], -x]] ``` **Output 1:** ``` [[0, 1], [-1, 0], [-2, 0], [1, 0]] ``` **Input 2:** ``` [[[0, 0], none], [[0, 1], +y], [[0, 2], +y], [[0, 3], +x]] ``` **Output 2:** ``` [[0, 0], [0, 2], [0, 3], [1, 3]] ``` **Input 3:** ``` [[[0, -1], +y], [[0, -2], +y], [[0, -3], +y], [[1, -2], -x]] ``` **Output 3:** ``` [[0, 0], [0, -1], [0, -3], [1, -2]] ``` **Input 4:** ``` [[[0, 0] +x], [[1, 0], +y], [[1, 1], -x], [[0, 1], -y], [[2, 0], +x]] ``` **Output 4:** ``` [[1, 0], [1, 1], [0, 1], [0, 0], [3, 0]] ``` **Input 5:** ``` [[[0, 0] +x], [[1, 0], +y], [[1, 1], -x], [[0, 1], -y], [[2, 0], -x]] ``` **Output 5:** ``` [[0, 0], [1, 0], [1, 1], [0, 1], [2, 0]] ``` **Input 6:** ``` [[[0, 1], -y], [[1, 1], -x], [[1, 0], +y], [[0, 0] +x], [[2, 0], +x]] ``` **Output 6:** ``` [[0, 0], [0, 1], [1, 1], [1, 0], [3, 0]] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes per language wins! [Answer] # [J](http://jsoftware.com/), 60 58 50 47 bytes ``` [:+/(*1,:1-(1<1#.+/=/+/)+{.(~:*[=i.{_,~])+/)^:_ ``` [Try it online!](https://tio.run/##pVFNS8NAEL33VzxUaNIkm27SVFjMRcGTePBadCkhoQahYHJQKv3rcfYjuyEiCJJMeJl582bebjtcsGWDUmCJGGsIioTh7unhftiJKA1WPBY8CfgNv2RRWqZRGkYnFpzFale@spOMz88h5V6EHMJFXR2OWLcckt4MHIlAgy@BDTJcUWWtq1QmpIJYI1IflV9YFWJmFDkV8rkOPVpIixmeBkSetEtFkEqAdplvIm23gpmHuYW6R5La4y1D/dG/79HXXY9q39U/bRbYgnu31393CxRjautSpKV6zXAz9rN6q3FssPHDuQp1XfOzsV5UFZql3RJ0hvru4O10RtKuxTEeJv3mrZcvnClu1jc8bhy6LgUzLTVuat1OtLN/yMqprqfy39Z13U7RD7FTzbrDNw "J – Try It Online") Takes input as a matrix of complex numbers -- starting positions in the 1st row, steps to walk in the 2nd row. Passes all test cases including those suggested by tsh and the cycle of 4 suggested by xnor. ## tldr how We iteratively adjust the steps to be 0 for impossible moves (same destination `(1<1#.+/=/+/)` or `+` swaps `{.(~:*[=i.{_,~])+/`) until they reach a fixed point `^:_`. Iteration is needed because some steps only become illegal after a walker changes from someone who will move to someone standing still. There's a chain reaction. After that iteration, impossible steps will have been converted to 0, and legal steps will remain what they were. Once that's done, we just add those steps to the starting positions `[:+/`. [Answer] # [Python 2](https://docs.python.org/2/), ~~127~~ ~~112~~ 104 bytes ``` def f(l):r=map(sum,l);exec"r=[[p,x][r.count(p)>1or[x+d,-d]in l]for p,[x,d]in zip(r,l)];"*len(l);return r ``` [Try it online!](https://tio.run/##lY1BDoIwEEX3nqJxRWVqGNhJ8CJNFwZKhEBpRkiql8dS0Ghcufozkzf/2ft4HUw6z5WuWR11/ERFf7HRbeqh47l2utxTIaUFpyQdy2EyY2T5GQeSLq5AVKoxrFP1QMyCdBD2R2Mj8v8q3x86bXxtTnqcyDCaLTVm9CopE8BWgRQIuEQaAkGgUnz3iSXLvV3pdMvM5zcnNoT5qveUvSZcjr/VqzI0YoyBCC6xyuDvh6CYnw "Python 2 – Try It Online") Takes input as a list of pairs of complex numbers, outputs a list of complex numbers. Initially has everyone walk unless they would swap and then repeatedly sends back anyone who collided until there are no collisions left. -8 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes ``` Wφ«≔⁰φFθ¿∧§κ¹∨№θ⟦Σ걧κ¹⟧⊖№EθΣλΣκ«≔⊟κφ⊞κ⁰»»Eθ⭆¹Σι ``` [Try it online!](https://tio.run/##VY4/D4IwEMVn@BQ3XhNIrI5ORBcHlcSRdCBQoIJFSlETw2evLf6/6b27e7@8rEpV1qaNMddKNBywIHD3vajvRSlxFkBBlr5XtAqwIyAKwEjmGOmNzPkN6wAoCWCvcNUOUmMXQHIYTljb5Y6Xqeb/r4TZw5pnip@41Dx/xbbp2UVdsiHkKWrixnV5l4nb8wSeGnnx0FcOOnNu9Ec/VuIHpa0rnaFPnJhwS2OSJAnp0ZY5Mls2nH/l4iPptA4pY8yEl@YB "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of pairs of complex numbers and outputs a list of complex numbers. Explanation: ``` Wφ« ``` Repeat while a flag value is non-zero. ``` ≔⁰φ ``` Zero out the flag value. ``` Fθ ``` Loop over the people. ``` ¿∧§κ¹ ``` If they want to move, and... ``` ∨№θ⟦Σ걧κ¹⟧ ``` ... they would be swapping with the person at their destination, or... ``` ⊖№EθΣλΣκ« ``` ... another person would end up at the same destination, then: ``` ≔⊟κφ ``` Set the flag value by removing that person's desired movement, and... ``` ⊞κ⁰ ``` Replace their movement with standing still. ``` »»Eθ⭆¹Σι ``` Print the final positions. (I've printed them on separate lines as that's what Charcoal's default output should be, although Charcoal doesn't know how to output complex numbers, so I've had to cheat slightly. I could extend that cheat and simply output the whole list as a Python array which would save two bytes.) ]
[Question] [ I can see that it is 101 'moving to the right' but I cannot think of a short way to generate it in R language. \$\begin{bmatrix} 0 & 1 & 0 & 0 & 0 & 0 \\ 1 & 0 & 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 & 0 & 1 \\ 0 & 0 & 0 & 0 & 1 & 0 \\ \end{bmatrix}\$ [Answer] # [R](https://www.r-project.org/), ~~24~~ ~~23~~ ~~22~~ 20 bytes ``` diag(0,6)+c(!-1:4,1) ``` [Try it online!](https://tio.run/##K/r/PyUzMV3DQMdMUztZQ1HX0MpEx1Dz/38A "R – Try It Online") Just use R's recycling! This does give a warning, but otherwise is fine. Thanks to Robin Ryder for the 2 byte golf. [Answer] # [R](https://www.r-project.org/), ~~30~~ 27 bytes ``` +!abs(outer(1:6,1:6,`-`))-1 ``` [Try it online!](https://tio.run/##K/r/X1sxMalYI7@0JLVIw9DKTAeEE3QTNDV1Df//BwA "R – Try It Online") Another alternative. Note this matrix shows which integers between 1 and 6 are exactly 1 apart. (i.e. \$|i - j| = 1\$). Thanks to @RobinRyder for saving a byte! I was forgetting `+` could be used as a unary operator. Thanks also to @Giuseppe for saving 2 bytes! If a matrix of logical values is permissible, then this also works: # [R](https://www.r-project.org/), 26 bytes ``` abs(outer(1:6,1:6,`-`))==1 ``` [Try it online!](https://tio.run/##K/r/PzGpWCO/tCS1SMPQykwHhBN0EzQ1bW0N//8HAA "R – Try It Online") This is also the closest to my shortest Jelly solution to this: # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` 6ạþ=1 ``` [Try it online!](https://tio.run/##y0rNyan8/9/s4a6Fh/fZGv7/DwA "Jelly – Try It Online") [Answer] # [R](https://www.r-project.org/), 34 bytes ``` x=cbind(rbind(0,diag(5)),0) x+t(x) ``` [Try it online!](https://tio.run/##K/r/v8I2OSkzL0WjCEwa6KRkJqZrmGpq6hhoclVol2hUaP7/DwA "R – Try It Online") Outputs ``` [,1] [,2] [,3] [,4] [,5] [,6] [1,] 0 1 0 0 0 0 [2,] 1 0 1 0 0 0 [3,] 0 1 0 1 0 0 [4,] 0 0 1 0 1 0 [5,] 0 0 0 1 0 1 [6,] 0 0 0 0 1 0 ``` Builds a \$5\times5\$ diagonal matrix, pads with 0s at the top and the right, and adds it to its own transpose. ]
[Question] [ # Context: Gynvael Coldwind, a famous security researcher, published a contest [in his blog post](https://gynvael.coldwind.pl/?lang=pl&id=710) (that is now complete). The goal was similar to the one described here, but with certain restrictions depending on which of the three allowed programming languages was chosen. I found the exercise fun and wanted to extend the challenge to all programming languages allowed. # Goal: The goal of this golf is to write a program as short as possible that generates a **PNG** file which, after converting to bitmap shares the same resolution and pixel color values as the following image ([alternate link](https://gynvael.coldwind.pl/img/confidence_2019_golf.png), SHA256: ab18085a27c560ff03d479c3f32b289fb0a8d8ebb58c3f7081c0b9e1895213b6): [![enter image description here](https://i.stack.imgur.com/Jlujd.png)](https://i.stack.imgur.com/Jlujd.png) # Rules: 1. The program must work offline, i.e. when the language runtime/interpreter is installed, no internet connectivity is installed to build/run the program, 2. The program may not rely on any external libraries (only use standard library of your language, as opposed to adding libraries from pip/npm/cargo/maven/whatever repositories), 3. The program must complete its operation within 60 seconds on a regular desktop computer (i.e. no brute-forcing the results). [Answer] ## C#, ~~849~~ ~~793~~ 771 bytes ``` using System;using System.Drawing;using System.IO;class P{static void Main(){dynamic x,y,i=new Bitmap(Bitmap.FromStream(new MemoryStream(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAGAAAAA2BAMAAADKYYHhAAAAGFBMVEUAAABdAgSMAwb///+jBAfFgYLRgYOugIE5HrT9AAAA20lEQVR4AWKgHIwCQThAFmVECAsA2qsDk4qBGIzjD7qAn5ngvlvAJJ3AdyscTqAr3PqaQwMgVYATKvQPlED5kQaAng2QBVnoCywBVeFQqKu6im83gcP1GFgVqEMVqiIP25MIzRjlmgSPZNufK/Qj1wC+bSKk2w/gHkDUaFZrEXht+85jcDc6FAHcqgsqvX3fkCxfcFZiaK3xL8EckS0ArfVO8u31C4y+FAQBBgbLAOYE9v8HxgDAgiiPXgk6gPykz8ctOzPIgHl0f8mjB1aDGQuyxeDgx3KB37t6B3NXgUgfIi7ZAAAAAElFTkSuQmCC"),0,312))),d=new Bitmap(1920,1080),g=Graphics.FromImage(d);for(y=0;y<54;y++)for(x=0;x<96;x++)g.FillRectangle(new SolidBrush(i.GetPixel(x,y)),new Rectangle(x*20,y*20,20,20));d.Save("s.png");}} ``` Tested with the following code: ``` class P { static void Main() { Bitmap a = new Bitmap(@"c:\projects\confidence_2019_golf.png"); Bitmap b = new Bitmap(@"c:\projects\s.png"); Console.WriteLine(a.Width + ", " + b.Width); Console.WriteLine(a.Height + ", " + b.Height); for (int y=0; y<a.Height; y++) { for (int x=0; x<a.Width; x++) { Color ca = a.GetPixel(x, y); Color cb = b.GetPixel(x, y); if (ca.R != cb.R || ca.G != cb.G || ca.B != cb.B) { Console.WriteLine(x + ", " + y); Console.WriteLine(ca.R + ", " + ca.G + ", " + ca.B); Console.WriteLine(cb.R + ", " + cb.G + ", " + cb.B); } } } } } ``` Ungolfed: ``` using System; using System.Drawing; using System.IO; class P { static void Main() { dynamic x = 0; dynamic y = 0; dynamic b = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAGAAAAA2BAMAAADKYYHhAAAAGFBMVEUAAABdAgSMAwb///+jBAfFgYLRgYOugIE5HrT9AAAA20lEQVR4AWKgHIwCQThAFmVECAsA2qsDk4qBGIzjD7qAn5ngvlvAJJ3AdyscTqAr3PqaQwMgVYATKvQPlED5kQaAng2QBVnoCywBVeFQqKu6im83gcP1GFgVqEMVqiIP25MIzRjlmgSPZNufK/Qj1wC+bSKk2w/gHkDUaFZrEXht+85jcDc6FAHcqgsqvX3fkCxfcFZiaK3xL8EckS0ArfVO8u31C4y+FAQBBgbLAOYE9v8HxgDAgiiPXgk6gPykz8ctOzPIgHl0f8mjB1aDGQuyxeDgx3KB37t6B3NXgUgfIi7ZAAAAAElFTkSuQmCC"); dynamic i = new Bitmap(Bitmap.FromStream(new MemoryStream(b, 0, 312))); dynamic d = new Bitmap(1920, 1080); dynamic g = Graphics.FromImage(d); for (y = 0; y < 54; y++) { for (x = 0; x < 96; x++) { g.FillRectangle(new SolidBrush(i.GetPixel(x, y)), new Rectangle(x * 20, y * 20, 20, 20)); } } d.Save(@"c:\projects\s.png"); } } ``` [Answer] ## HTML + Javascript, ~~607~~ ~~591~~ 527 bytes Thank you Epicness and Someone. HTML, 436 bytes ``` <img id=a src=data:;base64,UklGRgABAABXRUJQVlA4TPMAAAAvX0ANALXIcSTJkST68N2Xs2p6ZJgUYgEpOVBwcYtMwGKJpBDAL5EUqioEEAAFTf8n4Akeel/aoYdx8E3jdbec+Bj0CQIKAqIiKqjd3hEU1L/CRATRBWhApHdtTIzZysYT0r794RjJEja6QbvdpUT9W1xDMYkxMQYEjWM4HPkrhiZRGjZoojYx0THU87bTZpWN2U6bJGMxF1qbRQ69BMYY48POObP4kX5/5753WXNeKm2SAFRBVRKqWK2CKkjmvG1VVbHY7K+aM7lk5mS1qqlaq2raKuh/9u1jI0BVVQNzzmJ3VRVcNluTcPxlBPR/7f3rMRIA><a id=b download>SAVE<canvas id=c width=1920 height=1080 ``` Javascript, 91 bytes ``` b.href=c.toDataURL((d=c.getContext`2d`).drawImage(a,d.imageSmoothingEnabled=0,0,1920,1080)) ``` [JSFiddle](https://jsfiddle.net/wynj3hmL/) [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 707 bytes ``` #r"System.Drawing" using System.Drawing.Drawing2D;dynamic a=new Bitmap(new MemoryStream(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAGAAAAA2BAMAAADKYYHhAAAAGFBMVEUAAABdAgSMAwb///+jBAfFgYLRgYOugIE5HrT9AAAA20lEQVR4AWKgHIwCQThAFmVECAsA2qsDk4qBGIzjD7qAn5ngvlvAJJ3AdyscTqAr3PqaQwMgVYATKvQPlED5kQaAng2QBVnoCywBVeFQqKu6im83gcP1GFgVqEMVqiIP25MIzRjlmgSPZNufK/Qj1wC+bSKk2w/gHkDUaFZrEXht+85jcDc6FAHcqgsqvX3fkCxfcFZiaK3xL8EckS0ArfVO8u31C4y+FAQBBgbLAOYE9v8HxgDAgiiPXgk6gPykz8ctOzPIgHl0f8mjB1aDGQuyxeDgx3KB37t6B3NXgUgfIi7ZAAAAAElFTkSuQmCC"))),b=new Bitmap(1920, 1080),c=Graphics.FromImage(b);c.InterpolationMode=(InterpolationMode)5;c.PixelOffsetMode=(PixelOffsetMode)4;c.DrawImage(a,0,0,1920,1080);b.Save("b.png"); ``` Only compiles in the interactive window, saves the result in a file called `b.png` [Answer] # C (GCC/MinGW), ~~1439~~ ~~1406~~ ~~1386~~ ~~1382~~ ~~1092~~ ~~807~~ ~~806~~ ~~800~~ ~~789~~ ~~787~~ ~~786~~ 777 bytes -33 -4 -11 -9 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) -6 bytes thanks to [someone](https://codegolf.stackexchange.com/users/36445/someone)'s idea Edit: Why even dynamically calculate CRCs when the output is static? Dropping that part really slimmed things down. Somewhat beefier than other entries, but such is C life. Assumes `sizeof(unsigned int) == 4`, i.e. 32-bit integers, and little-endianness. The earlier RLE scheme is replaced by a slightly more complex one. Most of the image (except the "CONFIDENCE" text) is stored as a series of rectangles. Each rectangle is stored as four characters holding (x1, y1) and (x2 + 1, y2 + 1). We start with the lowest colour in the palette and upon hitting a space character in the image data, we increase the palette index. I have a feeling further compression could be had by storing colours slightly differently and exploiting the additive nature of the colours of overlapping areas. The "CONFIDENCE" text is stored as a series of characters holding 6 significant bits, each one of which corresponds to a "pixel" in the text. ``` #define Y*Q++-31 *o,C,x,i,W=5760,H=1080,Z[]={262749,394124,459939,8487086,8552901,8618449,~0};S(b,D,C,B,A,c)char*b;{for(B*=20;B<D*20;B++)for(x=A*20;x<C*20;)bcopy(Z+c,b+B*W+x++*3,3);}(*X)()=fwrite;main(j){char*p=calloc(W,H),d[]="\0\x81\26~\xe9",*Q="&&<57)V;22?E;9LOI3eI[%o7_1yA 7)<;2275;2?EC9I;I3V;I;LI[3_7_1o7_7eA 72<5;9?;_3e7 C;E?G;I?M;O?W;Y?[;]?GAIEMAOEWAYEaAcE??CA?ECG]EaG]9_;]?_ALEMG ?9C;L9M;_9a;_?aAa;c?=A?EIELG I9L;";for(;*Q;)S(p,Y,Y,Y,Y,C+=*Q<33&&Y);for(X("\x89PNG\r\n\32\n\0\0\0\rIHDR\0\0\a\x80\0\0\48\b\2\0\0\0g\xb1V\24\0_\5VIDAT\b\35",1,43,o=fopen("a.png","wb"));i<240;i++)"FStuybLGitTTJfRAaTuUzjBGiTVTJrRAFSTtybLG"[i/6]-64>>i%6&1&&S(p,C+1,j+1,C=17+i/48,j=26+i/6%8*6+i%6,6);for(;H--;p+=X(p,1,W,o))*d=!H,X(d,1,6,o);X("*vC\6\xc7\xe3\20W\0\0\0\0IEND\256B`\x82",1,20,o);} ``` [Answer] ## HTML + javascript, 504 bytes - Not competing I still need to get the colors sorted out. HTML, 35 bytes ``` <canvas id=g width=1920 height=1080 ``` Javascript, 469 bytes ``` d=g.getContext`2d` d[f='fillRect'](0,0,1920,1080) d[a='globalAlpha']=.4 d[l='fillStyle']=`#a00` '//>7|@2G:|;;5;|DB9>|R<D>|d.<:|h:B8'.split`|`.map(x=>x.split``.map(c=>(c[w='charCodeAt']()-40)*20)).map(x=>d[f](...x)) d[l]='#fff' d[a]=1 q=(h,x,y,p,z)=>{b=atob(h).split``;for(var n in b){for(j=8;j--;)b[n][w]()&1<<j&&d[f](x+(n%p*8+j)*z,y+((n/p)|0)*z,z,z);}} q('xkTXucgcKU1RiikFIVVXuiocKWVRiiwFxkTRucgc',520,340,6,20) d[a]=.4 q('xgADKKEEKKEEBgADISEEISEExgAD',600,520,3,40) ``` [JSFiddle](https://jsfiddle.net/q0jm2af8/) ]
[Question] [ This challenge is inspired by a board game I played some time ago. The story of this challenge doesn't necessarily have to be read, the **goal of the challenge**-section should explain everything necessary. ## The Story *People are locked inside a large room with a human-devouring monster. The walls of the room are enchanted, teleporting objects across the room when touched. Said monster marches across the room, hunting for flesh. The first human in its sight will be consumed by its sharp teeth.* ## The Goal of the Challenge You are given the map of the room, including the people's and the monster's location. ``` %%%KLMNOPQRSTA% %%J B %I % C H D G %% E F F E % G D H C % I% B J%% %ATSRQPONMLK%%% ``` Let's break down the components of the map. * **Letters from `A` to `T`:** If the monster steps onto one of these, it will be teleported to this letter's second appearance and not change its direction. There will only ever be zero or two of any letter on the board. * **`%`:** Wall tiles. Just for formatting & nice looks. * **`#`:** The monster's starting location. * **`*`:** The people's locations. * **:** Empty tiles, the monster can move freely on them. Some additional things to note about the map: * The map dimensions and object location will not be constant, so your code will have to dynamically adapt to that. --- The monster will **always** go in the direction that it currently facing (facing west at the start) **unless** it spots a human, in which case it will turn towards the **closest** human. The monster spots a human if there are no wall or teleporter tiles in a straight horizontal or vertical line between it and the human. Another thing to note is that if the monster is in front of a solid wall (`%`) or has to decide between two humans, it will always prioritize **right** over left. If the monster is **not** able to *turn right and make a step forwards* for some reason, it will turn **left** instead. So, in the end, the order that the monster prioritizes directions would we forward, right, left, backwards. ## Input * The map, including the monster's starting location and the people's positions as their respective characters. There should not be any other input than the map string, or the array of strings, or characters. The input may be received in any reasonable format; a single string or an array of strings for the map. ## Output The coordinate of the person that first gets eaten by the monster. The coordinates start from the top-left corner and are 0-indexed, so the first tile will have the coordinates (0|0). If you are using 1-indexing, please specify it in your answer. ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes in any language wins. * Standard loopholes are forbidden. * You may assume that the monster will always be able to reach a human. --- ## Test Cases Input: ``` %%%KLMNOPQRSTA% %%J B %I %* C H * D G %% E F # F E % G D * H C % I% B J%% %ATSRQPONMLK%%% ``` Output: `(10,2)`, since the monster cannot see the two other people when it runs past them, it gets teleported to the other `F` wall, where it will then see the last person. Input: ``` %%%KLMNOPQRSTA% %%J B %I * C H %%% * D G #% E F %%% % F E G D % H C * I% B * J%% %ATSRQPONMLK%%% ``` Output: `(12,3)` Input: ``` %%%KLMNOPQRSTA% %%J B %I %%% C H *%#% D G E F F E % G D H C I% B J%% %ATSRQPONMLK%%% ``` Output: `(6, 3)` Input: ``` %%%%%%%%%%%%%%% %#% %%% % %A%ABCD %*% % %*F G %%% % % %BC% FD % % % % %%%% % % % %% % % %% G % % % %*% % % % %%%%%%%%%%%%%%% ``` Output: `(1,9)` --- Good luck! [Answer] # [Python 2](https://docs.python.org/2/), ~~565 .. 422 4451 .. 444 4632 .. 468~~ ~~467~~ 463 bytes ``` u,U='*%' G=lambda s:u==s.strip('# ')[0]and len(N)-s.find(u) b=input() D=3;j=''.join;N,w,P,t,B=j(b),len(b[0]),[0,1,0,-1],{},map(j,zip(*b)) for c in N: l,r=N.find(c),N.rfind(c) if u<c:t[l]=r;t[r]=l if'#'==c:x,y=l%w,l/w while u!=b[y][x]: O=[B[x][y-1::-1],b[y][x+1:],B[x][y+1:],b[y][x-1::-1]];L,R=O[D-1],O[~D] if u<b[y][x]:X=t[x+w*y];x,y=X%w,X/w elif(G(O[D])<1)*(G(R)+G(L)+(U==O[D][0])):D-=0<G(L)>G(R)or(U==R[0])*-~(U==L[0])or-1;D%=4 x+=P[D];y+=P[~D] print x,y ``` [Try it online!](https://tio.run/##rVNtb9owEP7uX3EDWYmNYbBN@xDqSUAGfaFAaStVyvKBVzUoDSgEAZvWv858cQLJqCZtmj84d8/Zd8/jy6320fMy@HBoyUKhcNiIR2lwapCO9Ecv4@kI1tZGynVlHYXeyjSKYDCn6o6CKfizwOyx8roy94KpuWFkLL1gtYlMRmz5sb6QhlFZLL2g3hNbMRCRaMqFOWYC741VDiacqqiJqijXXPHjp3gZrcyF@K6q8DFjZL4MYQJeAD2LgC9C2dOFJkz0KmFiEvDmsLmYWJHjuzKsR07oSh9Ro2hIObF2Yi99uhX@@y3ZPnv@DDbv5NjZu87OVXn70mkqy9mXa5aFPHSoVLNcoQOxqdHkjFvviqHsOzae7zuvtpuwSNM@yUil2PK9W8fyT6r8kyoPM9@bmx1T3XTZRY1xZQ9ZqWN2Wcl8lJjRxWdhll2W1QvEv@CJZYjRIYZ4@RXtLtrLsFyr21R@IrAryYG6XN/jF/msQi@IQBU/qJ4SMg1HW1klJFwuX0ACYjS/CC1S0Et5oPwGbTRbNvo89nk7jnbSONBmi0Lb1nfQx2@SIPFPKYmOUhqnAO2fFubXd/VGz/ghZ/XIqMQCLQ/VODXsSGW98r3ILHwLCozM/PXMgtluNoEW/3xwDHX9pnvb6w/uhvcPDWoIUNB1pnozhq5SLlxtLYQulcGPp2yEOrGaFPqKUDtxivHeRuhrkkl/Ogjpd0rTXSLUOh0BuIp5NTOsrqmm2ni4H94N@r3b7o1SYrjkbxXpmkdFusMIHxUhe/q7In2K5hTBuaJEwlHRsWJeEf@PijSzrCKe/L5ZRW/1CM56lNDPKYJzRf/Uo@yKj@VnTN/MjVkM5ScthvLDlkDZeTtCpwoayk1dCmUGT1fMzZ5@/Dz7rCKdhWNP07pYIbWLGYoZnJ/K/Skp5zmaid0oQuMtHN5I@gs "Python 2 – Try It Online") Saved a lot of bytes thanks to [Halvard](https://codegolf.stackexchange.com/users/72350/halvard-hummel), [Ian](https://codegolf.stackexchange.com/users/74686/ian-g%c3%b6del) and [Jonathan](https://codegolf.stackexchange.com/users/73111/jonathan-frech) 1: Got longer, in order to fix the case of turning twice, and to find the location of the monster. 2: Got even longer.. Monster shouldn't change direction on when teleporting. [Answer] # [Perl 6](https://perl6.org), ~~343~~ ~~334~~ ~~333~~ ~~328~~ ~~322~~ 308 bytes ``` {my \m=%((^@^a X ^@a[0]).map:{.[0]i+.[1]=>@a[.[0]][.[1]]});my \a=m<>:k.classify ({m{$_}});my$m=a<#>[0];my$d=-1;{$d=($d,i*$d,-i*$d,-$d).min({$^q;first ?*,map {(((my \u=m{$m+$_*$q})~~"%")*(1+!($_-1))+(u~~"A".."Z"))*m+(u~~"*")*$_},^m}); $m+=$d;$m=$d+(a{m{$m}}∖~$m).pick while m{$m}~~"A".."Z"}...{m{$m}~~"*"};$m} ``` [Try it online!](https://tio.run/##3ZbLbtNAFIb3PMXgjKWZsTMiGxZNHZpLm6SllFIWiBBHVtMIqxmUNq1QZTlrnqAP2BcJc2JjG@rLODESYvPbc/vn2Od8Hi@ubuev1@IB4Rmy0NqTd1@EpRNiH9gO@oTsA2f0aky5cBZ7Hpe3rsFHjbHVkv3QHI@gOfZpE1Y6lthv7V3zy7mzXLqzB@IJD0/8zSgWlrNfa8k10Jha9UbTkxeCp6bLpNQDxVO5mfuNeNi@ac7c2@UdesNMuT3yCCGwyb0lTYWBJwzf@HS10nSNMtIwXhI8qTcoNci97GxrnGufNUqZCDqYnCVjMW0hw5HrLTyVF6kGcSBM4ftPPx5XWFC@cC@v0fev7vwKbQZiO59z7v3qY5ovHfx188XSgRco45OxmCghJyBvQU5B3oGcgbwHOQf5AHIB8hGkHaxF1ERJt2MQtJ10km5DxUWbySxloBu6DVLGWOnYeqFbPysEvYzbYeh2pDi/ljt6FLodKr6t/Cn90K1XPFXhNQ5Ct@52wcQyTNZbZ4cqO06kLFFv7aiyL6JqP48IOIuoOI1IOfk99@BG6d9grFLEShGWn@CulglYGhx67gY9LZOvNBj0Ar4U8MqPTE/gpUoXUqFLFS4FRAZaJlulsjlM1FlnB7MkWpWS9T@BpRcfGUpgscgiHwh1sJQOrlLnFio4t0qBpVcJFqoSLFQlWOjfAWtriWOslTno09B49sDxXSdgZVPjeT@G6WYsKMH8mlKNLJ4UB5U8QTJiRAVmqgTkJCBtYcl8/GGW5pP5PesXPOYu8iybeulPR3o2qyAAwFr/BA "Perl 6 – Try It Online") *(There are no newlines in the actual code. I inserted them just to wrap the lines for easier reading.)* **This is unable to deal with maps where it is possible to see outside of the map bounds. (I. e. maps with empty spaces at the border.) If this matters, +5 bytes.** But, since the teleporters block LoS now, it shouldn't. **Explanation**: It's a function which takes the map as a list of lists of characters. Let's break it down into statements: `my \m=%((^@^a X ^@a[0]).map:{.[0]i+.[1]=>@a[.[0]][.[1]]});`: Let's make a hash ("dictionary" for Pythonists) called `m` (it's a sigilless variable, so we need to be explicit about assigning a hash into it with `%(...)`) which associates complex keys of form `x+iy` with characters which are in the `y`th rown and `x`th column of the map. `my \a=m<>:k.classify({m{$_}});`: This makes an "inverse dictionary" of `m`, called `a`: there is one key corresponding to each value in `m`, and the value is a list of complex coordinates (keys in `m`) that contain that character. So, for instance `a{"#"}` will give a list of all coordinates where there is a `#` on the map. (This is also a sigilless variable, but we're in luck since `classify` returns a hash.) `my$m=a<#>[0];my$d=-1`: Set the initial monster position. We look up the `#` in the inverse hash `a`. We must use `[0]` since `a<#>` is still a list, even when it contains only 1 element. The `$d` contains the direction of monster; we set it to the West. (The direction is a complex number as well, so `-1` is west.) OK, the next statement is quite nasty. First, let's have a look at this: `{$^q;first ?*,map {(((my$u=m{my$t=$m+$_*$q})~~"%")*(1+!($_-1))+($u~~"A".."Z"))*m+($u~~"*")*abs($t-$m)},^m}` This is a routine that evaluates LoS in the given direction. If there is a human in this direction, it returns the distance to the human. If there is a wall or a teleport in this direction, it returns the total number of squares of the map. (The point is to give such a high number that it is greater than any legitimate distance to a human.) Finally, if the wall is in this direction *and* in distance 1, we return 2 × total number of squares of the map. (We want never ever be running through walls, so these need even a bigger score. We will be choosing the minimum shortly.) We use this in the construct `$d=($d,i*$d,-i*$d,-$d).min( LoS deciding block );`. Since we use complex numbers for everything, we can easily get directions which are relative forward, right, left and backwards from the original direction just by multiplying it by 1, i, -i (remember that the `y` axis goes the other way that you may be used to from math) and -1, respectively. So we form the list of directions in this order, and find the direction which has the minimal "distance to a human" (according to the block above), which makes sure that any human beats any wall and anything beats a wall which is right under the monster's nose. We use the fact that the `min` function gives the *first* minimal value. If there is a tie in distance between several directions, the monster will prefer forward to right to left to backwards, which is exactly what we want. So we get a new direction which is then assigned to `$d`. `$m+=$d;` just makes the monster step in the new direction. `$m=$d+(a{m{$m}}∖~$m).pick while m{$m}~~"A".."Z"` takes care of the teleports. Let's say the monster is at a teleport `A`. First we search for `A` in the inverse hash `%a` and that turns up the two positions of the teleport `A`, then we discard the current position using the set difference operator (which looks like a backslash). Since there are exactly 2 occurences of each teleport on the map and the monster is surely standing on one, the difference will be a set with 1 element. We then use `.pick` to pick a random element (believe or not, but this is the shortest way to get the element of 1-element set :—)). This kind of thing happens until the monster ends up somewhere not in a portal. Everything in the last 4 paragraphs describes one massive construction of form `{change direction; step; handle teleports}...{m{$m}~~"*"}`. This is a sequence that calls the block on the left of `...` until the condition on the right of the `...` is true. And that one is true when the monster is on a square with a human. The list itself contains return values of the huge block on the left, which is garbage (most likely `(Any)`) because it returns the value of the while loop at the end. Essentially, we use it as a cheaper while loop. The value of the list is discarded (and the compiler moans about a "useless use of `...` in a sink contest", but who cares). When this all is done, we return `$m` — the monster's position after it found a human, still as a complex number (so, for the first test, we give `10+2i` and so on). [Answer] # JavaScript (ES6), ~~258~~ 245 ``` g=>eval("m=g[I='indexOf']`#`,D=[w=g[I]`\n`+1,-1,-w,k=t=1],g=[...g];for(n=1/0;n;(o=g[m+=d=D[k]])>'@'?g[g[u=m]=t=1,m=g[I](o),u]=o:o<'%'?t=1:o<'*'&&(m-=d,k=k+t++&3))D.map((d,j)=>{for(q=0,u=m;g[u+=d]<'%';++q);g[u]=='*'&n>q&&(n=q,k=j)});[m%w,m/w|0]") ``` *Less golfed* ``` g=>{ var u, // temp current position q, // distance so far scanning for a human o, // value of grid at current position d, // offset to move given current direction n = 1/0 // current distance from human m = g.indexOf(`#`), // monster position w = g.indexOf(`\n`)+1, // grid width + 1 (offset to next row) D = [w,-1,-w,1], // offset for moves, clockwise k = 1, // current direction, start going west t = 1; // displacement for turn g=[...g]; // string to array while (n) // repeat while not found (distance > 0) { // look around to find humans D.forEach( (d,j) => { // for each direction // scan grid to find a human for(q=0, u=m; g[u+=d]<'$'; ++q); // loop while blank space if ( g[u] == '*' // human found at position u & n>q ) // and at a shorter distance than current { n = q; // remember min distance k = j; // set current direction } }) // if human found, the current direction is changed accordingly d = D[k] // get delta m += d // move o = g[m] // current cell in o if (o > '@') // check if letter (teleporter) { t = 1 // keep current direction, next turn will be right u = m // save current position in u g[u] = 1 // clear current cell, so I can find only the other teleporter m = g.indexOf(o) // set current position to other teleporter g[u] = o // reset previous cell content } else if (o > '%') // check if '*' { // set result, so we can exit the loop r = [ m%w, m/w|0 ] // x and y position } else if (o == '%') // check if wall { // turn m -= d // current position invalid, go back k = (k+t) % 4 // turn right 90° * t t = t+1 // next turn will be wider } else { t = 1 // keep current direction, next turn will be right } } return r } ``` **Test** ``` var F= g=>eval("m=g[I='indexOf']`#`,D=[w=g[I]`\n`+1,-1,-w,k=t=1],g=[...g];for(n=1/0;n;(o=g[m+=d=D[k]])>'@'?g[g[u=m]=t=1,m=g[I](o),u]=o:o<'%'?t=1:o<'*'&&(m-=d,k=k+t++&3))D.map((d,j)=>{for(q=0,u=m;g[u+=d]<'%';++q);g[u]=='*'&n>q&&(n=q,k=j)});[m%w,m/w|0]") var grid=[`%%%KLMNOPQRSTA%\n%%J B\n%I %* C\nH * D\nG %% E\nF # F\nE % G\nD * H\nC % I%\nB J%%\n%ATSRQPONMLK%%%` ,'%%%KLMNOPQRSTA%\n%%J B\n%I * C\nH %%% * D\nG #% E\nF %%% % F\nE G\nD % H\nC * I%\nB * J%%\n%ATSRQPONMLK%%%' ,'%%%KLMNOPQRSTA%\n%%J B\n%I %%% C\nH *%#% D\nG E\nF F\nE % G\nD H\nC I%\nB J%%\n%ATSRQPONMLK%%%' ,'%%%%%%%%%%%%%%%\n%#% %%% %\n%A%ABCD %*% %\n%*F G %%% %\n% %BC% FD %\n% % % %%%%\n% % % %%\n% % %% G %\n% %\n%*% % % %\n%%%%%%%%%%%%%%%' ] $(function(){ var $tr = $('tr') grid.forEach(x=>{ $tr.eq(0).append("<td>"+x+"</td>") $tr.eq(1).append("<td>"+F(x)+"</td>") }) }) ``` ``` td {padding: 4px; border: 1px solid #000; white-space:pre; font-family:monospace } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table ><tr/><tr/></table> ``` ]
[Question] [ ## Specifications Your program must can take in an integer `n`, then take in `n` more strings (containing only alphanumeric characters) in your preferred method (separated by whitespace, file input, hash table etc.). You must then find the permutation before the inputted strings when sorted in lexicographical order, and output that in your preferred method. If it is already sorted in lexicographical order, output the permutation in reverse regular lexicographical order. ### Rules 1. Code can be just a function 2. If you pipe in from a file, you can to exclude the file name's length from your program (just the filename, not full path) 3. If there are repeated characters, take the permutation before the first occurrence of the repeats ### Test cases ``` 3 abc hi def ``` The possible permutations of this (in lexicographical order) are: ``` abc def hi abc hi def def abc hi def hi abc hi abc def hi def abc ``` Now see that `abc hi def` is the 2nd permutation, so we output `abc def hi`. If instead we pick `abc def hi`(the first permutation), then output `abc def hi`. Another test case is in the title: your function should map `Permutation` to `Permutatino` ### Scoring: The winner is the code with the smallest score, which is the length of the code multiplied by the bonus. ### Bonus: 20% -90% (to keep non-esolangs in the fight) of your byte count if you can do this in O(N) time. -50% (stacks with the above -90% to give a total of -95%) if your solution isn't O(N!) which is listing out permutations, finding the element and getting the index, subtracting 1 from the index (keep it the same if the index is 0) and outputting the element with the subtracted index With the above 2 bonuses, I won't be surprised if there's a 2 byte answer. Hint: there is definitely a faster way to do this apart from listing all the permutations and finding the supposed element in the general case Congrats to @Forty3 for being the first person to get the O(N) solution! Here's some (C based) pseudocode: ``` F(A) { // A[0..n-1] stores a permutation of {1, 2, .., n} int i, j; for (i = n - 1; i > 0 && (A[i-1] < A[i]); i--) ; // empty statement if (i = 0) return 0; for (j = i + 1; j < n && (A[i-1] > A[j]); j++) ; // empty statement swap(A[i-1], A[j-1]); // swap values in the two entries reverse(A[i..n-1]); // reverse entries in the subarray return 1; } ``` If you want to test if your program is O(N), try with `n=11` and the strings being the individual letters of `Permutation`. If it takes longer than a second, it's most definitely not O(N). [Answer] # Python 2, ~~118~~ 96 - 50% = 48 bytes Takes input in the form `['abc','def','ghi']`. Note that this solution returns the list reversed if the input is sorted, as per a previous spec. ``` def f(n):m=n[1:];S=sorted;a=S(n);return[a.pop(a.index(n[0])-1)]+a[::-1]if m==S(m)else[n[0]]+f(m) ``` [Try it Online!](https://tio.run/nexus/python2#Lc1BCsQgDAXQq3RnpdMybhVP0WXIQjCCMEaxFub2NgOzeHyS8MmMlJa0srbFMxiL7vRX7YOiC/6Uves07s4QjlbbGo7Mkb4rwxv1bjRuAazdDea0FC@FoulzEfzuuCUZZ@uZh7wA1dRLkeiiiFsMEf6ZRRWsUM8H) Seems to be ~~the O(n) solution~~ more efficient than computing all permutations. **Explanation:** Recursively checks if everything after the current element is in `sorted` order. If so, returns the string immediately lexicographically before (`a.index(n[0])-1)`) the first element `+` the rest of the list reversed (`a[::-1]`). **Runtime: O(n^2 logn)** In the worst case (list is reversed), the function will call `sorted`, which has a runtime of **nlogn**, for each element in the list (`n` times). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 8 bytes ``` œ{ûD¹k<è ``` [Try it online!](https://tio.run/nexus/05ab1e#@390cvXh3S6HdmbbHF7x/3@0emJSsrqOgnpGJohMSU1TjwUA "05AB1E – TIO Nexus") **Explanation** ``` œ{ # get a list of sorted permutations of the input û # append a reversed copy excepting the last element of the original D # duplicate ¹k # push the first index of the input in the list < # decrement è # index into the list with this ``` [Answer] ## Python 2, 83 bytes -18 bytes, thanks to @Emigna Takes strings without number as input. As rules were clarified, this is the solution. [Try it online](https://tio.run/nexus/python2#RczBCsIwDMbx@54i4KGtU8Gr4mGXvcTYYdoMC7YpSQTfvrYy8BI@fn9IWZkiBEVWopdAiJlY953HFUY7uIvcpAJ6m5HjWxcNlKQG10/DfM0ckoJMcgrJ46f68TyX0Vqz3B/mAOYZ2q3fjHNd8zar/PPmG2z55wCwI/bI6MsX) ``` from itertools import* def F(A):s=sorted(permutations(A))+[A];print s[s.index(A)-1] ``` [Answer] # JavaScript, 460 399 369 332 - 95% = 16.6 bytes ## Unformatted ``` function f(n,v){var i=n-1,c=v[i],z="concat",y="slice",x="indexOf",w="reverse";for(;i>=0&&v[i]<=c;i--){c=v[i];}if(i==-1)return v;if(i==0){let s=v[z]().sort(),t=s[x](v[i])-1;return [s[t]][z]((s[y](0,t)[z](s[y](t+1)))[w]());}let p=v[y](0,i),r=v[y](i)[z]().sort()[w](),t=r[x](v[i])+1,m=r[t];r.splice(t-1,2,v[i]);return p[z]([m])[z](r);} ``` I am not convinced it is the O(n) solution but would appreciate if someone could take a quick glance and let me know. Also, I suspect there is some serious golfing which can be accomplished.. just haven't taken the time (yet). ## Formatted ``` function f2(n, v) { var i = n-1,c = v[i],z="concat",y="slice",x="indexOf",w="reverse"; for ( ; i >= 0 && v[i] <= c; i--) { c = v[i]; } if (i == -1) return v; if (i == 0) { let s = v[z]().sort(), t = s[x](v[i]) - 1; return [s[t]][z]((s[y](0, t)[z](s[y](t + 1)))[w]()); } let p = v[y](0,i), r = v[y](i)[z]().sort()[w](), t = r[x](v[i])+1, m = r[t]; r.splice(t-1,2,v[i]); return p[z]([m])[z](r); } ``` Fiddle: <https://jsfiddle.net/n2Lmswxf/8/> Edit 1 - whitespace and function name per @Emigna's suggestions. Edit 2 - using some pointers from the link @Emigna suggested. If I *ever* found this code in a system I had to maintain, I would hunt the developer down and flog him. Edit 3 - @Thunda - I hope it wasn't presumptuous to recalc the savings based on my latest golfing. Edit 4 - Removed a sort and simplified the final reassembly logic. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 - 50% = 4 bytes ``` Œ¿’»1œ?Ṣ ``` [Try it online!](https://tio.run/nexus/jelly#@3900qH9jxpmHtpteHSy/cOdi/7//x@tVKCko5QKxEVAnAvEpUBcAsSJUDoTiPOBOE8pFgA "Jelly – TIO Nexus") Runs in O(*n* log *n*) time. (This typically takes just over a second, due mostly to Jelly's startup time – the time of just over a second is true for both very short and fairly long inputs. There's some variation in how long it takes in TIO; the fastest I've observed is 0.914 real, 0.772 user, 0.121 system.) ## Explanation Jelly actually has builtins for most of the challenge, but the way they're defined requires a sort. As far as I know, Jelly uses a comparison sort to sort lists of strings, which is what leads to the O(*n* log *n*) performance. ``` Œ¿’»1œ?Ṣ Œ¿ Find index of {the input} in a sorted list of its permutations ’ Decrement it »1 saturating from below at 1 œ? Find the nth permutation of Ṣ the sorted input ``` `Œ¿` is a builtin with an optimized implementation (i.e. not slower than O(*n* log *n*)); it doesn't do brute-forcing. ## Variations If wrap-around is allowed (it was under an earlier version of the spec), you can remove the `»1` for a 6-byte solution and a score of 3. (Most of Jelly's builtins, including the relevant ones here, will naturally wrap around in the absence of other hints about what to do with an out-of-range value.) [Answer] # JavaScript ES6, 170 - 95% = 8.5 bytes ``` f=n=>a=>{while(--n&&a[n]>=a[n-1]);if(!n)return a;s=a.slice(--n);for(k=s.length;s[--k]>=a[n];);t=a[n];s[0]=s[k];s[k]=t;return a.slice(0,n).concat(s[0],s.slice(1).reverse())} function Permutatino() { input = document.getElementById("input").value.split(" "); console.log(input) num= input.length; document.getElementById("output").innerHTML=(f(num)(input)); } ``` ``` <input type="text" id="input" value="abc def ghi"> <button onclick="Permutatino()"> Run </button> <pre id="output"> ``` ``` n=>a=>{while(--n&&a[n]>=a[n-1]);if(!n)return a;s=a.slice(--n);for(k=s.length;s[--k]>=a[n];);t=a[n];s[0]=s[k];s[k]=t;return a.slice(0,n).concat(s[0],s.slice(1).reverse())} ``` This code is a sequence of O(n) operations. [Try it online!](https://tio.run/nexus/javascript-node#fdHBTsQgEAbgu0@hHDZMUshuPBL6IoQDVmhJETYMqwfjs9dWaroxtpfJBD7@geDkFGVrZPv5MfhgKWPxdDIq6lbOlV00CO/oU4Rsyy3HRyNQGo7Bdz8WhEuZjhJ5sLEvg0DF2FgPawGi1AbVWUtU49KNWhbxm7YmnZsIvEuxM4UutsF14wI823eb0VKAr2kmmILlIfXU0WegivSDJw15tW6u5qUjGuBhly2g4h1WczZ8yGragnfYBg6Hbrc6TLt/6UHaPfs/jVxtfrsVU3yKZP04@LOK1@ALJQQApm8) ## Explanation: ``` while(--n>0&&a[n]>=a[n-1]); ``` Find the last location in the array that is not sorted ``` if(!n)return a; ``` If already sorted return ``` s=a.slice(--n); ``` Get everything starting from the point where it was not sorted ``` for(k=s.length;s[--k]>=a[n];); ``` Find the index of the lexicographically closest element to the first element in the unsorted section which is lexicographically less than the first element. ``` t=a[n];s[0]=s[k];s[k]=t; ``` Swap the first element with the found element. ``` return a.slice(0,n).concat(s[0],s.slice(1).reverse()) ``` Return the first section of the array + the first element of the second section + the reversed remainder of the second section of the array. # Time complexity of operations: slice() O(n) concat() O(n) reverse() O(n) indexOf() O(n) //essentially what the for and while loops were # O(Nlog(N)) solution 143 - 50% = 71.5 bytes ``` n=>a=>{while(--n&&a[n]>=a[n-1]);if(!n)return a;s=a.slice(--n).sort();t=s.splice(s.indexOf(a[n])-1,1);return a.slice(0,n).concat(t,s.reverse())} ``` [Try it online!](https://tio.run/nexus/javascript-node#fZFBasMwEEX3OUWjRZgBW8RkaeQr5ADBC9UZ2QJlFCSlDYSe3bXjFodSezOLz/tvRsionlWlVfX47KwjyHOu9rudPnFdqWHmRY2lNbBlDJRugd90GZWW0dnmSaOMPiTAMqko4/UZR2n5TPejgdGDeZEVWP7Wf6r7bKg2nhudIGVRBvqgEAkQv/ohjt6RdL4FAweEk2g7KzJxJjNM/d6IGnGziI3ABC9gk2eGV7HJNsIL2AysLp2vWrW9vnTF9or9bxNXCpdb0sl6FtIRt6nDP@n4YQmEQMT@Gw) [Answer] # [Pip](https://github.com/dloscutoff/pip), 21 bytes 20 bytes of code, +1 for `-s` flag. ``` (YSSST*PMa^sy@?a-:1) ``` Takes input as a single, space-delimited string on the command line. [Try it online!](https://tio.run/nexus/pip#@68RGRwcHKIV4JsYV1zpYJ@oa2Wo@f//f93i/4lJyQopqWkKGZkA "Pip – TIO Nexus") ### Explanation ``` a is 1st cmdline arg; s is space (implicit) Part 1: a^s Split a on spaces PM Get all permutations of a ST* Map str() to each of them Because of the -s flag, this joins each sublist on spaces SS Sort the list using string comparison Y Yank into the y variable Part 2: y@?a Find index of a in sorted list of permutations y -:1 Subtract 1 (using compute-and-assign for lower precedence than @?) ( ) Index into part 1 using part 2 (Pip's indexing is cyclical, which takes care of the already-ordered-input case) Print (implicit) ``` [Answer] # Ruby, ~~55~~ 41 bytes ``` ->a{x=a.permutation.sort;x[x.index(a)-1]} ``` ### Explanation: * `permutation.sort` does exactly what is written on the box * find the original string * go back one step, if index is 0, wrap around to -1 [Answer] # Mathematica, 57 bytes ``` (a=Permutations@Sort@#)[[Max[1,Position[a,#][[1,1]]-1]]]& ``` Anonymous function. Takes a list of strings as input and returns a list of strings as output. [Answer] # [Python 2](https://docs.python.org/2/), 73,81 bytes ``` s=s.split() import itertools as i x=sorted(list(i.permutations(s[1:],int(s[0])))) ``` [Try it online!](https://tio.run/nexus/python2#bYpBCoQwEATvecXcjLCI4k3JSxYPWY3sQGJCehb8fXYeYJ26moLrZvKfnb5MRzi7lVPJVYglVMk5gjxUGhwGlMhie/OYmNtB33DYyBDLQwk1/cQL5wsW72nZXnyJrnHrlVaqKt2t/QE "Python 2 – TIO Nexus") **Edit:** Missed the lexicographical sort part of question. ]
[Question] [ # The Challenge Given an integer, calculate its score as described below. The score is calculated by raising each digit of the input Integer to the power `n`, where `n` denotes the index of the digit in Input (beginning with 1) when counted from left to right (the index of leftmost digit should be 1), and then summing them all together. If the original number happens to be prime, then add the largest digit of the input integer to the score, else subtract the smallest digit of the input integer from it. # Input Your program should take an integer as input. You can take the input in whatever way you want to. # Output Output the score of the input integer through whatever medium your programming language supports. Function `return` is also allowed. --- # Test Cases ``` 5328 -> (5^1)+(3^2)+(2^3)+(8^4)-2 = 4116 3067 -> (3^1)+(0^2)+(6^3)+(7^4)+7 = 2627 7 -> (7^1)+7 = 14 ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # Mathematica, 63 bytes ``` s+Max@If[PrimeQ[s=Tr[d^Range@Length[d=IntegerDigits@#]]],d,-d]& ``` Pure function taking a positive integer as input and returning an integer. Directly performs the indicated computation, with all the long Mathematica command names that requires. Perhaps the one innovation is noticing that, if `d` is the list of digits of the input, then the last addition/subtraction is the same as adding `Max[d]` if the initial sum was prime, and adding `Max[-d]` if not. [Answer] ## Mathematica, 68 bytes ``` #+If[PrimeQ@#,Max@x,-Min@x]&@Tr[(x=IntegerDigits@#)^Range[Tr[1^x]]]& ``` ## Explanation [![enter image description here](https://i.stack.imgur.com/Xe1FW.png)](https://i.stack.imgur.com/Xe1FW.png) Sets `x` equal to the list of digits of the input, then raises that to the power `Range[Tr[1^x]]`, effectively raising the first digit to the power `1`, the second digit to the power `2`, and so on up to `Tr[1^x]`, the length of `x`. `Tr` sums the resulting list, which is then passed into the function `#+If[PrimeQ@#,Max@x,-Min@x]&`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` DpiZëW(}¹gL¹SmO+ ``` [Try it online!](https://tio.run/nexus/05ab1e#@@9SkBl1eHW4Ru2hnek@h3YG5/pr//9vbGBmDgA "05AB1E – TIO Nexus") **Explanation** ``` D # duplicate input piZ # if input is prime then max digit of input ëW( # else -min digit of input } # end if ¹gL # range [1 ... len(input)] ¹S # input split into digits m # pow O # sum + # add ``` [Answer] # Python 3: 260 167 bytes ``` def s(n): t,l=0,list(str(n)) for i,d in enumerate(l):t+=int(d)**(int(i)+1) for i in range(2,n-1): if n%i==0:t-=int(min(l)) else:t+=int(max(l)) break return t ``` 93 bytes saved by Wheat Wizard [Answer] # JavaScript, 173 bytes Add an `f=` at the beginning and invoke like `f(n)`. ``` n=>{k=(n+"").split``;t=k.map((c,i)=>c**(i+1)).reduce((c,p)=>c+p);j=1;for(i=2;i<n;i++){j=n%i||n==2?1:0;if(!j)break}return j?t+Math.max.apply(Math,k):t-Math.min.apply(Math,k)} ``` --- **Explanation** Takes in an Integer. Converts it into String. Then, converts it into Array. Uses `map` over the Array to make a new array having all its elements raised to their `index+1`th (+1 because JavaScript used zero-based indexes). Then uses `reduce` to sum them all together. Checks whether the obtained number is prime. If it is then it `return`s the obtained number incremented by the largest digit of the Array otherwise `return`s the obtained number decremented by smallest digit of it. --- **Test Cases** ``` f=n=>{k=(n+"").split``;t=k.map((c,i)=>c**(i+1)).reduce((c,p)=>c+p);j=1;for(i=2;i<n;i++){j=n%i||n==2?1:0;if(!j)break}return j?t+Math.max.apply(Math,k):t-Math.min.apply(Math,k)} console.log(f(5328)); console.log(f(3067)); console.log(f(7)); console.log(f(123)); console.log(f(1729)); console.log(f(2)); console.log(f(1458)); console.log(f(91)); ``` [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), ~~17~~ 16 bytes (CP437) **EDIT**: Fixed so that it checks the input's primality. ``` ▓_^≥ⁿ;Σ┼Dp?╧+¿╤- ``` One of these days I need to get around to implementing vectorization. Maybe then I'll finally beat 05AB1E! Explanation: ``` ▓_^≥ⁿ;Σ┼Dp?╧+¿╤- Main wire: arguments: n ▓ ; Map the following over all digits of n: _^≥ⁿ Raise the digit to the (index + 1)th power Σ Push the sum of all that ┼Dp Is n prime? ? If so... ╧+ Add the maximum digit of n to the sum ¿ Else... ╤- Subtract the minimum digit of n from the sum (Implicit output) ``` [Answer] # Ruby, 98 bytes ``` ->n{i= ~s=0 a=n.digits a.map{|d|s+=d**(a.size-i+=1)} s>1&&(2...s).all?{|i|s%i>0}?s+a.max: s-a.min} ``` [Answer] # [PHP](https://php.net/), 174 bytes ``` function s($i){$i=str_split($i);foreach($i as $k=>$x){$r+=pow($x,$k+1);}if(p($r)){$r+=max($i);}else{$r-=min($i);}print$r;}function p($n){for($i=$n;--$i&&$n%$i;);return$i==1;} ``` [Try it online!](https://tio.run/nexus/php#PY3BCoMwEETv/QoPW0mwHmx720Y/pYhEXNQ1bCIVJN9u0xZ6G968YR6NG9zRr9wFWjjzCkjvQMYHeXo3UfgA7BexbTeknLU@g9HUsCVNCuOWl4LtAmNRaYzUK6dA9K@b2@27jnbyNpHSzMQ/4oQ4gGD8P6cd6z0dJcEAY1kC5TnwGQg1ig2rcGpMhfHw6nq7azw19fEG "PHP – TIO Nexus") [Answer] # [Python 3](https://docs.python.org/3/), 118 bytes ``` *a,=map(int,input()) x=sum(n**-~i for i,n in enumerate(a)) print(x+(-min(a),max(a))[all(x%z for z in range(2,x))*x>1]) ``` [Try it online!](https://tio.run/nexus/python3#HcsxDsIwDIXhnVNkQbKDO1BYy0UQg4eALNUmColkdeDqIWV9//t6ZFqUM4hVEsutAuLBl09TsBinr4TnuwQhC2IhWdNUuCbg8cplIPATTCo2FlL2Pdx5XcGP219uuytsrwQzOWL02/mBvc@X6w8 "Python 3 – TIO Nexus") Thanks to @math\_junkie for pointing out a bug. [Answer] # Python 2, 111 bytes ``` g=lambda n,z=1:n and(n%10)**len(`n`)+g(n/10,0)+int(['-'+min(`n`),max(`n`)][all(n%x for x in range(2,n))*n>1])*z ``` [Try it Online!](https://tio.run/nexus/python2#Jc3BCoMwEATQX9lLMRu3NKttLYL9ERFM0YZAsi3SQ/DnbWwPAwOPYTbXBRsfkwWhteNWwMqk5MAGtQ6zqFFGLJ2SExsyWHr5qL44FmX0f6No068MvQ0hLxM8Xwsk8AKLFTerigRRy50H1Ou2o9@xr@ozMTNdKKeublSba0PN0L6X/AJOedy@) Recursive function which calculates the sum starting with the last digit. `n and(n%10)**len(`n`)+g(n/10,1)` is the recursive portion of the function `int(['-'+min(`n`),max(`n`)][...])*z` returns `0` for all iterations except the first `all(n%x for x in range(2,n))*n>1]` is the primality test **Alternate solution (115 bytes):** ``` lambda n:sum(int(j)**(i+1)for i,j in enumerate(`n`))+int(['-'+min(`n`),max(`n`)][all(n%x for x in range(2,n))*n>1]) ``` [Try it Online!](https://tio.run/nexus/python2#HYzBDsIgEER/hYvpLqwHql6a6I8gSTGCoYHVYJv071G4TWbmvXC91@Ty4@kET98tQ@QVFpQSotIY3kVEWkRk4XnLvrjVw8wzomo/MxwHlSP3irLbe7DGpQR82EXD9wYXxy8PIzGi5Ju2WLu5TWY8nUlrTRfSdvqUv1cEiFh/) ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/68636/edit). Closed 8 years ago. [Improve this question](/posts/68636/edit) This challenge was [xnor's idea](http://meta.codegolf.stackexchange.com/a/5535/34638), taken from [Digital Trauma's challenge donation thread](http://meta.codegolf.stackexchange.com/questions/7804/secret-santas-sandbox). --- Your challenge is to write a program that, as xnor put it, "procedurally generate[s] the splotchy black-and-white marbled pattern on the covers of composition notebooks": ![1]](https://i.stack.imgur.com/yJedC.jpg) Your program can either display it on the screen or save it in a file. The image should be at least 300 pixels in each dimension, and it should be different between runs of the program. Your program should not just load an external image and use that as its output; the image should be generated by your program. This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), and it will use xnor's criteria for voting: * Similarity to the reference texture above. * Simplicity of generation method. [Answer] # Mathematica ``` Blur[Binarize[Blur[RandomImage[1, {1000, 1000}, ImageSize -> Large], 6], .52]] ``` Quite simple. Creates a random grayscale image, blurs it, takes the pixels above a threshold, and blurs it again. It uses a couple of hand-tweaked values. The result: ![](https://i.stack.imgur.com/Ux7SR.png) ]
[Question] [ What is the shortest C# statement that will convert a string representation of a number to an `int[]` that contains each digit? ``` string number = "1234"; number.Array.ConvertAll(line.ToCharArray(), c => Int32.Parse(c.ToString())); number.ToCharArray().Select(i => Convert.ToInt32(i.ToString())).ToArray(); number.Select(i => Int32.Parse(i.ToString())).ToArray(); number.Select(i => i - '0').ToArray(); ``` Can anyone beat my last approach? [Answer] # 28 bytes You can make your last approach a bit shorter by replacing the `'0'` by `48`. You can also strip all unnecessary spaces and use 1-char variable names (for example, `number` -> `n`): ``` n.Select(i=>i-48).ToArray(); ``` [Answer] ## C# without LINQ, *97* *86* 82 bytes ``` var n=Console.ReadLine();int i=n.Length;var o=new int[i];while(i>0)o[--i]=n[i]-48; ``` I've been hanging in the shadows for a while and wanted to try this out. I'm no golfer, or even that experienced with C#, but I wanted to see how small I could get it on my own, without using LINQ. It's nothing special, but at least I had my fun. I wasn't planning on posting this at first, since it's much longer than any good LINQ solution and doesn't really belong here, but I'm kinda curious if there is a shorter way to do it without LINQ. **Edit 1**: Instead of int.Parse it now substracts 48 from the char's ASCII code. Well, that's already much better. **2**: Now with var instead of string and int[]. [Answer] ## 76 bytes ``` number.ToCharArray().Select(var=>Convert.ToInt32(var.ToString())).ToArray(); ``` ]
[Question] [ **This is the companion thread to the main [Recover the mutated source code (link)](https://codegolf.stackexchange.com/q/42910/3808) challenge.** If you have successfully cracked a cop's answer, post your solution as an answer to this question. As a reminder, here are the robber rules from the main challenge again: > > The robber will attempt to change the cop's program (which completes > Task #1) into a program that completes Task #2 (not necessarily the > original program written by the cop) in the edit distance specified by > the cop. > > > An already-cracked submission cannot be cracked again (only the first > robber who cracks a submission gets credit). > > > After cracking a submission, please do the following: > > > * **Post an answer** to [this challenge's accompanying question (link)](https://codegolf.stackexchange.com/q/42911/3808), providing the language, your solution, and a link to the original answer. > * **Leave a comment** with the text "Cracked" that links to your posted answer. > * **Edit the cop's answer** if you have edit privileges (if you do not, either wait until someone else with the required privileges does > so for you or suggest an edit). > > > And scoring: > > If a robber successfully cracks a cop's submission, the robber's score goes up by the edit distance of that submission. For example, a robber that cracks a submission with an edit distance of 3 and one with a distance of 5 earns 8 points. The robber with the highest score wins. In the event of a tie, the robber who earned the score first wins. > > > # Leaderboard There are no cracked submissions yet. [Answer] # [Python 2, FryAmTheEggman](https://codegolf.stackexchange.com/a/42917/) ``` x=n=1;j=input(); while j>2: x,n=n,x+n;j-=1; ##while~-all(n%i for i in range(2,n)):n+=1; print n ``` Used 12 edits. Put in an extra `#` to make it 13. [Answer] # [Python 2, Sp3000](https://codegolf.stackexchange.com/a/42922/30688) ``` from fractions import* n=input() k,=P=[1] while n>len(P):k+=1;z=reduce(lambda x,y:x+y,P[~1:]);P+=[z]#*(gcd(z,k)<2) print P[-1] ``` [Answer] # [J, grc](https://codegolf.stackexchange.com/a/42923/7311) ``` f=:3 :'{.+/(!|.)i.y' f 45 1134903170 ``` [Answer] # [Python 3, Sp3000](https://codegolf.stackexchange.com/a/42915/30688) ``` x=n= int(input()) # 3 P = [1,1] #+2 = 5 k = 2 while n >=len(P): #+1 = 6 k += 1 for x in P: if k%x ==~0: break #+1 = 7 else: P += [P[-2]+x] #+7 = 14 print(x) ``` [Answer] # [Python 3, matsjoyce](https://codegolf.stackexchange.com/a/42952/30688) ``` a,c,n=1,1,int(input()) while n-1: #c+=1 ##########list(map(c.__mod__,range(2,46))).count(0): a,c=a+c,a n-=1 print(c) ``` The Fibonacci program was strangely already in there...only needed 5 edits to get it. [Answer] # [CJam by Martin Büttner](https://codegolf.stackexchange.com/a/42967/31414) ``` T1l~({_2$+}*p]; ``` Takes input `n` from STDIN [Answer] # [Python 2, Pietu1998](https://codegolf.stackexchange.com/a/42959/30688) ``` f=lambda p,i:p if p[45:]else f(p+[i]#f all(i%q for q in p[1:])else ,p[-1]+i) print f([1,1,1],2)[input('!')] ``` I used 9 edits to get a Fibonacci program. [Answer] # [JAGL, globby](https://codegolf.stackexchange.com/a/42921/30630) ``` T~2]d]2C{cSdc+c]}wSP ``` It might not be the most efficient approach, it it is almost definitely not the Cop's code, but it works, and its 12 away. [Answer] # [Ruby, histocrat](https://codegolf.stackexchange.com/a/42957/21475) ``` p [x=1,y=1,*(1..200).map{|i|z=y;y+=(y*x**(i-1)+x%2).divmod(i)[2-1]?x:1;x=z;y}].-([x-1])[gets.to_i-1] ``` ]
[Question] [ Write a program that outputs Lewis Carroll's poem [The Mouse's Tale](http://en.wikipedia.org/wiki/The_Mouse's_Tale) from Alice in Wonderland, drawn in its distinctive tail-like shape. [![The Mouse's Tale](https://i.stack.imgur.com/fVCJW.jpg)](http://www.lewiscarroll.org/2013/05/31/alice-discovers-concrete-poetry-in-wonderland/) Plain text of the poem: > > Fury said to a mouse, That he met in the house, 'Let us both go to law: I will prosecute you.— Come, I'll take no denial; We must have a trial: For really this morning I've nothing to do.' Said the mouse to the cur, 'Such a trial, dear sir, With no jury or judge, would be wasting our breath.' 'I'll be judge, I'll be jury,' Said cunning old Fury; 'I'll try the whole cause, and condemn you to death.' > > > Your output could be ASCII art or an image or an animation or a webpage or pretty much anything that follows the rules. The point of course is to be artistic and original. **The highest voted answer will win in approximately one week.** ## Rules * Your representation of the poem must exactly match the quoted text above. * Your representation must be legible. Any literate person with decent eyesight should be able to decipher it and not have to zoom in. * The tail must be vertically oriented, taking roughly 2 to 3 times more vertical space than horizontal space. * The tail must be thicker at the top and grow thinner as it gets to the bottom. * There must be at least 3 distinct curves or turns in the shape of the tail. (I count 5 above.) * You may not use existing images/layouts of the poem as your output or in your code. * You must actually write a program that generates your output. You cannot simply arrange some text in Photoshop. [Answer] # JavaScript, animated edition ## [Live Demo](http://jsfiddle.net/aLay9/2/) ![animated "The Mouse's Tale"](https://i.stack.imgur.com/sdgvT.gif) **HTML** ``` <div id='wrapper'> <p id='intro'> "It is a long tail, certainly," said Alice, looking down with wonder at the Mouse's tail; "but why do you call it sad?" And she kept on puzzling about it while the Mouse was speaking, so that her idea of the tale was something like this:&mdash;" </p> <div id='tail'></div> </div> ``` **CSS** ``` #wrapper { width: 300px; font: 16px serif; text-align: justify; } p { margin: 0; padding: 0; } p.wordEl { position: relative; } ``` **JS** ``` var poem = "Fury said to a mouse, That he met in the house, 'Let us both go to law: I will prosecute you.- Come, I'll take no denial; We must have a trial: For really this morning I've nothing to do.' Said the mouse to the cur, 'Such a trial, dear sir, With no jury or judge, would be wasting our breath.' 'I'll be judge, I'll be jury,' Said cunning old Fury; 'I'll try the whole cause, and condemn you to death.'\" ", words = poem.match(/.{0,15}[ ]/g), wordEls = [], tail = document.getElementById('tail'), startFontSize = 16, endFontSize = 8; for (var i = 0; i < words.length; ++i) { var word = words[i].slice(0, words[i].length - 1); var wordEl = document.createElement('p'); wordEl.className = 'wordEl'; wordEl.innerText = word; wordEl.style.setProperty('font-size', (Math.round(((words.length - i) / words.length) * (startFontSize - endFontSize)) + endFontSize) + 'px'); wordEls.push(wordEl); tail.appendChild(wordEl); } var counter = 0; setInterval(function() { ++counter; for (var i = 0; i < wordEls.length; ++i) { var sn = Math.sin((i*2 + counter) / 5) * 150; // sn = result of math.SiN var wsn = sn * (i / wordEls.length); // weighted sn wordEls[i].style.setProperty('left', (wsn + 150) + 'px'); } }, 50); ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/6674/edit). Closed 9 years ago. [Improve this question](/posts/6674/edit) Generate an ASCII wilderness map. **Example output:** ``` ................^^^^ ..................^^ ...^^^^........o.... .....^^^^........... .................... ........o....TT..... ..TTTT.............. TTTT.TTTT....~~~~~~. ..TT..........~~~~~~ .................... ``` **Anti-example (don't do this):** ``` .................... ...........T........ ...^..........oo.... ......^............. .................... ..............TT.... T.T.T.T.T........T.. .................T.. T.T.T.T.T..........T ..............TT...T ``` **Rules:** 1. Must be at least 20x10 characters in size 2. Must be different each run, i.e. random 3. Must contain continuous and varying shape areas of trees 'T', hills '^' and water '~', most of which should consist of more than 5 cells 4. The default, ground character is '.' 5. Must contain at least 2 villages 'o' that are usually not next to each other 6. Must not contain obvious patterns, such as rectangles or evenly spaced areas - "natural look" is the key 7. You don't need to explicitly check that the rules are followed (e.g. no need for anti-rectangle logic), but the great majority of the runs (say, 80%) must produce conforming results 8. With your submission, include an example output **Scoring:** Winner has lowest score from formula: `code character count` - `votes` [Answer] ## APL (~~99~~ 76) ``` F←⍳S←10 20⋄'.T^~^To'[⊃7⌊1++/(⊂7×F∊{?S}¨⍳2),T×{F∊(?S)∘+¨+\{2-?3 3}¨⍳99}¨T←⍳3] ``` ~~A bit longer than it needs to be (so that it gives better output) but I'll shorten it when the Golfscript answer comes in.~~ The GolfScript answer was posted so here's a shorter one. I thought of another (rather obvious, in hindsight) way to shorten it so that the output is not much worse than the original program, and it's even shorter than my original backup plan. (In the old version, I had five bitfields that I was xor-ing with each other, now I have three that I am adding to each other.) I have replaced the example output with output of the new version, of course. Explanation: * `F←⍳S←10 20`: size is 20x10, F is a matrix where each element is its coordinates * `{F∊(?S)∘+¨+\{2-?3 3}¨⍳99}¨T←⍳5`: generate 3 bitfields, by starting at a random coordinate, and taking 99 random steps to a neighbouring field and then setting that bit on. 99 seems high but it often backtracks as it is random. This makes the maps for the areas. * `(⊂7×F∊{?S}¨⍳2)`: Add in two villages. * `⊃7⌊1++/`: sum the areas, giving a matrix where each number represents a certain type. Cap it at 7, because the villages might appear in another area giving high numbers. * `'.T^~^To'[`...`]`: replace each number with the right character. There are 3 possibly overlapping fields so the highest possible value is 6. (3+3) Example output: ``` ....TTT.TTT...TTT.^^ ...TT....TTT....T..^ ....T....TT.......^^ ...~..o..T..^^...^^. ...~.........^^^^^^^ ...~~~~....^^..^^^.. ~..~~~......^.^.^^^^ ~~.~~~......^^.^^^.. ~.~~~~........o..... ~~~~~~.............. ``` and ``` .....o........~~..~~ ..............~~~~~. .^T.T..........~~.~. ^T~~TTTTTT.......~~~ ~~~~TT.TT.T......~~~ ^~^TTT....T.....~~~~ ^^^^T.....T...T..~~. ^^^^.......TT.T..... ^^^^.........TT..... ^^^^.........o...... ``` Old version: ``` F←⍳S←10 20⋄G←{F∊(?S)∘+¨+\{2-?3 3}¨⍳99}¨T←⍳5⋄'.T^~^To'[⊃7⌊1++/(⊂7×F∊{?S}¨⍳2),T×{(⊃⍵⌽G)∧~⊃∨/1↓⍵⌽G}¨T] ``` [Answer] **JavaScript - 294 290 characters** To encourage attempts, I took a crack at this myself. You can try a live demo [here](http://jsfiddle.net/9pBTF/4/) (you need to open your browser's JS console). Tested with Chrome and IE8. ``` R=function(a){return Math.random()*a|0};t=["~","T"];t.splice(R(3),0,"^");p=["XXX..","XXXX.","XXXXX"];b="....................";for(i=j=0;10>i;++i)j=i%3?j:R(15),s=b.substr(0,i%3?j+R(2):20),s+=p[R(3)].replace(/X/g,t[i/3|0])+b,k=R(19),console.log(s.substr(0,k)+".o"[i%2*R(2)]+s.substr(k,19-k));​ ``` Example output: ``` .................... .......~~~.......... ........~~~~~....... ...o................ ...............TT.TT ..........o....TTTTT .................... .....^^^.o.......... .....^^^^^.......... ..................o. ``` It's not ideal, as there is always only three areas (one of each kind), their maximum size is 5x2 cells and after a few runs, you start to notice limitations in their (and villages') placement. However, it fulfills the rules. [Answer] ### GolfScript, 97 characters ``` "T~^o"1/{:z{[20:s.*:<rand{.[s~)1-1s]4rand=+}z"o"=!9**]}3*++}%2/:x;<,{"."x{)3$\?)!!*+}/\;-1=}%s/n* ``` Example outputs: ``` .............~...... ...........~.~~..... ........~~~~~~...... ........~~~......... .......~~~.......... .......~............ ..^^..............T. ^^^^...........o..T. ...^....TTT...^...T^ ^........TT.o.^^^.^^ ^.......TT.....^^.T. ........T......^.TT. ................TT.. .................... ....~~~............. ....~.~............. ..~o~............... ..~.....TTTT........ .......TT..TT....... .................... ``` and ``` .............~...... .............~...... ....TTT.....~~TT.... ....T.T.....~~TT.... ....TT......~~~TT... .....T.....~~~~T.... .......^^.~~~~...... ......^^^..~~....... ......^.^........... .................... ..^^^^.............. ..^..^^............. ....^^^^^........... .......o........TT.. ................TT.. .................... ......o............. .............o...... .................... .................... ``` [Answer] ## Ruby 1.9 (~~127~~ ~~116~~ ~~112~~ 107) ``` m=?.*o=W=200 29.times{|i|o+=i%9-i/28>0?[-1,1,20].sample: rand(W);m[o%W]='T~^'[i/9]||?o} puts m.scan /.{20}/ ``` The output is a bit plain, but I think it mostly meets the spec! Some example outputs: ``` .................... ........TTTTTTT..... ........T^^^........ .........^.......... .........^.......... .........^^^.o...... .................... .....~.o............ ...~~~.............. ...~~~~~............ ``` Another: ``` .....^^............. ......^^............ .......^^........... ...........o........ .................... ..............T~~~.. .............TT~~... .............T.~.... .............T.~.... .o..^^.......TT~.... ``` And again: ``` .....TT............. ..............~..... ..............~..... ..............~~.... ..............~~~... ........^^^......... ....o.T...^......... ......TT..^^^....... ..o..TT....^^....... .....T.............. ``` ~~Due to the way it's coded, there's almost always a lone tree. I like to imagine it's the Deku tree.~~ [Answer] # Q (~~116~~ 107 char) Here's one in Q ``` (-1')20 cut@[199{.[t!`s#'(0 20 20 20;0 0 20 20;0 0 0 20;0 1 2 3)!\:t:"T^~.";(x;rand 30)]}\".";2?200;:;"o"]; ``` Sample output ``` ...........o........ ...~~....TTTT..~~o.. ......TTTTTTTTT....T T................... ......^^^........TTT ...~~~~............. .................... ............^^...... ..~~~..^^^^^^....... ....~..............T ``` and ``` ..........^^^..^...o .................... ........^.T......... .......~~...^....... .................... ....TTTTTTTT....^... ..~................. .o.....^^^^^.......T ............~~~~~~~~ ~~~~~....TTT........ ``` and ``` .................... ...~~~~~~~~~~.....~. ................TT.. ....TTTTT..~.TT.TTTT T................TTT TTT..........TTTTTTT TTT....T............ ........T.......TToT TTT..............^^. ...TTT..^.~~~~.o.... ``` I can tweak the stochastic matrix to affect the output but I think the above conforms what you're looking for. /edit: tweaked output /edit: reduced char count by only adding 2 villages [Answer] # K, 84 ``` f:{,/{x+!y}'[5?200;5?10]};m::200#".";{@[`m;x;:;y]}'[(f`;f`;f`;2?200);"~T^o"];10 20#m ``` Output: ``` "...................T" "TTTTT~....TTT...^^^." "...................^" "^^..............^^^^" "^^^..~~~~.......^^o." ".........TTTTT......" "..~~~~~~........TTTT" "TTT.~..............." ".........o.....^^^^." "..........TTTTT....." ``` and ``` "...............~~~.." ".......~~~~~......TT" "TTTT.^^^^^^^^......." "....TT......~~......" "..........^........." "...........oTTT..^^^" "^^^^^^..........^^^^" "^^...TTTTTTT........" "................o.~~" "~~~.............T..." ``` ]
[Question] [ Johnny is trying to create crossword puzzles, but he is having difficulty making words match each other. He has come up with several simple word rectangles: that is, groups of words that form a rectangle where all horizontal and vertical paths form a word. ``` //2x2 PA AM //2x3 GOB ORE //3x3 BAG AGO RED //3x4 MACE AGES WEES ``` However, to make a good puzzle, he needs some word rectangles that are somewhat larger than 3x4. Instead of agonizing over the arrangement letters for hours, Johnny would prefer to have a program that does this for him--and in as few characters as possible, because long blocks of code are extremely intimidating for casual programmers like Johnny. --- Given * a [text file](http://www.2shared.com/document/PqCZe55q/words.html) dictionary where words are separated by newlines in alphabetical order, * input specifying the number of rows and columns in the words rectangle (which can be provided however is most convenient in your programming language of choice) generate at least one word rectangle. If it is not possible to generate a word rectangle with the given lexicon and dimensions, the program need not have defined behaviour. It is not necessary for the program to be able to generate rectangles which contain more than 64 letters or have dimensions that exceed 8 in either direction. The program should be able to complete in a reasonable amount of time, say, in thirty minutes or less. --- EDIT: If you are doing an NxN rectangle, you are permitted to use a smaller dictionary file that only contains words that have a length of N letters. [Answer] # Haskell, 586 characters ``` import Data.List import qualified Data.Vector as V import System data P=P[String](V.Vector P) e=P[]$V.replicate 128 e (a:z)∈(P w v)|a>' '=z∈(V.!)v(fromEnum a);_∈(P w _)=w p∫w=q p w where q(P u v)=P(w:u).V.accum q v.x;x(a:z)=[(fromEnum a,z)];x _=[] l%n=foldl'(∫)e.filter((==n).length)$l d§(p,q:r)=map(\w->p++w:r)$q∈d;_§(p,_)=[p] (d¶e)i=filter(not.any(null.(∈e))).map transpose.(d§).splitAt i s i n d e m|i==n=["":m]|1<3=(d¶e)i m>>=(e¶d)i>>=s(i+1)n d e p[b,a,n]w=take n$s 0(a`max`b)(w%a)(w%b)$replicate b$replicate a ' ' main=do{g<-map read`fmap`getArgs;interact$unlines.concat.p g.lines} ``` Invoked by supplying 3 arguments: number of rows, number of columns, number of solutions; and the word list is accepted on `stdin`: ``` $> ghc -O3 2554-WordRect.hs [1 of 1] Compiling Main ( 2554-WordRect.hs, 2554-WordRect.o ) Linking 2554-WordRect ... $> time ./2554-WordRect 7 7 1 < 2554-words.txt zosters overlet seriema trimmer element remends startsy real 0m22.381s user 0m22.094s sys 0m0.223s ``` As you can see 7×7 runs relatively fast. Still timing 8×8 and 7×6.... It would be 9 characters shorter to remove the number of solutions argument and just produce all solutions, but then it becomes impossible to time. --- * Edit: (585 → 455) replaced custom data structure with a simple map of prefix string to possible replacements; oddly, this is a bit slower, perhaps because `Map String a` is slower than a hand-built tree of `Map Char a`... * Edit: (455 → 586) *Bigger?!?!!* This version does more optimization of the search space, using both the techniques of my original solution, and of the python and awk solutions. Further, the custom data structure, based on `Vector` is much faster than using a simple `Map`. Why do this? Because I'm think a solution that is closer to the goal of 8x8 in under ½ hour is preferable to a shorter solution. [Answer] # Python, 232 chars ``` x,y=input() H=[] P={} for w in open('words.txt'): l=len(w)-2 if l==x:H+=[w] if l==y: for i in range(y+1):P[w[:i]]=1 def B(s): if(x+2)*y-len(s):[B(s+w)for w in H if all((s+w)[i::x+2]in P for i in range(x))] else:print s B('') ``` It can only handle up to 6x6 in the 1/2 hour limit, though. [Answer] # Java (1065 bytes) ``` import java.util.*;public class W{public static void main(String[]a){new W(Integer.parseInt(a[0]),Integer.parseInt(a[1]));}W(int w,int h){M H=new M(),V=new M();String L;int i,j,l,m,n=w*h,p[]=new int[n];long I,J,K,M,C=31;long[]G=new long[h],T=new long[w],W[]=new long[n][],X;try{Scanner S=new Scanner(new java.io.File("words.txt"));while(0<1){L=S.nextLine();l=L.length();for(i=0;i>>l<1;i++){K=0;for(j=0;j<l;j++)K+=(i>>j&1)*(L.charAt(j)-96L)<<5*j;if(l==w)H.put(K,H.g(K)+1);if(l==h)V.put(K,V.g(K)+1);}}}catch(Exception E){}while(n-->0){j=1;if(W[n]==null){M=1L<<62;for(i=w*h;i-->0;){m=i/w;l=i%w*5;if((G[m]>>l&C)<1){X=new long[27];I=K=0;for(;K++<26;){J=H.g(G[m]+(K<<l))*V.g(T[i%w]+(K<<5*m));X[(int)K]=K-32*J;I+=J;}if(I<1)j=0;if(I<M){M=I;p[n]=i;W[n]=X;}}}}X=W[n];Arrays.sort(X);M=X[0]*j;X[0]=0;K=M&C;i=p[n]%w;j=p[n]/w;l=5*i;m=5*j;G[j]&=~(C<<l);G[j]+=K<<l;T[i]&=~(C<<m);T[i]+=K<<m;if(M>=0){W[n]=null;n+=2;}}for(long A:G){L="";for(i=0;i<w;)L+=(char)(96+(C&A>>5*i++));System.out.println(L);}}class M extends HashMap<Long,Long>{long g(Long s){return get(s)!=null?get(s):0;}}} ``` A long way from being the shortest, but I think it's the closest to meeting the timing constraints. I saved 14 bytes by assuming that the input file has been filtered to words of the right lengths; on my netbook, if you feed the whole `words.txt` then it spends the first minute preprocessing it, discarding most of what it produces, and then takes a mere 20 or so seconds to solve 7x7. On my desktop it does the whole thing in under 15 seconds, giving: ``` rascals areolae serrate coroner alanine latents seeress ``` I've let it run for over 50 hours without finding a solution to 8x7 or 8x8. 8-letter words seem to be a critical boundary for this problem - it just hovers around half-full without making much progress. The approach used is full pivoting and a heuristic based on the number of possible horizontal completions times the number of possible vertical completions. E.g. if we have intermediate grid ``` *ean* algae *ar** *ier* *nee* ``` then we give the top-left corner a heuristic value of `count(aean*)count(aa***) + count(bean*)count(ba***) + ... + count(zean*)count(za***)`. Of all the cells we pick the one with the smallest heuristic value (i.e. hardest to satisfy), and then work though the letters in descending order of the amount they contributed to the heuristic value of that cell (i.e. starting with the most likely to succeed). [Answer] ## F# Backtracking solution, but I'm going to optimize the search space later. ``` open System (*-NOTES W=7 H=3 abcdefg<-- searching from wordsW abcdefg abcdefg ^ partial filtering from wordsH *) let prefix (s : char[]) (a : char[]) = a.[0..s.Length - 1] = s let filterPrefix (s : char[]) = Array.filter (prefix s) let transpose (s : char[][]) = [| for y = 0 to s.[0].Length - 1 do yield [| for x = 0 to s.Length - 1 do yield s.[x].[y] |] |] [<EntryPoint>] let main (args : String[]) = let filename, width, height = "C:\Users\AAA\Desktop\words.txt", 3, 3 let lines = System.IO.File.ReadAllLines filename |> Array.map (fun x -> x.ToCharArray()) let wordsW = Array.filter (Array.length >> ((=) width)) lines let wordsH = Array.filter (Array.length >> ((=) height)) lines let isValid (partial : char[][]) = if partial.Length = 0 then true else seq { for part in transpose partial do yield Seq.exists (prefix part) wordsH } |> Seq.reduce (&&) let slns = ref [] let rec back (sub : char[][]) = if isValid sub then if sub.Length = height then slns := sub :: !slns else for word in wordsW do back <| Array.append sub [| word |] back [| |] printfn "%A" !slns 0 ``` [Answer] ## awk, 283 (may need to add 14 for parameter input flags) Call with e.g. `awk -v x=2 -v y=2`... Find first match and print it (283 chars): ``` {if(x==L=length)w[++n]=$0;if(y==L)for(;L>0;L--)W[substr($0,1,L)]++}END{for(i[Y=1]++;i[j=1]<=n;){b[Y]=w[i[Y]];while(j<=x){s="";for(k=1;k<=Y;k++)s=s substr(b[k],j,1);W[s]?0:j=x;j++}if(W[s])if(Y-y)i[++Y]=0;else{for(k=1;k<=Y;k++)print b[k];exit}i[Y]++;while(Y>1&&i[Y]>n)i[--Y]++}print N} ``` Find number of matches (245 chars, much slower): ``` {if(x==L=length)w[++n]=$0;if(y==L)for(;L>0;L--)W[substr($0,1,L)]++}END{for(i[Y=1]++;i[j=1]<=n;){b[Y]=w[i[Y]];while(j<=x){s="";for(k=1;k<=Y;k++)s=s substr(b[k],j,1);W[s]?0:j=x;j++}W[s]?Y-y?i[++Y]=0:N++:0;i[Y]++;while(Y>1&&i[Y]>n)i[--Y]++}print N} ``` For both programs (of course more so for the solutions count), the running time far exceeds 30 minutes for some values of x and y. Just as a matter of interest, here is the word count for each word length: ``` 2 85 3 908 4 3686 5 8258 6 14374 7 21727 8 26447 9 16658 10 9199 11 5296 12 3166 13 1960 14 1023 15 557 16 261 17 132 18 48 19 16 20 5 21 3 ``` ]
[Question] [ # Background The monkeys need your help again organizing their defense and have asked you, [Benjamin](https://bloons.fandom.com/wiki/Benjamin_(BTD6)) the code monkey, to create a program that will list all tower upgrade options as they appear in your insta-monkey collection. Each tower has three unique upgrade "paths", called "top", "middle", and "bottom", each having a tier represented by a number between 0 and 5 inclusive (0 meaning no upgrade). Up to two paths may be chosen for upgrading, that is contain an upgrade tier 1 or greater. Additionally, only one "main" path can contain a tier 3 or greater, with the other upgrade path (if it exists) becoming the "crosspath". Original question: [Bloons TD 6 Upgrade Paths](https://codegolf.stackexchange.com/questions/249343/bloons-td-6-upgrade-paths) # Task Output in some reasonable format all valid upgrade path triples in *the given order* (the triples themselves are ordered). Triples can be represented in any reasonable way, such as 025 or 0-2-5. The triples must be distinguishable from each other in some way, so a flat list of numbers without triple delimiters is not allowed. Here is the list of all 64 possible triples, as they appear in-game for your insta-monkey collection. The 5th tier (main path) monkeys are listed first, then 4th tier, etc. descending. For each main path position (top, middle, or bottom), the second tier crosspaths are listed, with the crosspath having the leftmost position listed first. Then the first tier crosspaths are listed, then no crosspath. For tier 1 and tier 0 monkeys, the same logic is followed, except duplicates are not listed. ``` 5-2-0 5-0-2 5-1-0 5-0-1 5-0-0 2-5-0 0-5-2 1-5-0 0-5-1 0-5-0 2-0-5 0-2-5 1-0-5 0-1-5 0-0-5 4-2-0 4-0-2 4-1-0 4-0-1 4-0-0 2-4-0 0-4-2 1-4-0 0-4-1 0-4-0 2-0-4 0-2-4 1-0-4 0-1-4 0-0-4 3-2-0 3-0-2 3-1-0 3-0-1 3-0-0 2-3-0 0-3-2 1-3-0 0-3-1 0-3-0 2-0-3 0-2-3 1-0-3 0-1-3 0-0-3 2-2-0 2-0-2 2-1-0 2-0-1 2-0-0 0-2-2 1-2-0 0-2-1 0-2-0 1-0-2 0-1-2 0-0-2 1-1-0 1-0-1 1-0-0 0-1-1 0-1-0 0-0-1 0-0-0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` 6p3’Ż€Œ!€ẎQMNṭṀƲÞṚ ``` * [Try it online!](https://tio.run/##AS0A0v9qZWxsef//NnAz4oCZxbvigqzFkiHigqzhuo5RTU7hua3huYDGssOe4bma//8 "Jelly – Try It Online") * [Test against supplied answers](https://tio.run/##PdExTsNAEIXhfm@B@5V2dia5BUg03IAGpaClMzkABR1IUEAbGkRjQgUK91hfZJn9vUGy3jx5xl/jq8vN5qbW9bXO48NhP293h/sTz/J5d356Vqa3Mo2/7z/PZXqsZf9RpldfzuNTvGjTn9uv75dah2FYxRxTWMUUs6f0LmQKOfoMyTMH@e9Ctq1P737l26UL2bohG7IhG7J12dAM@diFXGRDNmRDNmQLiqzIiqzI2mVFU@RjF3KRFVmRFVmR1be532RP6V3IxFfNzL0LmXAyTsZpN9LfC5nYCpm4ETL5H/gD "Jelly – Try It Online") A niladic link taking no arguments and returning a list of triples. ## Explanation ``` 6p3 | Cartesian product of 1..6 and 1..3 ’ | Subtract 1 Ż€ | Prefix each with zero Œ!€ | Permutations of each Ẏ | Join outer lists Q | Uniquify MNṭṀƲÞ | Sort by negated maximal indices tagged onto maximum Ṛ | Reverse ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 97 bytes ``` 520$*¶ 00$.` .*(...) $1,$1 %O^`\G\d (.)(..,.*?\1(.)*) $1$#3$2 O^` .+, G`0 A`[3-5].*[3-5]|[6-9] ``` [Try it online!](https://tio.run/##K0otycxL/P@fy9TIQEXr0DYuLgMDFb0ELj0tDT09PU0uFUMdFUMuVf@4hBj3mBQuDT1NoLiOnpZ9jCGQrQVSoKJsrGLEBVTBpaetw8XlnmDA5ZgQbaxrGqunBaZqos10LWP/xzhx6f4HAA "Retina 0.8.2 – Try It Online") Link includes footer that prettifies the output. Explanation: Based on my answer to the linked question. ``` 520$*¶ 00$.` .*(...) $1,$1 ``` List all the integers from `0` to `520` inclusive, padded to `3` digits, with each integer duplicated, the duplicates separated with a comma. ``` %O^`\G\d ``` Sort the first duplicate of each integer in descending order of digit. ``` (.)(..,.*?\1(.)*) $1$#3$2 ``` For each integer, after the largest digit in the sorted digits, insert another digit that is the number of digits appearing after the first occurrence of that digit in the original integer. ``` O^` ``` Sort the integers in reverse by this sort key. ``` .+, ``` Delete the sort key. ``` G`0 ``` Only keep those integers with at least one `0` digit. ``` A`[3-5].*[3-5]|[6-9] ``` Discard those with more than one digit greater than `2` or with a digit greater than `5`. [Answer] # [Python 3](https://docs.python.org/3/), 119 bytes ``` t=(0,1,2) print(*{(*(x*(i==j)+y*(i==k)for i in t),):0for x in(5,4,3,2,1,0)for j in t for y in(2,1,0)for k in t if j-k}) ``` A full program that takes no input and prints the ordered upgrade paths as Python tuples with a space separator. **[Try it online!](https://tio.run/##RYxBCsMgEEX3PcUsZ8wUbNJACXgdySgYERdK6dlNtIvs3uc9fqx5P8Lyiam1bFDzi2d6xCQho/qiwqJQjHE01QGe7JFAQAJkYtp0n@WauPKbF56vAz0aNxroWLu/jf8bseCe/ketnQ "Python 3.8 (pre-release) – Try It Online")** ### How? Go through from a "big choice" of five through to zero placing this digit left-right, placing a "small choice" of two through to zero in each of the other positions in turn, each time placing a zero in the remaining position, then deduplicate the results while maintaining order. ``` t=(0,1,2) # create "indices" tuple t = (0,1,2) for x in(5,4,3,2,1,0) # for "big choice" x=5..0 for j in t # for index j (where we want to try to place x) for y in(2,1,0) # for "small choice" y=2..0 for k in t # for index k (where we want to try to place y) if j-k # if these indices differ for i in t # go through the indices, i x*(i==j)+y*(i==k) # and assign a value (x, y or 0) ( ) # each triple (across i) as a generator (* ,) # ...splat to a tuple { :0 ...} # ...as the keys of a dictionary (to deduplicate keys) print(* ) # ...splat to print function ``` Perhaps the `print(*{...})` could be `print({...})` it will then print the `dict` representation, which is in order of its keys (the upgrade path triples), but will also show the dummy values `: 0` along with each key. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 57 bytes ``` ≔EΦEφ﹪%03dι∧№ι0∧›6⌈ι›²ΣEι‹2λ⟦⌈ι±⌕ι⌈ι⁻ΣιΣ⌈ιι⟧θW⁻θυ⊞υ⌈ιEυ⊟ι ``` [Try it online!](https://tio.run/##VY@xCsIwEIZ3n@IICBeIEBVcOomgi5WCozgEG@xB2mhj1LeP11ZRM4Rw//99XE6VaU/euJSWIdC5wdxccE3uZtv@OdVaK8h9GZ1HMdbzUiggKRUsmxJXPjY3JAVCi/do01rTwWLBxdw8qY419sAnmSnY86yzM7m1IaCYcdnJ4Sg4fDkFO3tmjHdiOf0pOcypiQH37@qg/c3pyNdVZqNHRc4CDv2rgiglFDFUGP@U2ahoib/ULcdJ4S@9KEspTe7uBQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on my answer to the linked question. ``` ≔EΦEφ﹪%03dι∧№ι0∧›6⌈ι›²ΣEι‹2λ⟦⌈ι±⌕ι⌈ι⁻ΣιΣ⌈ιι⟧θ ``` Generate all the valid triples, but then create a sort key of the maximum digit, the negated index of that digit in the triple, the other non-zero digit if any, and the triple. ``` W⁻θυ⊞υ⌈ι ``` Sort the triples in descending order by the keys. ``` Eυ⊟ι ``` Output just the triples. (This could be `Eυ⪫⊟ι-` to prettify the output at a cost of 2 bytes.) [Answer] # [Haskell](https://www.haskell.org/), 154 bytes ``` import Data.List x=unlines[intersperse '-'s|s<-reverse$sortOn(\x->(maximum$zip x[1,0..],sort x))$mapM id$['0'..'5']<$[1..3],elem '0's,sum[1|x<-s,x>'2']<2] ``` [Try it online!](https://tio.run/##Vc7BaoQwFAXQvV8RBsEpGMlLMrtxVl229AOsC6FCQ40jRkso8@82w6g3sxBvrnnP8924n7brlsXY4TpO7LWZmuLNuCnx5dx3pm9dZfqpHd0QnpZlPHM3d@Zj@3s/py4MffTHT88vR9t4Y2eb/pmB@YpyURR1fr/A/MtLapvhnZmvtMpEVhTZKavPaUVFoeq87VrLQu1yN9uKbv7MXe4vmQx3ZL3YxvSsZMMYICxlnpUlu87TME9J8niHryuWVQljhxOXXBzyRxRcbpHilhDXVvLTFkWI6xg9t4S4j4XD1sotUtwS4t5qIDWQGkgNpI6RGhwN5FNLiBFSA6mB1EBqINeogFRAKiAVkCpGKnAUkE8tIUZIBaQCUgGpgFTbmIw3yC1S3BKiwC92mYxbQhQwSBgkDPsGiu8SosAYIQpsIERxqJPlHw "Haskell – Try It Online") [Answer] # [R](https://www.r-project.org), 114 bytes ``` r=rowSums a=apply (b=(x=expand.grid(0:5,0:5,0:5))[r(x>2)<2&r(x>0)<3,])[order(-a(b,1,max),a(b,1,which.max),-r(b)),] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZJBTsMwEEUlljmFlQWyJTvy2I6EUMMJ2LFsu0jTQCulSeS2NJyFTVlwKDgNcX4MYhE9_8l43sLz_uGv18_z6VndfXlf-O7ydD4ck7Io-755S_im4ENRD33ZbrMXv99yfZ_L-RNi6fnwYMTC3IaDFgsr12LZ-W3tuSr5RpI8lIOQOF52-2qXTQXl-UYIuYb5-4Yf9m3NFoplj-XxlL2WzblOqs77ujqFcporo_SqzZVWJoBiImBMRuUBesTYQn-JgKllPIRkAigmAqbkIHIQOYgcRC6KHEY7iH4TAbPIQeQgchA5iEZYiCxEFiILkY0ii9EWot9EwCyyEFmILEQWIhtaTOw0ARQTARrXJ4OJiQCNmQYzDWZOnRT_EaDRQoBGJwE6TfrxWWs-LdX01pKRZFNRsqprmrI_1qxgqUrF_8KqTQUrCjYvAxYmruwP) A full program that prints a data frame with the relevant triples in rows. It also prints some redundant row and column names - hopefully that’s permissible. The footer verifies that the data frame is correct when compared to the canonical answer. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 234 bytes ``` from itertools import* s,r=sorted,range;[print('-'.join(map(str,p)))for p in s(set(chain.from_iterable(permutations(list(x)+[0])for x in s(product(r(6),r(3))))),key=lambda x:(max(x),-x.index(max(x)),sum(x),x,-x.index(s(x)[1])))[::-1]] ``` [Try it online!](https://tio.run/##RY3RasMwDEXf9xV@q7w5oaVQRka/JITiNm7rLbaEpID79anTDaYn3SvOET30jnn/SbwsV8ZkogZWxElMTISs72/i@Ch1C6Njn2/hqyeOWWHTbNpvjBmSJxBlR9baK7IhE7MRkKBwufuY21V8WsX@PAWgwGlWrxGzwBRFodiPfju82PLLEuM4XxQYDtYx7O067ic8jpNP59Gb0tW3pZKuKW3MYyh/2TqZ09qX/4vU3O@Gqui7rtkNw7I8AQ "Python 3.8 (pre-release) – Try It Online") ]
[Question] [ Given an input integer from 1, 2, ..., n, the task to write code to make a number as close as possible (as measured by absolute distance) to `e` using only the four mathematical operations +, -, \*, / and parentheses (brackets). You can use any of the integers up to `n` once but don't have to use all the numbers and you are not allowed to stick digits together to make new numbers for example. * The input will be single integer `n` between 1 and 20, inclusive * The output should be an arithmetic expression which is the closest possible to `e`. Your code should in principle be correct for `n` all the way up to `20` although of course it doesn't have to terminate in a sensible amount of time. Although not required, it would be great if it did terminate for smaller inputs at least. # What is e? ``` 2.71828182845904523536028747135266249775724709369995.... ``` # Examples * Input 1. Output 1. Distance \$e - 1 \approx 1.7182818284590451\$. * Input 2. Output 1+2=3. Distance \$3 - e \approx 0.2817181715409549\$. * Input 3. Output 3 - 1/2 = 2.5. Distance \$e - 2.5 \approx 0.21828182845904509\$. * Input 4. Output 2 + 3/4 = 2.75. Distance \$2.75 -e \approx 0.031718171540954909\$. * Input 5. Output 3+1/(2/5-4) = 2.722222222222. Distance \$2.722222222222 - e \approx 0.00394039376\$. * Input 6. Output 2+((6-1/4)/(5+3)) = 2.71875. Distance \$2.71875 - e \approx 0.00046817154\$. You can take `e` as input to your code if that is helpful. [Answer] # [Python](https://www.python.org), ~~280~~ 229 bytes *-51 bytes thanks to [@AnttiP](https://codegolf.stackexchange.com/users/84290/anttip)* ``` lambda n:min(chain(*map(g:=lambda p:["("+l+o+r+")"for i in range(1,len(p))for(l,r,o)in product(g(p[:i]),g(p[i:]),"+-*/")if eval(r)or"/"<o]+[str(p[0]+1)],permutations(range(n)))),key=lambda x:abs(eval(x)-e)) from itertools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY9NTsMwEIX3OcXIq5nabUkBgSxykpKF2zqtRfwj20WtKk7Cphs4AnfhANwDNynMwn72PM287_0zHPPOu_NXF70Fq_IOjA0-ZtBV1zx_7HM3ffz-6ZVdbRQ4aY3D9U6Vc2JVwK1srq0glwwZ77nnkTNinY9gwDiIym011qLXDgNR-cdeROGp9EL0m_064xbDUpqWxEUYWQTj08mckelAv6oeI_nI5uzJt3yZciyum5bX1Iqgo91nlY13CcdVjkqJF338i3aQapVwmHOgqSaqBliTdcze9-lKPLnCnrJOea2STtDAqYJStYRaDGoh4XZUtxIWs_tR3130Q3m8VdUALsBf2P8nzcoym5DkYA_RuIyDqWlGwA5NSV2NEc7n8f4F) Similarly to [@The Thonnu](https://codegolf.stackexchange.com/users/114446/the-thonnu)'s answer, uses brute force and times out for \$n>4\$. [Answer] # JavaScript (ES10), 160 bytes Expects `(n)(e)`. Works up to \$n=5\$ on TIO. ``` n=>g=(e,...a)=>n?g(e,...a,S=m=n--):a.map(p=>a.map(q=>p!=q&&[..."+-*/"].map(o=>g(e,`(${s=p+o+q})`,...a.filter(s=>s!=p&s!=q,(d=eval(s)-e)*d<m&&(m=d*d,S=s))))))&&S ``` [Try it online!](https://tio.run/##ZVBBbsIwELznFQZVYU1iV0ilh8KmJ3rriSNCwsVOGpTYiZ0iJODtqZOgqrRz8K41uzNjH8RRuL3Nq4ZpI1WbYqsxyRBUzDkXFBP9mt0u8RpL1IzRF8FLUUGFydDUmFQjrMNw48fGEZs@jrc9YbyUX97Bw9lhFZmovtJdr8XTvGiUBYeJG2EV@qOOQaI6igIcZYpO5bIMQyhRTqV3drRHGK7bvdHOFIoXJoOJJheiTpVVzuVGkx4X4lW@VNcoa42d0EVwt8RYxP4i@tfcodMIUmOhUA3RBMls4csSydzXKKLkHBDScV0YT6egKbyL5pOvaBwMuYZUSPpHdnNek5DfyTY67gV4Y9aNzXUGlFdCrrSE2ZzGg4In3/KTkvD0Qz57rjcTHw4GG0Zu7lt@MLmGif@NCfWO1/Yb "JavaScript (Node.js) – Try It Online") ### Algorithm We start with the list \$a=[1,2,\dots,n]\$. For each pair \$(p,q)\in a^2,p\neq q\$ and for each operator \$o\$, we remove \$p\$ and \$q\$ from the list and append a new expression \$(p \oplus o \oplus q)\$. For each new expression built this way, we compute its squared difference with \$e\$ and update the final output \$S\$ whenever we get a better score. This process is repeated recursively until all possible expressions have been tried out. (A leaf in the search tree is reached when all elements have been combined into a single expression.) Because the initial values are not considered as possible answers by this algorithm, we have to set the default answer to \$1\$ for the edge case \$n=1\$. ### Commented ``` n => // outer function taking n g = (e, ...a) => // inner function taking e and an array a[] n ? // if n is not equal to 0 (step #1): g( // do a recursive call: e, // pass e unchanged ...a, // pass all previous entries in a[] S = m = n-- // append n (decremented afterwards) // NB: S and m are eventually set to 1 ) // end of recursive call : // else (step #2): a.map(p => a.map(q => // for each pair (p, q) from a[]: p != q && // abort if p = q [..."+-*/"].map(o => // otherwise, for each operator o: g( // do a recursive call: e, // pass e unchanged '(' + ( // append a new expression s = p + o + q // consisting of s = p + o + q ) + ')', // surrounded with parentheses ...a.filter(s => // filter a[]: s != p & s != q, // remove p and q (d = eval(s) - e) // d is the difference between // the evaluation of s and e * d < m && ( // if d² is less than m: m = d * d, // update m to d² S = s // and update S to s ) // ) // end of filter() ) // end of recursive call ) // end of inner map() )) // end of both outer map()'s && S // return the best expression ``` ### Faster ungolfed version This version can compute \$n=1\$ to \$n=6\$ on TIO. [Try it online!](https://tio.run/##hVPBctowFLz7K15ziKXYFjid6aHGmeGQY089MkxHOAKEXdkjC7edhG@n71kmxJA2HCS0Xq1WT/t2spNtYXXjElM/qeNxXVtWKQcGckgznGY5fME5ijg8BwBFbdq6UqKqNyw0eQgRciIIIXkAWuDHTjHDeRYcgmC9N4XTtXmFew3Sn6P@Qggxt1b@wQ9L8VM2jP2IQXPIH2ABGtXSGFg/c@Hq785qs2EcljxGFfqtVOvIKExgesKsahG6SW@yAJGzAyVtsWVzbwFgLvCqjxIhtoBuGoOawvJ0@vOgNSahG5USaTciAeg1uvyUE34GAe8QRmEM4R0NCQ2TEJZnybqJobyQGuRKmME93N7CDv9ofkGgS7q9NdkIPQSjJVVZ/W4sFgOvFkHd4KDS@EIJoJPVXmXjze0v7dBieX1yIVsF069@F2p3pN1hVFZWyTJ7j52O2HcfsO9H7OQD9ucRe/Iv9ju1aYva0rZv0m2FXLXM6yQeeOQXFcFH8TtmPnUvLyeF3AP4WFRuUSmzcVukYRCHxXUVh@D2CtnV21KASeu/dxgCvcCY9c4xXow6sH9z7EgeUlSpxcRaV07Zvrt83kpKqybL5ZDbJX972OHN6hCMMT/3Zl57qq@VzyTZx94/Hv8C "JavaScript (Node.js) – Try It Online") It has a few improvements over the golfed version: * don't bother to try both \$a\star b\$ and \$b\star a\$ if \$\star\$ is commutative * return the shortest expression in case of a tie [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 121 bytes ``` Nθ⊞υEN⟦I⊕ι⊕ι⟧FυFLιFLι«≔§ικη≔§ιλζ≔§η¹ε≔§ζ¹δ¿∧δ⁻κλFE⟦∕εδ⁻εδ×εδ⁺εδ⟧⟦⪫()⁺⁺§η⁰§/-*+ν§ζ⁰μ⟧⊞υ⊞OΦι∧⁻κξ⁻λξμ»≔Συυ≔↔⁻Eυ§ι¹θ秧υ⌕η⌊η⁰ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVLNTsJAEE682afY9LSrRZFAxHAiGhKMPyQaL4RDaRd2w3YL-0MIxifxwkGjd9_Gp3G2dCtGDt3JzDfzzXwzff1MWKySPBabzbs1k1r7--CpL-fW3NlsTBVekE4wsJphG6HbeI53MRKh4WWsDQQTRTMqDU0xJxD-GxgRIJnkCmFLUGFvqJwa5nL_-c_BYVdrPpW4a_oypSvMIzQDTgYkeyAB0HoPxCJ0BhDdA623UOogPkG4K1OcgjwurcYzR-nncoqHV3zJU4qpq_BZpfPIM1o5A-GBESzmOucSh5iEJVA8O8PVocK74Wnt6BgSJdkJrl2OC2SwP-Rv4Oz9nKrY5Ar3uDBwB9iCk1DNv6rGFM4pONwJXoJyEQ82g1NEyELQ72asc2ENLVmccPs7C3cbg4IFKQ8xUFyaSo63UNHjMAkr-vMM2rCiPQjpvOlxosuf7GMY1pYiHH01Ts7P2o22-5qti3qzFTS3GT8) Link is to verbose version of code. Takes `e` as the first input and `n` as the second input. Explanation: Brute force, so as usual, times out for `n>4`. ``` Nθ ``` Input `e`. ``` ⊞υEN⟦I⊕ι⊕ι⟧Fυ ``` Start a breadth first search with a list of the initial integers and the expression to generate them (i.e. the value cast to string). ``` FLιFLι«≔§ικη≔§ιλζ ``` Loop over each pair of terms from the list. ``` ¿∧δ⁻κλFE⟦∕εδ⁻εδ×εδ⁺εδ⟧⟦⪫()⁺⁺§η⁰§/-*+ν§ζ⁰μ⟧ ``` If these are different terms and the second term is not zero then loop over the elementary operations on the pair of terms and pair the expressions with the results. ``` ⊞υ⊞OΦι∧⁻κξ⁻λξμ ``` For each result create a new list with the two terms removed and the new result appended and add this to the lists of lists to be processed. ``` »≔Συυ≔↔⁻Eυ§ι¹θ秧υ⌕η⌊η⁰ ``` Flatten the final list of lists and output the expression that produces the value closest to `e`. At a cost of 20 bytes I can avoid performing the addition or multiplication in both directions which speeds the code up a little but not enough to complete `n=5`: ``` Nθ⊞υEN⟦I⊕ι⊕ι⟧FυFLιFκ«≔§ικη≔§ιλζFE⁶Eη⎇π§⟦∕ξ§ζ¹⁻ξ§ζ¹×ξ§ζ¹⁺ξ§ζ¹∕§ζ¹ξ⁻§ζ¹ξ⟧μ⪫()⪫⎇÷μ⁴⟦§ζ⁰ξ⟧⟦ξ§ζ⁰⟧§/-*+μ¿‹⁰§μ¹⊞υ⊞OΦι∧⁻κξ⁻λξμ»≔Συυ≔↔⁻Eυ§ι¹θ秧υ⌕η⌊η⁰ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVLLTgIxFE3cyVc0s2q16EAGxbgiGhKMKInsCIsBCtMw7UAfBDF-iRsWGt2781P8Gm_nwSMyyaSdc3rPPb1n3r6GUaiGSRiv1x_WjMv136OflpxZ82DFgCk8J9eljtURthS1wxne5QhFvZtQGwCHigkmDRthTgDeB_oERMaJQtgSlK73TE5M5M5m31OCXkrHDa35ROKGackRW2JO0RS0Iig-QMVArRyVCjhrF5nDiKIuUzJUz3hGUVHRu-ULPmJ4uYVWFFWc2TaXVh8iulywg0QnPlyQ99iDKVpuevwj-hQJ2NwlXGIPEy_fFv5b0uSSgqLAjXtHwXcKINDbN-LDuLeAd14-OfVcl-xBfOymrzX2t4dEap-gIme3Ps6YCk2icJPHBrKGiTfkCGf3mO5eKnYf7vbCxfxayqN6sgLipsgCWKQ30ElsDctVXFh264LnQ5yTPPSO4tJsZlasUNHk4CRK-3MBbaK0vQ_t3_VgqPMf-bPnlRex1_-unl1W6tW6e4PalR_USkF24g8) Link is to verbose version of code. Takes `e` as the first input and `n` as the second input. At a cost of a further 12 bytes I can add some code that avoids repeated values but I don't know whether this can cause some results to be skipped. It does at least just about work for `n=5` though: ``` Nθ⊞υEN⟦I⊕ι⊕ι⟧FυFLιFκ«≔§ικη≔§ιλζFE⁶Eη⎇π§⟦∕ξ§ζ¹⁻ξ§ζ¹×ξ§ζ¹⁺ξ§ζ¹∕§ζ¹ξ⁻§ζ¹ξ⟧μ⪫()⪫⎇÷μ⁴⟦§ζ⁰ξ⟧⟦ξ§ζ⁰⟧§/-*+μ¿‹⁰§μ¹¿¬№EΣυ§ν¹§μ¹⊞υ⊞OΦι∧⁻κξ⁻λξμ»≔Συυ≔↔⁻Eυ§ι¹θ秧υ⌕η⌊η⁰ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVNNTwIxEE28ya9o9tRq0YWAYjwRjQlGlERuhMMCxW3YdrEfBDH-Ei8eNHr33_g_vDvd7bqgbLJpO2_mvbfT2eePcRypcRolLy9v1kyrra-d746cW3NtxYgpfE9OKz2rY2wp6kZzvI4RigZnkTYQHCsmmDRsgjmB8GZgSIBkmiqELUHZesXknYldbn6eEfRY2W1rze8kbpuOnLAl5hTNgCuG4i1QAtDKQRmBs3aUO4wp6jMlI_WA5xQVFYNzvuAThpdlaEVRzZntcmn1NqDPBdsK9JLtBV5jI0zR8lfjHzCkSMDmMuUSB5gEflv470jjKQVFDdfuNYbQMQDBYNNICO0uA8FhdW8_cCr5g_jUdV9rHJZJIrOfY9epwWeplSZr6a0VcGdlpvQf-qeSoGJE3HozZyoyqcIXPDEwJnBZbTnBeQtm6_1I3MHxCTchTxV_y4WqhWBx8SOdJtYwz-K82dIG97buiZ-XnuLwBQVcrFBxwcFJnOlzATJxJh-C_KsejbX_B94HQXWRBMPP-sFxrVVvubfRPAkbzUozz_gB) Link is to verbose version of code. Takes `e` as the first input and `n` as the second input. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 53 bytes ``` hoa.n1.xvNZss.ussmmms.i[\(k\)-db)bs_MB.cd2"+-*/"NtQ]S ``` [Try it online!](https://tio.run/##K6gsyfj/PyM/US/PUK@izC@quFivtLg4Nze3WC8zOkYjO0ZTNyVJM6k43tdJLznFSElbV0tfya8kMDb4/38TAA "Pyth – Try It Online") Uses brute force and times out for \$n>4\$ on TIO. It will prefer short answers given a tie. ### Explanation ``` hoa.n1.xvNZss.ussmmms.i[\(k\)-db)bs_MB.cd2"+-*/"NtQ]SQ # implicitly add Q # implicitly assign Q = eval(input()) ]SQ # list [[1... Q]] .u tQ # cumulative reduce lambda N,Y along [0... Q-2] with [[1... Q]] as the starting value m N # map lambda d over N m "+-*/" # map lambda k over valid operators "+-*/" m s_MB.cd2 # map lambda b over all 2 element combinations from d -db # get the elements in d not in b, [...] .i[\(k\) )b # interleave ["(", k, ")", [...]] with b s # reduce on +, first summing into a string, then prepending that string to [...] ss # flatten out unwanted nesting ss # flatten out more nesting o # sort this list based on lambda N a # the absolute difference between .n1 # e .xvNZ # and eval(N) or 0 if error is thrown h # take the first element ``` [Answer] # [Python](https://www.python.org), 331 bytes ``` def f(x,e): d={};A=[*C([*"()",""],x)] for o,p,q,r,s in[*product(A,sum([[*permutations(range(1,x+1),n)]for n in range(x+1)],[]),A,C("+-*/",x),A)]: try:S="".join("".join(map(str,l))for l in zip(o,p,q,r,s))[:-1];d[S]=eval(S) except:0 return min(d,key=lambda a:abs(d[a]-e)) from itertools import*;C=combinations_with_replacement ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RZGxbtswEIaRVU9BMENJ5ezG6FLI0GB4DJDF3QQioC3KZiMeGeoUyy3yJFm8NK-R50iepnRUN9Pdf-R9vPv5_BIOtPN4fPtxyW492xtWe_xCbK-RWHdA0kPKI1rcdpl1wUf61Odk2tiWTDxLwe0WfTRc_umpmXx_v7ipTcMaMYCRRcbq8vfTfFFW-VJUOReSA-cKBqky1vjIPAR4gAgds1jlIfq635BYQNc7UaWCia4nTdZjJ6LGrREzGK5mElCqUz-mPjYenMoKKiVhAUvBryb5V54egoVUaQ5G8VCsSs6nP71FcY5OB9FRhFbKE6494X7ZIP7PJWVVTGZqXlcrVZpH3YqVTDQzbEyg4jpj0VAfkbkEq-HeHMpWu3WtmS70uhN1pdXESJk10Ttmk3HkfZu2_XA3ny_LjXdri-OKd3tLu7toQqs3xhmk0dPXf3_hNO2yEC2SaMQ3-NDTBB9vHY9j_As) Brute-force so times out for \$n\ge4\$. I tried to test it on my computer with \$n=5\$ but it was taking ages (probably because for \$n=5\$ it has to loop through something like 8.8 trillion times), so I can just reassure with the fact that it works *in theory*. ]
[Question] [ Given a set of intervals \$\mathcal{I} = \{I\_1, \ldots, I\_m\}\$, where each interval \$I\_j\$ is represented by its bounds \$(a\_j, b\_j)\$, find a partition \$\mathcal{T}\$ of \$\mathcal{I}\$ of minimal cardinality such that for each set \$T\_i \in \mathcal{T}\$ it holds \$\bigcap T\_i \ne \emptyset\$. In other words, find a partition of minimal cardinality where all the intervals inserted in the same set have a common element. Elements \$\{a\_j, b\_j\}\$ can be integers, floats, chars, strings, or any other data type that has a **total** order and at least \$16\$ elements \* (boolean is not admissible). Your solution must support at least one such data type of your choice. \*: why \$16\$ and not any other number? It's an arbitrary limit, I want to give freedom to use any strange data type, but I do not want loopholish solutions. You can either output: 1. partition \$\mathcal{T} = \{T\_1, \ldots, T\_k\}\$, or alternatively 2. a set of numbers \$S = \{s\_1, \ldots, s\_k \}\$ such that \$s\_i \in \bigcap T\_i\$ for each \$i\$. ### Testcases ``` input output (format 1) output (format 2) {}: [], [], {(0, 1)}: [{(0, 1)}], [0], {(0, 1), (2, 3)}: [{(0, 1)}, {(2, 3)}], [0, 2], {(1, 2), (0, 3)}: [{(1, 2), (0, 3)}], [1], {(0, 2), (1, 3)}: [{(0, 2), (1, 3)}], [1], {(1, 2), (3, 4), (0, 5)}: [{(1, 2), (0, 5)}, {(3, 4)}], [1, 3], {(0, 1), (4, 5), (2, 3)}: [{(0, 1)}, {(2, 3)}, {(4, 5)}], [0, 2, 4], {(4, 5), (1, 2), (0, 3)}: [{(1, 2), (0, 3)}, {(4, 5)}], [1, 4], {(0, 1), (2, 5), (3, 4)}: [{(0, 1)}, {(2, 5), (3, 4)}], [0, 3], {(0, 2), (3, 5), (1, 4)}: [{(0, 2), (1, 4)}, {(3, 5)}], [1, 3], ``` ### Rules * you can use any reasonable I/O format, for example: + the input can be a list/set of tuples, or two lists; + in case 1., the output can be a list/set of lists/sets of intervals; each interval can be represented as a tuple, or the index of its position in the input; + in case 2., the output can be a list/set of numbers; * you can take the cardinality \$m\$ of the input set as an additional input; * the input set \$\mathcal{I}\$ may be empty (in this case you have to output an empty list/set); * you can assume each interval is not empty nor degenerate, i.e. \$a\_j < b\_j\$; * you can assume intervals are left-closed or left-open, and if they are right-closed or right-open, as long as it's consistent for all intervals; * you cannot assume the intervals in the input are sorted according to any particular criteria. This is codegolf, so the shortest code wins. Bonus [\$-i\$](https://en.wikipedia.org/wiki/Imaginary_unit) bytes if your solution works in less than exponential time. --- #### Tips * I think using closed intervals is the easiest way. I would have put it as a rule, but I prefer to leave freedom. * > > by lexicographically sorting the intervals, a minimal solution can be computed using a greedy algorithm. > > > [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` ˜æ.ΔI€Ÿ¢€àP ``` [Try it online!](https://tio.run/##yy9OTMpM/f//9JzDy/TOTfF81LTm6I5Di4DU4QUB//9HRxvqGMXqRBvomAJJYx2T2FgA "05AB1E – Try It Online") or [try all test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRfeWjl/9NzDi/TOzfl0LpHTWuO7ji0CEgdXhDwv1bnf3R0rE50tIGOgmEsnKGjEG2ko2AMFjDUUTACCRjABAygAoboKox1FEygKk1RzDIBCSCbCRPAZjbMdlO4kciWGiN0AiViAQ "05AB1E – Try It Online"). Finds the smallest subset of the ranges' bounds such that each of the ranges contains one of the values in set. ## Explanation ``` ˜ flatten the input ranges, to get a list of all bounds æ push all subsets, sorted by size .Δ find the first (and smallest) one such that: I push the input again € map each interval in the input Ÿ to the list of integers it contains ¢ count how many times each of these values appear in the subset. Because the minimum subset doesn't contain duplicates, each of these is 0 or 1. €à for each of the intervals, find the maximum P and take the product, check if all of them are 1 ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 59 bytes ``` f=lambda a:a and(z:=max(a)[0],*f([p for p in a if p[1]<z])) ``` [Try it online!](https://tio.run/##hZHdaoQwEIXvfYphr5IyFH@hyPoG@wbBixSVBtQEV0q70me3STZaf2kgMMwcv5w5qu/@Q7bRm@rGscpq3rwXHHiqb1uQR5o1/ItwyvwcXyrCFFSyAwWiBQ6iAsWC/PrIKR1N/2b6UpUt8WnqgUAiA5QhhQwarkj5yWu8vd5VLXpySS@UeqA60fZEYEUExbvs@rIgpqZZpj8ch58UTg/LEf45WuINxEcI6DGJTdNzltl9giCQECHawGYIwuDmWxzTgtByAl0Yjn/IWU/3pnTezoyVBWdmFtNTyPRWhBC7NxMHWztJnptZ3Yxjhr5KJjbKdUIHyZjKKh3JJqPJFjUhDkLahbMFPS3F25@VzCseW1rMZ46/WG2KaPK15oR/XRdRsuP8Ag "Python 3.8 (pre-release) – Try It Online") Takes a sequence of pairs representing left-closed, right-open intervals and returns a tuple of points. Same algorithm as earlier but upside down. ### Retired [Python](https://www.python.org), 62 bytes (-4 thanks @Jonathan Allan) ``` f=lambda*a:a and(z:=min(map(max,a)),*f(*filter([z].__le__,a))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jVFLaoRAECVbT1HMqlsqg44OBDPmBHMDEWlHJQ3tB8cEo-QUWWbjJjlNLpCcJraf8cNAIjRY71W997r6_TN7KR7TpGk-noro9u77IbIFi_2AqcxiwJKAVJYd84TELGtPiYxSVCOiRlwUYU6cyt16ngg9TzJ0UHmL0hyOwBNIszAhGrUUYOj4LtgghcJnJvC4PWeCF2RjbSht-ZZzVMkKfi5aNVeBLOdJQRi2foyiT-8HQIjulIfTwa5AmpVYSbuAyuKEgSwqnpFxcozW_Nx81a8WdJ_jolITDUGnPeSM1UQgkB2CsW5AqAe8a9URdrJVW7Qu0VGzg_S15gxdKBoI5qCxXyl3IZb8IrcpoT_zyz9zGh6H_nOj1ehsX_tL9Ou-M36xFmNyN6-ux7zcunftX_UX) ### Retired [Python](https://www.python.org), 66 bytes ``` f=lambda*a:a and(z:=min(y for x,y in a),*f(*filter([z].__le__,a))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jVHLaoNAFKVbv-KS1YzcBo0Gio2brvMHIjJGJQPjA2NLVPoVXXbjpv2a_kD7NXWMxgeBVhC855x7zpnx_TMri2OaNM3HcxHdP3w_RbZgsR8wlVkMWBKQyrJjnpASojSHM5bAE2AU1YioERdFmBOncteeJ0LPQ0Yp7Z3epH4v1WkWJkSjlgIMHd8FG2KWkfCFCdyvT5ngBVlZK0pbvuUcVbKCn4rWzVUgy3lSEIZtXhvr08ceEKJ7z7vDzq76cpWMC6gcDhjIoeIZGTaHas3P3Vf9akH3OC4qNdEQdHqBnGEaCQSyQTCWAoS6xzupjrCRUm0mnaODZwfpS88JOnM0EMzeY7tw7krM-VlvU0J_9pdf5rg8LP3nRIvVyX1tr9Vv50742bUYY7p583rM66kvqZe_-gs) Takes a splatted sequence of lists representing left-open, right-closed intervals and returns a tuple of points. Time-complexity is quadratic I believe. ### How? At each iteration finds the smallest right boundary. This point is used to define the next cluster. All intervals with smaller left boundary contain the point and are filtered out before the next iteration. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) (\$-i\$) ``` >Ạ¥ƇṀ€Ṃ$$ƬḟƝ ``` A monadic Link that accepts the intervals as a list of pairs and yields a minimal cardinality partition with self-intersecting parts as a list of lists of pairs. **[Try it online!](https://tio.run/##y0rNyan8/9/u4a4Fh5Yea3@4s@FR05qHO5tUVI6tebhj/rG5/w@3H530cOeM//@jo810FMxjdRSiDQ10FIwMQCxTHQULEG2uo2BoCGIY6yiYgmgjkBIjMMsQKARWbGgI02YEFooFAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/u4a4Fh5Yea3@4s@FR05qHO5tUVI6tebhj/rG5/3UOtx@d9HDnDKB41qOGOQq2dgqPGuZqRv7/Hx0dq8OlEB1toKNgGIvE1FGINtJRMIYKGeooGIGEDBBCBlAhQ0xVxjoKJlDVpmhmmoCEUM2GCWG3A@YSU7jBqNYbI3SDpWIB "Jelly – Try It Online"). ### How? ``` >Ạ¥ƇṀ€Ṃ$$ƬḟƝ - Link: Intervals Ƭ - collect up while distinct, applying: $ - last two links as a monad - f(CurrentIntervals): $ - last two links as a monad - f(CurrentIntervals): Ṁ€ - maximum of each Ṃ - minimum -> "M" Ƈ - keep those (I in CurrentIntervals) for which: ¥ - last two links as a dyad - f(I, M): > - {I} greater than {M}? (vectorises) Ạ - all? Ɲ - for neighbouring pairs - f(L, R): ḟ - {L} filter discard {R} ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` W⌊⌈θ«≔Φθ‹⌈κιθ⟦Iι ``` [Try it online!](https://tio.run/##PYq7CgIxEADru6/YchdW8FlZiWDlgX1IEY7gLeYiefgA8dvX08JmBobpB5f7qwuqj0GCB@wkyngbsXPPnxMRwattdqXIOeJBQvUZE8PRl/K/LsQgNCHRtm1OWWJFs3elopCd0lvVGLNm2FgGs2BYfj1nWFlrdXYPHw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @Albert.Lang's upside-down answer. ``` W⌊⌈θ« ``` While intervals remain, find the beginning of the rightmost interval. (This depends on underhanded behaviour of the version of Charcoal on TIO which returns `None` if it can't work out whether `⌊` is supposed to be `Minimum` or `Floor`.) ``` ≔Φθ‹⌈κιθ ``` Remove the intervals that contain that point. ``` ⟦Iι ``` Output the point. [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 11 bytes ``` Oᵖᵐ{Ťđṁ<}aş ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Flv8H26d9nDrhOqjS45MfLiz0aY28ej8JcVJycVQBQtuzoiO5YqONtAxjIXROtFGOsZgnqGOEZBnAOUZgHmGKHLGOiZgFaZIuk2APIQZEB66SRBbTKEmIEw3hqoGikEcCAA) ``` Oᵖᵐ{Ťđṁ<}aş O Find a set partition of the input ᵖ such that ᵐ{ } for each subset in the partition Ťđ transpose to get a list of heads and a list of tails ṁ< check that all heads are less than the smallest tail aş Find the shortest such partition ``` By default, Nekomata outputs all possible solutions. If you want only one solution, you can add the `-1` flag. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes ``` hlDm{.nd*FrM ``` [Try it online!](https://tio.run/##K6gsyfj/PyPHJbdaLy9Fy63I9///aA1DHQVjTR0FDWMdBVMQbaCjYKYZCwA "Pyth – Try It Online") Uses half inclusive range. Looks at all lists where one element is from each range, deduplicates this and then finds the shortest. ### Explanation ``` hlDm{.nd*FrMQ # implicitly add Q # implicitly assign Q = eval(input()) rMQ # map elements of Q to their ranges *F # fold over cartesian product m # map over lambda d .nd # flatten d to an unnested list { # deduplicate lD # sort by length h # take the first element ``` ]
[Question] [ I want to read two strings on separate lines, each string the same length and containing only 0's and 1's, and determine if the first is the one's complement of the second. How succinctly can this be done in Python3? (Sorry to specify the language, but this is for my son who's studying Python) A list comprehension seems to work but is quite ugly. ``` if ['0' if x=='1' else '1' for x in input()] == list(input()): print('yep') ``` Is there a slicker/shorter way to do this? [Answer] # [Python 3](https://docs.python.org/3/), ~~51 44 43~~ 41 bytes -7 thanks to [loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt)'s suggestion to use `*open`. -1 thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s suggestion to replace `any(...)` with `1in ...` -2 thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)'s suggestion of using `str.find` instead of `str.__eq__` ``` 0in map(str.find,*open(0))or print('yep') ``` **[Try it online!](https://tio.run/##K6gsycjPM/7/3yAzTyE3sUCjuKRILy0zL0VHK78gNU/DQFMzv0ihoCgzr0RDvTK1QF3z/39DAyDkAhEGAA "Python 3 – Try It Online")** This is a full program that takes input from stdin until an EOF (which we assume the user provides at the end of the second line) with `open(0)` and `map`s across the two strings by splatting (`*`), calling `str.find` on each pair of characters in turn. If `0` is `in` the result (i.e. the characters are equal and so the index of the first in the second is `0` rather than `-1` for "not found") then the right-hand clause of the `or` is not evaluated, and so we don't `print`. --- My previous version, with xnor's and dingledooper's suggestions, at \$48\$, is interactive without the EOF faff: ``` 0in map(str.find,input(),input())or print('yep') ``` --- You *could* save one more byte by printing to stderr instead of stdout by exiting the program early using `exit` in place of `print`. --- A note to your son - this is not how I'd want someone in my team at work to write code :) - readability counts, a lot. [Answer] # [Python3](https://docs.python.org/3/), 62 bytes Since the bits at the similar position need to be set in one of the inputs and unset in the other, their bitwise XOR must have all bits set. ``` x=input() int(x,2)^~-(1<<len(x))^int(input(),2)or print("yep") ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v8I2M6@gtERDkyszr0SjQsdIM65OV8PQxiYnNU@jQlMzDiQMVQKUzC9SKCgCCSlVphYoaf7/b2hgaGjAZWBoYGAIAA "Python 3 – Try It Online") *-5 bytes thanks to Arnauld* Updated from my previous answer where I incorrectly assumed that checking bitwise AND = 0 was a sufficient condition. ]
[Question] [ ## Intro Imagine a list of elements and their outcomes when some non-commutative function is applied to them. For example, we will use the elements `Rock`, `Paper`, and `Scissors`, the outcomes `Win`, `Lose`, and `Tie`, and an operator `*` such that `X*Y` = what would happen if you played `X` against `Y` As a list, you might write it this way: ``` [Rock*Rock=Tie, Rock*Paper=Loss, Rock*Scissors=Win, Paper*Rock=Win, Paper*Paper=Tie, Paper*Scissors=Loss, Scissors*Rock=Loss, Scissors*Paper=Win, Scissors*Scissors=Tie] ``` In table form, it might look like this: | top\*left | Rock | Paper | Scissors | | --- | --- | --- | --- | | **Rock** | Tie | Win | Loss | | **Paper** | Loss | Tie | Win | | **Scissors** | Win | Loss | Tie | One might observe that for any pair of elements, there is a pair of outcomes. For the unordered pair `(Rock,Paper)`, `Rock*Paper` gives `Loss` and `Paper*Rock` gives `Win`. You might think of a function which takes a pair of elements and outputs a pair of outcomes given by the table. In our initial example, that'd be `(Rock,Paper) => (Loss,Win)` A few more examples: ``` (Rock,Rock) => (Tie,Tie) (Paper,Scissors) => (Win,Loss) (Paper,Paper) => (Tie,Tie) ``` Note that order of input and output doesn't really matter here, since we're just asking which outcomes exist at all between the two elements. Finally, consider the inverse to this function, which takes a pair of outcomes as input and outputs tall pairs of elements which can have both outcomes. Here are all possible distinct inputs and their outputs for the example case: ``` (Win, Win) => (Win, Loss) => (Rock,Paper), (Paper,Scissors), (Scissors,Rock) (Win, Tie) => (Loss, Loss) => (Loss, Tie) => (Tie, Tie) => (Rock,Rock), (Paper,Paper), (Scissors,Scissors) ``` Note again that order doesn't matter here, so ``` (Win,Loss) => (Rock,Paper), (Paper,Scissors), (Scissors,Rock) (Loss,Win) => (Rock,Paper), (Paper,Scissors), (Scissors,Rock) (Win,Loss) => (Paper,Rock), (Scissors,Paper), (Scissors,Rock) (Win,Loss) => (Scissors,Rock), (Rock,Paper), (Paper,Scissors) ``` are all valid. Implementing this inverse is your challenge. ## Challenge Write a program or function which does the following: * Takes a list of ordered element pairs and their outcomes when some non-commutative function is applied, referred to as the "Interaction Table" from here onward. This can be done in any consistent reasonable format, specified by the solver. * Takes a single unordered pair of outcomes `x,y` as a second input, referred to as the "Given Pair" from here onward. This can be done in any consistent reasonable format, specified by the solver. * Outputs a list of all unique unordered pairs of elements `a,b` such that, according to the Interaction Table, `a*b` is one of `x,y` and `b*a` is the other. This can be done in any consistent reasonable format, specified by the solver. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), So shortest code in bytes wins. ## More specification * The Interaction Table does not actually have to be a literal table. It can be taken in any reasonable format, standard I/O etc. Just remember to specify exactly how you take input, especially if it's somewhat unusual. * Instead of taking the Given Pair as a second input, your program/function may take only the Interaction Table as input and output a program/function which takes the Given Pair as its only input and provides the expected output for the challenge. * You may restrict elements and outcomes to a reasonable degree, e.g. "only integers" / "only alphabetical strings" is fine, but "only digits 0-9" is not. * Since outputs will always be pairs of elements, you don't need to use a second delimiter to separate pairs, only individual elements. e.g. both `(A B) => (1 2) (3 4)` and `A B => 1 2 3 4` are both valid formats. * You may assume that there are no missing interactions, i.e. every element within the Interaction Table will be paired with every other element and itself in each possible permutation. * You may assume that the Interaction Table is given in some standard order, if that helps you in some way. * You may **not** assume that every Given Pair will have an output. In these cases, any falsy output or no output is fine, so long as you don't output an element pair. * You may **not** output duplicate pairs. `(A,B) => (1,2),(1,2)` is **not** valid, and since pairs are unordered, `(A,B) => (1,2),(2,1)` is also **not** valid. ## More examples Here is another example of a possible Interaction Table input ``` (("AxA=1","AxB=1","AxC=2"),("BxA=2","BxB=3","BxC=2"),("CxA=1","CxB=2","CxC=1")) ``` Which can correspond to this literal table | x | A | B | C | | --- | --- | --- | --- | | **A** | 1 | 2 | 1 | | **B** | 1 | 3 | 2 | | **C** | 2 | 2 | 1 | Some example Given Pairs and their outputs ``` (1,1) => (A,A),(C,C) (2,2) => (B,C) (2,3) => (1,2) => (A,B),(A,C) ``` Another possible Interaction Table input ``` ["What","What","Yeah"],["What","Who","Yeah"],["Who","What","Nah"],["Who","Who","Yeah"] ``` Which can correspond to this literal table | x | What | Who | | --- | --- | --- | | **What** | Yeah | Nah | | **Who** | Yeah | Yeah | Some example Given Pairs and their outputs ``` "Nah" "Yeah" => "Who" "What" "Yeah" "Nah" => "Who" "What" "Nah" "Nah" => "Yeah" "Yeah" => "What" "What" "Who" "Who" ``` One more possible Interaction Table input ``` "0 0 a 0 1 b 1 0 c 1 1 d" ``` Which can correspond to this literal table | x | 0 | 1 | | --- | --- | --- | | **0** | a | c | | **1** | b | d | [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 56 bytes -2 bytes thanks to @Wheat Wizard. ``` (!)#p|[x!y,y!x]==(p?reverse p)&&x<=y=(x,y)where x,y free ``` [Try it online!](https://tio.run/##bY1NCsIwEEb3PUWaQmmh3sDgBVyICi5KFyVMMRTbMIOagHePJTWmFVfz82beJ@@IdqPbXpJzRVpm@lWb1FY2NY0Qhd4hPAAJmC7z3GyFFYWpbPm8AgKbOtYhgOsYP46y56EIxs8KeBL3h1YDerAfiZbkJBXRiOThRQ2efc6j7hdEXwgKZOX7hsVtdP6D0RsSF3Cl9rnJrVXDNHUsY/UsrObXJnFv "Curry (PAKCS) – Try It Online") Takes the Interaction Table as a function and the pair as a list with two elements. For example, the Interaction Table of Rock-Paper-Scissors is given by the following function: ``` f "Rock" "Rock" = "Tie" f "Rock" "Paper" = "Loss" f "Rock" "Scissors" = "Win" f "Paper" "Rock" = "Win" f "Paper" "Paper" = "Tie" f "Paper" "Scissors" = "Loss" f "Scissors" "Rock" = "Loss" f "Scissors" "Paper" = "Win" f "Scissors" "Scissors" = "Tie" ``` And `f # ["Loss", "Win"]` would give the result: ``` ("Rock","Scissors") ("Paper","Rock") ("Paper","Scissors") ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 24 bytes ``` vh'Ḃ"ƛ£¹'h¥⁼;ht;s⁰s⁼;vsU ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ2aCfhuIJcIsabwqPCuSdowqXigbw7aHQ7c+KBsHPigbw7dnNVIiwiIiwiW1tbJ1JvY2snLCdSb2NrJ10sJ1RpZSddLCBbWydSb2NrJywnUGFwZXInXSwnTG9zcyddLCBbWydSb2NrJywnU2Npc3NvcnMnXSwnV2luJ10sIFtbJ1BhcGVyJywnUm9jayddLCdXaW4nXSwgW1snUGFwZXInLCdQYXBlciddLCdUaWUnXSwgW1snUGFwZXInLCdTY2lzc29ycyddLCdMb3NzJ10sIFtbJ1NjaXNzb3JzJywnUm9jayddLCdMb3NzJ10sIFtbJ1NjaXNzb3JzJywnUGFwZXInXSwnV2luJ10sIFtbJ1NjaXNzb3JzJywnU2Npc3NvcnMnXSwnVGllJ11dXG5bJ1dpbicsICdMb3NzJ10iXQ==) A mess. ## How? ``` vh'Ḃ"ƛ£¹'h¥⁼;ht;s⁰s⁼;vsU vh # Get the first item of each of the (implicit) first input ' # Filter-keep for: Ḃ" # Pair with reverse ƛ # For both: £ # Store in register ¹' # Filter-keep for first input: h¥⁼ # Is the first item equal to the contents of the register? (non-vectorizing) ; # Close filter ht # Get the first item of the results of the filter, and get the last item of that ; # Close map s # Sort the results ⁰s⁼ # Is it equal to the first input sorted? (non-vectorizing) ; # Close filter vs # Sort each U # Uniquify ``` [Answer] # [C (GCC)](https://gcc.gnu.org), 118 bytes ``` f(n,e,t,x,y,i,j)int**t,*e;{for(i=0;i<n;++i)for(j=0;j<n;++j)t[i][j]-x|t[j][i]-y|x==y&i>=j||printf("%d %d ",e[i],e[j]);} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6FjfL0jTydFJ1SnQqdCp1MnWyNDPzSrS0SnS0Uq2r0_KLNDJtDawzbfKstbUzNUH8LCA_C8zP0iyJzoyNzorVragpAVJAjm5lTYWtbaVapp1tVk1NQRHQrDQNJdUUBSBS0kkFqgASWbGa1rUQ26GOgDkGAA) Arguments description: * `n` is the number of elements; * `e` is a vector of `n` items, each representing an element; * `t` is the table, represented as an array of arrays; * `x` and `y` are the two result which form the pair to invert; * `i` and `j` are dummy arguments. [Answer] # [R](https://www.r-project.org/), 116 bytes ``` function(t,x,r=function(x)sub('(.*) (.*)','\\2 \\1',x),d=names(t),f=paste(t[d],t[r(d)]),c=d[f==x|f==r(x)])c[c<=r(c)] ``` [Try it online!](https://tio.run/##ZZExb8MgEIX3/Ao2oEJRjDOWIclaRVVbKapsDwQ7ilXVjgypPPS/u3fYULv1cHr38XhnoBtcogyjL635IFioom91RQUZ0bO@VR2wp9baCF9NbW3bWeCnuqFiRfCj3htC/EJgIWVKHuEsZUyfYgIPSWF05CFtGhH5LBAH8ZWTeLQd2QFJqAC1j@oASsaZe@@BHhR6Uq/AI4PjEFMO3iG9AkcCc1Kcc7pqR7DA6nulr2CYUDsnbfAcZyA6IGyLYRuyAaTBsCEJqDOoxDPjFbIS3HXzpYbLvTGubhvmRC86Fdue2/uZUbZ@4AQL7MxzSfIcjtFzUapGf1aWOS4u6qatq5jLykK4rGMlL7gwqswuSvXfUDpIK7jJzCNIw4sBJjOXCHwFgi/h/yUS/2hLNL5JIGj46/JsaYNuTuR49t9OErno0oUzrqUCr5tMVxwQtuS4QMd/xJvmG7eCaqIpH4Yf "R – Try It Online") R version 4 saves 14 bytes because you can say \(x) rather than function but isn't supported by TIO. This is a pretty straightforward approach, taking input as ('a,b') in string format (so no commas is the constraint for inputs/outputs). The table is a named vector to use R's indexing abilities to compute preimages and apply functions, and we build the function f (an unnamed vector on domain d) that takes (a,b) to (t(a,b),t(b,a)). Then we deduplicate at the end. 1 byte freed by replacing gsub with sub. Improved to [112 bytes](https://tio.run/##ZZExb4MwEIX3/AozGVdWFUzGekiyVlHVVooqQIpjiIKqQhQ7FUP/O70z2IWU4fTu8/M7bF97m0gd09dWfxIsVNL3uqKcDOhFXaorsOfWmADfdG1MezXA93VD@YLgR53Xh7gFz3zKmDzAScqQPsZ47pP86MB92jgi8EkgDmILK/Boa7IGklAOahPUFpQIMzfOAz0o9KROgUd4xzakbJ1DOAWOBOakOGd/VpZggdWPSp3BMKJ2Slrv2U1AcEDYCsOWZAlIgWFJElBHUIlj2ilkJbjr5lv2p1ujbd02seUdP0QHGUDHzO0Y0/jxgREssDfPBclzOEjHeCkb9VWZ2DJ@khdlbBXbrCy4zaKyYFzLMjtJ2f1AibqC6Uw/yUgXPUyNbcLxBQi@gvuPQNyDzdHwHp6g4d7l2NwG3ZSI4dx/nSBi1qUzZ1hLOV41Ga/XI2zJboZ2/4gzTTeuOFVEUdb3vw) by <https://codegolf.stackexchange.com/users/55372/pajonk>, and R version 4 improves this to 98 bytes. ]
[Question] [ # Objective Given a **positive** integer, spell it out in the conlang I made. # Specification Let \$n\$ be the inputted integer. \$n\$ shall be spelled out in the following specification. **The entire spelling is case sensitive.** With the decimal expansion of \$n\$, let **d** be the least significant nonzero digit of \$n\$. First, **d** shall be spelled out like this: * 1 = `Qun` * 2 = `Pis` * 3 = `Tel` * 4 = `Kal` * 5 = `Pan` * 6 = `Soh` * 7 = `Set` * 8 = `Qok` * 9 = `Nof` Second, an appropriate suffix (or a "particle" in linguistic sense?) will immediately follow. This is judged by two boolean conditions: (A) Whether **d** has any trailing zeros, and (B) whether **d** is ***not*** the only nonzero digit. * If neither holds, the suffix shall be `em`. * If only (A) holds, the suffix shall be `eh`. * If only (B) holds, the suffix shall be `at`. * If both hold, the suffix shall be `om`. Third, if (A) held, the length of the trailing zeros shall be spelled out recursively. Finally, if (B) held, **d** and the trailing zeros shall be stripped off, and the remaining digits shall be spelled out recursively. All words shall be intercalated by a single ASCII 0x20 whitespace. # Examples * 1 = `Qunem` * 2 = `Pisem` * 7 = `Setem` * 10 = `Quneh Qunem` * 11 = `Qunat Qunem` * 12 = `Pisat Qunem` * 19 = `Nofat Qunem` * 20 = `Piseh Qunem` * 42 = `Pisat Kalem` * 69 = `Nofat Sohem` * 100 = `Quneh Pisem` * 109 = `Nofat Quneh Qunem` * 440 = `Kalom Qunem Kalem` * 666 = `Sohat Sohat Sohem` * 1945 = `Panat Kalat Nofat Qunem` * 2000 = `Piseh Telem` * 2022 = `Pisat Pisat Piseh Qunem` * 44100 = `Qunom Pisem Kalat Kalem` * 144000 = `Kalom Telem Kalat Qunem` * \$10^{60}\$ = `Quneh Soheh Qunem` * \$10^{63}\$ = `Quneh Telat Sohem` # Rules I/O format is flexible. Standard loopholes apply. As for input, those that are not positive integers fall in *don't care* situation. As for output, trailing whitespaces are permitted, but leading whitespaces are not. # Ungolfed solution ## Haskell ``` import Data.List import Numeric.Natural spellNDos :: Natural -> String spellNDos 0 = "" spellNDos n = go (reverse (show n)) where go "" = "" go str = let (zeros, digit:remaining) = partition ('0'==) str digitSpell = case digit of '1' -> "Qun" '2' -> "Pis" '3' -> "Tel" '4' -> "Kal" '5' -> "Pan" '6' -> "Soh" '7' -> "Set" '8' -> "Qok" _ -> "Nof" suffix = case (null zeros, null remaining) of (False, False) -> "om " (False, _ ) -> "eh " (_ , False) -> "at " _ -> "em " in digitSpell ++ suffix ++ spellNDos (genericLength zeros) ++ go remaining ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 172 bytes ``` f=lambda n:(d:=n.strip('0'))and' QPTKPSSQNuieaaoeoonsllnhtkf'[int(l:=d[-1])::9]+'eeaomhtm'[(t:=n!=d)+1%len(d)*2::4]+(' '+f(str(N:=n[::-1].find(l))).strip())*t+' '+f(n[:~N]) ``` [Try it online!](https://tio.run/##LY/PboMwDMbvforsMDkGrSIpYyMSTzCpatXdGIdUAYGWBgTppF326sz9c7Asfd/P9ufpN/Zj2L5P87p2lbfnk7MiGOlMFTZLnIdJYoZENjgUh/3nx/54POwuQ2vt2I5jWLwPffzusB5ClN5Urn5RDRlTNim2rR3PfTxjLSPve6ocperZt0E6SrQxeZNKFJh2ki/JHSO1MTy@6YbgpCeiRwSiJKZ3kpG/XUPrEKZLXEQlEBEUaHgDlYFSoDSoEnQGuYaiZJHVrIQ8z6AoCvbyV3ZZ1ZnWLN8Adm9ckhSPtgVevFkmP0SJXwGpVtdoAN04Cz7OJe4ZjJjm6/P3L9of6yUbHJ7Wfw "Python 3.8 (pre-release) – Try It Online") Straightforward implementation of the specification. Input a string. Makes use of string indexing and various other tricks to simplify finding the least significant digit and removing digits. This makes the task much easier to accomplish because with numbers, one would have to perform messy tasks such as dividing by powers of 10 or using the `%` operator to "index into the number", and because of this difficulty it is golfier to convert the number to a string then perform some indexing. Then I thought, "Why not just use a string for the input?" and the code was thus shortened by 25 bytes, maybe more. Thanks @ovs for -2 bytes. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 86 bytes ``` ⊞υNWυ«≔⊟υι¿ι«≔⌕⮌÷¹⊕↨ιχ⁰θ≧÷Xχθι§⪪”↶0OP⊘ηS℅ê*k⮌⁰nI¿'⊗ξ!»NV”³ι≧÷χι⊞υι⊞υθ¿θ¿ιom¦eh¿ιat¦em→ ``` [Try it online!](https://tio.run/##hVDBaoNAED3rVwyeRrCg9tacUkpBSoOJ/YFtnMSh667R1RRKvt3uqmkJPXRhD/PezHuPt69Eu9dCjmPedxX2EWSq6c2mr9@pxTBc@eeKJQH2IXz53rrr@Kgw140FImDLe3wA5Im90s@sStzRQG1HmCnzxAOXhIkT37dUkzJU4qOwLEeQxKF9EcT2n5yg9yqaWWnHx8r8KkSQ67ONlcRuc7H38paVwbXJVEmfWDSSDQYAsO1Vzt0byRchc6EKXRVktvpjow9BBPfT/T92zmgxWdq5nea4roBTCEsPc5xA10G4ApIdXRGqfpDbVWH@rLpjl0wPhA9TLDdf/Ms4pnGajneD/AY "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υNWυ« ``` Start processing with the input value. ``` ≔⊟υι¿ι« ``` If the current value to process is zero then ignore it and continue on to the next value. ``` ≔⌕⮌÷¹⊕↨ιχ⁰θ≧÷Xχθι ``` Find the number of trailing zeros in the current value and remove them. ``` §⪪”↶0OP⊘ηS℅ê*k⮌⁰nI¿'⊗ξ!»NV”³ι ``` Output the prefix corresponding to the last nonzero digit. ``` ≧÷χι ``` Divide the value by `10` again. ``` ⊞υι⊞υθ ``` Push the final value and the number of trailing zeros to the list so that they get processed. ``` ¿θ¿ιom¦eh¿ιat¦em→ ``` Output the appropriate suffix and allow a space before any other output. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 72 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` "SDĀÅ¡¦ηRεDg≠UθćsgV.•¿Õ¾¸”mÚÄú±pE”¿м∍•3ôsè™.•DĀ€y‹•2ôYĀX«Cè«Y®.V‚"©.V˜ðý ``` [Try it online](https://tio.run/##AY4Acf9vc2FiaWX//yJTRMSAw4XCocKmzrdSzrVEZ@KJoFXOuMSHc2dWLuKAosK/w5XCvsK44oCdbcOaw4TDusKxcEXigJ3Cv9C84oiN4oCiM8O0c8Oo4oSiLuKAokTEgOKCrHnigLnigKIyw7RZxIBYwqtDw6jCq1nCri5W4oCaIsKpLlbLnMOww73//zQ0MTAw) or [verify all test cases](https://tio.run/##bYy/SgNBEIdf5dh6OGb3LitXpfDyAgYPg1goSLAIBg4C6RZJ/FPYCDZBQVNIJCIKEWNQAzPXCYfPsC9yjgpWTjO/@X4fs59v7@ztVr1@mKV1FfjDs0DVK9VMC8dDuqab8nmtfErb/uRqvZwXR3k7C70b05LP6Z3m3l12eMQDXtBjtyEXLT9f/fGpKBHPcp74wfjbl3f@4K7v3Yschmetwm3QdJUnNG3RfZh5N1J0G2YfF/zAbxVUmxoMrIBG0Bq0AZ2AQYgN2ESgUEwgjhGstdLFNWmFGjRG8I8grSylMbDYUb8hkiBOhFjDv/DPbH0B). **Explanation:** ``` "..." # Push the recursive string explained below © # Store it in variable `®` (without popping) .V # Execute it as 05AB1E code ˜ # Flatten the resulting list ðý # Join this list with space delimiter) # (after which the result is output implicitly) S # Convert the current value to a list of digits # (which will be the implicit input in the first iteration) D # Duplicate this list of digits Ā # Check for each digit if it's non-0 Å¡ # Split the list of digits at the truthy (non-0) indices ¦ # Remove the leading empty list # (e.g. "20230050" → [[2,0],[2],[3,0,0],[5,0]]) η # Get the prefixes of this list R # Reverse it ε # Map over each prefix-list: D # Duplicate the current list of lists g # Pop the copy, and push its length ≠ # Check that this length is NOT 1 U # Pop and store this in variable `X` θ # Pop and push the final digit-list from the current prefix ć # Extract head; pop and push first item and remainder-list # separately s # Swap so the remainder-list of 0s is at the top g # Pop and push its length (to get the amount of 0s) V # Pop and store this in variable `Y` .•¿Õ¾¸”mÚÄú±pE”¿м∍• # Push compressed string "nofqunpistelkalpansohsetqok" 3ô # Split it into parts of size 3 s # Swap so the extracted head is at the top è # (Modular 0-based) index it into the list of triplets ™ # Titlecase it .•DĀ€y‹• # Push compressed string "ematehom" 2ô # Split it into parts of size 2 YĀ # Push `Y` (amount of 0s), and check if it's NOT 0 X« # Append `X` (prefix_length != 1) C # Convert it from binary to an integer # (0 if X=0,Y=0; 1 if X=0,Y=1, 2 if X=1,Y=0, 3 if X=1,Y=1) è # Index that into the list of pairs « # Append the two strings together Y # Push `Y` (amount of 0s) again ®.V # Do a recursive call with this as argument ‚ # Pair the result together with the string ``` [See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•¿Õ¾¸”mÚÄú±pE”¿м∍•` is `"nofqunpistelkalpansohsetqok"` and `.•DĀ€y‹•` is `"ematehom"`. [Answer] # JavaScript (ES6), ~~148 145~~ 144 bytes Expects the input integer as a string. ``` f=s=>x=s.replace(/[^0]0*/g,q=>s=b[+q[0]+3]+b[!s+2*!f(q.length-1+'')]+' '+x+s,s="",b="omehatemQunPisTelKalPanSohSetQokNof".match(/[A-Z]?../g))&&s ``` [Try it online!](https://tio.run/##fZPNb4IwHIbv@yuwB/moQouOxQMuOy9ZNO40wpLKCrhBq5Yt/ves8wMZtHLo6f319/R5wyf5ISLZb7bVmPEPWtdpKML5IRTunm4LklDLi95RjBwvG@3CuQjXEdxFKIaTGK6jgYC@M0itnVtQllX5GEPTtGNoGiY8QDESIQCjdQh4SXNS0XL5zRYb8UqLZ1IsCFvxfEWrJf964SlwS1IluVz3NH6LH13Xy2x7OBR1wpngBXULnlmpBTAwms@2Dc8z5KW0vOvE/F5MLu7HHnoxCdSPYQQUS3P1aowVYVJpwj7oc2rDs25YitOFfaS4Wcc81WDInvrhQIMh61Spu3K01SnrwGgGdA/UkU@790tmXp7CGv4g6IxI8hO/9hWz6T3474ewkx953mzh@v52C/IfUIV9HyhaaE69hKvmRrKUcJR8hlSqwFLfZbJt74h3HlRtxIg5ToCYAQ0A2rX@2ctvjEz6I3LXRXv9Cw "JavaScript (Node.js) – Try It Online") ### How? We first extract all suffixes and prefixes from the string `"omehatemQunPis...Nof"` into the array `b[]`, using the regular expression `/[A-Z]?../g`. ``` f = // f is a recursive function taking s => // a string s x = // the final result is saved in x s.replace( // look for all digit groups consisting of /[^0]0*/g, // a non-zero digit followed by 0 to N zeros q => // for each such group q: s = // update s: b[ // append the prefix according to +q[0] + 3 // the leading non-zero digit ] + // b[ // append the suffix according to !s + // whether this is the leading group 2 * !f( // and whether there's at least one zero, q.length // which is deduced from the result of a - 1 // recursive call with the number of 0's + '' // coerced to a string ) // ] + // append: ' ' + // - a space x + // - the result of the recursive call s, // - the previous value of s s = "" // start with an empty string ) // end of replace() && s // return s ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 71 bytes ``` Dœṗ`ḊĖF€ṚµḢỊ;ȦḄị“ðỌÇƭḌ€h»s2¤ṭḢị“÷mƬ@wƇ75Ẉ⁸f0¦mḃ⁾æÑdṛƁ/.ⱮṾ»s3¤Ɗ,Lß$K⁸¡)K ``` A full program that accepts a positive integer and prints the result **[Try it online!](https://tio.run/##y0rNyan8/9/l6OSHO6cnPNzRdWSa26OmNQ93zjq09eGORQ93d1mfWPZwR8vD3d2PGuYc3vBwd8/h9mNrH@7oAarKOLS72OjQkoc714KVglVszz22xqH8WLu56cNdHY8ad6QZHFqW@3BH86PGfYeXHZ6Y8nDn7GON@nqPNq57uHMfUL/xoSXHunR8Ds9X8QaqPrRQ0/v///@mBgYGhkBkZGxiYAAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##LYyxSgNBEEB/xiZhiLuby4YjjYWkufyABMFCRSSpLIKdZ4STS5oQiKCCKOGqRLQQdz1JsWsWf2P2R9bhsBgG3nsz5yeDwWUI@9s56rsjVPnPouuvV6jvzQeqFyzzzm@B6gbLib96tG9YTm3m1qimVJ2Z8kKYJep1lVbF59Ct9kYua7fw69an6pSZYohq7NONLezsGPWDS3cb/v0V9Ybum2bpcujZp52EavNcS8L222b0PaE5CKHPQUAbOAPOgQvgMQgGkQAZEyTKYogiBlJKclGLLFHBhCBcBWSrrl6X/6t5@Ac "Jelly – Try It Online"). ### How? ``` Dœṗ`ḊĖF€ṚµḢỊ;ȦḄị“...»s2¤ṭḢị“...»s3¤Ɗ,Lß$K⁸¡)K - Main Link: positive integer, N D - decimal digits of N ` - use as both arguments of: œṗ - partition before truthy indices Ḋ - dequeue (remove leading empty list) Ė - enumerate (e.g. [a,b,c]->[[1,a],[2,a],[3,c]]) F€ - flatten each Ṛ - reverse µ ) - for each "Part": Ḣ - head (i.e. the original index) - Note: this removes it too Ị - is insignificant (i.e. are we dealing with the final d? = NOT B) Ȧ - any and all? (0 if any zeros else 1 = NOT A) ; - concatenate -> [NOT B, NOT A] Ḅ - from binary -> 2(NOT B)+(NOT A) ¤ - nilad followed by link(s) as a nilad: “...» - "atehemom" s2 - split into twos -> ["at","eh","em","om"] ị - index into -> appropriate suffix Ɗ - last three links as a monad - f( Ḣ - head -> d - Note: again, this removes it too ¤ - nilad followed by link(s) as a nilad: “...» - "QunPisTelKalPanSohSetQokNof" s3 - split into threes -> ["Qun","Pis","Tel","Kal","Pan","Soh","Set","Qok","Nof"] ị - index into -> appropriate prefix ṭ - tack -> [prefix,suffix] $ - last two links as a monad - f(Part): L - length (number of trailing zeros, since we've removed the index and d) ß - call this Link (the whole Main Link) , - pair -> [current, recursed] ¡ - repeat... ⁸ - ...times: chain's left argument - treated as True if we have zeros K - ...action: join with space characters K - join with space characters - implicit, smashing print ``` ]
[Question] [ In this challenge, the goal is to create a pristine [truth machine](https://esolangs.org/wiki/Truth-machine) in as few bytes as possible. For reference, a truth machine does the following: * Takes input, which is always 0 or 1 * If the input is 0, it is printed and the program terminates * If the input is 1, it is printed forever A [pristine program](https://codegolf.stackexchange.com/questions/63433/programming-a-pristine-world) is one that does not error on its own, but will error if any single substring with a length \$1\le n<p\$ is removed (where \$p\$ is the length of the program). For example, if the `main` did not error in some language, it would be pristine if all of the following produced an error: ``` mai man min ain ma mn in m n ``` The goal of this challenge is to write the shortest program or function (in bytes, per language) which is a pristine truth machine. [Answer] # [Rust](https://www.rust-lang.org/), 109 106 bytes ``` fn t(n:i8)->Result<Box::<Iterator::<Item=i8>>,i8>{if n==0{Err(0)}else{Ok(Box::new(std::iter::repeat(1)))}} ``` [Try it online!](https://tio.run/##bU/BasMwDL3vK7ybPLKS3opb5zDYYafB9gHBW9XFNFYyW1kLwd@eyS0UBgMj6Yn39J7jlHhZDqQYyPiNfmzeME09756GszG7F8boeIjXMVi/aZpKyuwPiqyt5@cYodYZ@4Tz6xEuKsITJN4b40VtTMQRHcNaa51zsQrOE@j5TimXEkZu8fse3oeAwqngoVBXE52iG0HrFeGZpW@F3iMr7nxq5QWfPrBzP56@lJX09Y1xlY64l31w/Nn9qyn2SknkVttmXV1Q@QwJpALz9m/AurodFqu8/AI) Returns a result whose ok variant is a dynamically typed iterator that always yields one wrapped in a smart pointer so the compiler can know its size. The error variant is simply zero. The code does emit a deprecation warning, so it may randomly stop working at some point in the future. Rust's type inference is too good for me to get a pristine closure, and as verbose as this solution is it is still shorting than fully listing the returned iterator's type and much shorter than using the main function and reading from stdin. -3 bytes because there is a method to create an endlessly repeating iterator [Answer] # [W](https://web.archive.org/web/20191222053946/https://github.com/a-ee/w) `s`, 1 byte ``` w ``` The `s` flag tells the program to get it's input from STDIN rather than arguments. It's pristine because there is only one subset of program to remove. The power of triviality. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 159 bytes ``` class P{static void Main(string[]a){System.Console.Write( #region a[0]);while(1.ToString()==a[0]){System.Console.Write(a[ #region 0]);}}} #endregion #endregion ``` [Try it online!](https://tio.run/##Sy7WTc4vSv3/PzknsbhYIaC6uCSxJDNZoSw/M0XBNzEzT6O4pCgzLz06NlGzOriyuCQ1V885P684PydVL7wosyRVg0u5KDU9Mz@PKzHaIFbTujwjMydVQcNQLyQ/GKxTQ9PWFiyFXXtiNNwAkPba2lou5dS8FKgQgvn//38DAA "C# (.NET Core) – Try It Online") ]
[Question] [ I've invented an SQL-like language. Let's call it SelectQL. You can't `INSERT` anything, you can only `SELECT`, and I don't have the time for an interpreter. How about you help? # The Challenge Write a full program or a function that takes in a database of tables and a valid SelectQL `SELECT` string, interprets the string, and outputs the resulting `SELECT`ion. ## `SELECT` Specification The `SELECT` SelectQL statement is as follows (optional portions are in curly brackets): ``` SELECT [column] FROM [table] {WHERE ( [condition] {[AND/OR] [condition] ... } ) } ``` * `[column]` can be `ALL` for selecting all columns, or a valid column name in the `[table]`. * `[table]` is the name of a table. * The `WHERE` clause is optional. A `WHERE` clause is followed by a list of `[condition]` separated by any of `AND` or `OR`, surrounded by parentheses `()`. * A `[condition]` is a key-value pair separated by an equals sign `=`. * `[condition]` can be preceded with `NOT` to select the complement of the condition. * Operator Precedence: `NOT` has higher precedence than `AND` and `OR`. `AND` and `OR` is executed left to right. * Conditions involving arrays/lists (`{980, "abc"}` in `data` below) will look for the existence of a requested value in the array, and return the whole array if true. * `key` must be a column in `[table]`. * SelectQL query strings are ***case insensitive***. ## Table Format Your program should take in an SelectQL database (array of arrays, list of lists, delimited string, JSON object, etc) in the following format: ``` [ [table name, (column names), [(row), (row), ...]], [table name, (column names), [(row), (row), ...]] ] ``` * `table name` is the name of the table. * `[column names]` is a list of unique strings which are column names. These are the keys in `[condition]`. * Each column's values all must have the same type. * `[row]` is a list-like of values. Each row must be the same length as `[column names]`. * There can be no `[row]`s. * Elements in `[row]` cannot be empty. Empty strings or arrays are not considered empty. ## Types There are three types in SelectQL: `number`, `string`, `array`. Numbers are at least 1 digit in `0-9`, with an optional decimal point with at least 1 digit. Strings are double-quote-delimited sequences of characters. Empty strings are possible (`""`). Arrays are curly-bracket-delimited comma-separated sequences of numbers, strings, or arrays. Arrays can be heterogeneous. Empty arrays are possible (`{}`). # Input * A valid SelectQL database, and * A valid SelectQL `SELECT` query. It will always `SELECT` a valid table in the database. # Output * The result of the query. The result must have the columns as well as the resulting rows. # Examples The examples will use the following database: ``` [ [data, (d1, d2, 3, ~!@#), [(123, "", {980, "abc"}, "false"), (456, "this isn't empty!", {{},{}}, "-123.4444"), (1, "2", {3, 4}, "five")]], [no, (yes, a, 1.5, what), []] ] ``` ``` Format: string --> result ----------------- "SELECT ALL FROM data" --> [(d1, D2, 3, ~!@#), [(123, "", {980, "aBc"}, "false"), (456, "this isn't empty!", {{},{}}, "-123.4444"), (1, "2", {3, 4}, "five")]] "SELECT D1 FROM DATA" --> [(d1), [(123), (456), (1)]] "SELECT d1, 3 FROM data" --> [(d1, 3), [(123, {980, "aBc"}), (456, {{},{}}), (1, {3,4})]] "SELECT ALL FROM DATA WHERE (NOT d1=123)" --> [(d1, D2, 3, ~!@#), [(456, "this isn't empty!", {{},{}}, "-123.4444"), (1, "2", [3, 4], "five")]] "SELECT all FROM data WHERE (d1=123)" --> [(d1, D2, 3, ~!@#), [(123, "", [980, "aBc"], "false")] "SELECT ~!@# FROM DATA WHERE (3={} OR d2="")" --> [(~!@#), [("false"), ("-123.4444")] "SELECT all FROM DATA WHERE (d1=2)" --> [(d1, d2, 3, ~!@#), []] "select all from no" --> [(yes, a, 1.5, what), []] "select 3 from data where (3=980)" --> [(3),[[{980, "aBc"}]] ``` # Additional Rules/Clarifications * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Input and output can be in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). * Please explain your answers. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the program with the smallest number of bytes wins! [Sandbox Link](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/18941#18941) [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 473 bytes ``` from re import* def s(d,q): o,f,c=search(r' (?:all|(.*?)) from (\S+)(?:.*?\((.*)\))?',q,I).groups() for x,l,r in d: u=str.lower;h=bool;m=o and o.split(', ')or l;y=[] for g in r: p=0;_,*t=split('(?: (?:(and)|or) |^)(not )?(.*?)=',c or'',0,I) while t: a,n,k,v,*t=t p=h(a)&p&(b:=h(n)^any(i==u(k)and(j==eval(v)or list==type(j)and eval(v)in j)for i,j in zip(l,g)))|p|b if 1-h(c)|p:y+=[j for i,j in zip(l,g)for z in m if i==u(z)], if u(f)==x:print([m,y]) ``` [Try it online!](https://tio.run/##jZNhT9swEIa/51ccmUR8YCrawsRaWV01ijaJgQRI@5CGKW0S4pLGwXFbgqr99e5sGGxsSMsHO757773HcVw1Jldl96jSm02m1Rx0CnJeKW12vCTNoGYJv8OeB4pnfCrqNNbTnOkA2KAXF8WatXYGiOBK2fhyFylOoTGjBI4RBwG/41@wdaPVoqoZepApDfe84BpkCQk5w0LURrcKtUp1PxcTpYr@XCiIywRUq64KaVjAIUAqLPqNCCOqsS431kFbB6jEfv873zHiSU4UlpCRB66VRlhfIyuVARw4YhHwKSgdBHyf6KzDKpdFCsa5QcxLfsuX1tC4QCVyFuN2tc0mPXot8TouGyaFWLBbpCZsJkS6jAu2dJSyNkKYpkrZzGbhKUW4M7Tkks8s@4OsWMFvEHFdrSe2kcygvZezKQV6za4IZ/APuQ092MDc6h3EA0bcc@ULlqEQ971Ky9KwcM6bCDfJBASEHoR@EpvY58D8pE2Tn3Ts2LXDj62P73zkELJ2p0trioUfjvbpLZ5M/YjmLC7q1ErYweF7Wptc1iDrMjCQzivTbNmSMOJhZNV7ZNM6oMdVtClie4VkfeDM5JK8Iosd@qVyTE1aWxIL6Ldbh3Za5bFxVFHkRZ5Hv@OE@5ej09GnKxiensLJxflXcJvCP5PH7cfc8fBq@DqXEE337dJnX1sL3z6PLkbAzs5tnaBN4Ws93YMXs1/6N7T2K/9t3qWfGs4vIOmIsT/23@7wexF16Lwo67RIp8Yp3WWkT/oq1X1MOMhVntJFp750wvhf@yfEx6OF4dmx2wahPp@xY978BA "Python 3.8 (pre-release) – Try It Online") This uses @hyper-neutrino's style of input/output, but is otherwise a completely different implementation. -5 bytes thanks to @cairdcoinheringaahing. [Answer] # [Python 3](https://docs.python.org/3/), 682 bytes ``` from regex import* s=lambda x:str==type(x)and x.lower()or list==type(x)and[*map(s,x)]or x V=eval E=lambda x:str(V(x.group())) def f(d,q): c,t,w=match("select (.+) from (.+?)(?: where \((.+)\))?$",s(q)).groups() K=[[C for C in map(s,y)if{*c.split(", ")}&{"all",C}]for x,y,z in d if s(x)==t][0];r=[] for R in{s(x):[{s(k):l for k,l in zip(y,r)}for r in z]for x,y,z in d}[t]: if w: v=sub("not \w+",E,sub(r'(\S+)=(\[((?2)(, *(?2))*)?\]|"[^"]*"|\d+)',lambda x:str(e(s(R[x.group(1)]),s(V(x.group(2))))),w)) while len(v)>5:v=sub("\w+ \w+ \w+",E,v,1) if~-V(v):continue r+=R, print([K,[[q[x]for x in K]for q in r]]) e=lambda x,y:x==y or list==type(x)and any(e(v,y)for v in x) ``` [Try it online!](https://tio.run/##jVRtT9swEP7c/IrDm4bdmoq2MG2Zsq4qnSbBQCqIfXA8KW0cGpEmaWKaBCh/nZ1T3tnQIjV27u557rk7u2mlZ0ncu70NsmQOmTpTJYTzNMl008qdyJtPfA9KO9eZ4@gqVbRkXuxD2Y6SQmWUJRlEYa6fOkVz7qU05yWT6C2tU0ctvcgaPWOjp7Rsn2XJRUoZY5avAgiozxfMthpTrnnhzD09nVGSq0hNNdB2i0GtEXd9Rvs2FDOVKXCpcbmM9d8TntMFY2vanDKrse8IMYQAZQwhjGGtq2JhcNWctvM0CjUlHAhbfbgiXhQRPlxJE13yil8ahA9hADnWhQVKsS2/ZI6QVsPEjNF/ZVy2wOWc2VGd6JxHBngZprTiGVsZW1ZbXjCvhJZYbAMTFGZtLJ38YkJJnGhwixbhI26@s03qHreYQ11Bab/LKIemWVmT9V15TcRvIpvk2vVbbJM/67CiOR2L@y53mGTYn8e2IwU@vMDuY/JiFkYKIhXTJfu6a99pQR1w9zN6lrxTB4fBzdYpBtrTJNZhfKHQmLWcMbcaaRbGmop9LsRClOuSTbn79XZhtpmUzFIPp4FXduk4FfzlJIEXV1jGEkdm0EuDLtmtPwEHhNUQxPe0hwOkxO@YOfpd8@6Z183Gt3eEcRC00@3hN9rE50/buPMmUyJxDbwoVyaE7ux@xG89C3MI83hTg5qnutowECG5kCZ6C2naO/jUiA5aTC6B1Ds1WbhELow0quKk1lSp3CgxAkmnvWuWYubpWpWUlrQsPPETtB6PDkbDExgcHMD38dFPqKtiL7x7nbVzb3AyeOX0UVDvDfADtUHDrx@j8Qjo4ZEBOlgYewXAy/BIdw/4V7Dp9Wv6Ht4UOBqD33Vc4pI3cjxFYY7uk9C7229C68uPrX3p6609tdD1XwKmxlGz/@sCylwPGQaHe3UpKPdh2rXu2z8 "Python 3 – Try It Online") -5 bytes thanks to Razetime -18 bytes thanks to caird coinheringaahing this was painful This uses `[]` for arrays because that's Python's list representation. Please let me know if this is invalid. The DB is just taken in the representation given in the question as a native Python object. [Answer] # Python 3, 583 bytes: ``` import re, operator as o def f(a,q): [[c,b]],z=[(c,d)for t,c,d in a if t==(r:=re.findall(' (.+) FROM (\w+)',q)[0])[1]],lambda n,m,w:[o.pos,o.not_][w](n in m if type(m)==set else n==m) d=[dict(zip(c,i))for i in b] p=lambda e,i:(eval((v:=e.pop().split('='))[-1]),i[re.sub('NOT\s','',v[0])],v[0][:3]=='NOT') return (g:=[c,r[0].split(', ')][r[0]!='ALL']),[[i[j]for j in g]for i in d if(y:=lambda e,u:True if not e else(z(*p(e,i))if not e[:-1]or not u else[o.and_,o.or_][u.pop()=='OR'](z(*p(e,i)),y(e,u))))(re.findall('(?:(?:NOT\s)*\w+\=(?:\{.*?\}|".*"|\w+))+', q),re.findall('AND|OR',q))] ``` ]
[Question] [ [The Mel calendar](http://conlinguistics.org/arka/e_data_palt_1.html) is used in the fictional world of Kaldia. Your goal is to convert dates into the Mel calendar. This calendar has 13 months of 28 days each, plus 1 or 2 extra days after the last month. A year that is divisible by 4 but not by 100, or divisible by 400 has 366 days, and other years have 365 (i.e. our leap year rules, but with years in the Mel calendar). You should use the [month and day name abbreviations](http://conlinguistics.org/arka/e_study_yulf_150.html): **months:** dia vio lis gil ful dyu mel ral zan pal mik fav ruj **days:** dia vio lis gil ful dyu mel ral zan pal mik fav ruj ser rav tan lin rez jil din ket len lax nen pin mat kun mir The extra days outside of any month have the month name of `myuxet` (no abbreviation here), and the day names are `axet` and `teems`, respectively. `0 dia dia` is 1988/11/30. You can take the input date as a string or a (year, month, day) tuple; alternatively, for functions, the parameter can be in your standard library's date type. The output should be a space-separated string. ## Test cases ``` 1776-07-04 => -213 ral ket 1859-12-15 => -129 dia rav 1917-04-14 => -72 ful nen 1981-02-04 => -8 lis mik 1988-11-30 => 0 dia dia 1988-12-01 => 0 dia vio 1988-12-28 => 0 vio dia 2017-01-01 => 28 vio ful 2019-04-22 => 30 dyu lis 2019-11-30 => 30 myuxet axet 2019-12-01 => 31 dia dia 2021-11-29 => 32 myuxet axet 2021-11-30 => 32 myuxet teems 2089-11-30 => 101 dia dia 2389-11-30 => 400 myuxet teems ``` You should be able to handle dates from 1 AD to 9999 AD at least. [Reference implementation in Perl 6](https://tio.run/##ZZLfa9swEMefk7/iEN5IIAqWnCYOngvdOuhDYA9bH0obhjbLQ40kB8fO6ob0X89OsvOj7MHIus99T1/daS1LPT2YBj7m6WGH65NIfxfmF0QjkimxVYVWmz9K57XOmtpIXQr9KuxaaKNWudiW9fNGlqXYVsJqZUv5@qx0puxKVlpaLV6stGtljahWtTWqJIk7w6bBT6AzPp1EUx/IUjvOREOLnDZSlD5m0gwytQUeJ3bsom8EyNtAPJrliJimfpEVGT6aNGXRskOjTwKjUElpNtcdS7IPPKZsuT8k/Y1ogORqA5i0y@FWVHJcFXjwniT9vChhQNhsNqXhjIYTMgJCOYsArwx4H7dn8dWcMk7ZlaeMz9GiwIytp3PmhJS12hkHbBtgB1oYMxryY@EYsLGATewYWmQ0Ct0u9DXxOyOUsTPCqVwiHrcIw0cVD50T1ql47Bma6djcueTc7SIs2dTOzImdjCBr@wyurWd@dBOxS6c85Mxp@dwz/r@25V3tE/fTahPii8NZ@L56dAknYfhePgR6DYEeQWBg1@/h@wkEpJAP/Iyt/DsI9HCY9HvrUtkKSKC9QODceyp3yVZ22mMKDL7ffbtf3MLNlx/3N4vFA3z@iilDJ9n3e/4t4f/@8A8) [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 174 bytes ``` {~(.year,(|[X]("diaviolisgilfuldyumelralzanpalmikfavrujserravtanlinrezjildinketlenlaxnenpinmatkunmir".comb(3)xx 2)[^364],|("myuxet"X <axet teems>))[.day-of-year-1])}o*-726436 ``` [Try it online!](https://tio.run/##ZZJda9swFIav419xMGbYIwqSnPqDrIVuHfQisIu10BIy0BZ5qJHl4NhZ3DT769mR7XyUXRhbfs5z/OrIK1nq6JA38CG7Puz@@qNGinLov82e5r67UGKjCq3Wv5XOar1o6lzqUuhXYVZC52qZiU1Zv6xlWYpNJYxWppSvL0ovlFnKSkujxdZIs1ImF9WyNrkq3dGvIv/ph8F2CzyY/Qij8Xz45rt5U29l5T7BJ4F3qKTM1zdBMBstREOKjNhchM2DffGRxDwah9Fh4qxFA26m1oDGLoM7UclRVaCxdydOVpTguyyOI0JjQsfuEFzCWQi4A8B4ds2Sq5QwTthVSxlPATeNFZuWpsyKhHVuzAGnALihDiaMUH5snADOCXAmPUsIYySkdkXbnnidEWrsjHDIl4gnHcLXR4tTm4T1Fk9ahmF6ltqUnNtViC2b2oY5sVMQZN2Ywc74zI9pQnaZlFPOrMvTlvH/3Y73vU@8PbquILn4OKPvu4eXcEzpez0AcgOeHoKXw84Z4A/qCbiGzG/P2Mg/vqeDYOIMVqUyFbiebgWB5z5QmS02snePJeB/v//2OL2D2y8Pj7fT6TN8/oolgVX2zqD9l/B5f/gH "Perl 6 – Try It Online") Generate a list of all the valid dates and then indexes the day of the year into that list. ### Explanation ``` { } # Anonymous code block o*-726436 # Subtract some days from the input (.year, # Output the year [X]("...".comb(3))[^365] # Then produce a list of all months/days (| , |("myuxet"X <axet teems>)) # And the extra days [.day-of-year-1] # And get the current date ~ # Stringify the list ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~199~~ ~~195~~ 193 bytes Oof, only ~~23~~ ~~27~~ 29 bytes saved over the sample Perl code... -4 bytes from @NickKennedy. -2 bytes from @Neil. ``` ->d{d-=62764e6;y=d.yday;s="diaviolisgilfuldyumelralzanpalmikfavrujserravtanlinrezjildinketlenlaxnenpinmatkunmir".scan /.../;[d.year,y<364?s[y/28]:"myuxet",(y<364?s:%w[axet teems])[y%28-1]]*' '} ``` [Try it online!](https://tio.run/##PY3RboIwGEbvfQqCGtFYpFWh6NCX2B0jplvLUi2VtEWtxlcfAzHcnZyc7/9V9W3rPPmqwY4@KEhCFIUrFm5tQn1Lid3qxKWcXPhZcP3LRV4JaquCCUXEnciSiIKfcnJR1VEzpcjFECm4VOx@5IJyeWJGMCnITTJZclkQc6pkwZXr6x8inYXv@4tt2vxiRM3txzJc7XVqFwhnG7ew1Y0Zd@69/WZ8TUljHMNYobNpascIA5hls4kzedZlZbTjDkeHnTN85OknL5gv2dWbjQ6@LgU33h5Mp9nTrWEUhSCIQLAaQLyOAUQArgcwhq0CsLExhiBAryDGzQ8IlsEbGwt7RHiAgnYGW9tg3F5AqMNu1iHqAgRbi@IeXwHu22WPf@fS8LPUNZD/ "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), 148 bytes ``` ÐUVW;f1Uf -726436 -ÐTT i1Ui¹z864e5 `¹avio¦sgÅ~ldyu´llzpal·kfavruj rvt¦nzjÅanket¤nlaxnpµtkun·r`pD ò3 [Ui Vz28 gW¯D p"myuxet")VgWp"axet"`ems`] ``` Saved 4 bytes thanks to @Shaggy. +A lot more bytes due to bug-fixes. Takes months as 0-indexed numbers. Japt does have built-in date handling, but it's not very good. Seriously, 34 bytes to initialize a date, then subtract days from it, and then calculate which day of the year it is? [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=0FVWVztmMVVmIC03MjY0MzYKLdBUVCBpMVVpuXo4NjRlNQpguWF2aW%2bmc2fFfmxkeXW0bJ9seoRwYWy3a2ZhdnJ1aqByn3Z0hKZunHpqxWFua2V0pG5sYXiabnCItXRrdW63cmBwRCDyMwpbVWkgVnoyOCBnV69EIHAibXl1eGV0IilWZ1dwImF4ZXQiYJJlbXNgXQ&input=MjM4OQoxMAozMA) ``` ÐUVW; Initialize date object with given inputs f1Uf -726436 Subtract 726436 days; Store in variable 'U' -ÐTT i1Ui¹z864e5 Store the day of year in variable 'V' `...` Compressed string of all the days pD Repeated 13 times ò3 Split into chunks, where each chunks is 3 chars long, store in variable 'W' [Ui Year Vz28 gW¯D p"myuxet") Month VgWp"axet"`ems`] Day ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~181~~ 164 bytes ``` “BƥṠĿZȧ{ḷċ'#1ƇIræżzḤ$ḅ3ṃefɲ⁴S⁵ẊKḲ&8ɲz⁸Ẋ⁼ṣẸÇɼ:İ~¢ȥ³QⱮ:Ṗỵrɼ¬ṂĿZ⁵ṣ»Ḳḣ€3ḣ13pƊ;“¬ỵƇnḄẋFƬ@§Żị»ḲḢWpƊ¤ “ÇġƁʠÇỤḷṁÑWðṫ⁷m¥ṛʂɲðḊk¶`Ḣ»ḲjḢ$;;“","%Y%m%d"))+3499e5)”ŒVm7_2ȷ;ị¢$}ʋ/K ``` [Try it online!](https://tio.run/##LY/BSsNAEIbveQqJrVJUzGxak7Qg4kEQTyIoetGD9aBWpDcVxVQl0J704EUFbaseLKLV2k1TEJI2NH2L2ReJ09jTfjPzzz//7mb394/CUJzfz/vPaD92fjd6ryfIm53S@Cj41mLee@m2j5FXY8ivVLQvsjtBXZjfK8JsYKu4hLw@pgf1Y2FyKoXZRruCLe5ZQTvd@Thzy71n92tZfL6n0b5Fp5EP2m4N7QIdGjjYFdchC@QVUaip9IB66BczlIdUTsO3DpBfYqu04Nfm3Neug05puFBeI6FblUjqWZ0n3@w/ehY6VcqOtuldr3kfaL8Js5lz6WN3/UJQpw4v7rk/W7QduewSxDKDa/KkHF@P5@LbciIxoSYNI5tKiPOH7s1qTttkvWZmcLgcO@2XppfCwcLI1OwICTKeJaHz7VkUfz0MZVkGTZtRNCUpgZ4ygEFKAgOoBuoYOihMiUAHUJV/YAoMgekSFZoC1CEwlCRjEUTiCFg0YgDAjCFEI32oUf@BgvwB "Jelly – Try It Online") Jelly has no built-in date handling, so this falls back on the functionality within Python’s time module. ### Explanation ``` “Bƥ...⁵ṣ» | Compressed string "diact viol lisk gild full dyu mela rale zanja palay miked fava ruj ser rave tanas linac rez jilt dinar ket lend lax nene pinas mat kune mire" Ḳ | split at spaces ḣ€3 | first 3 characters of each Ɗ | following links as a monad ḣ13 | first 13 p | Cartesian product (with all 28) ; ¤ | concatenate to: “¬...ị» | compressed string "myuxet axet teems" Ḳ | split at spaces Ɗ | following two links as a monad Ḣ | head p | Cartesian product (with last two) “Ç...Ḣ» | Compressed string 'time .local ( .mk ( .strp ("' Ḳ | split at spaces jḢ$ | join using first item (i.e. time) ; | concatenate to input ;“"...)” | concatenate this to '","%Y%m%d"))+3499e5)' ŒV | eval as Python m7 | take every 7th item (year and day in year) ʋ/ | reduce using following links as a dyad _2ȷ | subtract 2000 (from first value, the year) ;ị¢$} | concatenate with right argument (day in year) indexed into above link K | join with spaces ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 247 bytes ``` n=>$"{(n=n.AddDays(4049)).Year-2e3} {((k=n.DayOfYear-1)<365?s.Substring(k/28*3,3):"myuxet")} {(k<365?s.Substring(k%28*3,3):k<366?"axets":"teems")}";var s="diaviolisgilfuldyumelralzanpalmikfavrujserravtanlinrezjildinketlenlaxnenpinmatkunmir";int k; ``` [Try it online!](https://tio.run/##ZZBda9swFIav61/hiQ2kEXmWnA@7qVMGZTAYrGyDMeiNFh93quWzIMlZU5Pfnsn2kpvdvXrO8x4hbR3fOn360OH25k55@KZbmMXOW42Pm7o8Ybl5TXqKJSbvq@pOHRydp/OCseQHKMslZMe4p7QJ8zD8XI9UsJtsubh1ydfu57SKNu9k/jabZeyatIfuGTxhQ7H5X3xzFofZ8paoIDtyTTxA60KLrPfKxq4klVZ7/dto96hN3Znq0LVgrDIvCnfKtLqp1d52Tw6sVXuv0Gi08PKkTaWxAW8AjXpGwJ3GVvmmw1Zbstbo42Z9@vNLG6AfMbkHaCh7VYZHxX10Ndytcdf5uIy/gKo@aQTK1tHVd6s9jCfSp8cHX24efC@OZDbas5qefze5V9YBHTFjoXo8idVqydMVT@eRyBcFF5KLRSQKMSAuAi1ywVM5CkWecyF4lv6LgYpLlHkk06EmBhpiMWyQcopTbYpyEqQYqCwucRTyi5ud418 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] ## JavaScript (ES6), ~~297~~ ~~269~~ ~~252~~ ~~249~~ 245 bytes ``` f= d=>(d=new Date(+d+3498336e5),d=(d-Date.UTC(y=d.getUTCFullYear(a=`diaviolisgilfuldyumelralzanpalmikfavrujserravtanlinrezjildinketlenlaxnenpinmatkunmir`.match(/.../g))))/864e5,y-2e3+` ${d<364?a[d/28|0]+` `+a[d%28]:`myuxet ${d&1?`teems`:`axet`}`}`) ``` ``` <input type=date oninput=o.textContent=f(this.valueAsDate)><pre id=o> ``` Takes input as a JavaScript date object in UTC (would be 1 byte less as a JavaScript timestamp number). Edit: Saved ~~3~~ 7 bytes thanks to @Arnauld. [Try it online!](https://tio.run/##ZZHdjpswEIXv@xRW1FZEicE/JDGbkr1o1SdoL1arlbBihzoxJuInXbbts6cDIYS0ICTj78zM8fFenmS5Lcyxwi5X@ryLzyreeCp2@if6IivtzdSMh5HgfKkX07mKPYXbff/7t89eEys/1RUsv9bWPmlZeDJOlJEnk1tTpsbuaquaOtO2kPZNuqO0mTns5Kmo96UuCnmqpLPGFfptb6wy7qArq52Vr067o3GZrA61y0yR@LDc/vAC3/eDdApPIJahXswbzDSfJej9L/WJL8NH@awCJn6TF9hLZvD3gYmXhyRr6lddtaqP9DGptM7K5CGRsJf8gXd6XqdxGW@2uStzq32bp145n8SbyXznDVGUMHb9LvUmdLVaYrLCJJxM1ygIEGaUIzgiAv@dQCwiTBmmi6uAsghBMCA6dYKItuWYDh1WDEFYCM594YJiwkYTBIJEEaTXY4EpxZz0mHTN4btRKKZ3FC5lTJkYKJBrLSOtMXqrZaLD4K3HUeubsR5z6N3UrbcBj30B7qNvs75JRuY4HXtnhNG2A4uumP3f4SK5DRkk3cVeNOLeCCX3Y/g/PCTkrsn5Lw "JavaScript (Node.js) – Try It Online") if the snippet still isn't working for you for some reason. [Answer] # [Haskell](https://www.haskell.org/), ~~387~~ ~~373~~ 372 bytes ``` import Data.Time.Calendar t(a:b:c:r)=[a,b,c]:t r t _=[] w=t"diaviolisgilfuldyumelralzanpalmikfavrujserravtanlinrezjildinketlenlaxnenpinmatkunmir" (%)=mod a y=map(show y++)$[' ':m++' ':d|m<-take 13 w,d<-w]++" myuxet axet":[" myuxet teems"|y%4<1,y%400<1||y%100>0] f d|n<-read.show$diffDays d$fromGregorian 1988 11 30=last$(a=<<[0..])!!n:[(reverse.a=<<[-1,-2..])!!(-n-1)|n<0] ``` [Try it online!](https://tio.run/##fY5PT4NAEMXvfIqR0AjhT3bbxioBLzbx4k1vhJhpd9CV3YUsSyum372iJh48OIc3eW8m@b1XHFpS6nyWuu@sgy06zJ6kpuwOFRmB1nMh5rt8n9uorDDZJfs6dzDH8FxWtXcsnS8kHmSn5PAiVTMqMY2alEX1gaZHpWXb4MGObwNZiweHRklj6eNNKiFNS27mKHw3ZHppNLp2NFpa3wsXUak74SFMpcY@HF67I0xxHAXVJVzmOo6/ljjpInXYEvAVHBNRpMc6jn3Q0/hODnAWP69@vSPSg3@aFuuCJ7MyVvDTbDljt6z2GhAnU6SWUGRfvEDIptniNIAIGtvpe0svnZVogN9cXwPnsGKlwsEFIZZFUbEsq6OLC5NXoaUD2YGy7zzlSbr8uYWpSXk0U1h91ihNKToP5ulH9@jsgwmav6TN5grYBtj6/78lW/KfRudP "Haskell – Try It Online") Takes input as a `Day` object. This was pretty fun to write! Basic idea is to build a list of dates and index into it for the result. Function `a` takes a year and outputs every date in that year in chronological order. Function `f` expands on `a` concatenating them together for successive years starting at 0. The trick is that for dates before the epoch we need to traverse backwards starting from the year -1 so we pass a values -1,-2... and reverse each list individually before concatenating them together. Finally, in function `f` we calculate the number of days between the epoch and our date (converting it from `Integer` to `Int`) and index into our list, taking care to fix our index if it's negative. EDIT: golfed it down (-14) EDIT 2: golfed down the day/month names list (-1) ]
[Question] [ ## Challenge: In the language of your choice, write a program that generates a leaderboard with random scores and outputs it, then take a new score as input and check if it can be placed in the leaderboard, and output which place it is in. ## Specifications: * You must **generate a list of 50 "random" scores, in descending order and output it** * The "random" scores will range from **0 to 255** * If 2 scores are the same, it doesn't matter which is placed first in the descending order * If the input score isn't higher than any of the scores in the list, **output 0 or a falsy statement.** (the input will be 0 to 255, no need to check) * If the score **IS** higher than a score in the list, output the position it would take in the leaderboards. * Generate and output the leaderboards/list first in descending order, before taking input. ## Example I/O: Random list: (the three dots are so I don't have to add 50 line text here. You should output each score. 12 is the 50th place) ``` 201 192 178 174 ... ... 12 ``` Input: ``` 180 ``` Output: ``` 3 ``` (because this score would place no.3 in the leaderboards) Input 2: ``` 7 ``` Output 2: ``` 0 ``` (because it is lower than everything on the leaderboard) This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins. [Answer] # [Python 2](https://docs.python.org/2/), 102 bytes ``` from random import* lambda n,l=[randint(0,255)for i in[0]*50]:(l,[sorted(l+[n]).index(n),0][n>max(l)]) ``` [Try it online!](https://tio.run/##JU7BCsMgFLv7FR61K8MVysagu3XXXXYTD24qFexTXi1rv76zNJcQkpCkNQ8Rmm1zGEeKGkwhP6aIuSKuC3r8GE2hDp3cTQ@ZibppW@4iUk89SKGqVqg7C7WcSssaFk4SFD97MHZhwGuhJDxGvbDAFd8yrndCC36DD5a@cbaH3pGwLFDHPKQ5M86JXb42Zdq/nj1ixCOZ9DRt5QS53AS5/gE "Python 2 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/)**, 125 128 127 126 125 119 115 bytes** ``` from random import*;x=sorted(choices(range(256),k=50));print(x[::-1]);print((sum(map(int(input()).__lt__,x))+1)%51) ``` Could probably be golfed quite a bit Edit: Changed from sample to choices, as sample does not allow repetition. Pointed out by [@Arnold Palmer](https://codegolf.stackexchange.com/users/72137/arnold-palmer) -2 bytes, thanks to [@Arnold Palmer](https://codegolf.stackexchange.com/users/72137/arnold-palmer) -4 bytes, thanks to [@Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) [Try it online!](https://tio.run/##NclBCoMwEEDRq3QjzFhbjCVdKJ6klCCa1tAmGZIR0tOnceHq8/j049W7W86v4O0pTG4pMZZ84HpIYyzVC8yrN7OOUP5bQyfv2HxG2SIOFIxjSI@@v4jnQYibBTsR7DCONgbEq1JfVqpJiGeBlRSYcyfbPw) [Answer] # [R](https://www.r-project.org/), 69 bytes ``` n=scan();cat(r<-sort(sample(256,50,T)-1,T));`if`(any(r<n),sum(r>n),0) ``` reads `n` from STDIN; prints the list to STDOUT, and returns the index or `0`. [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOjmxRKPIRrc4v6hEozgxtyAnVcPI1EzH1EAnRFPXEEhoWidkpiVoJOZVAtXlaeoUl@ZqFNkBGQaa/3UN/wMA "R – Try It Online") [Cleaner output format](https://tio.run/##DcZRCoAgDADQ62wwQQP70TpFB0iiQFCLzT46/fLn8Vi1LXKkBhg4Grm5g6T6lBMmP5O3tKFxg1CydGDa87VDah9wbEjyVuB1xCKqcfoD) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` ⁹ẋ50ḶX€ṢṚṄ€>ƓS‘%51 ``` [Try it online!](https://tio.run/##ATAAz/9qZWxsef//4oG54bqLNTDhuLZY4oKs4bmi4bma4bmE4oKsPsaTU@KAmCU1Mf//MTA "Jelly – Try It Online") -3 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). *Now with interactive I/O!* Full program. First 50 lines are the scores, last line is the index. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes ``` AE⁵⁰‽²⁵⁶ηF⁵⁰«⊞υ⌈ηA§η⌕η⌈η⁰»IυD⎚NθI﹪⁺¹L⪫Eυ× ›ιθω⁵¹ ``` [Try it online!](https://tio.run/##TU5LasMwEF3Hpxi8GoEMccChkFVIaUmpgwm9gBqrkUAfR9K0gdCzq3KzyWbeDPN@JyXCyQuT8zZGfXbYiwm7JYejcKO3uOrWjHFQbFN9@QDlxeBWLQaKColDL67akkXFCmFxt9imvRvlFRWHF@3GGR9oHJaF@lsNQbuEOxET0ix@JjthwZ2RIszL3k2UDmQ/ZcBLuR8EvR/JeBwMRWw5vEt3TgrfvL7XL70@tJURa6g5vAYpUvHQHC5szv/5n11bYJNzu3rKzXduovkD "Charcoal – Try It Online") Link is to verbose version of code. There's no `Sort` function in Charcoal, so I loop 50 times extracting the highest remaining element and then setting it to zero each time, using the ambiguous `AssignAtIndex` command. There is an experimental `Reduce` function in Charcoal but I'm too wary of it so I'm taking the length of a string instead. Unfortunately this gives me a 0-indexed answer to I have to add 1 modulo 51 to give the desired answer. At least generating the 50 random numbers was easy. [Answer] # Mathematica, 105 bytes ``` (P=Position;Print[If[(d=Min@Nearest[s=Reverse@Sort@RandomSample[Range@251-1,50],#])<#,s~P~d,s~P~d+1],s])& ``` [Try it online!](https://tio.run/##JcyxCsIwFEDRXxEK0mKEpthJA1kdKqEdQ4ZgXjRgkpIXHPvrT9HlwllutPUZ7kheUKuEyhhqyOmsSkhVX71unZhCkjewBbBqFDO8oSDIJZcqZ5tcjouN6wv0Fw@Qw8iPnI29YY3pLg3DTW3u3wM3DE23p999J70eTr0hog8 "Mathics – Try It Online") [Answer] ## [TXR Lisp](http://nongnu.org/txr), ~~78~~ 76 bytes ``` (opip(pos-if(op > @@1)(prinl[sort[(gun(rand 256))0..50]>]))(if @1(+ 1 @1)0)) ``` Run: ``` 1> (opip(pos-if(op > @@1)(prinl[sort[(gun(rand 256))0..50]>]))(if @1(+ 1 @1)0)) #<intrinsic fun: 0 param + variadic> 2> [*1 3] (247 243 238 237 234 209 204 202 196 193 183 181 179 177 174 174 164 159 156 155 143 141 138 134 134 132 131 117 105 98 89 88 82 77 75 66 65 64 55 52 46 34 32 28 28 26 24 21 18 5) 0 3> [*1 3] (252 250 241 236 234 229 228 219 210 206 205 204 193 188 184 168 166 164 163 160 158 158 148 138 137 130 123 118 111 103 97 93 92 85 81 73 69 60 60 53 52 44 38 31 19 16 15 12 10 1) 50 4> [*1 245] (251 248 244 238 237 228 225 223 222 220 219 216 208 197 196 192 191 176 159 157 155 149 140 138 121 119 115 113 108 106 105 101 87 82 79 69 67 59 54 42 40 38 34 19 18 12 11 9 4 4) 3 5> [*1 255] (255 241 228 228 226 224 222 222 217 214 211 197 197 193 191 185 176 175 173 166 162 142 141 139 132 132 122 122 110 110 109 106 104 83 82 81 81 79 74 69 69 65 61 60 59 51 41 37 25 14) 2 6> [*1 255] (248 244 240 234 231 220 214 211 207 206 205 200 197 188 187 184 183 182 173 153 150 149 144 130 127 126 122 113 109 98 94 89 74 66 60 60 58 54 54 51 49 45 21 15 12 12 10 8 7 3) 1 ``` [Answer] # Ruby, 78 bytes ``` puts h=[*0..255].sample(50).sort.reverse s=gets.to_i p (h.index{|i|i<s}||-1)+1 ``` [Answer] ## Javascript, ~~155~~ ~~148~~ ~~134~~ ~~115~~ 101 bytes Not very short, but: ``` l=[...Array(50)].map(x=>Math.random()*256|0).sort((a,b)=>b-a);console.log(l);f=x=>l.findIndex(v=>x>v) ``` Returns position when higher than at least one score. Otherwise [`-1`](https://codegolf.meta.stackexchange.com/a/2192/39320). Edit: apparently you don't have to output scores line by line. So shorter now. ``` l=[...Array(50)].map(x=>Math.random()*256|0).sort((a,b)=>b-a);console.log(l);f=x=>l.findIndex(v=>x>v) console.log(f(200)) console.log(f(60)) console.log(f(30)) console.log(f(2)) ``` 14 bytes saved by @Downgoat [Answer] # [Gaia](https://github.com/splcurran/Gaia), 17 bytes ``` {256ṛ(}₅₀]ȯv:q<∆q ``` There was a small bug with the random function, so this won't work quite properly on the version on TIO, but will work locally. [Try it online!](https://tio.run/##S0/MTPz/v9rI1OzhztkatY@aWh81NcSeWF9mVWjzqKOt8P9/QyMA "Gaia – Try It Online") ### Exaplanation ``` {256ṛ(} Get a random integer from 1 to 256 and decrement it. ₅₀ Do that 50 times. ] Collect the results in a list. ȯv Sort in descending order. :q Copy and print. <∆ Find the index of the first score that is less than the input (input won't be read until this point). q Print that index. ``` [Answer] # [Haskell](https://www.haskell.org/), 176 bytes Haskell is certainly the wrong tool for this job, far too long.. ``` (sequence(randomRIO(0,255)<$[1..50])::IO[Int])>>=g.sort import System.Random import Data.List g l=mapM_ print(reverse l)>>getLine>>=print.(#l).read x#l=1+length(takeWhile(<x)l) ``` [Try it online!](https://tio.run/##NY5Ra8IwFIXf@ysuxIcEZ9CxvogVxA0pdFMcYw9OJNjbNngTu@RuOIa/vSvCng6cw/dxGhNPSNT9jgQUi5fV22L1BMvNBsTomogSK@sRKvjoZMTPL/RHlMH48uy2@VqO7@7TVM0Gu4nW6XivptN8vcs979V8ntU6ngMn1rV9wOtPZHR6e2P/y0fDRhc2clIDZc60zwdog/UsA35jiAjUm2rkon/RK2@bloKUDmjK5CIomwwJfc2NZHPC98YSytlFkeqcsR4yqLqHPw "Haskell – Try It Online") [Answer] # Bash + GNU utilities, 76 ``` shuf -i0-255 -n50|sort -nr|tee s sed 1i$1i s|sort -nr|sed -n /i/=|dc -e?51%p ``` [Try it online](https://tio.run/##S0oszvj/vzijNE1BN9NA18jUVEE3z9Sgpji/qATIKqopSU1VKOYqTk1RMMxUMcxUKEZIgQR18xT0M/Vta1KSFXRT7U0NVQv@//9vaGEAAA). ### Explanation ``` shuf -i0-255 -n50 # generate random leaderboard |sort -nr # sort it in descending numerical order |tee s # output and save to file s sed 1i$1i s # insert new score with an "i" suffix |sort -nr # sort again |sed -n /i/= # output line number of line containing "i" |dc -e?51%p # mod 51 of line number ``` [Answer] # [Perl 5](https://www.perl.org/), 77 + 1 (-p) = 78 bytes ``` @a=sort{$b<=>$a}map{int rand 255}1..50;say"@a";1while$a[$i++]>$_;$_=$i<51&&$i ``` [Try it online!](https://tio.run/##BcFRCoMwDADQq4gEf8TSyvJVK17AE4whkQkLuLa0BRHx6svei1vaUWQil0MqF6yDG4HuL8WLfakS@XfVI95GKdQ201lPVFtzfHjfgJ7AbfsaYbGwOOABTdMAizzwF2Lh4LN0MypttHTxDw "Perl 5 – Try It Online") Outputs the scoreboard space separated on the first line. Outputs the position for the new input on the second line. Second output is blank (falsy) if the new score isn't high enough to make the leaderboard. [Answer] # [Röda](https://github.com/fergusq/roda), 112 bytes ``` {a=[seq(1,50)|[-abs(randomInteger()%256)]for _|sort]a|print-_ parseInteger _|indexOf-_,[sort(a+-_1)]|[(_+1)%51]} ``` [Try it online!](https://tio.run/##LcoxCsMgFADQvafIElASIRbs1gN06gFE5Bd/ikO@6dehEHN2m0Dn9zgFaAtE6ra2wd1m/Ag9mklWq@CVBQOFtDyo4BtZyP5qbtLNiTtfc@LioK4cqSh/WYEz/uOhkQJ@n7Pyoz2jgEF5LV21wg9a9ka7ve3NTD8 "Röda – Try It Online") This reads the input from the input stream as a string (like if it was stdin). The answer could obviously be shorter if I can suppose that the input is a number object, as the `parseInteger _` call would not be needed. I'm not sure if I can do that. [Answer] # [MATL](https://github.com/lmendo/MATL), 18 bytes *Thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) for removing 1 byte and for a correction!* ``` 8W50&YrqSPtD<sQ51\ ``` ### Example run The leaderboard is shown as a line of numbers separated by spaces. The gif only shows the first few, to keep image size reasonable. [![enter image description here](https://i.stack.imgur.com/GlvII.gif)](https://i.stack.imgur.com/GlvII.gif) ### Explanation ``` 8W % Push 2 raised to 8, that is, 256 50 % Push 50 &Yr % Random vector of 50 integers from 1 to 256, independently uniformly distributed q % Subtract 1 to each result. This makes the integers go from 0 to 255 SP % Sort, reverse. This sorts in descending order tD % Duplicate and immediately display < % Implicit input. Is it less than each entry in the sorted random vector? s % Sum. This counts how many entries are less than the input Q % Add 1 51\ % Modulo 51. Implicitly display ``` [Answer] # Java 8, 208 + 19 = 227 bytes It's golfs like these that make me question my choice of language. The I/O order specification prohibits the use of lambda parameters and return values for I/O, but I use a lambda anyway to avoid the main class boilerplate. The lambda can be assigned to `Runnable`. Byte count includes lambda and required import. ``` import java.util.*; ``` ``` ()->{int n,p=0;List<Integer>l=new Stack();for(;p++<50;l.sort((a,b)->b-a))l.add(new Random().nextInt(256));System.out.print(l);n=new Scanner(System.in).nextInt();for(int o:l)if(n>o)p--;System.out.print(p%51);} ``` ## Ungolfed lambda ``` () -> { int n, p = 0; List<Integer> l = new Stack(); for (; p++ < 50; l.sort((a, b) -> b - a)) l.add(new Random().nextInt(256)); System.out.print(l); n = new Scanner(System.in).nextInt(); for (int o : l) if (n > o) p--; System.out.print(p % 51); } ``` It's pretty readable once ungolfed. My favorite part about this solution is that it sorts the scoreboard 50 times (whenever a new score is generated) in order to save one byte. This results in a noticeable delay while the board is generated. `p` is incremented to 51 as the scoreboard is populated, and then is decremented to the input score's ranking. The remainder by 51 is taken so that rank 51 is displayed as 0. Since each initial score is produced by a newly-seeded generator, the scores probably don't have the usual guarantees of randomness. But they seem random enough to me. [Answer] # [PHP](https://php.net/), 119 bytes ``` <?php while($c++<50)$l[]=rand(0,255);rsort($l);foreach($l as$s)echo"$s ";for($i=fgets(STDIN);$i<$l[++$p-1];);echo$p%51; ``` [Try it online!](https://tio.run/##FYyxCsMgFAB/RcIr@LAFE3B6CV26dOnSbiWDWFMFiQ8N9PNtsh3ccRy4tfHKgcUvxOQlOKVGoxHSe56KXT9SnwdjkErNZZOQkJZcvHVhZ2ErVPQu5A6q6A4jIU7L129VPl@3@wMJ4ri/lAK@9DMhHTXwyfTU2qD1Hw "PHP – Try It Online") Please note, when trying it online, you are required to give the input *before* you have seen the starting leaderboard, but this is not how it actually runs from a CLI: the leaderboard is printed first and the program waits for the user input. **Explanation** ``` <?php ``` Generate 50 random numbers and store in the leaderboard, `$l`. ``` while ($c++ < 50) $l[] = rand(0, 255); ``` Sort them in descending order. ``` rsort($l); ``` Print them out space-separated. ``` foreach ($l as $s) echo "$s "; ``` A loop, comparing the user input score `$i` with the score in position `$p` in the leaderboard. ``` for ( ``` Before we start, get the user input. ``` $i = fgets(STDIN); ``` We loop from the top of the board (`$l[0]`) and keep looping for as long as `$i` is less than the score in that position. `$p` is initially undeclared so we increment it *before* each comparison (so it starts as an integer), but have to subtract 1 for a 0 start. ``` $i < $l[++$p - 1]; ); ``` Print the resulting position. If `$i` is less than any score on the leaderboard `$p` will equal 51. Using modulus 51, results in 51 becoming 0, but the other positions remaining unchanged, ``` echo $p % 51; ``` [Answer] # [Ly](https://esolangs.org/wiki/Ly), 58 bytes ``` (50)[>0(255)?<1-]>ar&s&ulrns>1<[L[>"\n"ou;]ppl>1+<]"\n"o0u ``` [Try it online!](https://tio.run/##y6n8/1/D1EAz2s5Aw8jUVNPexlA31i6xSK1YrTSnKK/YztAm2ifaTikmTym/1Dq2oCDHzlDbJhbMNyj9/9/EFAA) Outputs a space-separated list of scores, then the position of the given input after a newline. Explanation: ``` (50)[>0(255)?<1-]> # simple loop to create list of 50 scores ar&s&ulr # arrange the list, reverse it, print it, then reverse it back ns # take input and save it >1< # prepare counter [ # while the stack is not empty L[>"\n"ou;] # check if the value is lower than the input, if so, output a newline and the counter, then terminate ppl>1+< # otherwise, pop a value off the stack and increase the counter ] "\n"o0u # output a newline and 0 if we finished the loop without terminating ``` ]
[Question] [ Thanks [@NathanMerrill](https://codegolf.meta.stackexchange.com/users/20198/nathan-merrill) for allowing me to post this! The following is entirely his wording from [this sandbox post](https://codegolf.meta.stackexchange.com/a/10794/58826) (deleted): --- We define a "Fresh" substring as a substring that is different from any other substring that starts earlier. For example, if I take the string `"abababc"` and split it: `["ab","ab","a","bc"`], the first and the last substring are fresh, but the middle two are not, because they can be found earlier in the string. For this challenge, you need create a list of the smallest possible fresh substrings for each position in the string. If there are no fresh substrings, output and empty list or empty string, etc. For example, if you were passed `"ABABCBA"`, you should return `["A","B","ABC","BC","C"]`. Test Cases: ``` ABABCBA A,B,ABC,BC,C, // ABC instead of AB because there is an AB earlier in the string AAAAAAA A,,,,,, ABCDEFG A,B,C,D,E,F,G ABDBABDAB A,B,D,BA,ABDA,BDA,DA,, ACABCACBDDABADD A,C,AB,B,CAC,ACB,CB,BD,D,DA,ABA,BA,AD,, ``` The empty items are not mandatory. [Answer] # [PHP](https://php.net/), 141 bytes ``` for($r=[];$i<$l=strlen($a=$argn);$i++)for($t=1;$t;$t*=$t<$l)in_array($s=substr($a,$i,$t),$r)|strpos($a,$s)<$i?$t++:$r[]=$s.$t="";print_r($r); ``` [Try it online!](https://tio.run/##ZZFdT4MwFIbv@RVLdy5AjibeypqlH9t@xFwWJCiYpZC2uzDqz/Ya30JijDangZ4@79MSxm6cNtuxG7Pnwbd10@XZUSittNFK8Hr1MxRrRpdRhjkTahl/GJVqnopnShu72x/@mQxb3vGeDwmxOM4q/QtKiGUNETY4TVTSGQiV0Ra4slas1kANqKRUeDF4YmGRtjaFwM0ei/ipDlT7F1e8X11oY049UyyqCV@ek5fHU0X9hi4yRH9pXU61XHC0y7KYqSjvK4qoG0kRbNG7c@19/ZZTkOH6hChyvJiZfPGBzjiEuRmKDfVbimX5QP54khTuIBSiGn3v4jldArdpm25YvQ69ywWLpGDx6ESVfU5fbrht8Ivabw "PHP – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~105 103 88 81~~ 79 bytes -~~15~~ 24 bytes (!) thanks to user1502040 ``` import Data.List f s=[a|a:_<-zipWith(\\)<*>scanl(++)[]$map(tail.inits)$tails s] ``` [Try it online!](https://tio.run/##FcaxCoMwEADQvV9xSIakoh9QtGBw7N5BpRxBydEkBu@m0t/unLbDg@eRn2sIpVDM@yEwomB7I5bTBtxP@MbLo2telO8kXs@z6c5XdpiCrmszLSpi1oIUWkokbNT/DLyUiJSgh3xQElCwQTXY0f4MtiqftDcOnV@/ "Haskell – Try It Online") `t` gets a list of lists of all of the substrings starting from each position. `f` builds up that list using scanl, so at index i we have a list of all of the substrings possible before index i. At each index, we take the set difference between the substrings calculated in `t` and those made illegal by `f`, to get the legal substrings at that index. The lists are guaranteed to be sorted by length, so we can finally just take the first item if it exists. It skips empty items, as they are "not mandatory" per the spec. Still learning Haskell, so I'm sure I've done something odd somewhere. The `map head(filter(>[])` seems especially verbose to say "take the first item if exists, else nothing." [Answer] # C#, ~~175~~ 158 bytes ``` s=>{int i=0,j,l=s.Length;var a=new string[l];for(;i<l;++i)for(j=0;j<l-i;){var t=s.Substring(i,++j);if(!s.Substring(0,i).Contains(t)){a[i]=t;break;}}return a;} ``` Full/Formatted Version: ``` using System; class P { static void Main() { Func<string, string[]> f = s => { int i = 0, j, l = s.Length; var a = new string[l]; for (; i < l; ++i) for (j = 0; j < l - i;) { var t = s.Substring(i, ++j); if (!s.Substring(0, i).Contains(t)) { a[i] = t; break; } } return a; }; Console.WriteLine(string.Join(",", f("ABABCBA"))); Console.WriteLine(string.Join(",", f("AAAAAAA"))); Console.WriteLine(string.Join(",", f("ABCDEFG"))); Console.WriteLine(string.Join(",", f("ABDBABDAB"))); Console.WriteLine(string.Join(",", f("ACABCACBDDABADD"))); Console.ReadLine(); } } ``` [Answer] # [Python 3](https://docs.python.org/3/), 136 bytes ``` l=[];n=input();a=len(n) for x in range(a): i=x+1 while n[x:i]in l or n[x:i]in n[:i-1]: i+=1 if i>a:x=i;break l+=[n[x:i]] print(l) ``` [Try it online!](https://tio.run/##PcuxCgMhEATQ3q/YUpEURzplA/kOsTDg5ZYseyKGeF9vDCGZZhh4U4627XIegzFEL0hSnk0bn5CzaDFq3St0IIGa5J51Mk4BYbeLgtdGnEFCdxQnYJj0vyQ4Oi1xaiCLy6dWoEtyHcnfak4PBWwxfA9RlUrSNJsxrr@8AQ "Python 3 – Try It Online") Includes the empty items [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ;\0;Ṗ ṫJ;\€µḟ"ÇZḢ ``` A monadic link accepting a list of characters and returning a list of lists of characters. **[Try it online!](https://tio.run/##AT8AwP9qZWxsef//O1wwO@G5lgrhuatKO1zigqzCteG4nyLDh1rhuKL/w4dq4oCdLP//IkFDQUJDQUNCRERBQkFERCI)** (the footer formats the list separating it with commas so it does not get implicitly printed as the representation would be smashed together). ### How? ``` ;\0;Ṗ - Link 1, offset prefixes: list e.g. [["x","xy","xyz"],["y","yz"],["z"]] \ - cumulative reduction with: ; - concatenation [["x","xy","xyz"],["x","xy","xyz","y","yz"],["x","xy","xyz","y","yz","z"]] 0; - prepend a zero [0,["x","xy","xyz"],["x","xy","xyz","y","yz"],["x","xy","xyz","y","yz","z"]] Ṗ - pop (head to penultimate) [0,["x","xy","xyz"],["x","xy","xyz","y","yz"]] ṫJ;\€µḟ"ÇZḢ - Main link: list of characters e.g. "ABABC" J - range of length [1,2,3,4,5] ṫ - tail ["ABABC","BABC","ABC","BC","C"] \€ - cumulative reduction for €ach with: ; - concatenation [["A","AB","ABA","ABAB","ABABC"],["B","BA","BAB","BABC"],["A","AB","ABC"],["B","BC"],["C"]] µ - monadic chain separation, call that p Ç - call last link as a monad with p - gets relevant substrings to not use (with a zero in place of an empty list for the first index) - ... that is: [0,["A","AB","ABA","ABAB","ABABC"],["A","AB","ABA","ABAB","ABABC","B","BA","BAB","BABC"],["A","AB","ABA","ABAB","ABABC","B","BA","BAB","BABC","A","AB","ABC"],["A","AB","ABA","ABAB","ABABC","B","BA","BAB","BABC","A","AB","ABC","B","BC"]] " - zip with: ḟ - filter discard [["A","AB","ABA","ABAB","ABABC"],["B","BA","BAB","BABC"],["ABC"],["BC"],["C"]] Z - transpose [["A","B","ABC","BC","C"],["AB","BA"],["ABA"],["ABAB"],["ABABC"]] Ḣ - head ["A","B","ABC","BC","C"] ``` [Answer] ## JavaScript (ES6), 81 bytes ``` f=(s,t=0,u=t+1,v=s.slice(t,u))=>s.indexOf(v)<t?s[u]?f(s,t,u+1):[]:[v,...f(s,t+1)] ``` ``` <input oninput=o.textContent=f(this.value).join`\n`><pre id=o> ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~19~~ 18 bytes *-1 byte because empty items can be ommitted* ``` !&`(.+?)(?<!\1.+) ``` [Try it online!](https://tio.run/##K0otycxL/P9fUS1BQ0/bXlPD3kYxxlBPW/P/f0dnRydnR2cnFxdHJ0cXFwA "Retina – Try It Online") Explanation: ``` ! Print matches as newline separated list &` Consider overlapping matches (.+?) Capture the shortest possible substring (?<!\1.+) Enforce freshness .+ Scan backwards \1 Fail if the match appears earlier in the string If matching is impossible, skip this element ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 77 bytes ``` ->s,*a{s.scan(""){a<<(1..$'.size).map{$'[..._1]}.find{!($`+_1)[..-2][_1]}} a} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3fXXtinW0EquL9YqTE_M0lJQ0qxNtbDQM9fRU1PWKM6tSNfVyEwuqVdSj9fT04g1ja_XSMvNSqhU1VBK04w01gaK6RrHRIIlarsRaqKEhBQpu0UqOTo5Ozk6OSrFcEC4EwLlOzi6ubu4IrgtQuYujE1zAGajC0dnJBSjm6OKiFAsxe8ECCA0A) [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ¬ËUsE å+ k@bX <EÃg ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=rMtVc0Ug5Ssga0BiWCA8RcNn&input=IkFCQUJDQkEiLVE) Outputs `null` when there are no fresh substrings Explanation: ``` ¬ËUsE å+ k@bX <EÃg ¬ # Split the input into an array of characters Ë # For each index E: UsE # Get the suffix of the input with length E å+ # Get all prefixes of that suffix k@ à # Remove the ones where: bX # The first time it appears in the input <E # Is before E g # Return the shortest one remaining ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ã ü@bXÃmg ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4yD8QGJYw21n&input=IkFCQ0RFRkci) ``` ã ü@bXÃmg :Implicit input of string U ã :Substrings ü :Sort and group by @ :Passing each X through the following function bX : First index of X in U à :End grouping m :Map g : First element ``` ]
[Question] [ Given a list of pairwise distinct integers, sort it in alternating order: The second number is larger than the first, the third is smaller than the second, the fourth is larger than the third etc. (This order is not unique.) E.g., `5 7 3 4 2 9 1` would be valid output. Extra points (since this is code golf, subtract from the number of characters): * 15 for not using any built-in sort functionality. * 15 if your code does not reorder inputs that are already ordered this way. * 10 if the output order is random, i.e., multiple runs with the same input yield different correct outputs. [Answer] # Golfscript, 21-30 = -9 ``` ~(\{.2$>0!:0^{\}*}/]` ``` Bonuses: does not use built-in sort constructs (-15); does not modify a sorted array (-15) Since, in general, it's not possible to sort an array of integers as defined, this assumes that either all integers are distinct, or "larger" and "smaller" actually mean "or equal". Explanation: Algorithm taken from Stack Overflow: [What is the most efficient way to sort a number list into alternating low-high-low sequences?](https://stackoverflow.com/a/20872022/499214) * `~(\` evals the input, which should yield an array, pops the first element and swaps it before the array. * `{...}/]`` iterates the block over the array, collecting the results on the stack so that they can be reused immediately, then collects them into an array and stringifies the array so that it's displayed in a sensible format. The block: * `.2$>` duplicates top two elements of the stack (in reverse order) and compares them, yielding 0 or 1. * `0!:0` pushes an negates a zero, then overwrites zero with its negated version. This, the variable `0` alternates between the values 0 and 1. This is used to define the comparison sense. It's nice to have a variable initialised to the logical zero, and `0` just happens to be a variable *and* initialised to the value of 0. * `^{\}*` XORS the sense with the comparison result, then swaps the top two elements if the result is true. Example: ``` ;"[3 8 1 6 5 4 7 2 9]" ~(\{.2$>0!:0^{\}*}/]` #[3 8 1 6 4 7 2 9 5] ``` [Answer] # Mathematica ~~24~~ ~~19~~ 18 = 58 - 40 ``` u = {1, 4, 9, 2, 7, 5, 3, 8, 6} u//.s:{x___,y_,z_,___}/;y>z⊻OddQ@Tr[1^{x}]:>RandomSample@s ``` > > {4, 5, 3, 8, 2, 7, 1, 9, 6} > > > It doesn't reorder ordered list. For a list with an even number of elements one can save 2 characters: ``` n=0;u//.s:{x___,y_,z_,___}/;OddQ@n++⊻y>z:>RandomSample@s ``` [Answer] # Mathematica 81-15-15-10=41 ``` f[t_] := t //. {l___, x_, y_, z_, r___} /; x > y > z || x < y < z :> f@RandomSample[s = {l, x, z, y, r}] /; s != t ``` Examples ``` f@{1, 2, 3, 4, 5, 6, 7, 8} > {1, 4, 3, 6, 5, 7, 2, 8} f@{1, 2, 3, 4, 5, 6, 7, 8} > {8, 3, 5, 2, 7, 4, 6, 1} f@{8, 3, 5, 2, 7, 4, 6, 1} > {8, 3, 5, 2, 7, 4, 6, 1} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 19-40 = -21 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` äÎäÎשUªá fÈäÎäÎ×Ãö ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=5M7kztepVarhIGbI5M7kztfD9g&input=WzUgNyAzIDQgMiA5IDFd) ``` äÎäÎשUªá fÈäÎäÎ×Ãö :Implicit input of array U ä :Consecutive pairs Î : Signs of differences äÎ :As above × :Reduce by multiplication ©U :Logical AND with U ª :Logical OR with á : Permutations of U f : Filter by È : Passing each through the following function äÎäÎ× : As above à : End filter ö : Random element ``` ## w/o Bonuses, 9 bytes ``` á æÈäÎäÎ× ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4SDmyOTO5M7X&input=WzUgNyAzIDQgMiA5IDFd) ``` á æÈäÎäÎ× :Implicit input of array á :Permutations æ :First element to return true when È :Passed through the following function äÎäÎ× : As above ``` [Answer] # C (57 = 97 characters - 40 bonus) ``` i,t,j;f(a[],n){for(;++i<n;)if(a[i^i&1]>a[i^!i&1])for(i=n;--i;)t=a[j=rand()%n],a[j]=a[i],a[i]=t;} ``` Bogosort with alternating compares shuffling with Fisher-Yates. The shuffle loop uses the same index as the comparison loop so when the shuffle is done the comparison loop is automatically reset. The indexes in the array we compare have their lowest bit flipped based on the index we compare, it works without parentheses thanks to nice operator precedence and associativity. Assumes that `rand` is actually random or at least seeded properly. [Answer] # Ruby 1.9+ (20 = 35 characters - 15 bonus) Ah, the good ol' `minmax`! ``` f=->a{a[1]&&(m=a.minmax)+f[a-m]||a} ``` Sample run: ``` irb(main):004:0> f[[1,2,3,4,5,6,7]] => [1, 7, 2, 6, 3, 5, 4] ``` # Ruby 1.9+ (43 = 83 characters - 40 bonus) A solution that satisfies all the bonuses: Shuffles the argument array until it's alternatingly (?) sorted. To check the array, it is zipped toghether with a shifted copy of itself and an alternating array of `<` and `>` symbols, forming something like `[[1, :<, 2], [2, :>, 3], [3, :<, 4], [4, :>, 5], ... ]` ``` f=->a{a.shuffle!until a.zip([:<,:>].cycle,a[1..-1]).all?{|x,o,y|!y||x.send(o,y)};a} ``` [Answer] # Python (75 = 115 characters - 40 bonus) The same strategy as the second entry in my Ruby answer, except it loops on `while` instead of `until` and the condition is negated (from "all correct" to "any uncorrect"). ``` from random import* def f(a): while any(eval(`x`+o+`y`)for x,y,o in zip(a,a[1:],"><"*len(a))):shuffle(a) return a ``` [Answer] This is my first ever code golfing attempt. Not sure how happy I am with it (there *must* be a better way to get list of each character in stdin than `raw_input()` and a list comprehension) but for a first try I think I'm proud. # Python 2.7 (117 = 117 chars - 0 bonuses) ``` def f(l): o=[] l.sort() while len(l):o.append(l.pop(0));l=l[::-1] return o print f(map(int,raw_input().split())) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 75-40=35 bytes ``` f=x=>x.some((c,i)=>c>x[i-1]^i%2)?f(x,x.splice(Math.random()*2,0,x.pop())):x ``` [Try it online!](https://tio.run/##vclBCsIwEADAu/8QdmUbTKqIQusLfEGpENJUU9JsaIrk97FnH@B1ZtIfnczi4loFHmwpY5ObNovEswUw5LBpTZs7V8n@6fYK7yNk2j56Zyw89PoWiw4Dz4AHRcetIkdAxFsuhkNib4XnF4zQnelCNZ1I0ZVkj7j7eblN/Q8vXw "JavaScript (Node.js) – Try It Online") [Answer] # Python 3 (119 = 159 chars - 40 bonuses) ``` def o(x): a,s=x[0],1 for b in x[1:]: if(b-a)*s<0:return 1 s,a=-s,b import random s=list(map(int,input().split())) while o(s):random.shuffle(s) print(*s) ``` [Answer] # Python 3 (may be 2 also) ``` def f(a): for i in range(len(a)-1): if (a[i+1]-a[i])*(-1)**i<0: a[i:i+2]=a[i+1],a[i] return a ``` 100 characters (100) Do not used builting sorting (-15) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 18 - 40 = -22 bytes ``` Ṗ'¯±:k+$•⁼;:?c[_|℅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZYnwq/CsTprKyTigKLigbw7Oj9jW1984oSFIiwiIiwiNSw3LDMsNCwyLDEsOSJd) This is why bonuses are a bad idea [Answer] ## JavaScript, 87 Fairly straightforward approach: sort given array in ascending order, then swap every two elements starting with the second one (`[a[i],a[i+1]]=[a[i+1],a[i]]`). According to author, function is OK, so here's a function (*87 characters*): ``` function s(a){a.sort();for(i=1;i<a.length-1;[a[i],a[i+1]]=[a[i+1],a[i]],i+=2);return a} ``` Version with I/O (*94 characters*, you are supposed to type array like this: `3,7,9,2,1,4,5`): ``` a=(prompt().split(",")).sort();for(i=1;i<a.length-1;[a[i],a[i+1]]=[a[i+1],a[i]],i+=2);alert(a) ``` ]