text
stringlengths
180
608k
[Question] [ Your challenge today is to output a given term of a sequence enumerating all of the integers. The sequence is as follows: If we have a 0-indexed function generating the sequence `f(n)` and `ceil(x)` is the ceiling function, then `f(0) = 0`; `abs(f(n)) = ceil(n/2)`; `sign(f(n))` is positive when `n` and `ceil(n/2)` are either both even or both odd. To help understand this sequence, the first few terms are as follows: `0 1 -1 -2 2 3 -3 -4 4 5 -5 -6 6 7 -7...` Your task is to write a program to that takes an integer `n` and outputs the `n`th term of the sequence. Input may be 0 or 1-indexed only. Test cases (0-indexed): ``` 0 => 0 1 => 1 2 => -1 3 => -2 4 => 2 5 => 3 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins! [Answer] # [Python 2](https://docs.python.org/2/), 26 24 bytes ``` lambda x:-~x/2/(1-(x&2)) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCSreuQt9IX8NQV6NCzUhT839afpFCpkJmnkJRYl56qoahgaYVF2dBUWZeiUaaRqamJtd/AA) [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~8~~ 6 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` I».»⌡± ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=SSVCQi4lQkIldTIzMjElQjE_,inputs=NA__) or [try the first couple numbers](https://dzaima.github.io/SOGLOnline/?code=SSVCQmUlQkIldTIzMjElQjElMjMlMEEldTIyMkJIJUIzRU8ldTAxM0MlM0ElMjNw,inputs=MTU_) (changed a bit so it'd work) 0-indexed. Explanation: ``` I increment the input » floor divide by 2 . push the original input » floor divide by 2 ⌡ that many times ± negate ``` Or simpler: ``` (input + 1) // 2 negated input // 2 times I » ± . » ⌡ ``` [Answer] # JavaScript (ES6), 18 bytes 1-indexed. ``` n=>n/(++n&2||-2)|0 ``` ### Demo ``` let f = n=>n/(++n&2||-2)|0 for(n = 1; n < 20; n++) { console.log(n + ' --> ' + f(n)) } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` HµĊN⁸¡ ``` [Try it online!](https://tio.run/##y0rNyan8/9/j0NYjXX6PGnccWvj//39jAA "Jelly – Try It Online") Uses dzaima's algorithm. -1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). [Answer] # C, 25 bytes ``` f(n){return~n/2*~-(n&2);} ``` [Answer] # [Haskell](https://www.haskell.org/), 26 bytes ``` f x=div(x+1)2*(-1)^div x 2 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwjYls0yjQttQ00hLQ9dQMw7IVahQMPqfm5iZp2CrUFCUmVeioKKQm1igkKYQbaCnZ2gQ@x8A "Haskell – Try It Online") The other Haskell answers seem to be overcomplicating things… ^^ [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 6 bytes ``` heQeV_ ``` [Try it here!](http://pyke.catbus.co.uk/?code=heQeV_&input=3&warnings=0&hex=0) Uses [dzaima's approach](https://codegolf.stackexchange.com/a/142894/59487)... ~~Beats~~ Ties Jelly! # Explanation ``` h - Increment the input, which is implicit at the beginning. e - Floor halve. Q - Push the input. e - Floor halve. V_ - Apply repeatedly (V), ^ times, using negation (_). - Output implicitly. ``` The hex-encoded bytes equivalent would be: [`68 65 51 65 56 5F`](http://pyke.catbus.co.uk/?code=68+65+51+65+56+5F&input=3&warnings=0&hex=1). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` ;DîsF( ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f2uXwumI3jf//jQE "05AB1E – Try It Online") Uses dzaima's algorithm. [Answer] # [Python 2](https://docs.python.org/2/), 21 bytes ``` lambda x:-x/2*~-(x&2) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCSrdC30irTlejQs1I839afpFCpkJmnkJRYl56qoahgaaVQkFRZl6JQppGpibXfwA "Python 2 – Try It Online") [Answer] # Java 8, 15 bytes ``` n->~n/2*~-(n&2) ``` EDIT: Is Java really the shortest of the non-golfing languages?! o.Ô **Explanation:** [Try it here.](https://tio.run/##LU7LDoIwELzzFXsyrQRUEk@IfyAXjsZDLcUUYUtoITEGfr0uYLKP7OxMZmoxish0Cuvy7WUjrIWb0PgNADQ61VdCKsiXcwVAsmUiTwmZqKmsE05LyAEhA4/RdcZDsp8jhruE@3QjdcOzIdKfOxpdQks@rHC9xtf9AYJvJpXpVwudHVPQl@x0phWG/y9A8bFOtbEZXNyR1DXIMKZUfI20hZqCyf8A) I'll use the table below as reference of what's happening. 1. `~n` is equal to `-n-1`. 2. Since integer division in Java automatically floors on positive integers and ceils on negative integers, `~n/2` will result in the sequence `0,-1,-1,-2,-2,-3,-3,-4,-4,-5,-5,...` 3. `n&2` will result in either `0` or `2`, in the sequence `0,0,2,2,0,0,2,2,0,0,2,...` 4. `~-x` is equal to `(x-1)`, so `~-(n&2)` (`((n&2)-1)`) results in the sequence `-1,-1,1,1,-1,-1,1,1,-1,-1,1,...` 5. Multiplying the two sequences of `~n/2` and `~-(n&2)` gives is the correct sequence asked in the challenge: `0,1,-1,-2,2,3,-3,-4,4,5,-5,...` Overview table: ``` n ~n ~n/2 n&2 ~-(n&2) ~n/2*~-(n&2) 0 -1 0 0 -1 0 1 -2 -1 0 -1 1 2 -3 -1 2 1 -1 3 -4 -2 2 1 -2 4 -5 -2 0 -1 2 5 -6 -3 0 -1 3 6 -7 -3 2 1 -3 7 -8 -4 2 1 -4 8 -9 -4 0 -1 4 9 -10 -5 0 -1 5 10 -11 -5 2 1 -5 ``` [Answer] # Mathematica, 24 bytes ``` (s=⌈#/2⌉)(-1)^(#+s)& ``` -14 bytes from @Misha Lavrov [Answer] # [Haskell](https://www.haskell.org/), ~~25~~ ~~43~~ 42 bytes ``` ((do a<-[0..];[[-a,a],[a,-a]]!!mod a 2)!!) ``` [Try it online!](https://tio.run/##BcFBDoIwEAXQq/wmLiBpm@JWOck4ix@wSmyhAc/P8N6Xx@9diuXxZV03b@AzSIpRHyKBnuqFPlDVubrNIO69c71VLitGtH1Z/7ihsiFDhhiHlNTOKRd@DgtTaxc "Haskell – Try It Online") 1-indexed. *Edit:* The previous version had the signs in a wrong order, thanks to @Potato44 for pointing out. Fixed for 18 bytes ... *Edit 2:* Thanks to BMO for -1 byte! [Answer] # [Python 3](https://docs.python.org/3/), 29 bytes ``` lambda n:-~n//2*(-1)**(n%4>1) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPSrcuT1/fSEtD11BTS0sjT9XEzlDzf1p@kUKmQmaeQlFiXnqqhqGBgaZVQVFmXolGmkampuZ/AA "Python 3 – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 9 bytes ``` _F/hQ2/Q2 ``` **[Try it here!](https://pyth.herokuapp.com/?code=_F%2FhQ2%2FQ2&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11&debug=0)** Uses [dzaima's approach](https://codegolf.stackexchange.com/a/142894/59487). [Answer] ## Haskell, 36 bytes ``` g x=x: -x:g(-x-signum x) ((0:g 1)!!) ``` [Try it online!](https://tio.run/##BcFBCoAgEAXQfaf4QgtdGLoVPEm0cJGTpCJZMLef3rvSvM9aRQgcOcByIG3ZzkL9a2Cz5Ki1CwRvlDLSUumIGE/pL1a0NJCxu23z7pAf "Haskell – Try It Online") [Answer] ## Batch, 29 bytes ``` @cmd/cset/a"%1/2^(%1<<30>>30) ``` [Answer] ## JavaScript (ES6), 18 bytes ``` f= n=>n/2^(n<<30>>30) ``` ``` <input type=number min=0 value=0 oninput=o.textContent=f(this.value)><pre id=o>0 ``` 0-indexed. [Answer] ## Javascript, 17 bytes ``` n=>~n/2*~-(n&2)^0 ``` ``` f= n=>~n/2*~-(n&2)^0 ``` ``` <input type=number min=0 value=0 oninput=o.textContent=f(this.value)><pre id=o>0 ``` This one is 0 indexed. It's entirely bitwise trickery. [Answer] # [Cubically](https://github.com/aaronryank/cubically), 23 bytes (1-indexed) ``` FDF'$:7+8/0_0*0-8*7/0%6 ``` [Try it online!](https://tio.run/##Sy5NykxOzMmp/P/fzcVNXcXKXNtC3yDeQMtA10LLXN9A1ez/fxMA "Cubically – Try It Online") The main difficulty when writing code in Cubically are: * There is only 1 write-able variable, and * Get constants is hard. So, this solution calculate ``` ((((n+1)/2)%2)*2-1)*n/2 ``` where `/` denotes integer division. That only need 1 temporary variable, and constants 1 and 2. Explanation: ``` FDF'$:7+8/0_0*0-8*7/0%6 FDF' Set face value of face 0 to 2, and value of memory index 8 (cube is unsolved) to 1 (true = unsolved) $ Read input :7 input +8 + 1 /0 ( ) /2 _0 ( ) %2 *0 ( ) *2 -8 -1 *7 ( ) *n /0 /2 %6 Print ``` [Answer] # TI-Basic (TI-84 Plus CE), 20 bytes ``` ‾int(‾Ans/2)(1-2remainder(int(Ans/2),2 ``` A full program that is called like `5:prgmNAME`. TI-Basic is a [tokenized lanugage](http://tibasicdev.wikidot.com/one-byte-tokens), all tokens used here are one byte, except for `remainder(` which is two. `‾` represents the regative token, which is typed with the `(-)` key. Examples: ``` 0:prgmNAME => 0 1:prgmNAME => 1 2:prgmNAME => -1 #etc ``` Explanation: ``` ‾int(‾Ans/2)(1-2remainder(int(Ans/2),2 ‾int(‾Ans/2) # -int(-X) is ciel(X), so ciel(Ans/2) int(Ans/2) # int(X) is floor(X), so floor(Ans/2) remainder(int(Ans/2),2 # 1 if floor(Ans/2) is odd else 0 (1-2remainder(int(Ans/2),2 # -1 if floor(Ans/2) is odd, else 1 _int(_Ans/2)(1-2remainder(int(Ans/2),2 # -ciel(Ans/2) if floor(Ans/2) is odd, else ciel(Ans/2) ``` Same formula as a Y-var function: ``` Y1= ‾int(‾X/2)(1-2remainder(int(X/2),2 ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 16 bytes ``` 1+d2~+2%2*1-r2/* ``` I am sure there's a way to make 0..1 to -1..1 in dc shorter, but no ideas for now. [Try it online!](https://tio.run/##S0n@H/3fUDvFqE7bSNVIy1C3yEhf63@sQrGBAle0QkpKnkL0o7ZJsQEKOQYVCgUKxXkKhtoKKQqGBgYKdoYKQHWGXAYKOYYV/wE "dc – Try It Online") [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), ~~86~~ ~~74~~ ~~72~~ 70 bytes ``` {({}[()]<({}<>([({})]{(<{}([{}]())>)}{}())<>)>)}{}<>{}{<>([{}])(<>)}<> ``` [Try it online!](https://tio.run/##JYqxDYBADAPXsXvKKItEXzw0ICQKWiuz54Oozj57f@f1nPO4qwRlgMOa5ogGh2BKhHKAdGYX0vyP5kp9156Jtm2qals "Brain-Flak (BrainHack) – Try It Online") ## Explanation There are two parts to this code. The first part ``` ({}[()]<({}<>([({})]{(<{}([{}]())>)}{}())<>)>)}{} ``` does the brawn of the computation. It determines `ceil(n/2)` and whether or not to negate the output. To explain how it works I will first explain how one would calculate `ceil(n/2)`. This could be done with the following code ``` {({}[()]<({}([{}]()))>)}{} ``` This counts down from **n** each time it performs a not (`([{}]())`) on a counter and adds the counter to a result. Since the counter is zero half the time we only increment every other run starting with the first one. Now I want to also compute the sign of our results. To do this we start another counter. This counter only changes state if the first counter is off. That way we get the desired pattern. We put these two counters on the off stack to ease with moving them around when the time comes. Now once we have finished that computation our stack looks like this ``` parity(n) ceil(n/2) sign ``` So we need to do some work to get the intended result this second part does it. ``` <>{}{<>([{}])(<>)}<> ``` [Answer] # [Perl 5](https://www.perl.org/), 32 + 1 (`-p`) = 33 bytes ``` $_='-'x(($_+++($b=0|$_/2))%2).$b ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lZdV71CQ0MlXltbW0MlydagRiVe30hTU9VIU08l6f9/43/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online") [Answer] # [Proton](https://github.com/alexander-liao/proton), 23 bytes ``` n=>-~n//2//(-1)**(n//2) ``` [Try it online!](https://tio.run/##KyjKL8nP@59m@z/P1k63Lk9f30hfX0PXUFNLSwPE0fyfll@kkKlgpWCop2doUM2lAAQFRZl5JRqZOuq6duo6aRqZmppctf8B "Proton – Try It Online") Port of [Halvard's solution](https://codegolf.stackexchange.com/a/142898/59487). # [Proton](https://github.com/alexander-liao/proton), 23 bytes ``` n=>-~n//2*(-1)**(n%4>1) ``` [Try it online!](https://tio.run/##KyjKL8nP@59m@z/P1k63Lk9f30hLQ9dQU0tLI0/VxM5Q839afpFCpoKVgqGenqFBNZcCEBQUZeaVaGTqqOvaqeukaWRqanLV/gcA "Proton – Try It Online") Port of [Leaky's solution](https://codegolf.stackexchange.com/a/142896/59487). A bit more Protonic, 24 bytes: ``` n=>-~n//2*(**)(-1,n%4>1) ``` [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~27~~ 26 bytes ``` g=(:+1)'\2`~(a-g)%2|?-g\?g ``` ## Explanation ``` g= set worker var 'g' to (:+1) our index (plus one for the ceil() bit) '\2` integer divided by 2 (the int div needs a code literal: '..` ~(a-g)%2 IF index - temp result is odd (index 2 minus result 1 = 1) |?-g THEN PRINT g negated \?g ELSE PRINT g ``` [Answer] # Clojure 122 bytes Verbose, even when golfed. I'm going for the sympathy vote here... :-) Golfed: ``` (defn d[n](let[x(int(Math/ceil(/ n 2)))y(cond(or(and(even? n)(even? x))(and(odd? n)(odd? x)))(Math/abs x):else(- 0 x))]y)) ``` Ungolfed: ``` (defn dizzy-integer [n] (let [x (int (Math/ceil (/ n 2))) y (cond (or (and (even? n) (even? x)) (and (odd? n) (odd? x))) (Math/abs x) :else (- 0 x)) ] y)) ``` [Answer] # Excel VBA 32-Bit, ~~39~~ 37 Bytes Anonymous VBE immediate window function that takes input from cell `A1` and outputs to the VBE immediate window ``` ?[Sign((-1)^Int(A1/2))*Int((A1+1)/2)] ``` Restricted to 32-Bit as `A^B`is not valid in 64-Bit (`A ^B` is as close as can be achieved) [Answer] # [Julia 0.6](http://julialang.org/), 16 bytes It's just the java solution except I need `÷` for integer division. ``` n->~n÷2*~-(n&2) ``` [Try it online!](https://tio.run/##yyrNyUw0@5@mYKuQlJqemfc/T9euLu/wdiOtOl2NPDUjzf@peSlcDsUZ@eUKaXoaBlaGBpr/AQ "Julia 0.6 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` !m?I_%2İZ ``` [Try it online!](https://tio.run/##yygtzv7/XzHX3jNe1ejIhqj///8bAgA "Husk – Try It Online") 1-indexed. ## Explanation ``` !m?I_%2İZ İZ List of all integers (builtin) [0,1,-1,2,-2,...] m map to the following function ? %2 if the number is even, _ negate it. I otherwise return it ! find element at input index ``` # Alternate solution, 9 bytes ``` !⌊½¹¡_⌊½→ ``` [Try it online!](https://tio.run/##yygtzv7/X/FRT9ehvYd2HloYD2Y9apv0//9/QwA "Husk – Try It Online") Uses the same equation as the SOGL answer. [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` z°U&2ªJÑ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=erBVJjKqStE&input=MTc) ]
[Question] [ Given a 2-dimensional [jagged array](https://en.wikipedia.org/wiki/Jagged_array) and a fill value, pad the array in both dimensions with the fill value to ensure that it is square and not jagged (i.e., all rows are the same length, and that length is the same as the number of rows). The fill values should always be added to the "edges", which may be the start or the end, but not in the middle. For example, with the fill value `8`, this array: ``` [[1, 5, 3], [4, 5], [1, 2, 2, 5]] ``` could become: ``` [[1, 5, 3, 8], [4, 5, 8, 8], [1, 2, 2, 5], [8, 8, 8, 8]] ``` Here is another valid output: ``` [[8, 8, 8, 8], [8, 1, 5, 3], [8, 4, 5, 8], [1, 2, 2, 5]] ``` However, the padding should be minimal: the size of the output square should be equal to the maximum of the length of the rows and the number of rows. For example, this is not a valid output for the input above: ``` [[1, 5, 3, 8, 8], [4, 5, 8, 8, 8], [1, 2, 2, 5, 8], [8, 8, 8, 8, 8], [8, 8, 8, 8, 8]] ``` ## More test cases All using fill value `0` for simplicity. ``` Input: [] Output: [] ``` ``` Input: [[], []] Output: [[0, 0], [0, 0]] ``` ``` Input: [[5]] Output: [[5]] ``` ``` Input: [[0, 0], [0], [0, 0, 0]] Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] ``` ``` Input: [[1, 2, 3, 4]] Output: [[1, 2, 3, 4], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] ``` ``` Input: [[1], [2], [3], [4, 5]] Output: [[1, 0, 0, 0], [2, 0, 0, 0], [3, 0, 0, 0], [4, 5, 0, 0]] ``` ## Rules * The array's elements and the fill value can be of whatever type or set of values you like, as long as there are at least two distinct possibilities. For example, you could use characters, where the array is a multi-line string (where each line is a row), or you could restrict the values to single digits... * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden * [Standard I/O rules](https://codegolf.meta.stackexchange.com/q/2447) apply * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins [Answer] # [Haskell](https://www.haskell.org/), 67 bytes ``` m%v|let l?x=take(maximum$length<$>(1<$m):m)$l++repeat x=(?v)<$>m?[] ``` [Try it online!](https://tio.run/##TU9LCsIwEN17illESGgEbSuItPYEniAECSXW0kwJTSxdeHZjUhcKw8y8D/N5KDdoY0LA7fwy2oNpltqrQVNUS49PJEaPnX9U5EIPFUF2RkZMlk3aauVhqWkzsyhiI2Tw2vlbq5x2UIOgQhw4HDkUkoMoY5tqpPI1jjLCE@MQfUlIcP@FX0/BofwnkylP6TdvVeVmg6of40pU9gp26kcPIv4DL6DIZwbVDn6nyfBu70Z1Luxaaz8 "Haskell – Try It Online") [Answer] # [J](http://jsoftware.com/), 25 bytes ``` 4 :'y([{.!.x&>{.)~>./$>y' ``` [Try it online!](https://tio.run/##y/r/P81Wz0TBSr1SI7paT1GvQs2uWk@zzk5PX8WuUv1/ha2eQqIVV2pyRr5CBYSyUEiDMdV1dXXVubgginSIUmejY2VKhDIDawUDKKFgQIyxCoYKRgrGCiZEqDW0NrQ2tjZRwOKO/wA "J – Try It Online") *Note: -3 off TIO for `f=.`* Note that in J ragged arrays must be boxed. This was surprisingly hard considering that J auto fills ragged arrays by default. Unfortunately, the default behavior is not quite enough for what's needed in this challenge. ## how We take the fill as the left arg `x` and the input arrays as the right arg `y`, and use an explicit (rather than tacit) verb because the fit conjunction `!.` required to specify fill requires a value or named variable. * `>./$>y` - The max `>./` of the dimensions `$` of the opened input `>y`. We'll use this as the left argument of the main verb. * `([ {.!.x&> {.)` The main verb, consisting of a fork whose right tine `{.` expands the boxed input to the required dimension by filling it with blank boxes. This handles what will ultimately become the "vertical expansion". * `{.!.x&>` For each box `&>` (the original input, plus the empty expansions produced in the previous step), take `{.` the required length, filling missing items with the specified fill `!.x`. This handles the "horizontal expansion". [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~21~~ 19 bytes ``` {y^x .!'2#|/#'x,,x} ``` [Try it online!](https://tio.run/##NYwxCsMwFEOvIpPB3/CbfjsxlOouHZMhkNmh7dndOKZokNBD2m77ute6PN/Hq2B0Pg2f@@CLavnWBaMXkYiMiTMyI9KpHPgIFAm0Zs7orGfV3DuDUY2n4Y/adsLcuUZqol6vjYf6Aw "K (ngn/k) – Try It Online") * `|/#'x,,x` get the size of the output (i.e. the maximum of the count of each row, and of the number of rows) * `!'2#` build a list of two copies of 0..size (e.g. `(0 1 2 3;0 1 2 3)`) * `x .` dot-apply into the input (out of bound accesses result in `0N`s) * `y^` replace nulls with the fill number [Answer] # [R](https://www.r-project.org/), ~~80~~ ~~90~~ ~~93~~ 88 bytes *Edit: -5 bytes thanks to Kirill L., but only after +10 bytes to fix bug, and +3 more bytes after belatedly realising that the fill-value should be given as input...* ``` function(l,f,m=matrix(f,d<-max(0,seq(l),lengths(l)),d)){for(i in l)m[F<-F+1,seq(i)]=i;m} ``` [Try it online!](https://tio.run/##NY69CsIwFEZ3n6LjvXgLRs1QbNa@hDiUtolXklTzAwXx2WMtyDecM5zhCyX7R2/MNKqisx8Szx4saXLK9SnwAprGtnb9AgeK0wsskp28Sfe4KtKI@NZzAK7YVxbdtWvrbi@2lPGm@OI@hf0zJ2U5JhhAkKQT0gBnkj8IOq6TiLv/E9h6ahosXw "R – Try It Online") [Answer] # [JQ](https://stedolan.github.io/jq/), 49 bytes Takes input as an array of `[array, fill-element]`, where the array can hold any non-null type. ``` .[1]as$a|.[0]|transpose|transpose|map(map(.//$a)) EXPLANATION: .[1]as$a| # input array's second argument is in variable a .[0]| # the first argument transpose| # transposed, automatically placing null as a fill element transpose| # back to normal map( # for each row map( # for each element .//$a # if it's null, the fill element, else it. # // is like or in other languages, . means "it" or "it unchanged" ``` <https://jqplay.org/s/8ADEt9WJGL> [Answer] # JavaScript (ES6), 92 bytes Expects `(array)(value)`, where `array` contains positive integers (or any other truthy values). ``` a=>v=>[a,...a].sort((a,b)=>b.length-a.length)[0].map((_,y,A)=>A.map((_,x)=>(a[y]||0)[x]||v)) ``` [Try it online!](https://tio.run/##fY7NCoMwEITvPkWOWViD9Qd6UfA5QiirtbbFGlERBd89TY2FHqSwMDvLN8M@aaKh7B/d6Lf6WplbaijNpjSThEIIUmLQ/cg5YQFpVoimauvx7tO@gAyUeFHH@QUXzC2Sf@1sDSe5qHUNQM5WJgBT6nbQTSUaXfMblx5j8oQsQRYp/JjYGrfZc7hNojwF/AzgHYQduxHBMeF6ImTxX8oVhU5@n9lD5g0 "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = jagged array v => // v = fill value [a, ...a] // build an array consisting of the jagged array itself // followed by each of its rows .sort((a, b) => // sort this array ... b.length - a.length // ... from longest to shortest entry )[0] // and keep the longest one .map((_, y, A) => // for each row at position y in this array A[]: A.map((_, x) => // for each entry at position x in A[]: (a[y] || 0)[x] // attempt to get the value at (x, y) in a[] || v // if it fails, use the fill value instead ) // end of inner map() ) // end of outer map() ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 26 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")) Anonymous infix lambda, taking fill as left argument and array as right argument. ``` {g←1⌷∘↑↑⍮∘⍉↑⋄⍺@(⍸~g=⍨⍵)g⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/vzr9UdsEw0c92x91zHjUNhGEeteB2L2dIHZ3y6PeXQ4aj3p31KXbPupd8ah3q2Y6kKj9nwbU96i371FX86PeNY96txxabwLS0Dc1OMgZSIZ4eAZzZYHU9E31Cvb3Axs/OQ1EQQT@q@vq6iq4efr4KIR7hngoGCgA@epcBgpZCurR0YY6CqY6CsaxOgrRJkAmiAYKGYGRaWysOhfM2LbJQJ1pQGwAdIMBTDtIPUgVlGuKxDbQUTAASUMIIAfEj0W2GGiFsY6CCbIgSK0RiEC4CCiL5gMLC4gXgDTJfgDqQXgCZgDMFzC@KTIHlz@QbEfyCFwUq08A "APL (Dyalog Extended) – Try It Online") `{`…`}` dfn; left argument (fill) is `⍺`, right argument (array) is `⍵`  `g←` define `g` as a tacit function:   `1⌷∘` the first layer of the 3D array that consist of    `↑` the 3D array consisting of the following two layers, padded with 0s:   `↑⍮∘⍉` the 2D array consisting of the given rows, padded with 0s, and the transposed…    `↑` 2D array consisting of the given rows, padded with 0s `⋄` then:  `⍺@(`…`)` place fills **at** the indices given by:   `⍸` the **ɩ**ndices where…   `~` there are zeros (lit. NOT)…   `g` in the fully padded version of…   `=⍨` the array identical to the given one, but with all elements made into 1s (lit. self-equality)  `g⍵` in the fully padded given array [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), ~~47 37~~ 32 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {⍺@((,⍳x)~⍸↑=⍨⍵)⊢(x←2/⌈/⍴↑⍵)↑↑⍵} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37Uu8tBQ0PnUe/mCs26R707HrVNtH3Uu@JR71bNR12LNCoetU0w0n/U06H/qHcLUA4sDqTArFoA&f=s1BIU3jUN9Ur2N9PPTpWncsAmR9tGKsTbRSroxBtDCJMdBRMY2PVAQ&i=AwA&r=tryAPL&l=apl-dyalog&m=dfn&n=f) A dfn submission which takes fill element on the left, and ragged array on the right. It calculates the indices of the existing elements and replaces everything else with the fill element. -10, borrowing an idea from Adám's answer. -5 from user. [Answer] # [Functional Bash](https://www.gnu.org/software/bash/)\*, 167 161 147 bytes \* This is bash with the additional constraint that you can't mutate variables. -14 bytes thanks to pxeger ``` m=`sort -n <(awk '{print NF}' $1) <(wc -l<$1)|tail -1` s=`seq $m` paste -d\ $1 <(printf "`printf "$2 %.s" $s`\n%.s" $s)|sed s/^\ //|cut -d\ -f-$m ``` [Try it online!](https://tio.run/##lYw7b8JAEIT7/RUjdHC4WGzzkCgMHZRJkdaK7mJsQGDzuEMUmN/uLAmRolSORtoZjb7ZD@s2TdEPbk05M@5w9uAKSd9ed9C343lbebws7xoqDqS@ZuB9Irn2drsHx4aczPITVGnoaJ3PwasUggv9NS/QMT9BDdEduA6UM2n1TEHt8hVc@J4iDOvs4r8fcMGqbO6UZ5sDtEaNNXo9FGLTZ8nMmiizHkmyeH3D/DdCJFUbcNIWjBBR9LjiLScxhhhh/A@c4ocg@jNqPgE "Bash – Try It Online") The two arguments are: * `$1`: file name containing lines of input * `$2`: The fill character The basic approach is to get the side length of the square (stored in `m`) and then create an `m` x `m` file of the fill, `paste` it with the original file, and take `m` fields from each line. Would love to know if there's a terser approach. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` ≔⌈⊞OEηLιLηζIE…⁺ηEζυζ…⁺ιEζθζ ``` [Try it online!](https://tio.run/##XYu7CgMhFET7/QpLBQN5VluFbRNiLxYisgquGh8h2Z83GmGL3ObcGc4IxYNw3JRyjVHPFt75Wy95gSRH9fAy8ORCLT1UGNyknZOCGqHtV6iFFY0DCdomOPGYfvr0EUZOynlITI5t3doVg9wHGPwZejOe3ag3lkL3eACUHlgFoMeOU8cZgwtjrOxe5gs "Charcoal – Try It Online") Takes the fill as first input and the jagged array as second input, but they can be trivially reversed if necessary. Outputs using Charcoal's default array format, which is each element on a separate line with rows double-spaced from each other. Explanation: ``` ≔⌈⊞OEηLιLηζ ``` Take the length of each element of the jagged array, tack on the length of the array itself, and then take the maximum of the result. ``` IE…⁺ηEζυζ…⁺ιEζθζ ``` Concatenate an array of empty arrays to the jagged array, then chop to the desired length. For each element of that array, concatenate an array of the fill value, then chop to the desired length. Print the result. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṭ`zṖ€ɗ⁺⁹ ``` A dyadic Link accepting a, possibly jagged, two-dimensional array on the left and a fill value on the right which yields a square array which is filled rightwards and downwards with the fill value. **[Try it online!](https://tio.run/##y0rNyan8///hzrUJVQ93TnvUtObk9EeNux417vx/ePnRSQ93zvj/PzraMFaHSyHaCEwag0kTHQXT2Nj/BgA "Jelly – Try It Online")** (Footer added to format the resulting array, so that one can see the empty case work.) ### How? ``` ṭ`zṖ€ɗ⁺⁹ - Link: array, A; filler, F ⁹ - use the right argument, F, as the right argument of: (seems to be required for the ⁺, below) ⁺ - repeat this link twice: ɗ - last three links as a dyad - f(current A, F): ` - use left (A) as both arguments of: ṭ - tack - e.g. [[1],[2,3]] -> [[1],[2,3],[[1],[2,3]]] (only thing that matters is that the tacked list has the length of A) z - transpose with filler (F) -> rectangular array right-filled. Ṗ€ - pop an element off of each (removing the tacked lists) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ ~~17~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2FDªI怨 ``` -9 bytes by porting [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/219050/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##yy9OTMpM/f/fyM3l0CrPc9seNa05tOL//@how1idaCMgNgZiEx3T2FguCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@ZUGyvpJCYlwJk63Ap@ZeWAGWAEjqVCaH/jdxcDq2KOLftUdOaQyv@1@oc2mb/PxoIDHVMdYxjdaJNdEyBpKGOERCaxsbqWMTqKERHx@oYgOlokBCUaQBiRBsgBECajHVMkASA8kZADDMXZFosAA). **Previous 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:** ``` Dª€gà©nи®ô¹ì²ζø®∍ ``` [Try it online](https://tio.run/##yy9OTMpM/f/f5dCqR01r0g8vOLQy78KOQ@sObzm08/CaQ5vObTsM5D3q6P3/PzraMFYn2giIjYHYRMc0NpbLAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@ZUGyvpJCYlwJk63Ap@ZeWAGWAEjqVCaFhEZH/XQ6tetS0Jv3wgkMr8y7sOLTu8JbIw2sizm07DGQ/6uj9r3Nom/3/aCAw1DHVMY7ViTbRMQWShjpGQGgaG6tjEaujEB0dq2MApqNBQlCmAYgRbYAQAGky1jFBEgDKGwExzFyQabEA). **Explanation:** ``` 2F # Loop 2 times: D # Duplicate the current matrix # (which will be the implicit input-matrix in the first iteration) ª # Append the matrix to itself ζ # Zip/transpose; swapping rows/columns, I # using the second input-character as filler €¨ # And then remove the last item of each row # (after the loop, the resulting matrix is output implicitly) D # Duplicate the first (implicit) input-matrix ª # Append the matrix to itself € # Map over each inner list: g # Pop and push its length à # Pop and push the maximum # (we now have the dimension of the output-square, which is either # equal to the amount of rows or amount of columns, whichever of # the two is larger) © # Store this maximum in variable `®` (without popping) n # Square it и # Repeat the second (implicit) input that amount of times as list ®ô # Split it into parts of size `®` ¹ì # Prepend the first input-matrix at the front ζ # Zip/transpose; swapping rows/columns, ² # using the second input-character as filler ø # And then zip/transpose the rows/columns back ®∍ # Shorten the matrix to the first `®` amount of rows # (after which the resulting matrix is output implicitly) ``` [Answer] # [Python 2](https://docs.python.org/2/), 75 bytes ``` def f(M,v):n=max(map(len,M+[M]));print[(r+[v]*n)[:n]for r in(M+[[]]*n)[:n]] ``` [Try it online!](https://tio.run/##RYxLCoMwEIb3OcUsk5pFfUGxeARPMMxCqGJAxxCsbU@fToptYZjH9w@ff23TykWMt2GEUXd2Nw23S//US@/1PLDtMuzImKsPjjfUIcOdTmywYRrXAAEca/lB@lKKj8nNA@SNAvG1jv1900Yd@oiYW6gtlGQBK1nTFFR8qiY5L0p8QtN@VnikpYXqR1JcpPbXpOgN "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal/wiki), ~~15~~ 14 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page) ``` UO⌈⊞OEθLιLθηPθ ``` Matrix-input as a list of string-rows; filler-character as string input; and output as a printed multi-line string, which is allowed based on the first rule. [Try it online (verbose)](https://tio.run/##PYhLCoAgFAD3nSLeSsEg@kCHKGofLSwiBfOXRrd/2abFwMxsgvvNcIU4rsrogwz8kWc8yRQvMdrd82B8mpY4lve7PoIgktLfHf1C0GyIKkjrpQ7pIc4zlMCgStSJpoWF5dDBgsWtXg) or [try it online (pure)](https://tio.run/##S85ILErOT8z5///9nq3v96x/1NPxqGsekPF@z9JzO97vWXNuJ4jYcW77@z0bzu34/z86WslASUfJCIiNgdjEVClWR0HJQikWAA). **Explanation:** Determine the length of each row, the amount of rows, and then only leave the maximum of those combined: ``` Maximum(PushOperator(Map(q, Length(i)), Length(q))) ⌈⊞OEθLιLθ ``` Draw a square of that size, using the second input-character as filler: ``` Oblong(..., h) UO...η ``` Then print the first input on top of that to finish the intended result: ``` Multiprint(q) Pθ ``` [Answer] # [Scala](http://www.scala-lang.org/), 75 bytes ``` a=>p=>{val m=(a.map(_.size):+a.size).max a.padTo(m,Seq())map(_.padTo(m,p))} ``` [Try it online!](https://tio.run/##dU/NCsIwDL7vKXJssI79CSJs4NGDJ73JkKgdTLZa3ZDh2LPPdquCotDwJd9P2lZHKqi/HM7iWMOacgmiqYU8VbBUqnXuVEC2gI247kytZJ2mECegGwNfPPQUJypOWhMrY0ZuSYrt3Sp/CFxMaGw02TjkKjptL6zkOs8QR@OLU4hdr265rAvJMmYspnwOMw4hcgfM1SzS83vQYjCcGSIyD9H5XPCTHAQOo/7P4HHwrOmNmjLs38z4mpBDZDzz3x67LLAYWozsH6Z@EOpg1z8B "Scala – Try It Online") # [Scala](http://www.scala-lang.org/), 108 bytes ``` a=>p=>{val m=a.map(_.size)./:(a.size)(_ max _) Seq.tabulate(m,m)((i,j)=>scala.util.Try(a(i)(j))getOrElse p)} ``` [Try it online!](https://tio.run/##fU9Na8MwDL3nV@gogfHSLxiFBHboYYexw3YbJaidOxzszEvc0a30t2d2YgbdaMHiPT29J@Ruy4b7902tth4eWDegDl41rx3cOXfMPtnAbglP6uMl1n3j12soSggkwh8dei5KV5THGLMFS8sOK9npb0XyZok8UqzA8gEqykJWet7sDXuFVlhC1KKmouziWXLvtZHP7RcyasKa6E35x3ZlOgWOTr1rdeNNgzsMe4aaCFgImJGIl@E8dImGwXR4CyLCW6LsPBzE/J84DMY8XTTkAvJk@sUgRfViZrxmJmB@xZOWTROefSqlTv0P "Scala – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), ~~91~~ 83 bytes ``` wc<I -lL|read l w repeat w-l echo>>I while read i do<<<${(pr/l>w?l:w//$1/)i} done<I ``` [Try it online!](https://tio.run/##HYsxCsMwDAB3vUJDhmQIbtci3KkFQ6BvMI6CDaIJrkGQNG93TbeDu9s/sS79cFQN5HCU6ZvZzyiokHljX1BHAQ5xtdaBxiSM/yLBvBJRd/RbNmL1Ljc1pruaIZ1NvZlcPSH4QvR4PdsbARrAgpf6Aw "Zsh – Try It Online") Works character-wise, taking input from a file `I` and the first command-line argument. This was going to be a suggestion to Jonah's [Bash answer](https://codegolf.stackexchange.com/a/219093), but it became sufficiently different that I thought I'd post it separately. * `wc -lL` - output the number of lines and the maximum line length * `<I` - from the file `I` * `|read l w` - and store those values in the variables `l` and `w` respectively * `repeat w-l` - repeat [the difference between `w` and `l`] times: + `echo` - print a blank line + `>>I` - append that to the file `I` + this adds extra blank rows if needed; because if `w-l` is negative, the `repeat` won't execute at all * `while read i` `do` `done<I` - for each line in `I`: + `${i}` - take that line, and + `(p)` - substituting in the values of `m` and `1`, + `(r/l>w?l:w//$1/)` - pad on the right using the character `$1` to the length `l>w?l:w` - `l>w?l:w` is the maximum line length and number of lines. + `<<<` - and print that line [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~33 32 29~~ 10 bytes ``` 2(:wJ⁰ÞṪvṪ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=2%28%3AwJ%E2%81%B0%C3%9E%E1%B9%AAv%E1%B9%AA&inputs=%5B%5B1%5D%2C%5B2%5D%2C%5B3%5D%2C%5B4%2C5%5D%5D%0A8&header=&footer=) Thanks to lyxal for -23 bytes. [Answer] # [Lua](https://www.lua.org/), ~~205~~ 187 bytes ``` load("t=".. ....."c=#t for i=1,c do c=math.max(c,#t[i])end p=io.write p'{'for i=1,c do for j=1,c do _=j==1 and p'{'p(t[i]and t[i][j]or 0)p(j==c and'}'or',')end _=i~=c and p','end p'}'")() ``` [Try it online!](https://tio.run/##VY3RCsIwDEV/JdSHthCKVfeYLxljlG5ix2bHqCiU@uu1nfhg8pDccG7u/DA5z94MggViSoGqxSwdAlz9Bo40Whg8WFpMuKnFvITFQ2hdJ8f7ACs5r56bCyOsPPI/SxXTT/Q0EWkw1VPAVdQXVdXZTl1hj3IVBbIV4on7jSPfQ3py7@@5eJHvuQVgUsicc4waoUE4J4yXspWh8VS6SekD "Lua – Try It Online") ### Human readable code: ``` load( "t=".. ..... "c=#t for i=1,c do c=math.max(c,#t[i]) end p=io.write p'{' for i=1,c do for j=1,c do _=j==1 and p'{' p(t[i]and t[i][j]or 0) p(j==c and'}'or',') end _=i~=c and p',' end p'}' ") () ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 16 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ⁸)⁸∔0;{LM}⁷;:*⁸n ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyMDc4JXVGRjA5JXUyMDc4JXUyMjE0JXVGRjEwJXVGRjFCJXVGRjVCJXVGRjJDJXVGRjJEJXVGRjVEJXUyMDc3JXVGRjFCJXVGRjFBJXVGRjBBJXUyMDc4JXVGRjRF,i=JTVCJTIyYWFhYWElMjIlMkMlMjIlMjIlMkMlMjJjJTIyJTVEJTBBJTIyeCUyMg__,v=8) Takes an array of strings and a filler string as input. [Answer] # [Julia](http://julialang.org/), 82 bytes ``` f(a,b,L=max(length.([a;[a]])...),B=fill(b,L))=[(x->[x;B][1:L]).(a);fill(B,L)][1:L] ``` [Try it online!](https://tio.run/##VY7BqsIwEEX3@YrBVQbG0mp1Yalgd4J/kJdFxFYjMUoboSLv2/umqW9hCGeScy8h16ezJuuHoZGGjnQob6aXrvbncEmkMoUyWmOSJEhV2VjnJHcQSyX7@Vb1RaVVtjlwQxosYl5xPskh1F3ooIRd25rXe@Leh3VO2S9vJYTSxBgJSk/n1WemBGn0H/J1NFOYESwIlgT5v4ilReQyMifgp4Tg3dxbGP8C1sfZCeB1st3DmZccDUbzaK0Pzkv8ypvYoBS/S7MfP0NR@9PwBw "Julia 1.0 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 83 bytes ``` def f(l,v):x=max(map(len,l+[l]));return[a+[v]*(x-len(a))for a in l+[[]]*(x-len(l))] ``` [Try it online!](https://tio.run/##dY3dCsIwDIXv9xS5TFwE3Q@I4pOUXBRscdB1o8wxn77WVUQFIZCcfOdwxvt0HXwd48VYsOh4puNy7vWCvR7RGc@uVE6ITsFMt@CVLtUsG1y2iaEmskMADZ2H5FPyJo5I4hg6P6FFVQCoPUPLUAs/RZNEvtK7WqeVQhgORMVXLLtWtvtlOVszNH94Dld5fVa/7PEB "Python 3 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/) with `-m32`, ~~173~~ 163 bytes Thanks to ceilingcat for -10. Takes an `NULL`-terminated array of strings and fill character, and returns a `NULL`-terminated array of padded strings with number of rows equal to the string length. The function scans each string to find the longest length, then creates a destination array of the largest of the row count and maximum string length, plus 1. For each row, a string containing the fill character is allocated and generated, with the original string contents (minus the trailing `NUL`) then copied over the new string. The generated array is then returned to the caller. ``` *b,r,c,l;f(s,f)int*s;{for(r=c=0;s[r];)c=fmax(strlen(s[r++]),c);for(c=r=r>c?r:c,l=b=calloc(c+1,4);r--;*s?*stpcpy(*b,*s++)=f:0,b++)memset(*b=calloc(c+1,1),f,c);s=l;} ``` [Try it online!](https://tio.run/##hZDNbsMgDMfveQqUaRoQMqUfu5TRvkC17bJTmgMloY1E0grItKrKqy8z7Q5TtXZIWOZv@2djlW6UGga6ZpYpZrjGjmlSt546ftQ7i61QIuMutwUnSuhGfmLnralaDFqSFIQpwkOiElbYuVrYGXDEWihpzE5hlYzYlHCbppy6BXV@r/YHDP2oSxIi9Cxja3CaqnGVB/133YgwHfBOGN4Pd3WrTFdW6Nn5st49budRBIOiRtYt/tjVJUHHCCG1lRZR6vJChCdCOCg0L8gRvbwvl6hnl3Ics9O9Fn66EcuyUHw2J/9a4mg8md4KB8I4mEkw08uewQenZ/A36oPteARCWL0XjiPqOdp33uE4DWfVxoQhD6tF5zWExHP81dabupUGSWvlYbZqTwUhvROBAmSC9hZ2q3Gc37sCWNCwAxa/QP20epNlWZV/8TSGYR@yB/Ivto/64UtpIzduSE0zpM1k/A0 "C (gcc) – Try It Online") [Answer] # [Japt](https://ethproductions.github.io/japt/), 14 bytes Takes an array of strings plus a single string as input, outputs an array of strings. I spent five bytes finding the length of the longest string in the input, I would expect that to be somewhat crunchable. ``` úV ÕúVUñÊo Ê y ú // Right-pad every item in the first input to the length of the longest one V // using the second input. Õ // Transpose the rows with the columns, ú // then right-pad every item again as above, except this time Ê // pad to the length ñÊo // of the longest item (sort by length, get the last item) U // in the first input V // using the second input as padding. y // Finally, transpose back and implicitly output the result. ``` [Try it out here.](https://ethproductions.github.io/japt/?v=1.4.6&code=+lYg1fpWVfHKbyDKIHk=&input=WyIxMjMiLAogIjEyMzQiLAogIjEyIl0KIjgi) [Answer] # [Husk](https://github.com/barbuz/Husk), ~~13~~ ~~14~~ ~~12~~ 14 bytes *Edit: +1 byte to fix bug, then -2 bytes using a different approach, but then +2 bytes after realising we need to provide the fill-value as an argument* ``` ₁₁²¹ T⁰ż+³RøLT ``` [Try it online!](https://tio.run/##yygtzv7//1FTIxAd2nRoJ1fIo8YNR/doH9ocdHiHT8j///@jow11jGJ1QKSOMYzWMYmN/W9pCQA "Husk – Try It Online") **How?** ``` ₁₁ # apply helper function ₁ twice # helper function: T0 # transpose, padding with zeros, ż+¹ # input list zipped by element-wise concatenation with Rø # a list of empty lists, LT # as long as the longest list in the input list ``` --- Note after reading the other answers: I realised that a port of [Jonathan Allan's approach](https://codegolf.stackexchange.com/a/219050/95126) is 1 byte shorter at [~~11~~ 13 bytes](https://tio.run/##yygtzv7//1FTIxAd2nRoJ1duScijxg1WuecWH9r8////6GhDHaNYHRCpYwyjdUxiY/9bWgIA)... [Answer] # [APL](https://www.dyalog.com/), ~~34~~ 30 bytes ``` {M↑M↑¨(,∘S¨⍵),M/¨S←⍺⍴⍨M←⌈/⍴↑⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/2vdR20QQPrRCQ@dRx4zgQyse9W7V1PHVP7Qi@FHbhEe9ux71bnnUu8IXxOnp0Afx2iYC1dT@TwMKUaCf61HfVKCggULao941KBxUfttkQwVDoDZTqJiFQpqChqGCqYKxpoaJgqkmkG0EhKaaUHljiLyRJoL4DwA "APL (Dyalog Classic) – Try It Online") Might as well put my own APL answer here, even if it is longer than Adám's. Takes vectors of vectors, and outputs vectors of vectors. The output with `[]` is a little funky as a result of this, the output is still `[]`, but it would be something akin to an empty vector of vectors. -4 bytes thanks to looking at a portion of Razetime's answer. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 80 bytes ``` a=>v=>a.map(g=A=>A.map((_,i)=>A.map((_,j)=>x[j]=x[j]||v,x=a[i]=a[i]||[])))&&g(a) ``` [Try it online!](https://tio.run/##fU7LCoMwELz7FTlJFlJpfUAvG/A7QiiLVVGskVrEQ/491aQHD1JYZmeWmWF7Wmiu3t30uYzmWbsGHaFcUFLyoom3WKIsPeUP0cFB9JtYVa9xB2sXsSKpTnuwVmkAiOOWE7jKjLMZ6mQwLW@4ihhTN8EKwTItdpFvIrDtnPopdKSB3wGik3Dwesf13BF6MsHyv65QlIZ1fOYXcl8 "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 82 bytes ``` a=>v=>[a,...a].map(A=>A.map((_,i)=>A.map((_,j)=>x[j]=x[j]||v,x=a[i]=a[i]||[])))&&a ``` [Try it online!](https://tio.run/##fU7LCoMwELz7FTlJFrah9QG9RPA7QiiL1aJYI1rEQ/491aQHD1JYZmeWmWE7Wmiupnb8XAbzrF0jHclikYUiFEKQFm8aeSmL0hP@wBYOotvEqjotd7B2wVWSarUHa5UGgDgmV5lhNn0tevPiDVcRY@qGLEeWatxFtonAtnPiJ9eRBn4HiE7Cwesd13NH6EmRZX9doSgJ6/jML@S@ "JavaScript (Node.js) – Try It Online") Can omit `&&a` claiming return to where `a` was [Answer] # [Go](https://go.dev), 144 bytes ``` func f(L[][]int)[][]int{d:=len(L) for _,e:=range L{if len(e)>d{d=len(e)}} for j,e:=range L{for i:=len(e);i<d;i++{L[j]=append(L[j],0)}} return L} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVBLasMwFNzrFA-vLKLGaT5QnLqbbr3oPphibMkotWUjOxB46A7ddxMKPVTO0QtUkkUTkJ5mRiNpnr6-m_5yTYey-igbDl0pFZHd0OtpGYluiv5J07elapa9bpJzws9DMray4mP0c5rEw9P1U5xUBSLOD8WhkGqiYcU6zVqu4pwS0Wt4ZzzNtL2IQ45SgNvi9KXGOpuhMd53vPc5QabBsJfP9V4uFpgfjkVWDgNXdewwW7nDmk8nrSA3Idevz-XaiikgqcqRj5Bm4OLNAQniI4Mdg41hBHBrsQdWXPuxM5ajm7agJzhruGKw8uZQLXWK35vPbxhsA_eWta93T1lkwtdULtjctM-JRConvba94nFFyZu2gVt1D0UsFb1Rai8LrV8u8_oH) ]
[Question] [ [Robbers' Thread](https://codegolf.stackexchange.com/questions/231322) Your challenge is to find an existing challenge, and implement it in a way such that certain inputs fail. At least one input must not produce the correct output (use the other submissions on the challenge as a reference for this, but be sure to double-check). This must fail *consistently*, and you must know at least one input that fails. The challenge must satisfy the following: * +10 net score * Open * Not language-specific * Posted before 8 Jul 2021 * Unlocked * Not [tips](/questions/tagged/tips "show questions tagged 'tips'") * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") * Have at least 3 existing answers The robbers will be trying to find an input which fails. You must share the challenge, the language and your code. If a robber has not cracked your solution after a week, it is safe and you can reveal your failing input. You may specify bounds - for example, you can say that inputs must have less than 20 digits, as long as there is an invalid value within those bounds. You should also say that input is a string/list of numbers/number/tuple/whatever. # Scoring Your score is the length of your shortest *safe* program, in bytes, with shorter being better. You are allowed to post multiple submissions. [Here](https://data.stackexchange.com/codegolf/query/1434981/valid-questions-for-it-almost-works)'s an SEDE query for valid questions kindly provided by [fireflame241](https://codegolf.stackexchange.com/users/68261/fireflame241). [Answer] # [Python 2](https://docs.python.org/2/), 120 bytes, [“DDoouubbllee ssppeeaakk!!”](https://codegolf.stackexchange.com/q/188988/88546), [cracked](https://codegolf.stackexchange.com/a/231460/88546) by [Sisyphus](https://codegolf.stackexchange.com/a/231460/88546) ``` import re def f(s): try:s=re.search('[a-z]{4}|[^a-z()]',s)<0<eval(s)=='hax'or s except:0 return''.join(c*2for c in s) ``` [Try it online!](https://tio.run/##DY3LDoIwEEX3fMW4mtYoIcQVgZ1/QTCpdQhVbJtpMeDj22t3d3HOuX6Lk7N1SubpHUdgKm40wiiCbAqIvDWhYyoDKdaTwF4d38Pn9Pv2l7yEHPAQZFu19FJzVroOJ7WiYwgF0KrJx6YqcjQubBHLuzNW6H09ZkKDsRBk8mxszId4dst1Jgie1GOHMv0B "Python 2 – Try It Online") As in the question, only printable ASCII are allowed as input. ([Guess my password](https://codegolf.stackexchange.com/q/213962/88546) is possibly a better fit for this challenge, ¯\\_(ツ)\_/¯). --- The cracked solution used a Python bug to segfault the program. I'll reveal mine in two days, but before then I'd love to see if anyone can figure out a solution closer to what I had intended. ~~As an incentive, I'll offer +50 rep to any new answer which cracks this before the two days. In particular, it must not produce an error on the line containing `s=...`, regardless of whether it gets caught.~~ --- **No one found my intended solution, so here it is**: > > `max(max(dir()for(hax)in(dir)()))`, [Try it online!](https://tio.run/##FY3NCoMwEITveYrcdre0ItKT1CcRCyFGTKkxbNKi/Xn2dHsYmIFvZuKe5zU0pfglrpw1OzW6SU@YqFU6896mjl2VnGE7I/Tm9Bre5@@nv4pDGuCY6FJf3NPcpdJ1MJsNVtZJabdZF3NbKxnNDw4A1W31Ae2hmYSw2gedqET2IcshLGbDv0bPSEKgTJHwkgmJCKj8AA "Python 2 – Try It Online") > > > And here is an explanation: > > First, let's determine what is expected of us to solve this challenge. We must input a Python expression, such that it evaluates to the string `'hax'`. The regex also places two restrictions upon us: only letters and parentheses are allowed, and there can be no consecutive substring consisting of four letters. > > > These restrictions don't leave us with many options. We're essentially being limited to a small set of builtins (e.g. `max`, `chr`), and a few basic constructs like `for` or `and`. I've so concluded that most of the obvious approaches are very unlikely to succeed. You may or may not have noticed that the target string, `'hax'`, exactly matches the regex; this tiny detail is a crucial one. > > > I've teased you long enough, so let's begin dissecting the solution: > > `max(max(dir()for(hax)in(dir)()))` > > > Some of the parentheses used here are only to ensure that no spaces exist in our program. Removing the extra obfuscation, we get: > > `max(max(dir()for hax in dir()))` > > A lot easier to read! > > > Within all the `max`s, there is a list comprehension, which iterates through `dir()` using the variable `hax`. The `dir()` is completely arbitrary, anything will work as long as we can loop over it. For each iteration in the comprehension, we store the result of `dir()`. When no arguments are given like this, it returns a list of names in the current local scope (see [**`dir`**](https://docs.python.org/2/library/functions.html#dir)). As a result, the entire comprehension contains `[['.0', 'hax'], ['.0', 'hax'], ...]` Note that the `.0` is a "secret" variable which stores the list comprehension itself. > > > We are now 90% of the way there! By calling `max` once on the result, we obtain a single copy: `['.0', 'hax']`. Calling it once more, we finally get our result: `'hax'`. > > > [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes, [Is it double speak?](https://codegolf.stackexchange.com/q/189358/66833), [Cracked](https://codegolf.stackexchange.com/a/231325/65836) by [Stephen](https://codegolf.stackexchange.com/users/65836/stephen) ``` ṾḊṖ⁼2/Ạ ``` [Try it online!](https://tio.run/##y0rNyan8///hzn0Pd3Q93DntUeMeI/2Huxb8//8/JCQjIzOzuFhBAUKmpOTnl5YmJeXkpKYqKBQXFxSkpiYmZmcrKgIA "Jelly – Try It Online") Given how difficult Jelly can be to understand, I've provided an explanation to help the Robbers: ``` ṾḊṖ⁼2/Ạ - Main link. Takes a string L on the left Ṿ - Uneval L. This makes sure we're processing a string, as Jelly can try to evaluate the input if it's all digits ḊṖ - Dequeue and pop. Remove the quotes that Ṿ puts around the string 2/ - Split into chunks of 2 (e.g. [A, B]), then over each chunk: ⁼ - Is A equal to B? Ạ - Is this true for all A? ``` --- Note that this wasn't my intended crack. Another answer incoming [Answer] # [Taxi](https://bigzaphod.github.io/Taxi/), 1134 bytes, [Draw an asterisk triangle](https://codegolf.stackexchange.com/q/95780/65836), [Cracked](https://codegolf.stackexchange.com/a/231342/65836) by [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string) ``` Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to The Underground.'\n'is waiting at Writer's Depot.Go to Writer's Depot:n 5 l 2 l.Pickup a passenger going to Rob's Rest.Go to Rob's Rest:n 1 r 1 r 1 r 1 r.[a]Pickup a passenger going to KonKat's.'*'is waiting at Writer's Depot.Go to Writer's Depot:s 1 l 1 l 1 l 1 l.Pickup a passenger going to KonKat's.Go to KonKat's: n 3 r 2 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 2 l.Pickup a passenger going to Post Office.Pickup a passenger going to Rob's Rest.Go to Rob's Rest:s 1 l 1 r 1 r 1 r.0 is waiting at Starchild Numerology.Go to Starchild Numerology:s 1 l 1 r 2 l.Pickup a passenger going to Magic Eight.Go to Post Office:w 1 r 2 r 1 r 1 l.Go to The Underground:n 1 r 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:n 3 l 2 l.Pickup a passenger going to The Underground.Pickup a passenger going to Magic Eight.Go to Magic Eight:s 1 l 2 r.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:s 2 l 4 l.Go to Rob's Rest:w 2 l 2 l 1 r 1 r 1 r.Switch to plan "a". ``` [Try it online!](https://tio.run/##nVOxTsMwEP2VU5dIDBa0sGQsIIYKqFoQAzC4ydU5YezIdhv69cFp4pBGiJQOJ8tn37t3z8@Of1FZ3mlwGubaOnhcrynBuIALkD5MtbI5JR@bHDjk3FpUAg0ITUpUVU8ZwpSvUK7JZmh2rAbrp2MbEAfRnlWKRhi9USmL3lREFgpOrrrBHbwYcmgiCzeYa9d0O0zGCq58r/EA84Ve@YoF2oDyk/AI9extsFf@/hfYTKsZd5Fl0dkJhIM4bbCjetVYYRuDgolnOx7Q@HqXSK2wqW52@4mHNet45GRtbcdbtbbncCjZ0nGTZCRTeNh8otFSi@Cr3446iEP877mgBG5JZIFY3/V7/Vrn/5i548rWHfIknSdH6Nz/B/@bqZNptBnyxIK2aLaEBUwNpSKQ7qc9mmcOl60ynWct9kfj3tMuC3JJVl3NJVcw4iNWlt8 "Taxi – Try It Online") Terminates by error. Prints leading newline (allowed by linked challenge, [see comments](https://codegolf.stackexchange.com/questions/95780/draw-an-asterisk-triangle#comment233242_95780)). Always fun to bang my head against Taxi's map :D [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes, [Make a ;# interpreter](https://codegolf.stackexchange.com/q/121921/66833), [Cracked](https://codegolf.stackexchange.com/a/231338/66833) by [Stephen](https://codegolf.stackexchange.com/users/65836/stephen) ``` ṣ”#Ṗċ€”;%Ø⁷Ọ ``` [Try it online!](https://tio.run/##y0rNyan8///hzsWPGuYqP9w57Uj3o6Y1QLa16uEZjxq3P9zd8///fyVr8oEyGWqUAA "Jelly – Try It Online") Since the challenge was first posted, Jelly's had a few updates, including some nice new nilads (`127` \$\to\$ `Ø⁷`) to save a byte :) [Answer] # [Python 3](https://docs.python.org/3/), 252 bytes, [Is this number a prime?](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime), [cracked by ovs](https://codegolf.stackexchange.com/a/231403/64121) ``` I=int(input()) L=I<2 l=int('1ecvme02wjate5lzjhukn4elhetiycct0crct68uhrtiafbxxfcmvqjvz',36) while l: i=I;j=J=l&131071;_=1 while j: while~j%2:j>>=1;_*=1|-(i&7in(3,5)) j,i=i,j;_*=1|-(j&3==i&3>2);j%=i L+=pow(J,~-I>>1,I)!=(i<2)*_%I l>>=17 print(L<1) ``` [Try it online!](https://tio.run/##Nc/RboIwFAbg@z5FdwG2riaUTlmEw30N72C0qeF0FRkpoGbx1RnO7O7k/5I//2lvob40apo0YBMYNm0fGOekAl2kxP@FC2nNcLZJOrpDsGt/d3X/1XxYX9uAN2NCYjoTNp993QU8nI7X68mch2833BdCbTgZa/SW@i2hCDp3sAMfSyWTTOZ7kIS@3M3@Oh8uSreuLGH2JcifFcM4w4YpsZ6XUeoEAgr3jy5WABirMuW5iwAJrd6hvYxsJx4rXZZSaP4GDIuUL/eRJtQ/qzPSds/nqkLyaUp/AQ "Python 3 – Try It Online") Inputs should be positive integers please. I don't expect this to be cracked (prove me wrong!) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes, [Is it double speak?](https://codegolf.stackexchange.com/q/189358/66833), [Cracked](https://codegolf.stackexchange.com/a/231331/66833) by [hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino) ``` ṾḊṖŒœE ``` [Try it online!](https://tio.run/##y0rNyan8///hzn0Pd3Q93Dnt6KSjk13/H25/1LTm/38ldSUdBaWQkIyMzMziYgUFCJmSkp9fWpqUlJOTmqqgUFxcUJCampiYna0EAA "Jelly – Try It Online") My last answer got cracked due to weird `2/` behaviour, so here's a golfier version. I've got the explanation as well: ``` ṾḊṖŒœE - Main link. Takes a string L on the left Ṿ - Uneval L. This makes sure we're processing a string, as Jelly can try to evaluate the input if it's all digits ḊṖ - Dequeue and pop. Remove the quotes that Ṿ puts around the string Œœ - Odd-even. Group the elements at even indices, and those at odd indices E - Are they both equal? ``` --- `Ṿ` (uneval) will surround a string with `“...”`, which `ḊṖ` will remove. Unless the string has `“` in it, in which case it will treat each character in the string as a char literal `”x` and will join them by commas: `“abc` `Ṿ` is `”“,”a,”b,”c` [Answer] # JavaScript, 163 bytes, [Hello, world!](https://codegolf.stackexchange.com/questions/55422/hello-world), [cracked](https://codegolf.stackexchange.com/a/231339/65836) by [Stephen](https://codegolf.stackexchange.com/users/65836/stephen) ``` n=>{if(typeof n=="object"||n-32!=n-32)return "Hello, World!";var d=n-32;return [40,69,76,76,79,12,0,55,79,82,76,68,1].map(x=>String.fromCharCode(n-d+x)).join("")}; ``` Small byte save by offsetting the char codes by 32. **Intended crack:** > > > ``` > (() => { > var f = x => x; > var i = 0; > > f.valueOf = () => i++ < 2 ? 0 : i; > > return f; > })() > ``` > > This is a function which will return `0` the first two times it's cast to a number (to bypass the initial checks), then return an incrementing value. It results in an output of `Igopt2'_x|wp.`, instead of the correct one. > > > > > [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes, [Shortest code to determine if a string is a palindrome](https://codegolf.stackexchange.com/questions/11155/shortest-code-to-determine-if-a-string-is-a-palindrome), cracked by [A username](https://codegolf.stackexchange.com/questions/231321/it-almost-works-cops-thread#comment530154_231341) ``` Ǎ⇩Ḃ= ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C7%8D%E2%87%A9%E1%B8%82%3D&inputs=Helloolleh&header=&footer=) Returns `1` for palindromes and `0` for non-palindromes. The challenge states that numbers affect palindrominess, but as A username pointed out, this ignores numbers. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes, [Least common multiple](https://codegolf.stackexchange.com/questions/94999/least-common-multiple) ``` Π?ġ/ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CE%A0%3F%C4%A1%2F&inputs=%5B56%2C122%5D&header=&footer=) Cracking it should be easy, so no Hints [Answer] # [Python 3](https://docs.python.org/3/), 580 bytes, [Simulate a Rubik's cube](https://codegolf.stackexchange.com/q/92404/53748) - Safe! Not going to win by byte count but maybe it'll make for an enjoyable rob. ``` import re exec("d,*r=[[f]*9for f in' YBRGOW'];u,q,v,p,s,w,x,y,z=lambda v:[v[x],y(y(y(v[z]))),v[s],y(v[q]),v[0][::-z],v[p][::-z]],3,lambda w:[y(w[0])]+[w[j%p-~all(s<len(set(f))for f in w)][:q]+w[j][q:]for j in(z,x,q,p)]+[w[s]],4,5,lambda u:[y(u[0])]+u[x:s]+[u[z],y(y(y(u[s])))],2,lambda f:[f[int(v)]for v in'630741852'],1;r="+"(r);r=".join("".join("uuuvu v uuvuu wwwuvuuuw uvuuu wuvuuuwww".split()[778194%ord(t)%9]*(ord(n or'y')%6)for t,n in re.findall("([B-U])(['2i]?)",input())))+"(r);y=' '.join") for u in[d,r[0]],r[z:s],[d,r[s]]: for w in 0,q,6:print(y(y(v[w:w+q])for v in u)) ``` A full program reading a valid move sequence from STDIN that attempts to print the net of a Rubik's cube scrambled as instructed. I'll also specify a bound of 20 face turns :) **[Try it online!](https://tio.run/##NVFNi9swEL3nVwhDkJRMQr422WgbCnvppVBYKKUMOqRrm3Xw@kO2pNiH/vXsyIkt8MxYT@89P1Vd@1EW29st@6xK0zKTTJJr8i6iGGbmhJjq2TEtDUtZVnD29/Xtx68/XL9YqMFBBQ14uEIH/Sk/f/6Lz8wpdHjV0ImwHPZaSgkOm/DJYa3DsNKo1KLX1FaPVsMWHhReYSc8gaSeo8fLtFr8P@e5aL7lSSGapBWplKMn5iUx1HpOQI210mHjQhuiJ2M1VHeShgR28DRK2CBh7xIWr6ohkCWvD9uW8GRbw2Y8kCpMMSta4eSg4EIc@@3qsFs/P224hvWLOUXzSBgZmuWlJAfRWK21ztKZUCzz3odqPRsKe0zeR8umyrNWSDwcntfH3bQ0sWjl9KhnIrQFKw3vuJzuh99voQgBmGSZZkUcEooEvi5@aymQbzL9XUaQFZUlQnru3roTZ3xwFclJILFEgTEYykLTu6coYJgpMTVhAeKDyoqy3KvKhAzuN@uVn9N1jmkwK@Xt9rb5yb8A "Python 3 – Try It Online")** Or see a few working ones [here](https://tio.run/##TVNtq9owFP7urwgBSaJRtHr1mjsZiNxx4cKgIGNk@eBuW1bRtrZNYx3bX3fnpApr4bzl5DxPn6RFW//Ks9ntI4/iNWPsxy09FXlZkzLuxZf4g9NIDsq11okZrJK8JAlJM0a@b8IvX78x82LlWTaykJV08iJbeV0f96ef0Z40Sjf6YmTL8W301QghZKMrLDX6bDCZGK3U6GogLO6hkTN5H@GUbrmDJmGG2ulDvxj93R@PvPp0jDNexTVPhHhwIk7AhLMZQqPRZ2Vw4QAL/ArEzrLohlQAMJdPDwiLELaDsPqiKmiywPVO20I/0DYyeGxIlE50mtW8ER6hQTkWs8lyPn1@CpiR05dyTYeUlwKD8SEHBvThrbWNhT3oLHHOobeOeEfumXN0XBXHtOZCL5fP09W8n5cRr0V/ZQYcw4zkJWuZ6C/859cyQwHKeJykWYQKUa43o50RXLMgNZ8FlWlWWBgIT8etXTPCPCsqejjEwggdyRK0MGCvIIX0OSimegRbHKJMQMuFKkrUoDtZp9wQjvOhBrFC3OAm9XoesyJroimVhO68Sb0N0L4ztGFXeGdbDLbbwPtdGLxuwk0QwgpatmVQCRkku@A1oMaTrhCvgwGO8Pj4fgUVqXyt48recEnR338oG8Pe077mlRC@w190/APEfxvE7R8 "Python 3 – Try It Online") (the last one places the cube into the [Superflip](https://en.wikipedia.org/wiki/Superflip)) ### Failing inputs > > The simulator performs a quarter-turn of a face by rotating the entire cube as need be, turning the cube's "U" face a quarter-turn, and rotating back. To turn the "U" face it permutes the stickers on the face and, separately, the stickers around the "U" face's edge, on the "L", "F", "R", and "B" faces. The latter is performed by concatenating two slices, but the code: > > `...+[w[j%p-~all(s<len(set(f))for f in w)][:q]+w[j][q:]for j in(z,x,q,p)]+...` > > should be: > > `...+[w[j%p+z][:q]+w[j][q:]for j in(z,x,q,p)]+...` > > ...or with less obscured code: > > `...+ [faces[j%4+1][:3] + faces[j][3:] for j in (1,2,3,4)] +...` > > i.e: > > `...+ [first_3_of_previous + last_6_of_current for LFRB] +...` > > > > This is only the case when `all(s<len(set(f))for f in w)` is `False` (`~False = ~0 = -1-0 = -1`) > or, equivalently, when: > > `all(5 < len(set(stickers)) for stickers in faces)` > > > > Otherwise `~all(...)` evaluates to `~True = ~1 = -1-1 = -2` and stickers are copied from the wrong faces for this band (instead of using the first three stickers of each of the FRBL faces to fill the LFRB band it uses the first three stickers of each of the RBDF faces. > > > > > > [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes, [Stack Exchange Vote Simulator](https://codegolf.stackexchange.com/questions/63369/stack-exchange-vote-simulator), [Cracked](https://codegolf.stackexchange.com/a/231330/100664) because I misread the challenge ``` C⁽꘍R:£80>[¥₁-±N|0 ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=C%E2%81%BD%EA%98%8DR%3A%C2%A380%3E%5B%C2%A5%E2%82%81-%C2%B1N%7C0&inputs=%27%5Evv%27&header=&footer=) ~~Just to start things off. I feel this will get cracked very easily though.~~ I misread the challenge. My intended crack was an empty string - Vyxal barfs on reducing empty lists/strings. Input is a string of `^v`. Here's an explanation: ``` C # Charcodes R # Reduced by... ⁽꘍ # Bitwise xor :£ # Store a copy to register 80>[ # If it's over 80 ¥₁- # Subtract 100 ±N # Get the sign negated |0 # Else return 0. ``` Hint: The bug's in Vyxal itself, not my code. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `Ṡ`, 0 bytes, [Simple Cat Program](https://codegolf.stackexchange.com/questions/62230/simple-cat-program), cracked by [A username](https://codegolf.stackexchange.com/a/231334/100664) [Try it Online!](https://lyxal.pythonanywhere.com?flags=%E1%B9%A0&code=&inputs=Hello%2C%20Waffles!&header=&footer=) [Answer] # [Python 3](https://docs.python.org/3/), 71 bytes, [Convert YYYYMM to MMMYY](https://codegolf.stackexchange.com/q/83591/55372), cracked by [SevC\_10](https://codegolf.stackexchange.com/a/231351/55372) ``` lambda s:" JFMAMJJASONDAEAPAUUUECOENBRRYNLGRTVC"[int(s[4:])::12]+s[2:4] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYSknBy83X0dfLyzHY38/F0dUxwDE0NNTV2d/VzykoKNLPxz0oJMxZKTozr0SjONrEKlbTysrQKFa7ONrIyiT2f0ERSCJNQ93IwNDMwERdU/M/AA "Python 3 – Try It Online") Probably way too easy, but worth a try. [Answer] # [Python 3](https://docs.python.org/3/), 119 bytes, [Simple cat program](https://codegolf.stackexchange.com/questions/62230/simple-cat-program) ``` while 1: i=input() if 1583454170589139748634332997977758356543730781438558028881854463983253%ord((i+'e')[0]):print(i) ``` [Try it Online!](https://tio.run/##DcnBCoMwDADQe7/Cy7Bll9YkJhX2JWO36QyUVrQy9vWdtwdv@9W1ZGjtu2qauzCZTh@at7Nad3HpAgkgYWBPEgNERhkBAYYYOTLz1TQSAoNnCQhCJH4QkSCEOEIUGAhuZX9bq/d@7t3Tv9y07ZqrVddanY@q@WOWMxtT95KSSSX9AQ) It's not the prettiest or the shortest, but I'm hoping it at least takes you all a second to figure it out. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), [Generate Recamán's sequence](https://codegolf.stackexchange.com/q/37635/53748), [cracked](https://codegolf.stackexchange.com/a/231372/53748) by [pajonk](https://codegolf.stackexchange.com/users/55372/pajonk) ``` ạLṪḟȯ+L$Ṫ;@ Ç¡Ṗ ``` A full program that accepts a non-negative integer, `n` and attempts to print the first `n` terms of the Recamán sequence. **[Try it online!](https://tio.run/##y0rNyan8///hroU@D3euerhj/on12j4qQKa1A9fh9kMLH@6c9v@/oQEA "Jelly – Try It Online")** Shouldn't prove at all difficult to crack. --- > > This actually implements [A335299](https://oeis.org/A335299), which first differs from Recamán's sequence at \$n=57\$ for which this gives \$27\$ instead of \$87\$ due to the code using the absolute difference instead of (a) performing subtraction and (b) ignoring negative values. > > > [Answer] # [Python 3](https://docs.python.org/3/), 74 bytes, [Is this number a prime](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime), [cracked](https://codegolf.stackexchange.com/a/231384/10894) by [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper) ``` x=int(input()) print(x>1 and next(d for d in range(2,x+1)if x/d==x//d)==x) ``` [Try it online!](https://tio.run/##FcdBCoAgEADAe6/Yo0uBmFgn@4uwWl5WEYPt9VanYerTr8J2DPGZu8pc764Qp9r@ymEgMAFH6YoglQYEmaEFPqNaF5kN5gSiyXvRmvADx9ics/sL "Python 3 – Try It Online") [Answer] # JavaScript, 151 bytes, [Is this even or odd?](https://codegolf.stackexchange.com/questions/113448/is-this-even-or-odd), [cracked](https://codegolf.stackexchange.com/a/231391/79857) by [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) ``` x=>{var b=[...x.toString(2)].reverse()+"";try{eval.call(window,(t=y=>y?t(y/256n)+String.fromCharCode(Number(y%256n)):"")(x))}catch{};return +[...b][0]} ``` Input must be a positive bigint. **Intended Solution:** (similar to Bubbler's): > > > ``` > 3615512360242432329658769258555380793536772285803851385241947165871497272426648554788915044798172040751481373577054244237102559357n > ``` > > This is a representation of the payload: > > ``` > String.prototype[Symbol.iterator]=function*(){yield 0} > ``` > > This results in `[...b]` always returning `[0]`, so the input (which is odd) results in the output returned for even numbers. > > > > > > > [Answer] # [Pip](https://github.com/dloscutoff/pip), 11 bytes, [Output a string's cumulative slope](https://codegolf.stackexchange.com/q/94519/16766) - Safe! ``` Yq$-A[RVyy] ``` [Try it online!](https://tio.run/##K8gs@P8/slBF1zE6KKyyMvb/f4/UnJx8HYXy/KKcFEUA "Pip – Try It Online") (The crack also works on TIO.) ### Explanation ``` Yq Read a line of input and store it in y [ ] Make a list containing RVy y, reversed y and y A Get the ASCII value of (the first character of) each of those strings $- Fold on subtraction ``` --- Failing inputs: > > `00`, `000`, `.0`, and in general anything that looks like a numeric literal for `0`. These inputs do not output anything. If you turn warnings on using the `-w` flag, [you'll see](https://tio.run/##K8gs@P8/slBF1zE6KKyyMvb/fwOD/7rlAA) a warning "Cannot take ASC of empty string." > > > Why? > > It's an interpreter bug which was fixed in [this commit](https://github.com/dloscutoff/pip/commit/e5680daef6fce85e6206ae311e62250c8009c321#diff-b1534f3f58d78f527c22bf15c92758355aa12b1dfb5d799852f36880fa0c6487L708) (thus the requirement to use the TIO version of Pip). > > > > When I wrote the code for the `A` operator, I wanted to raise a warning and return nil if the operand was an empty string. So I started by testing whether the operand was falsey. I must have been thinking about Python strings, which are only falsey if they're empty; but in Pip, strings and numbers are a single type, Scalar. A Scalar is falsey if it is the empty string *or* if it is zero. Thus, the implementation of `A` choked if you passed it `0` or any other literal for zero--a [pretty annoying bug](https://tio.run/##K8gs@P8/Xq9YzzFewVchwPH///@65TkA). > > > [Answer] # [Python 3](https://docs.python.org/3/), 63 bytes, [Is this number a prime](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime), [cracked](https://codegolf.stackexchange.com/a/231374/10894) by [pppery](https://codegolf.stackexchange.com/users/46076/pppery) ``` lambda x:next(d for d,_ in enumerate(iter(int,1),2)if x%d<1)==x ``` [Try it online!](https://tio.run/##DcjBCoAgDADQX9kl2MBLSQWRfxKE4SShVsgC@3rrHd/96n6JrdEt9fDnFjyUSbgoBohXhmBWSAIsz8nZK2NSzphETUumoxShNGFuyblS7/w/Rhz63o5E9QM "Python 3 – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 40 bytes, [Find the first word starting with each letter](https://codegolf.stackexchange.com/questions/77263/find-the-first-word-starting-with-each-letter), [cracked by EliteDaMyth](https://codegolf.stackexchange.com/a/231355/100664) ``` kBð\_9ɾṅṠ↔⌈:£ƛh⇩⅛¥ƛh⇩;¼ḟ¥$i=[|¤;;';ðvp∑Ṫ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=kB%C3%B0%5C_9%C9%BE%E1%B9%85%E1%B9%A0%E2%86%94%E2%8C%88%3A%C2%A3%C6%9Bh%E2%87%A9%E2%85%9B%C2%A5%C6%9Bh%E2%87%A9%3B%C2%BC%E1%B8%9F%C2%A5%24i%3D%5B%7C%C2%A4%3B%3B%27%3B%C3%B0vp%E2%88%91%E1%B9%AA&inputs=Ferulas%20flourish%20in%20gorgeous%20gardens.&header=&footer=) I made this while navigating various random bugs. It should work on the current implementation of Vyxal, but may not in the future. My intended crack: Anything involving zeroes. `kBð\_9ɾṅṠ` assembles a string, and here's how it works: ``` kB # Push lowercase + uppercase alphabet ð # Push space \_ # Push underscore 9ɾṅ # Push 1-9 - no 0! Ṡ # Concatenate all ``` Then everything not in that is removed, including zeroes. [Answer] # [Rattle](https://github.com/DRH001/Rattle), 3 bytes, [Simple cat program](https://codegolf.stackexchange.com/questions/62230/simple-cat-program), [cracked](https://codegolf.stackexchange.com/questions/231322/it-almost-works-robbers-thread/231367#231367) by [hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino) ``` |!p ``` [Try it Online!](https://www.drh001.com/rattle/?flags=&code=%7C!p&inputs=this%20is%20an%20input%201%2C2%2C3) This should be relatively easy to crack. It takes advantage of one of Rattle's core features! Hint: A perfect cat program is simply `|` ]
[Question] [ Every now and again, I'll encounter a large string of alphabetical text encoded as numbers from 1-26. Before I knew that I could just google a translator online, I had to personally, painstakingly copy and paste the entirety of the encoded text into a text document and translate it myself. Thankfully, I did know about find-and-replace features, which I used to search for all copies of each number and convert them to their corresponding characters. Only one problem... If you do this in numerical order, it will come out garbled. This is because the single digit numbers used to encode a-i also appear as part of the remaining two digit numbers encoding j-z. For example, `26` *should* decode to `z`, but since both 2 and 6 are less than 26, we decode those first. `2` becomes `b`, and `6` becomes `f`, so `26` becomes `bf`. Note also that for `10` and `20`, there is no conversion for `0`, so we end up with `a0` and `b0` respectively. ## Challenge Given a string of alphabetical characters (`abcdefghijklmnopqrstuvwxyz`), output the result of converting to numbers and back again using the algorithm described above. You may assume input is all lowercase or all uppercase. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. Important: You may *not* zero index. Full conversion list: ``` a: a b: b c: c d: d e: e f: f g: g h: h i: i j: a0 k: aa l: ab m: ac n: ad o: ae p: af q: ag r: ah s: ai t: b0 u: ba v: bb w: bc x: bd y: be z: bf ``` ## Examples ``` xyzzy => bdbebfbfbe caged => caged jobat => a0aebab0 swagless => aibcagabeaiai ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 32 bytes ``` [j-s] a$& [t-z] b$& T`j-z`0a-i0l ``` [Try it online!](https://tio.run/##K0otycxL/P8/Oku3OJYrUUWNK7pEtyqWKwnICknI0q1KMEjUzTTI@f@/orKqqpIrOTE9NYUrKz8psYSruDwxPSe1uBgA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` [j-s] a$& [t-z] b$& ``` Precede the letters `j-z` with an `a` or `b` as appropriate. ``` T`j-z`0a-i0l ``` Translate them to `0` or `a-i` as appropriate. (`l` expands to `a-z` but only `a-f` get used as the replacement list gets truncated to the length of the translation list.) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` øAṅ₄ɾkaĿ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDuEHhuYXigoTJvmthxL8iLCIiLCJqb2JhdCJd) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 70 bytes ``` s=>s.replace(r=/./g,c=>parseInt(c,36)-9).replace(r,i=>'0abcdefghi'[i]) ``` [Try it online!](https://tio.run/##XcxBCoMwFATQfU8h3ZiAGqFQ6CLue4bSxf/JTxoJRhJpq5dPtRvBmdXAY3p4Q1LRjVM9BE3ZyJxkl5pIowdFLErRCFsp2Y0QE92HianqcuX1je@mcrIrW0ClydiXKx/uybMKQwqeGh8sM@z8nZdlPnNerBGiQI2EZi2dDlCBJb3D/zyaPiBMu4EWCAHbI0sfsJ5S2uTGHK5vgAQOXP4B "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` A0ìDIkSè ``` I/O as lowercase list of characters. -2 bytes thanks to *@CommandMaster* [Try it online](https://tio.run/##DcM7EkAwAEDBu6RWuIIZjVppFD5BBEH8T6Rwixws3s6ssUWppPdR6L440al7vc9EIQJRsmJNyYYtOyr21Bw4cqLhzIUrLTfuPHjy4s1H5D8) or [verify all test cases](https://tio.run/##yy9OTMpM/e94aFVZpb2SwqO2SQpK9pXBh1b@dzQ4vMbl0Lrs4MMr/nvp/I9WqqisqqpU0lFKTkxPTQHSWflJiSVAurg8MT0ntbhYKRYA). **Explanation:** ``` A # Push the lowercase alphabet 0ì # Prepend a leading "0" D # Duplicate it I # Push the input character-list k # Get the (0-based) index of each character in the "0abc...xyz" string S # Convert it to a flattened list of digits è # (0-based) index each into the "0abc...xyz" string # (after which the result is output implicitly) ``` If `None` is a valid output for `0`, builtin `.b` could be used for an alternative 8-byter in the legacy version of 05AB1E, with uppercase character-lists as I/O: [try it online](https://tio.run/##DcO7DkAwAEDRf@kswmCV1Lve1FsMmpjMvr/uSY4X3MZ/rJWfekPtGmtPIYUjIsZMmDJjzoKKJSvWbNiyY8@BIzUnzly4cuPOQ1w/). (The `.b` results in `"@"` in the new version of 05AB1E for `0`: [try it online](https://tio.run/##DcM5CoAwAADBv6QWnyDEO94ab7EwYCEWFuL74w7M8x7mOq2Vn7o97RprNyGFI3wGDBkxZsKUihlzFixZsWbDlh01ew4cOXHmwlXsPw).) [Answer] # [><>](https://esolangs.org/wiki/Fish), 35 bytes ``` i"`":@-:9)?\+o "*-$a,"`"+o\:a%:0="0 ``` [Try it online](https://tio.run/##S8sszvj/P1MpQcnKQdfKUtM@RjufS0lLVyVRByimnR9jlahqZWCrZPD/f1Z@UmJJBQA) **Explanation** ``` i"`":@- # get input and subtract 96 from it to convert letters to 1-indexed numbers and save a copy of 96 for reverse conversion later :9)?\+o # if number is > 9 move down, else print with saved 96 added \:a% # mod a copy of the number by 10 "*- :0="0 # if the result is 0, subtract 48 $a,"`"+o # divide the other copy by 10 and print with 96 added \ # handle the print of the mod copy on the first row ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~74~~ 67 bytes * -6 bytes thanks to [@jdt](https://codegolf.stackexchange.com/users/41374/jdt). ``` p(c){c&&putchar(c^96);}c;f(*s){for(;c=*s++%96;p(c%10?:80))p(c/10);} ``` [Try it online!](https://tio.run/##bY/vaoMwEMA/16c4BEuiLbNQymome4G9wdrBJUaX4aIYu9qKrz53tbQfynIf8rs//LhTS1WiLcaxZor3aj6vD636xIapj@2Gi0GJnIWO93nVMKHS0EVRsN0Img5W8WvyHHNO/LSKaXY0tvW@0Vj2U5mMe703U5V1LVAdwhu@r/cp9PDmd6fz@eQviBQWOpvoq5LYTuSOWJTaOR8G8Y9Hd3ePzKSWOYV@kGGMWqKMr4mR1EGp0aC5SukmYBengRRiQd8LrAVEkeFAu8/qhpo584PS7azuaq1anSUwpQCNdoeyTYDsdJTZLy47mT0n8SxnU4kYHt7NubM7619mB28Yf1VeYuHG5fEP "C (clang) – Try It Online") [Answer] # [lin](https://github.com/molarmanful/lin), 41 bytes ``` $a0`,.+10`t2`/\"`rev `_`"`' , `,*10`d tro ``` [Try it here!](https://replit.com/@molarmanful/try-lin) Decided to go for a different non-regex approach, which came out quite nicely. Turns out that `tro` surprisingly accepts an iterator of iterators, which saved quite a few bytes. For testing purposes: ``` "jobat" ; outln $a0`,.+10`t2`/\"`rev `_`"`' , `,*10`d tro ``` ## Explanation Prettified code: ``` $a 0`, dup 10`t 2`/\ ( `rev `_` ) `' , `,* 10`d tro ``` * `$a 0`,` alphabet with 0 in front as *a* * `$a 0`,.+ 10`t` duplicate and create `0abcdefghi` * `2`/\ ( `rev `_` ) `'` 2-digit pairs (`00 0a 0b ... ig ih ii`) * `, `,* 10`d` zip with *a* and remove first 10 pairs (`[j a0] [k aa] [l ab] ... [x bd] [y be] [z bf]`) * `tro` transliterate [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` m!₁ṁod€₁ …"az0 ``` [Try it online!](https://tio.run/##yygtzv7/P1fxUVPjw52N@SmPmtYAmVyPGpYpJVYZ/P//PzEpOSU1LT0jMys7Jzcvv6CwqLiktKy8orIKAA "Husk – Try It Online") Inspired by [Kevin Cruijssen's approach](https://codegolf.stackexchange.com/a/250182/95126), although comes-out a bit longer in [Husk](https://github.com/barbuz/Husk)... ``` … # Fill-in the gaps with character ranges "az0 # in the string "az0" # (fill-in works both backwards & forwards, resulting in: # "abcde...vwxyzyxwv...edcba`_^]\...43210") # = assign this as '₁' ṁo # Now, for each input letter €₁ # get the index of first occurence in ₁ (=index in alphabet) d # and split the decimal digits; m # Then, for each digit !₁ # retrieve the element in ₁ using modular 1-based indexing # (so zero retrieves the last element) ``` [Answer] # [R](https://www.r-project.org), 75 bytes ``` \(s,`[`=gsub)chartr("j-z","0a-i0a-i","([j-s])"["a\\1","([t-z])"["b\\1",s]]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY1RCoMwDIbfdwrJXlqw4N724i6wI6hgoq2rDAamstmr7MUNdqjdZrU6QsjP95Hk-Rrmt8k_ozPq-D2XgtO6qPOOR5LNBQc3COiVhxQyVHbpEEXRK64kFIBleYjAKR8BRcBVJbeTxgh4TN5PIPdJfkqoJU0mlN4F02Cn283EvMD-Rug2iBlqQsoWznfsrpr5ryyFFSSNFu36bZ7X-QM) Straightforward replacement. --- ### [R](https://www.r-project.org), ~~84~~ 81 bytes *Edit: -3 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).* ``` \(s)gsub("`",0,intToUtf8(strtoi(unlist(strsplit(paste(utf8ToInt(s)-96),"")))+96)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY0xDoJAEEV7T0HWZidCQmWw0N7SBDsLZ2SXrCFAmCEKV7FBEw_lbVwEM8X8-S__z-PZDC-7fbdio-RzOGmGnFvS6qzCOHSlpNVRbKJZGqmcbsvCsYwX14UTXSOL0T6cpNW-9ACizRpCpQBg5RXMxdZqde_6vlOwDLa7gDIyZP2YhScXzE02k58ezWtFKLOJMRpCikefb5gXhvmPHPkIkkGHbvo2DNP-Ag) Going with the algorithm. [Answer] # [Perl 5](https://www.perl.org/), 27 bytes ``` s/./-96+ord$&/ge;y/1-9/a-i/ ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX09f19JMO78oRUVNPz3VulLfUNdSP1E3U////4rKqqpKruTE9NQUrqz8pMQSruLyxPSc1OLif/kFJZn5ecX/dQsA "Perl 5 – Try It Online") [Answer] # [Lexurgy](https://www.lexurgy.com/sc), 92 bytes ``` a: {j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}=>{a\0,aa,ab,ac,ad,ae,af,ag,ah,ai,b\0,ba,bb,bc,bd,be,bf} ``` Naive 1-1 substitution. [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ;£ÒCaXî°gCi0 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O6PSQ2FYw66wZ0NpMA&input=WwoieHl6enkiCiJjYWdlZCIKImpvYmF0Igoic3dhZ2xlc3MiCl0tbVI) ``` ;£ÒCaXî°gCi0 ; # C = "abcdefghijklmnopqrstuvwxyz" £ # For each letter in the input: CaX # Find its 0-based index in C Ò # Add 1 à # Join to a string ® # For each character in the new string ° # Coerce to a number g # Get the character at that index in: Ci0 # C with a 0 added to the front ``` [Answer] # [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 129 bytes (5×27=135 codels) ``` uqijsvudnbddt feussskiu L?q sa dttlvqfeumdctss?Lr????saa???????????????s Lkjftrqavqcefcnbftmnkss K ssvc ``` [![Code](https://i.stack.imgur.com/egOw9.png)](https://i.stack.imgur.com/egOw9.png) [Try Piet online!](https://piet.bubbler.one/#eJydT02LwkAM_S85v8KkdVqnJ-sHggh76IIf1YNoBUGrUD3J_vdNxo7snhZ25sFMkpeXlyftr4ea8qqy6IEN-kjAsOAYGbinr8CAXYDUMyEk_jrtsZpPt6i4ryKBKcT0R5-qGEhGOZ0Isx9gpaBq0q8ysX7eeMmkv3J_IummqpyTpWSgQayTOwNWDagN2-2pBLGTwb2sOLydO13N4d_wen5k0NuC2vpGOUVRRKDz6SJ_Nv5IXLd7yo-7c1uDTs3tcZfqcrVerwabRjo2zaiYTsYhmH0Mi88QlItiOp-U5YC-vgFlgGcR) Input the string in upper-case with the [sentinel value](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/24639#24639) `@`. **Explanation** [![Step 1](https://i.stack.imgur.com/kd10h.png)](https://i.stack.imgur.com/kd10h.png) Read char from input, subtract 64 and check if it is greater than 9. [![Step 2](https://i.stack.imgur.com/PgCsN.png)](https://i.stack.imgur.com/PgCsN.png) If c<=9: check if its check if it is greater than 0 (else terminate). [![Step 3](https://i.stack.imgur.com/Gd65X.png)](https://i.stack.imgur.com/Gd65X.png) Add 64, print char and start over. [![Step 4](https://i.stack.imgur.com/hGWew.png)](https://i.stack.imgur.com/hGWew.png) If c>9: duplicate, push 10 on stack, duplicate, roll, divide, print char, modulo and check if it is greater than 0. If c>0: print char (as above) and start over. If c=0: print number and start over. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` ⭆⭆S⊕⌕βι§⁺β0⊖ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWILE88wpKSyBcDU0dBc@85KLU3NS8ktQUDbfMvBSNJB2FTE1NoIxjiWdeSmqFRkBOaTFIVMlACSjqkopQD1KnqWn9/39WaXHJf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` S Input string ⭆ Map over characters and join ⌕ Index of ι Current character β In lowercase alphabet ⊕ Incremented ⭆ Map over characters and join β Lowercase alphabet ⁺ Concatenated with 0 Literal string `0` § Indexed by ι Current character ⊖ Decremented (auto-casts to integer) ``` [Answer] # [Factor](https://factorcode.org/), 53 bytes ``` [ 96 v-n [ >dec ] map-concat 48 v+n "`" "0" replace ] ``` Needs modern Factor for [>dec](https://docs.factorcode.org/content/word-__gt__dec,math.parser.html) but here's a version that works on TIO for +1 byte: [Try it online!](https://tio.run/##Rc29CsIwFIbhvVfxkVVaHET8uQBxcRGnIniMx1qpaZqc/orXHuPk@vLAeycttQun4/6w2@BF8sg6/iUPz03LRrPPeBBHMdiqFClNgaaHdSwyWlca@Utsk6Tp3xjGaRqhqeAbnvWVIumpqNh7fEKO9RJdapCjNZacZ5zj2aa6NjrSxQrdzEBdlJorx7YiHUWIAln4Ag "Factor – Try It Online") [Answer] # JavaScript (ES6), 71 bytes ``` s=>s.replace(/[j-z]/g,c=>"ab"[c>'s'|0]+"abcdefghi0"[parseInt(c,36)%10]) ``` [Try it online!](https://tio.run/##XczBCoMwEATQe79CAkWlalIKvem93yAeduOaRsSIK22V/nuqvQjOnAYe08ILWI92mNLe1eSb3HNecDbS0IGmSJZtulTSJDovBKAodRFy@FXVZV26psY8rRLlACPTo58indzu8fmqqthr17PrKOuciZpIfOZlmUUcB2ukDLBGwmYtnQ5Qg6F6h/95NK1DmHYDCggB1ZHxG0xHzJvcmMX1DZDAgvU/ "JavaScript (Node.js) – Try It Online") [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 25 bytes ``` )**96?-imXX@azr@'0+]jsi\[ ``` [Try it online!](https://tio.run/##SyotykktLixN/V@tpGBrp6Bkba0b@19TS8vSzF43MzciwiGxqshB3UA7Nqs4Myb6f214zv@KyqqqSpDipJSk1KQ0IEzlSk5MT00BiYEZXFn5SYklIG6iQWJqUmKSAVdxeWI60KZisGBmElBZYlJqYmZiJgA "Burlesque – Try It Online") ``` )** # Map ord(a) 96?- # Subtract 96 (get index into alphabet) imXX # Concat and separate by digit @azr@ # Alphabet [a,b,..,z] '0+] # Prepend [0,a,b,..,z] jsi # Select indices \[ # Concat ``` [Answer] # [Python 3](https://docs.python.org/3/), 79 bytes ``` lambda s:s.translate({n:'AB'[n>83]+'0ABCDEFGHI'[n%74%10]for n in range(74,91)}) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqlivpCgxrzgnsSRVozrPSt3RST06z87COFZb3cDRydnF1c3dwxMopGpuompoEJuWX6SQp5CZpwDUlJ6qYW6iY2moWav5v6AoM69EI01DPSIyKipSXVOTCy7i7Oju6oIi4uXv5BiCIhIc7uju4xocjKrM0dkbKPAfAA "Python 3 – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), 74 47 bytes ``` sed "s/[j-s]/a&/g;s/[t-z]/b&/g"|tr j-z 0a-i0a-i ``` [Try it online!](https://tio.run/##HY3LCoMwEEX3fsVFRHQRYruVLvoHBZfiYkbji4LQCbSm@u1pGoYZOIc7XCaZ/ViUXy9mQCq6XZV0mnI91QGscp3mAOlhX1iVQ0Vq@a8/Eys2PKJFdsUNWWH6eUN2wYGxRIc8RzSPe9PUOJN/Hp/duR08sOExjImypymUxxt53ZgsqCLDxFVU8qbpaURAC4cgsaGFFv8D "Bash – Try It Online") *-27 thanks to [Neil's idea](https://codegolf.stackexchange.com/a/250156/15469)* # first approach, 74 bytes ``` sed "s/./\"'&\"/g"|xargs printf '%d-96\n'|bc|sed '/../s/./&\n/'|tr 1-9 a-j ``` [Try it online!](https://tio.run/##HcvBCoMwEATQe75iidScNPZS8NB@SS67GtNI0ZINVCX/nkaZy/CYIeR3zmxHkKxbbaSqjdROpg2DY/gGv8QJ1G1s@odZVKIhnWOl21afh9osWqUY4N70gM2cK9j249jh@QIaydJUYkUFA7ryK3qVAvNKGE/ADi0hdcX4h@5jmS/2VKZIFj36PItVkEAR/w "Bash – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 16 bytes ``` sm@+G0tsdjkmhxGd ``` [Try it online!](https://tio.run/##K6gsyfj/vzjXQdvdoKQ4JSs7N6PCPeX/f6WKyqqqSiUA "Pyth – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 76 bytes ``` f=lambda s:s and'ba'[2-(q:=ord(s[0])%32)//10::2]+'0abcdefghi'[q%10]+f(s[1:]) ``` [Try it online!](https://tio.run/##DcoxDoMgFADQvadgMUC1EXRoS@JJCMNHQG0UFExavTx1estbj30Mvn2tMWfXzbBoAyiJhMAbrAHL5kE20YVoSJJM0aJtaF1zJkSjSsxA98a6YZyw3ArOVOmuxoWi2YWIPJo8kvcFVtKPsYrgB0vez4o3LaUV/h3neeAK9zBYc/kJGvbL9IVhtilhJW4IrXHyO3HEU5r/ "Python 3.8 (pre-release) – Try It Online") [Answer] # [R](https://www.r-project.org), 68 bytes ``` \(x,y=utf8ToInt(x)-96)intToUtf8(rbind(y/10+96*(y>9),48--y%%10%%-58)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMG6nNSSEqO80lwjEMN2aWlJmq7FTZcYjQqdSlsgxyIk3zOvRKNCU9fSTDMzryQkPxQoqFGUlJmXolGpb2igbWmmpVFpZ6mpY2Khq1upqmpooKqqa2qhqQk1ayaKDRpKFZVVVZVKmgrKCrZ2CkkpSalJaUCYyoWmLDkxPTVFSROsCsxGV5CVn5RYAjMn0SAxNSkxyQBdUXF5YnpOanExXF1mEtCwxKTUxMzETIgDFyyA0AA) Calculates 2 decimal digits for each letter, and then calculates the corresponding codepoint values, setting unused values (leading zeros) to zero, which is not output by the `intToUtf8` function. --- # [R](https://www.r-project.org), 54 bytes ``` \(x)chartr('1-9','a-i',Reduce(paste0,utf8ToInt(x)-96)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMG6nNSSEqO80lwjEMN2aWlJmq7FTbMYjQrN5IzEopIiDXVDXUt1HfVE3Ux1naDUlNLkVI2CxOKSVAMdoFqLkHzPvBKgYl1LM01NqO6ZKGZqKFVUVlVVKmkqKCvY2ikkpSSlJqUBYSoXmrLkxPTUFCVNsCowG11BVn5SYgnMnESDxNSkxCQDdEXF5YnpOanFxXB1mUlAwxKTUhMzEzMhDlywAEIDAA) Port of [Kjetil S's Perl answer](https://codegolf.stackexchange.com/a/250198/95126). [Answer] # [C (GCC)](https://gcc.gnu.org), ~~101~~ ~~88~~ 87 bytes ``` f(char*s){for(char*x;*s;)for(asprintf(&x,"%d",*s++-64);*x;)putchar(*x+(*x++^48?16:0));} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVDtasIwFP3dPkWIKE1bR4VO3GI3Eo3iGBPWiVPnRPoxA1srNoWC-CT74x8fyhfYcyyxZYzccG5yzzm5N9-nYPURBMdzoxZGMU8isBo-TVb-ePLcY3qNJ8FnHkagm4mQp1ebu1Mu4mbnPI2NYLPemRnax-muzAtsZhip4zrb7ngiYqNR2LAeQtvMLKvZdhGWJLTNheIbZmGpbb27nftW-9ZBCB8q-x-pBl9rnhgI7HVN0QFPFu5ycbP09vB1Np_PoA17ZMj6Eh_GlLxI9Kdk-Mh8Hx5wJYoKJWpdKxXtU0YHcrF_UuIQRgl1VDqi8pZQRkZkdLFQs6hOuOdgwLsutiyOZD8XbxMIT_bEl5KoxYZA-K-QevLdslB9BAT1TMZbAm1hpwhrunbQq2mPxxJ_AQ) Prints to standard out. Uses `asprintf`, which is a GNU-specific function and may or may not require a definition in the header, so I don't know if it's okay. This is basically the first C function I've ever written, so there are almost certainly ways this can be improved. --- -13 bytes from @c-- by iterating one character at a time, removing parens, and changing the ternary -1 bytes from @ceilingcat by moving the `char*x` declaration into the for statement [Answer] # [Dyalog APL](https://www.dyalog.com/products.htm), 32 bytes ``` {(⎕A,'0')[27@(0∘=)⍎¨∊⍕¨⎕A⍳⍥⎕C⍵]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70qpTIxJz89PrEgZ8GCpaUlaboWNxMe9U191DahWgNIO-qoG6hrRhuZO2gYPOqYYav5qLfv0IpHHV2PeqcCaaCCR72bH_UuBbKcH_Vuja09tEK9orKqqlJdQT05MT01BUhn5ScllgDp4vLE9JzU4mJ1iD1Q62DWAgA) ``` ⎕A⍳ ⍵ find each character's index in the alphabet ⍥⎕C case insensitively (casefold both arguments first) ⍕¨ turn each number into string ∊ flatten nested array to get the individual digits ⍎¨ turn each digit back into a number 27@(0∘=) turn 0s into 27s [ ] index into ⎕A the alphabet ,'0' with a 0 at the end at the 27th position ``` [Answer] # [J-uby](https://github.com/cyoce/J-uby), 43 bytes ``` ~(:gsub+(:ord|:+&-96))&/./|~:tr&"a-i"&"1-9" ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWN7XrNKzSi0uTtDWs8otSaqy01XQtzTQ11fT19GvqrEqK1JQSdTOV1JQMdS2VoFqcCkpLihXcopUqKquqKpViuWD85MT01BQkflZ-UmIJEr-4PDE9J7W4WCkWYtKCBRAaAA) [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` c_uH sAÇ©d96 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Y191SCBzQcepZDk2&input=WwoieHl6enkiCiJjYWdlZCIKImpvYmF0Igoic3dhZ2xlc3MiCl0tbVI) (Includes all test cases) ``` c_uH sAÇ©d96 :Implicit input of string c_ :Map codepoints u : Modulo H : 32 s : Convert to string in base A : 10 Ç : Map the range [0,A) © : Logical AND with d96 : Add 96 and get character at that codepoint ``` [Answer] # [Julia 1.7](https://julialang.org), 52 bytes ``` !x=replace(join([x...].-'`'),('1':'9'.=>'a':'i')...) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZBBasMwEEXX9Skm2kgCx6TQRRNQVj1CdsakI2ts5ArbWAqxc5VussmhcpvKtbsps5jP-_wPM9-P5uIs3u-PS6i278-3zagG6h2WJJrOtiIfsywrsi3_5DIV_JUf-J5n6sgxKstldOWafRr1Ycsgkhc2TrfbxEAdgWmjSVdxiKXRKbEmsziLnGHTaQwLxB2SRr375f6KtSPvV8vqGEFNaNGyRCYJOncO5IM_9-g9GVAQkcg3XzSBUmDyKAqougFmYtt5eWFkIZN-sG1wrWCnuQDmAtvWB2Ap_K9dD_x70g8) * `replace` supports multiple patterns as of Julia 1.7 # [Julia 1.0](http://julialang.org/), ~~66~~ 65 bytes ``` ~x=join(get.([Dict('1':'9'.=>'a':'i')],[join([x...].-'`')...],0)) ``` [Try it online!](https://tio.run/##XYzBjsIgEIbP8hSEC5B0ST3uJnjyLUijg4zNVNIawWzrwVevtN3TZg7z5fvnn@4ZCfbjPL9H2w3UqxazUe5Il6zkXv7Ib2nsQUIhkrqp3HrkRmNMY77kWeqFqlrrOdi1xXZinF6vSXB74MIHj/5aBkVVkgu0GLZkw0V2g4e8SagBPfh69ekX2ogp/UXkSwU8AgEJphmDGE8ZU06nO6SEgVtelHLvG07cWh5cgYZfhwdfDPXLSiroRrP7g/oce/X/h54/ "Julia 1.0 – Try It Online") * -1 byte thanks to MarcMush: replace `(Dict(_),)` with `[Dict(_)]` for [accessing multiple dictionary values](https://discourse.julialang.org/t/how-can-i-access-multiple-values-of-a-dictionary-using-a-tuple-of-keys/56868). [Answer] # [Knight](https://github.com/knight-lang/knight-lang) (v2), ~~49~~ 46 bytes ``` ;=y,=xP;Wx;=y+y-Ax 96=x]x;W=y]y=x+x&[yA+96[yOx ``` [Try it online!](https://knight-lang.netlify.app/#WyI7PXksPXhQO1d4Oz15K3ktQXggOTY9eF14O1c9eV15PXgreCZbeUErOTZbeU94Iiwiam9iYXQiLCIyLjAiXQ==) This uses the quirky nature of `+(List, Number)`. It acts similarly to appending to a String where it will append individual digits, with the exception that the elements will be Number instead of String. So for example, `+ @ 42` will result in `[4, 2]`, compared to `+ "" 42` which will be `"42"` or `+ @ "42"` which will be `["4", "2"]`. This has a bunch of perks: * Creating a list is only one char (`@` for empty, `,` with an existing expression), compared to empty string which is 2 (`""`) * The digits will be a Number, so there is no need to convert from ASCII to do char math. I can therefore use the `&` operator to both test if the digit is 0 without a compare, and append that `0` if it is due to coercion rules. ``` ; = y , # Set y to a list with one dummy argument (which is x) : = x PROMPT() # Read a string into x # Convert to a list of numbers containing each digit (with a preceeding dummy value) ; WHILE (x) # While x is not empty ; = y + y (- ASCII (x) 96) # Push DIGITS of x[0] - 'a' - 1 as Number to y : = x ] x # Pop front char from x # Convert back # x = "", y = [ dummy, digit, digit ] ; WHILE (= y ] y) # While y is not empty, popping front beforehand : = x + x ( # Append to x... & [ y # Either y[0] if it is zero (which is coerced to '0') : ASCII (+ 96 ([ y)) # or y[0] + 'a' - 1 converted to ASCII : ) : OUTPUT x # Output the string in x ``` * -3 bytes for taking Samp's advice and making `y` for `WHILE(= y ] y)` [Answer] # [J](http://jsoftware.com/), 34 32 bytes ``` "."0@(,&":/)&.:(('0',97}.a.)&i.) ``` [Try it online!](https://tio.run/##HYxNC4JAGITv@yte97AfoOvWoXBDEYJOnbpLvKurKYEHjdLot28qw8DMwzCdTwKzKw6BSTgnVPEaUgMcQtBgFkcKzrfrxVNFdS5CRk0smTJCcM3D5PhTqCRrlfSSuPLRg9iDFpGBWrIszs23fI3ypO57KNZDTT7TPE@QZmAr62y9yJESG1etbAuk6y2Oa0WNzqLVZHhj83TDsMHWLjO0DltsifR/ "J – Try It Online") [Answer] # Batch, 432 Bytes ``` SETLOCAL ENABLEDELAYEDEXPANSION&(CMD /U /C^"<NUL SET /P=abcdefghijklmnopqrstuvwxyz^"|FIND /V ""|FINDSTR /N "^")>a&(CMD /U /C^"<NUL SET /P=%s%^"|FIND /V "")>t&FOR /F %%Q in (t)DO (FOR /F "tokens=1-2 delims=:" %%A in ('FINDSTR /RC:"%%Q" a')DO (IF %%A GEQ 20 (SET /Ad=%%A+76&CMD /CEXIT !d:96=48!&<NUL SET /P=b!=exitcodeAscii!) else IF %%A GEQ 10 (SET /Ad=%%A+86&CMD /CEXIT !d:96=48!&<NUL SET /P=a!=exitcodeAscii!) else <NUL SET /P=%%B)) ``` Assuming @ECHO OFF and passing it as ``` CALL golf.bat swagless ``` produces ``` aibcagabeaiai ``` This can probably not the best way, but I thought that this was a pretty cool way to do it. Ungolfed: ``` (CMD /U /C^"<NUL SET /P=abcdefghijklmnopqrstuvwxyz^"|FIND /V ""|FINDSTR /N "^")>a (CMD /U /C^"<NUL SET /P=%1^"|FIND /V "")>t FOR /F %%Q in (t) DO ( FOR /F "tokens=1-2 delims=:" %%A in ('FINDSTR /RC:"%%Q" a') DO ( IF %%A GEQ 20 ( SET /Ad=%%A+76 CMD /CEXIT !d:96=48! <NUL SET /P=b!=exitcodeAscii! ) else IF %%A GEQ 10 ( SET /Ad=%%A+86 CMD /CEXIT !d:96=48! <NUL SET /P=a!=exitcodeAscii! ) else <NUL SET /P=%%B ) ) ``` ]
[Question] [ ## Flavortext The [Bystander Effect](https://en.wikipedia.org/wiki/Bystander_effect) is a phenomenon where individuals are less likely to help a victim if other people are present. The idea is that as there are more people around, the individual burden is less, and each individual thinks "someone else will help them", which results in the counterintuitive fact that fewer people will help when there are more people. (This is why if you're in public and something bad happens and you / someone else needs help, you should address random individuals ("you in the red shirt") to help specifically rather than "someone please help" to bypass this psychological phenomenon) Let's take a very simplified interpretation of this theory and assume everyone has a numerical threshold for helping. ## Specification A list of people will be given, each with a threshold to help. The threat level is 1. A person will help if and only if the threat level divided by the number of people in the crowd is greater than equal to their threshold. When a person decides to help, they leave the crowd. This means that the individual threat, which is the threat level (1) divided by the size of the crowd, is now higher as a result because the crowd is smaller. The total threat level (1) never changes, for simplicity. How many people end up helping? ## Input You are given a list of floating point numbers in any reasonable format. This list will be non-empty, and every number will be in the inclusive range from 0 to 1. You may assume the list is sorted in either order you would like. ## Output You are to output a single integer, indicating how many of the individuals decide to help. ## Example Consider the test case `0.2, 0.2, 0.3, 0.6, 0.8`. The crowd has five people, so the threat to each individual is 0.2. Therefore, the first two people will help. Now, the crowd is `0.3, 0.6, 0.8`. Since there are only three people, the threat to each individual is now 0.3. Therefore, the third person will now decide to help. The crowd is now `0.6, 0.8`, so the individual threat is 0.5, and nobody decides to help anymore. Therefore, the final result is `3`. ## Test Cases ``` 1 -> 1 0.5, 0.8 -> 2 # 0.8 initially won't help, but will when 0.5 leaves 0.2, 0.2 -> 2 # both will help initially 0.2, 0.2, 0.3, 0.6, 0.8 -> 3 # 0.2 and 0.2 leaving prompts 0.3 to help, but the other two won't help 0, 0.25, 0.33, 0.5, 1 -> 5 # all of them help only after the previous person left, starting with 0 0, 0.25, 0.34, 0.34, 1 -> 2 # 0 and 0.25 help, but 0.34 is just a bit too indifferent to help, which means 1 will never help either 0.5, 0.5, 0.5 -> 0 # nobody helps. RIP ``` ## Reference Implementation [This implementation](https://tio.run/##jZExb4MwEIXn@FecmEBFlDTNUikdO3aouqEMTjiC1YttgaOUX0/vgiEZuxiM33v@7uGH0Dq7GUePzhPCDsj0IT1rnzbkdMjBWH8JaVb0ngw/s0ypFslj17O4VCq0HerA72ulrq3hjCnqTa2Mrc0RRVft1apxHYfV@JuDuJ3lHaC9nLHTAdPJlbFtZRqIqc9AaOcjeN9Fp4jm9EJ7j7ZOb9GZHMx4T8IkYQuHgIjXd8aGNPl0B1cPgNQjXA0RiLNIJOTA1/@oWfjdIjSOyF2NPcX57g6GNT0chyMPneRQTefVDWgPy9gybiTZ8xVL4VVs43/9wDQPx1kXHiMX2C88a2PvoML00CL/vyj8MFYTdNhfKIgo9pZDEtluH2ouZBxLWENZvGx52bzysv0D) (Python) shows the final answer at the very end. It also breaks down the process stage-by-stage. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9 8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) (Saved 1 when the assumption of sorted input was allowed, and another realising there was no need to floor the inverses.) ``` İ<Jṣ1ṪL ``` A monadic Link accepting a list of floating-point numbers in \$[0,1]\$ sorted in descending order that yields an integer. **[Try it online!](https://tio.run/##y0rNyan8///IBhuvhzsXGz7cucrn////0YY6CgZ6xiYI0sgUSMYCAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///IBhuvhzsXGz7cucrn/@H2R01r/v@PjjaM5dKJNtCz0FEw0DOFsI1AbCMkcTMQYQwWhUsZgjWAJSAyIDZcwtgEQUJlYgE "Jelly – Try It Online"). ### How? Effectively this evaluates how many people need to be in the crowd to stop each person helping, identifies crowd sizes that would be too big for anyone to help if those most likely to help have been removed, then counts those in excess of the biggest of those crowd sizes. ``` İ<Jṣ1ṪL - Link: list of thresholds, T e.g. [1, 0.34, .34, .25, 0] İ - inverse (T) [1, 2.94, 2.94. 4, inf] J - range of length (T) [1, 2, 3, 4, 5] < - less than? [0, 0, 1, 0, 0] ṣ1 - split at ones [[0, 0], [0, 0]] Ṫ - tail [0, 0] L - length 2 ``` --- Equivalently: ``` İ<JṚÄċ0 Ṛ - reverse [0, 0, 1, 0, 0] Ä - cumulative sums [0, 0, 1, 1, 1] ċ0 - count zeros 2 ``` [Answer] # [J](http://jsoftware.com/), 13 bytes *-2 thanks to Jonah!* ``` -&#(#~%<#)^:_ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/ddWUNZTrVG2UNeOs4v9rcqUmZ@QraFinaSoYIrEN9EyB2AJFxAiEMUWA2BiIzdDVKxiCZEHGGIPkTXHImYCJ/wA "J – Try It Online") ``` -&#(#~%<#)^:_ ( )^:_ until result does not change %<# (1 % element) smaller than length of the list #~ filter out other elements -&# length(original list) - length(filtered out list) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Lİ<SɗƬạLṪ ``` [Try it online!](https://tio.run/##y0rNyan8/9/nyAab4JPTj615uGuhz8Odq/4fbn/UtCby///oaMNYHYVoAz1THQUDPQsI2wjENkJmgwhjEGGGUKajYAiWA@s0BsuaYpEwgZBItkCI2FgA "Jelly – Try It Online") Does not assume sorted input. :/ Since shrinking the crowd never makes anyone not help, this calculates the new crowd size from the previous one until nobody new leaves. ``` Ƭ Loop until a fixed point, starting from L the length of the input: <Sɗ how many elements of the input are strictly greater than İ the reciprocal? ạL Subtract each intermediate result from the length of the input, Ṫ and return the last one. ``` Uses `Ƭ ... Ṫ` instead of `ÐL` because `ÐL` passes the previous left argument as the right argument rather than reuse the original right argument, given a dyad. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ×JỊẠÐƤS ``` [Try it online!](https://tio.run/##y0rNyan8///wdK@Hu7se7lpweMKxJcH/H@5cFHq4XfP//2jDWB2FaAM9Ux0FAz0LCNsIxDZCZoMIYxBhhlCmo2AIlgPrNAbLmmKRMIGQsTrRQDvAKBYA "Jelly – Try It Online") Assumes the input is sorted descendingly (thanks to [@caird](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing)). 8 bytes without that assumption: ### [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` JU×ṢỊẠƤS ``` [Try it online!](https://tio.run/##y0rNyan8/98r9PD0hzsXPdzd9XDXgmNLgv8fbn/UtOb//2jDWB2FaAM9Ux0FAz0LCNsIxDZCZoMIYxBhhlCmo2AIlgPrNAbLmmKRMIGQsTrRQDvAKBYA "Jelly – Try It Online") The idea here is that if we consider the sorted list, once anyone doesn't go, nobody after them will go either. Furthermore, considering an individual, they will only go if everyone *before* them went, so their individual condition for helping is `1/reversed_index > threshold`, i.e. `threshold * reversed_index < 1`. Thus: ``` JU ' [len(l)..1], i.e. reversed index ×Ṣ ' times the sorted values Ị ' <=1 ẠƤ ' map 'all' over prefices, results in 1s over the prefix of helpers S ' sum ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~16~~ 13 bytes ``` IL⊟⪪⭆A›×ι⊕κ¹1 ``` [Try it online!](https://tio.run/##LYo9C8IwFAB3f0XGF4ilVRCho0MXLRncSodQHiaQD01e9OfHRFyO47hNq7gFZUv5aGORwRwIpoiKMMLdOExwM9647ODFBbuif5CuWn3gnDOZk4YsmAzPVsedjMYTXFQi@M@5fmMpy9J3Z8H67tRwbDj8sK5l/7Zf "Charcoal – Try It Online") Link is to verbose version of code. Requires input sorted in descending order. Edit: Saved 3 bytes after following @DominicvanEssen's advice. Explanation: ``` A Input array ⭆ Map over elements and join κ Current index ⊕ Incremented × Multiplied by ι Current value › Is greater than ¹ Literal `1` ⪪ Split on 1 Literal string `1` ⊟ Pop last element L Length I Cast to string Implicitly print ``` [Answer] # JavaScript (ES6), 39 bytes Essentially the same answer as below but it assumes that the input is sorted from lowest to highest, which is now allowed. ``` a=>(n=a.length)-(a.map(k=>n-=k*n<=1),n) ``` [Try it online!](https://tio.run/##lc6xDsIgEAbg3adgBFNoAWscpC9iHC6VVi0ejW18fRSiHWxj4g1/bvhy91/hAUN9v/QjR3@yoTEBTEXRgHAW2/HMOAVxg552pkJuujXujWQZslB7HLyzwvmWNvQgyeIcGSN5TuTqixeizEghdstczbmKXP3JY@gY2/TszfWMJ5wK6cRfq5yul7/45pNyKhOe "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 46 bytes ``` a=>(n=a.sort().length)-(a.map(k=>n-=k*n<=1),n) ``` [Try it online!](https://tio.run/##lc7BDoIwDAbgu0@x42rGYEOMB8uLGA8LAirYEUZ8/ZlNw0FIjD38p6/tfzdP46rxNkwJ2UvtG/QGS05opLPjxEH2NbXTFRJu5MMMvMOSEuy2dEQFgsBXlpzta9nbljf8pNjqnAFYmjK1@eKZLATL5GGd6yXXges/eYg8xD4@@/B8wQVT0cdOedwo5uvFD75751zGvwA "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input ( n = a.sort() // sort the input; although the sort is in lexicographical // order, it's OK for floats in [0, 1] .length // initialize n to the length of the array ) - ( // a.map(k => // for each value k in a[]: n -= // decrement n if: k * n <= 1 // k * n is less than or equal to 1 ), // end of map() n // subtract the new value of n from the original value ) // ``` [Answer] # [R](https://www.r-project.org/), ~~56~~ 44 bytes *Edit: saved 12 bytes after looking at [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/223733/95126): please upvote that!* ``` function(c,d=sum(c|1))match(T,1/c<d:1,d+1)-1 ``` [Try it online!](https://tio.run/##hVJfa4MwEH/vpzjYw5TZztg5xlj3vrcx9l6ixiVDc2LOSmHfvbtESmW0XR7uBHO/f5f@oHHcttLut6Npmq1WTbc51IMtyaCNyqTauKGNyh8Rx62kUkefibgvX6pnkVR3Il6KMwBRGQk4f@IYbmD5CmJxdixd5Qmkq6dLYxk3/9tYQ0Y2zR5GtLcEfjyBYiDwaDBqZfleDo2SO@UucWWeK7vGVSDpCdIPnWivI/qy9uVxMnNEXAf1GUhbhe7VGfsFXY9tR85PAeHMDGkFrED1QCPOrF6gD@QhwHWg508xM5RzY/GAtQduJ0toOURZk@dgtq5XO4ODg071Di1LrCkBR7Inr3Q0nEf6P/3DsYo/uzt6z2cu/U0wDr4HRyChMGwckcOuTF2rXlk6pTJqU2polbSOscNmrNqx@GBGGR/W1ac1lTPrTrlZLLDaByy3go@398XhFw "R – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes ``` LengthWhile[#,l=Tr[1^#];1>=l--#&]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yc1L70kIzwjMyc1WlknxzakKNowTjnW2tDONkdXV1ktVu1/QFFmXkm0sq5dmoNyrFpdcHJiXl01V7VhrQ5XtYGeqY6CgZ4FhG0EYhshs0GEMYgwQygDS4C1GYOlgExDdAkTGIlsC4So5ar9DwA "Wolfram Language (Mathematica) – Try It Online") Requires input to be sorted, least to greatest. --- Iteratively, 35 bytes: ``` 0//.x_:>Tr@UnitStep[x#-Tr[1^#]#+1]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b730BfX68i3soupMghNC@zJLgktSC6Qlk3pCjaME45VlnbMFbtf0BRZl5JtLKuXZqDcqxaXXByYl5dNVe1Ya0OV7WBnqmOgoGeBYRtBGIbIbNBhDGIMEMoA0uAtRmDpYBMQ3QJExiJbAuEqOWq/Q8A "Wolfram Language (Mathematica) – Try It Online") No sorting requirements. [Answer] # [Haskell](https://www.haskell.org/), 33 bytes ``` f(x:y)|sum(x<$x:y)<=1=1+f y f _=0 ``` [Try it online!](https://tio.run/##dZFBj5swEIXv@RWj7EoBQSiQpqqisKdeKvVQ9bpaVaaMF7fGRngIQep/T8dOsptWXQ6DwfPefM9uhfuFWp9OMjru5vi3G7vouL/3631VVEUiYV5I@F7lp04oUzV2ARCp1Mb7texEHzWD7aGMM9cLE72rVutVnElHL993q3h///CM9EUZZK1GgmM1oGii5eMySVSSLJ@W8W73@MmOtcanS88MFfgu8AP7QRmKJAurOT2mc8z/PM6pgDee9QMUizzbppBnH/@3W8Jd2FJGkRJazzBZsyJoUfcp1CPBpLSGqUXDfVtmEgd0bFl6y/Ity9pSe1Z6o1f3F6EvG18@XNBYuAksJQjThLefpcwzx7ZdT84rgOwNGrUIPAgHoMnegC/yMCOk3oQpvCwueFuewihgpdd3Z0BrOLmQ5K3YtB/woOzooMfBWcMkklJwJAbyQJPidPlfU95fa3Fzrtck2xtm3wXKwc/REQioFcewlk@oUVLigIZeM06t@tFCh8I49g3HafDAjIEZlY9@vd1z@ecqcqYwtrbNHCQug2@fv/4B "Haskell – Try It Online") The relevant function is `f`, which takes as input the list of tolerances in increasing order. ## How? The only trick I think it's worth showcasing is the `sum(x<$x:y)` part. Its job is to compute `x*length(x:y)`, but: 1. it's 2 bytes shorter, and 2. since `x` is a `Double` and `length` returns an `Int`, Haskell would complain if we tried to multiply them together; to fix this issue, the monstrosity we would need is `x*toEnum(length$x:y)`, which is 9 bytes longer than `sum(x<$x:y)`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ×Ị¥ÐḟL$ÐLLạL ``` [Try it online!](https://tio.run/##y0rNyan8///w9Ie7uw4tPTzh4Y75PiqHJ/j4PNy10Of/4fZHTWv@/482jNVRiDbQM9VRMNCzgLCNQGwjZDaIMAYRZghlOgqGYDmwTmOwrCkWCRMIGQsA "Jelly – Try It Online") ``` ×Ị¥ÐḟL$ƬẈ.ịI ``` [Try it online!](https://tio.run/##y0rNyan8///w9Ie7uw4tPTzh4Y75PirH1jzc1aH3cHe35//D7Y@a1vz/H20Yq6MQbaBnqqNgoGcBYRuB2EbIbBBhDCLMEMp0FAzBcmCdxmBZUywSJhAyFgA "Jelly – Try It Online") ``` ×Ị¥ÐḟL$ƬẈạLṪ ``` [Try it online!](https://tio.run/##y0rNyan8///w9Ie7uw4tPTzh4Y75PirH1jzc1fFw10KfhztX/T/c/qhpzf//0YaxOgrRBnqmOgoGehYQthGIbYTMBhHGIMIMoUxHwRAsB9ZpDJY1xSJhAiFjAQ "Jelly – Try It Online") Go upvote [Jonathan Allan's](https://codegolf.stackexchange.com/a/223733/66833) or [Unrelated String's](https://codegolf.stackexchange.com/a/223734/66833) answers, they're much better. ## How they work ``` ×Ị¥ÐḟL$ÐLLạL - Main link. Takes a list L on the left $ÐL - Repeat the previous 2 links until it reaches a fixed point: L - Yield the length of the list ¥Ðḟ - Remove elements which return false under the previous 2 links: Ị - They are less than or equal to 1 when × - multiplied by the length L - Get the length of the fixed point L - Get the length of L ạ - Absolute difference ×Ị¥ÐḟL$ƬẈ.ịI - Main link. Takes a list L on the left $Ƭ - Repeat the previous 2 links until it reaches a fixed point. Return all steps: L - Yield the length of the list ¥Ðḟ - Remove elements which return false under the previous 2 links: Ị - They are less than or equal to 1 when × - multiplied by the length Ẉ - Lengths of each step .ị - Get the first and last I - Subtract them ×Ị¥ÐḟL$ƬẈạLṪ - Main link. Takes a list L on the left $Ƭ - Repeat the previous 2 links until it reaches a fixed point. Return all steps: L - Yield the length of the list ¥Ðḟ - Remove elements which return false under the previous 2 links: Ị - They are less than or equal to 1 when × - multiplied by the length Ẉ - Lengths of each step L - Length of L ạ - Absolute differences Ṫ - Get the last one ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~72~~ \$\cdots\$ ~~43~~ 42 bytes Saved 7 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! Saved ~~3~~ 4 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!! ``` f=lambda l:l>[]>1>=len(l)*l.pop()and-~f(l) ``` [Try it online!](https://tio.run/##bY/BTsQgEIbvfYpJTAMY2mxZ12ya0Kfw1vRQ26nbiJQAa9SDT@DNq77cvkgFVqMHCfnzZ/5vZsA8@8OixXoBwzLO@q6Go5@K/TpJ1T/cjj2oWjVt11SNVKipYpeqNIuhrNdj8TqFwurReQcSaFt1HNpNueOwKfdnL6IXf32UbZTrX4xDlbLUuU3p7p/g6qwdy/DJ4OBxjGsDIdINfYETLBsOONyjjSE5fb4RDuT08U5YNi0WPEeYNbzMhqaXc/gZxuoMwol/mahbbChRzy0@onUob@wRGUuEsbP2QHIHRQNBc0cgh8BCmPa9vEUpXcfWLw "Python 2 – Try It Online") Assumes the input is sorted from highest to lowest. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` >Lİ$x@ƊÐLL_@L ``` ``` >Lİ$x@ƊÐLL_@L >Lİ$ arg is greater than 1/len(arg) x@ filter (finds people left) ÐL apply until converged L_@L length of argument minus length ``` [Try it online!](https://tio.run/##y0rNyan8/9/O58gGlQqHY12HJ/j4xDv4/D/c/qhpjfv//9HRhrE6CtEGeqY6CgZ6FhC2EYhthMwGEcYgwgyhTEfBECwH1mkMljXFImECIWNjAQ "Jelly – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 15 bytes ``` l-Qu.xf<c1lGTGY ``` [Test suite](http://pythtemp.herokuapp.com/?code=l-Qu.xf%3Cc1lGTGY&test_suite=1&test_suite_input=1%0A0.5%2C+0.8%0A0.2%2C+0.2%0A0.2%2C+0.2%2C+0.3%2C+0.6%2C+0.8%0A0%2C+0.25%2C+0.33%2C+0.5%2C+1%0A0%2C+0.25%2C+0.34%2C+0.34%2C+1%0A0.5%2C+0.5%2C+0.5&debug=0) Explanation: ``` l-Qu.xf<c1lGTGY | Full program l-Qu.xf<c1lGTGYQ | with implicit variables -----------------+------------------------------------------------------------------------------ f G | filter the list G for elements T such that c1lG | 1 / length of G < T | is less than T .x Y | unless an error is thrown in which case return the empty list u Q | repeat the above until a previous result is repeated, starting with the input l-Q | length of input with the elements of the resulting list removed ``` ]
[Question] [ Write a software that prints on stdout the number of answers and the number of comments(visible and collapsed of question and answers) of this question/page. Your script must run with this page closed when it starts. Expected example output: ``` A12C40 ``` Where A stands for Answers and C for Comments. [Answer] # Perl, 91 96  92 chars ``` $_=`curl -sL qr.net/_9`;s/<[^>]+nt="(.+)/$c+=$1/ge;say"A",s/<td.*"ans//g,C,$c+s/<tr.*"com//g ``` --- Some stuff just to break solutions of others ha ha ha :-P show **93** more comments href nt="99" (ha ha crash @Fez Vrasta) a ,show **99**show **99** ha ha [href](http://bit.ly/answercell) [href](https://codegolf.stackexchange.com/questions/20277/answercell) [href](https://codegolf.stackexchange.com/questions/20277/comment) ha ha haha :-D jeeez, just broke my own answer! I discovered that one of the above tricks, which I thought does nothing, will start working *after* this answer is not edited for some time! So your solutions will work only for some time. That's why you had seen +1 more answer in your solutions.. It's a timed bomb! My answer is already prone to it :-) Aaah, found a way how to launch it NOW... [Answer] ### XQuery, 169, 160, 165 ``` let$d:=html:parse(fetch:binary('http://qr.net/1_'))return"A"||count($d//*[@class="answer"])||"C"||count($d//*[@class="comment"])+sum($d//*[@class="comments-link"]/b) ``` More readable (with spaces): ``` let $d:= html:parse(fetch:binary('http://qr.net/1_')) return "A" || count($d//*[@class="answer"]) || "C" || count($d//*[@class="comment"]) + sum($d//*[@class="comments-link"]/b) ``` [BaseX](http://basex.org) was used as XQuery processor. [Answer] # Python 3, 180 ``` import lxml.html as h s=h.parse('http://qr.net/1_').find('body').cssselect print('A',len(s('.answer')),'C',len(s('.comment'))+sum(int(e.text)for e in s('.comments-link b')),sep='') ``` I'm assuming that this question won't have multiple pages of answers. [Answer] ## BASH + AWK ~~163~~, ~~144~~, ~~138~~, ~~111~~, ~~110~~, ~~114~~, ~~131~~, ~~132~~, 105 ``` curl -sL http://qr.net/_9|awk -F'[<>]' '/^[\t]*>s/{c+=$4}/<tr.*"c/{++c}/<t.*"a/{++a}END{print "A"a"C"c}' ``` Which is the same as this, but without redirecting to a file: ``` curl -sL http://qr.net/_9>f awk -F'[<>]' '/^[\t]*>s/{c+=$4}/<tr.*"c/{++c}/<t.*"a/{++a}END{print "A"a"C"c}' f ``` ### Current output ``` A16C76 ``` ### Explanation curl Transfer a URL. * `-s` in `curl` is for silent. And `-L` to follow redirects. awk To parse the file. As some answers had some code to break other answers, the parsing has been changed so that it parses from the beginning of the line `(^`) to make sure it is not broken. * `-F'[<>]'` set field separators as `<` or `>`. This way the text can be parsed properly for the "show XXX more comments". * `/^[\t]*>show <b>/{c+=$4}` on lines containing "spaces....>show", get the 4th field (based on `<`, `>` separators) and add the value to the comments counter. * `/^[ ]*<tr.*s="comm/{++c}` on lines containing "spaces... * `/^<td.*rcell">/{++a}` on lines containing "", increment the counter of answers. * `END{print "A"a"C"c}` print the output. [Answer] ## PHP which actually works (302 chars) Unlike all of the other answers so far, this returns the correct answer even when the question spills onto more than one page. ``` <?function g($a,$b,$i){return json_decode(gzinflate(substr(file_get_contents("http://api.stackexchange.com/2.1/$a/$i/$b?site=codegolf"),10,-8)))->items;}$i=array(20277);foreach(g("questions","answers",20277)as$x)$i[]=$x->answer_id;echo"A".(count($i)-1)."C".count(g("posts","comments",implode(";",$i))); ``` [Answer] ### R, 326 ``` library(XML);b=htmlParse("https://codegolf.stackexchange.com/questions/20277");z=xpathApply;x=do.call(sum,sapply(z(b,"//tbody",xmlAttrs),function(x)as.integer(x[[1]])))+length(z(b,"//tr[@class='comment']",xmlValue));y=gsub("[^0-9]","",z(b,"//div[@class='subheader answers-subheader']/h2",xmlValue)[[1]]);cat("A",y,"C",x,sep="") ``` With indentation and explanations: ``` library(XML) b=htmlParse("https://codegolf.stackexchange.com/questions/20277") z=xpathApply x=do.call(sum,sapply(z(b,"//tbody",xmlAttrs), #Take the first attribute of tag tbody function(x)as.integer(x[[1]]))) #And sum them (=nb of hidden comments +length(z(b,"//tr[@class='comment']",xmlValue)) #+nb of visible comments y=gsub("[^0-9]","", #This is more straightforward as the number of answers is given on front page. z(b,"//div[@class='subheader answers-subheader']/h2",xmlValue)[[1]]) cat("A",y,"C",x,sep="") ``` Tested with [this page](https://codegolf.stackexchange.com/questions/20034/the-answer-to-life-the-universe-and-everything), it gives the right number of comments (including hidden) **on the front page** and the right number of answers, i. e. `A23C63`. And here is a solution at **482 characters** that grab the correct number of comments if the question ends up spreading on several pages: ``` library(XML);h=htmlParse;z=xpathApply;v=xmlValue;a=xmlAttrs;s=sapply;c="http://codegolf.stackexchange.com";f=function(b,i){do.call(sum,s(z(b,"//tbody",a)[i],function(x)as.integer(x[[1]])))+length(z(b,"//tr[@class='comment']",v))};b=h(paste0(c,"/questions/20277"));x=f(b);u=unique(s(z(b,"//div[@class='pager-answers']/a",a),`[`,1));if(length(u))x=x+sum(s(u,function(x)f(h(paste0(c,x)),-1)));y=gsub("[^0-9]","",z(b,"//div[@id='answers-header']/div/h2",v)[[1]]);cat("A",y,"C",x,sep="") ``` Indented: ``` library(XML) h=htmlParse z=xpathApply v=xmlValue a=xmlAttrs s=sapply c="http://codegolf.stackexchange.com" f=function(b,i){do.call(sum,s(z(b,"//tbody",a)[i],function(x)as.integer(x[[1]])))+length(z(b,"//tr[@class='comment']",v))} b=h(paste0(c,"/questions/20277")) x=f(b) u=unique(s(z(b,"//div[@class='pager-answers']/a",a),`[`,1)) #Grab all URLS of pages if(length(u))x=x+sum(s(u,function(x)f(h(paste0(c,x)),-1))) #Apply comment computation of all URLs y=gsub("[^0-9]","",z(b,"//div[@id='answers-header']/div/h2",v)[[1]]) cat("A",y,"C",x,sep="") ``` Tried on [this question](https://codegolf.stackexchange.com/questions/17005/produce-the-number-2014-without-any-numbers-in-your-source-code) and outputted: `A125C499`. [Answer] ## HTML, 37 *Sorry, Blatant rule abuse follows!* ``` <script src=http://q0x.eu/1></script> ``` ### Explanation `q0x.eu/1` redirects to: [http://api.stackexchange.com/2.1/questions/20277/comments?site=codegolf&callback=...](http://api.stackexchange.com/2.1/questions/20277/comments?site=codegolf&callback=%28function%28d%29%7Bc=d.items.length;document.write%28%27%3Cscript%20src=%22http://q0x.eu/2%22%3E%3C/script%3E%27%29%7D%29) where the callback is: ``` (function(d){ c=d.items.length; document.write('<script src="http://q0x.eu/2"></script>') }) ``` `q0x.eu/2` redirects to [http://api.stackexchange.com/2.1/questions/20277/answers?site=codegolf&callback=...](http://api.stackexchange.com/2.1/questions/20277/answers?site=codegolf&callback=%28function%28d%29%7Ba=0;g=%5B%5D;d.items.map%28function%28f%29%7Ba%2b%2b;g.push%28f.answer_id%29%7D%29;document.write%28%27%3Cscript%20src=%22http://q0x.eu/3?n=%27%2bg.pop%28%29%2b%27%22%3E%3C/script%3E%27%29%7D%29) ``` (function(d){ a=0; g=[]; d.items.map(function(f){ a++; g.push(f.answer_id) }); document.write('<script src="http://q0x.eu/3?n='+g.pop()+'"></script>') }) ``` and `q0x.eu/3?n=...` redirects to [http://api.stackexchange.com/2.1/answers/.../comments?site=codegolf&callback=...](http://api.stackexchange.com/2.1/answers/.../comments?site=codegolf&callback=%28function%28d%29%7Bc%2b=d.items.length;g.length?document.write%28%27%3Cscript%20src=%22http://q0x.eu/3?n=%27%2bg.pop%28%29%2b%27%22%3E%3C/script%3E%27%29%3aalert%28%27A%27%2ba%2b%27C%27%2bc%29%7D%29) ``` (function(d){ c+=d.items.length; g.length ? document.write('<script src="http://q0x.eu/3?n='+g.pop()+'"></script>') : alert('A'+a+'C'+c) }) ``` I was originally trying to do it legitimately and might still have a go, but this was fun nevertheless! [Answer] ## Ruby 175 (counts across pages, using the API instead of the DOM) ``` require'open-uri';require'json' q=JSON.parse(open("http://qr.net/oyJn").read)["items"][0];a=q["answers"] puts"A#{a.count}C#{[q,*a].reduce(0){|m,o|m+o["comments"].to_a.count}}" ``` That's 242 without the shortened url: ``` require'open-uri';require'json' q=JSON.parse(open("http://api.stackexchange.com/2.1/questions/20277?site=codegolf&filter=!azbR89z2Zw*dg.").read)["items"][0] a=q["answers"] puts"A#{a.count}C#{[q,*a].reduce(0){|m,o|m+o["comments"].to_a.count}}" ``` Previous 291 answer: ``` require'open-uri';require'json' def g(o,l,f);JSON.parse(open("http://api.stackexchange.com/2.1/#{o}/#{l}/#{f}?site=codegolf").read)["items"];end q=20277 p=g("questions",q,"answers").inject([q]){|m,o|m<<o["answer_id"]} puts"A#{p.count-1}C#{p.map{|i|g("posts",i,"comments").count}.reduce(:+)}" ``` Credits to Peter Tailor for the idea of using the API, and Charles for pointing towards a better API. [Answer] ## Python with [stackpy](https://pypi.python.org/pypi/stackpy) 160 **Implementation** ``` s=__import__("stackpy").Site("codegolf");q=s.questions(20277);a=q.answers print"A%dC%d"%(len(a),sum(len(s.answers(e.id()).comments)for e in a)+len(q.comments)) ``` **Output** ``` A13C60 ``` **Note** Yesterday I contemplated in using the stackexchange API but took some time for me to understand how it works. Today, I saw there were couple of answers on the same theme. To make my answer a bit different, I though of using an external library. Also realize that other answers which relies on parsing for patterns like are likely to break at anytime soon, so a more definite answer is to rely on a robust method like this one. [Answer] ## R 239 ``` library(XML);F=function(x,y,f=length,z='')sum(as.double(xpathSApply(htmlParse('http://qr.net/1_'),sprintf('//%s[@class="%s"]%s',x,y,z),f)));cat("A",F("div","answer"),"C",F("a","comments-link ",xmlValue,"//b")+F("td","comment-text"),sep="") ``` After I posted my answer, the output is: ``` A13C60 ``` [Answer] Cannot believe that nobody has came up with it until now! Most direct solution to use :-) # jQuery, 116 101 chars (off competition) Perhaps this doesn't go with the rules, I keep it just for fun - jQuery solution can't be missing :) At least as a reference to test your scripts!!! ;-) Try running from the FireBug console: ``` $('.comments-link').click(); setTimeout("alert('A'+$('.answer').length+'C'+$('.comment').length)",999) ``` If you have slow connection, increase the timeout :-) Thanks @Fez Vrasta for the great idea of clicking the "show more" links! --- Some other stuff to break solution of others, class="comment" and the timed bomb [ha](http://bit.ly/answercell) [ha](http://bit.ly/comment) [Answer] ## PHP: ~~184~~ 172 ``` <?$h=file_get_contents('http://qr.net/_9');preg_match_all('/<t.*nt="([0-9]*)/',$h,$c);echo 'A'.substr_count($h,'rcell">').'C'.(array_sum($c[1])+substr_count($h,'mment">')); ``` Explanation: ``` <? // short open tag $h = file_get_contents('http://qr.net/_9'); // store in $h the content of the shortened url of the page preg_match_all('/<t.*nt="([0-9]*)/', $h, $c); // find each "show/hide X more comments" and store the numbers in $c echo 'A' // output A .substr_count($h,'rcell">') // output the count of the occurrences of 'rcell">' (short for '"answercell">') .'C' // output C .( array_sum( $c[1] ) // output the sum of the collapsed comments found before + substr_count( $h, 'mment">') // output the count of the occurrences of 'mment">' (short for '"comment">') ); ``` *For the first time PHP beats other languages in golf-scripts :')* --- **Some extra markup to this topic to avoid regex "cheats":** [show **9999** more comments](http://goo.gl) [Answer] ## Node, 403 ``` r=require;m='comments' r('http').get("http://api.stackexchange.com/2.1/questions/20277?site=codegolf&filter=!azbR89z2Zw*dg.").on('response',function(p){p.pipe(r('zlib').createGunzip(o="")).on('readable',function(){o+=this.read()}).on('end',function(){d=JSON.parse(o).items[0] r('util').print("A",d.answer_count,"C",(d[m].length+d.answers.reduce(function(p,c){return p+(c[m]?c[m].length:0)},0)))})}) ``` Only hits the API once... can likely be shortened, but I'm new to Node. [Answer] ## 153 151 147, C# & CsQuery C# With CsQuery: ``` var d = CsQuery.CQ.CreateFromUrl("http://qr.net/1_"); Console.Write("A" + d[".answer"].Count() + "C" + d[".comment"].Count()); ``` Full program: ``` class P{static void Main(){var d =CsQuery.CQ.CreateFromUrl("http://qr.net/1_");Console.Write("A"+d[".answer"].Count()+"C"+d[".comment"].Count());}} ``` ### 118 C# & CsQuery in LINQPad or in Roslyn If running through LINQPad is allowed then: ``` var d =CsQuery.CQ.CreateFromUrl("http://qr.net/1_");Console.Write("A"+d[".answer"].Count()+"C"+d[".comment"].Count()); ``` Produces: > > A14C48 > > > Some more fun. ### F# with CsQuery, 143: ``` [<EntryPoint>] let main x= let d=CsQuery.CQ.CreateFromUrl("http://qr.net/1_") printfn "A%dC%d" d.[".answer"].Length d.[".comment"].Length 0 ``` ]
[Question] [ Your task is to build a program that identifies the shape of the input. The shapes to be identified can be any of the following: ### Square To be identified as a square, the source must have lines of all equal length, and the same number of lines as characters per line (newline characters excluded). An optional trailing newline is acceptable. ``` $_=' $_=" $_"' ;say ``` ### Rectangle To be identified as a rectangle, the source must have lines of all equal length, but the number of lines does not match the number of characters per line (newline characters excluded). An optional trailing newline is acceptable. This can be either horizontal or vertical. ``` $_= "no t a squ are ";# $_="but it is still a consistent shape!";## ``` ### Triangle To be identified as a triangle, the source must either start with one character, and each subsequent line must have one additional character (including the last), or after the first line, each subsequent line should have one character fewer until the last, which has only one. ``` $ _= "So this "."". shape; $_="or even, this way !! " ``` ### Mess Anything that doesn't follow a consistent format as per the above, must be identified as a mess. ## Rules * You may return any four consistent printable values to identify each shape. * **Your source code must also adhere to one of the above shapes (no, not a mess).** * A single trailing newline in your source is acceptable. * You can assume input does not contain any blank lines (including trailing newlines), is not empty, and does not consist only of newlines. * All shapes must have a height and width of >= 2, otherwise this is defined as a mess. * [Standard loopholes are forbidden.](https://codegolf.meta.stackexchange.com/q/1061/9365) * The shortest solution in bytes, in each language, wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes ``` L€ṀR,Ṛ$ċƲȧ3 L€,;¥LE€S+Ç ỴµZL«L>1ȧÇ ``` [Try it online!](https://tio.run/##y0rNyan8/9/nUdOahzsbgnQe7pylcqT72KYTy425QII61oeW@rgCGcHah9u5Hu7ecmhrlM@h1T52hieWH25X@E@@VgA "Jelly – Try It Online") `0` = Mess `1` = Rectangle `2` = Square `3` = Triangle [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 45 bytes ``` lᵐ{≥₁|≤₁}o{l>1&t>1&}↰₃ lg,?=∧1w|=∧2w|t⟦₁≡?∧3w ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P@fh1gnVjzqXPmpqrHnUuQRI1eZX59gZqpUAce2jtg2Pmpq5ctJ17G0fdSw3LK8BUUblNSWP5i8Dqn3UudAeKGBc/v9/tJKhko6CkqERhDSGUiZKsQA "Brachylog – Try It Online") Code is a rectangle (despite the way it renders on my screen). Outputs: 1 for square, 2 for rectangle, 3 for triangle, and nothing for mess --- ### Explanation: ``` lᵐ{≥₁|≤₁}o{l>1&t>1&}↰₃ lg,?=∧1w|=∧2w|t⟦₁≡?∧3w lᵐ Get the length of each string { } Verify ≥₁ The list is non-increasing | or... ≤₁ The list is non-decreasing o Sort it to be non-decreasing { } Verify l>1 The number of lines is greater than 1 & and... t>1& The longest line is longer than 1 character ↰₃ Call the following lg,? Join the number of lines with the line lengths =∧1w If they are all equal, print 1 (Square) |=∧2w Or if just the line lengths are equal, print 2 (Rectangle) |t⟦₁ Or if the range [1, 2, ... <longest line length>] ≡? Is the list of lengths ∧3w Print 3 (triangle) Otherwise print nothing (mess) ``` [Answer] # Java 10, ~~231~~ ~~221~~ ~~219~~ ~~217~~ ~~213~~ ~~211~~ ~~207~~ 203 bytes ``` s->{var a=s.split("\n");int r=a.length,l=a[0].length(),R=0,i=1,L,D;if(r>1){for(L=a[1].length(),D=L-l; ++i<r;R=L-a[i-1].length()!=D?1:R)L=a[i].length();R=R<1?D==0?r==l?1:2:D*D>1|l>1&L>1?0:3:0;}return R;}; ``` Function is a rectangle itself. `1` = Squares; `2` = Rectangles; `3` = Triangles; `0` = Mess. -14 bytes thanks to *@OlivierGrégoire* -4 bytes thanks to *@ceilingcat* **Explanation:** [Try it online.](https://tio.run/##vVXBctowEL3zFbLSaU0CDm5vOIYLhxxIOwO5RZmOMAKUKjKRZDKZlG@nK4Nlk4SaTDplwKzk1dunt8/WHV3R9t301yYRVGt0Rbl8biDEpWFqRhOGvtthPoESf2wUl3OkmxFMruEHX22o4Qn6jiSK0Ua3e88rqhCNdaCXghsfE4mbkV2vYhoIJudm0RIxvenc7kZ@szWKOy0eh61haxDxma96YfN5lip/CHlhJW8QD9siapyd8QsVjWBAb3i7kuDFg37YHTXtOl5OQ@roIuwP4rjTV3EsIOdrd3A66IW/RS/8POyF/U73W7cTrRUzmZJoFK2jTdSA7S2ziYDt7Xa5SvkU3YNIOylubmlzK9D4SRt2H6SZCZZwxwjp4/FDRhXTXZzrhdD5Kfr0M/6Sx/CBGJcxdvORpk/o9PwQrAwSH1scIuFKsP0jGEZ2HW6WtSaCFpD7YR04pBBZXBziG9m7OwcFGLHEUDkXrzQoyGCZFqFBjqJ@yIoQ9HO50ckRqhBJAJSA3YA@ABEJEHYyOqlqY7WfZAZxU8BzDU3mQpQ0klRqDoWky9ELumQeQB3FZFeAyBKayBIU6OVwltoet@sF1xVWjo9h2tTVtWvzglDK5n@ke9eKv9G8gk2lieOyiRXqOMA42FMuqlWNyG0Hx7aD@VYIDsDicNmqFb1sYqqKEmzFZOstIo/0qQg9z7Hb/h3TxlQRmYMXnACQSM@z5Kp0nE0Ud/aV8yIEHft15cATioNj5ZxIm/@R7l0xvde4v7mqlMdD73WYVcKryvBDoUX66BSYAIITBmR0/dJs2q8vt0UDTSwOyGMRwAt27Xu0N64seLoI58J55wgv7DfHAAuAIvCAgDuqVC7rgC5fvKSPeB3XGOHwCZRmCg7xJJ0yeBNpJmbOEoeqvT7B4fmzVv/HhziR/@UU3ym3bqw3fwA) ``` s->{ // Method with String parameter and integer return-type var a=s.split("\n"); // Input split by new-lines int r=a.length, // Amount of lines l=a[0].length(), // Length of the first line R=0, // Result-integer, initially 0 i=1, // Index integer, starting at 1 L,D; // Temp integers if(r>1){ // If there are at least two lines: for(L=a[1].length(), // Set `L` to the length of the second line D=L-l; // And set `D` to the difference between the first two lines ++i<r; // Loop over the array ; // After every iteration: R=L-a[i-1].length()// If the difference between this and the previous line !=D? // is not equal to the difference of the first two lines: 1 // Set `R` to 1 : // Else: R) // Leave `R` the same L=a[i].length(); // Set `L` to the length of the current line R=R<1? // If `R` is still 0: D==0? // And if `D` is also 0: r==l? // And the amount of lines and length of each line is equal: 1 // It's a square, so set `R` to 1 : // Else: 2 // It's a rectangle, so set `R` to 2 :D*D>1& // Else-if `D` is NOT 1 nor -1, l>1&L>1? // and neither `l` nor `L` is 1: 0 // Set `R` to 0, since it's a mess : // Else (`D` is 1 or -1, and `l` or `L` is 1): 3 // It's a triangle, so set `R` to 3 :0;} // In all other cases it's a mess, so set `R` to 0 return R;} // Return the result `R` ; // No-op to make the method a rectangle ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~32~~ 27 bytes ``` ,U⁼€JẸ,E;SƲ$ ZL«L’aL€Ç$æAƝ ``` [Try it online!](https://tio.run/##y0rNyan8/18n9FHjnkdNa7we7tqh42odfLjt0CYVriifQ6t9HjXMTPQBSh1uVzm8zPHY3P8Pd2853P7/fzZXSgoQpXAVp6QVc6VkAyGEzIZSKVxpWSnZxTlZaQA "Jelly – Try It Online") Now taking input at a list of lines and switched `>1×` with `’a` and using `SƲ` after `L€` instead of `FLƲƊ`. These allowed me to condense into two lines and I saved 5 bytes in total. The following values are the same as before. `[0.0, 0.0]`=Mess `[0.0, 1.5707963267948966]`=Rectangle `[0.0, 0.7853981633974483]`=Square `[1.5707963267948966, 0.0]`=Triangle --- `ZL«L` gets the minimum of height and width and `’` subtracts 1 from it. `Ç` calls the second link and at the end if the input is a single line the result of `Ç` gets logical ANDed with the previous number if there is only a single line the output will be `[0.0, 0.0]`. In the second link: `,U` yields a list of line lengths paired with it's reverse. `J` is `range(number of lines)` and `⁼€` checks whether each of them are equal to the result of `J`. `Ẹ` (Any) yields 1 if the input is a triangle. `E` checks if all line lengths are equal (rectangle/square). `SƲ` with a `$` to group them into a single monad checks whether the total number of characters is a square number. So at the end of the second link we have `[[a,b],c]` where each number is `0` or `1` indicating whether the input is a triangle, rectangular, and has square number of characters respectively. However a square number of elements doesn't imply the input is a square since an messy input like ``` a3. 4 ``` has a square number of elements but isn't a square. This is where `æA` (arctan2) comes in. `0æA0` == `0æA1` == `0`. In other words, if the input has square number of elements but is not a rectangle, then it is not a square. There are certainly more clear ways to do this but what does that matter when we have bytes to think about and we are allowed consistent arbitrary output. Note I was previously using `æA/` instead of `æAƝ` (and a `,` instead of a `;` in the second link) but the former method distinguishes between triangles that have square number of elements and those that don't but they should obviously be counted as the same thing. [Answer] # [Python 2](https://docs.python.org/2/), ~~129~~ ~~114~~ ~~109~~ ~~107~~ 113 bytes ``` l=map(len,input().split('\n'));m=len( l);r=range(1,m+1);print[[1],0,r,r[::- 1],[m]*m,0,[max(l)]*m,l].index(l)%7/2 ``` [Try it online!](https://tio.run/##jU/NTsMwDL73KVoPtARCWbkgLcpTcEyqKbCIRkrcKMmAPv1wxSZxQlys78f@bKelTjM@nc9BRZtYcCg8plNlvC8p@Mq2Brecy6jIYk3gMqts8d2xQcT7gcuUPVath1HsRBZZ7/cPDREdx7tIko72iwW@kjD2Ho9upbfPj7QSdtAAwM1B0RKqsFYgLItdyLiY8Hqqra8GfWlL9SG01uDbjMWX6pD0MtnkOpCbzXXI4EEZhJfZYJ18IdgD9JdO@St6zgbdBz19bfy0i8GuM2j/l2Xw5/S/g74B "Python 2 – Try It Online") --- Prints * `0` = `Mess` * `1` = `Triangle` * `2` = `Square` * `3` = `Rectangle` [Answer] # Java 10, ~~274~~ ~~323~~ ~~298~~ 229 bytes First triangle submission. ``` s -> { var a=s. split ("\n"); int i,l= a.length, c,f=a[0]. length(),r= l<2||f<2&a[1 ].length()<2? 0:f==l?7:5;var b=f==1;for(i=1; i<l;){c=a[i++]. length();r&=c!=f? 4:7;r&=(b&c!=f+1)| (!b&c!=f-1)?3:7;f=c ;}return r;} ``` `0` Mess `1` Rectangle `3` Square `4` Triangle Try it online [here](https://tio.run/##rZRdb9owFIav8a8w2dQmAtJCN1XCuFzvYjdjdzWajHHAXXpCbYcKFX47O07IStFUVRq5sHP88b7HPtbzINey9zD/vV@Vs9woqnLpHP0uDdAX0jLgtc2k0nSylCv9ba7Bm8xoGybDLDX10KaajyfeGlhQA6vSJ4y0dqRFWgdl56XHbl2YOX1E/cPi@ymVduGSSvHUxZ3EnO4d6d2RF0rJWlpKJHcpJW6VG09JHAmI0LbKq5tzItNcw8Ivu0R1My7vr6e4uB6Kk67lJB8NtttsNLiQ930yTZup0WBMrocZ5/n4dviVoROZcQz7LCtsbLAnZpSz5EWhqOl0jmWZveCqzbMx@TK8DUE8uwhxp59sSdyug14/Gd/gdMYVYTurfWmBWrajh2/PCD35Jhvn9WNalD5d4b35HOJo8lRKq4c06pxcVPq2LNHnX/xSALYiCp2IMGJObqIkVKn1L@0fWnkJi/yD8gJEBIXAm5cC3FMpADMLg@zTGU2iWYml9QKMw/dk8jy4qQKcQW3A8UqjHVzfs/1pzYddBdSHm4TDLY0L/yleIza1GzuTUTheYQXotYZu4/UsNwLa7WD6js137dwHLOQZJGbqDCICZudRUQLmB6WrK@qXmq5ssbDy8dLR4hmoK0qL8FLFXP9/hbAcvTsByB4BAT74xAN98BkE/MShRiI0CcOxhkG4qIGQgIZBQeEIQwL6XRUoQ5EyOHUMGiMASYOMSWxgzTR93RkgczPEF8NMFlvchEsqZgkYDC3TudO0kcGEDjI1s0ISr0rM/qUU5pJsjzF1jVIZ5qSQU7ziZXOGY4UaoQ1BBVQMDVvfsq2u1Y7s9n8A). Edited multiple times to golf it a bit more. Of course I could save a lot of bytes by turning this into a rectangle as well (~~281~~ ~~267~~ ~~259~~ 200 bytes, see [here](https://tio.run/##rZRdb9owFIavya8w2UQTASnQTZUwKde76E3ZHUaTCQ64MyfUdqgQ8NvZMUlGQVOFNHIRfxz7fY99rOeVr3n7dfb7sMqnSiYkUdwY8swlkK1Xk2CFTnkiyGjBV@LHTICVqRTaBV2UyGJqc4wHI6slzImEVW5D6tX2Xs2rlcrGcovNOpMzskT9cvF4Qriem/CoeOliLsYxOZj203bNNeGxicxKSRv4DPyQHpNpqZhHSsDcLlppzMedSTkKwpaO1aC326XEG/QafNw9hQa9YaefxrEaPva/txLq5KcxTnRpmulAYisHiobbBCVlszmJvGor1Y04qcfp8Fv/0fWDacMNm91wF9SLfrsbDh8wmsYJ3Wthcw1E0/2BeuTiG22MFcsoy220wquxCgJ/9JZzLfrEb17cRXR@8/7XX/EdA/wz3zXMxxE1fOOHrhC1f2m/iMRymKsr5RkwHzKG98wZmLecAWbmJumXG5r40xwLaRlIg09GKuXckgyMRG3A@aNG3bl@ZvtTy6tdGRSHG7nDLaRx/QivEX@FG72RkTtephmItYBW5fXONwzqdWf6ic2zMOYKC34DiWlyAxEG09uoJAxmpdL9PbELQVY6m2u@vDMkewdislwjn5JsJv6/QliO9hODLSEMHAXwiSNmsClI42rE3C@kOFcRBxdVzGFQUoc4hQ/oYdA9gQVDZ2xhgHRBroTa8WUSnXY6sjz08cVQmQYaN@GSI6gY9PqaCmUEqWQwoVKm4JRL4qRE9V82YS7ndOqgVIo5OT4VkKzO8FHhnJoMSm5qemKa21DUau/tD38A)). The result of the identification is manipulated using bitwise AND, yielding a bitmask as follows: ``` 1 1 1 triangle square rectangle ``` Ungolfed version: ``` s -> { var lines = s.split("\n"); // split input into individual lines int i, // counter for the for loop numLines = lines.length, // number of lines current, // length of the current line previous = lines[0].length(), // length of the previous line result = numLines < 2 // result of the identification process; if there are less than two lines || previous < 2 & lines[1].length() < 2 // or the first two lines are both shorter than 2 ? 0 : previous == numLines ? 7 : 5; // it's a mess, otherwise it might be a square if the length of the first line matches the number of lines var ascending = previous == 1; // determines whether a triangle is in ascending or descending order for(i = 1; i < numLines; ) { // iterate over all lines current = lines[i++].length(); // store the current line's length result &= current != previous ? 4 : 7; // check if it's not a rectangle or a square result &= (ascending & current != previous+1)|(!ascending & current != previous-1) ? 3 : 7; // if the current line is not one longer (ascending) or shorter (descending) than the previous line, it's not a triangle previous = current; // move to the next line } return result; // return the result } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` Jm0w,ET ỴẈµLe|Ç ``` [Try it online!](https://tio.run/##1VG9TsMwGNzvKZyPSF2iij3KyFJ1A@bKSU3j4ia0dqkqMQBLmGFhZ2WESgGJIVEfxH0R4zYMfQWWT3ff/Sw3FUqtnRvMTlfR2QXs94f9emo@h@Kurdz2xdZvu4efZtNsWFvtHt/Z9tnWr86FGCWg8xImlxrUJ@pD5/xGxEA4SqhcQNyKIur0FV8jCEAHDVT4GOPQ8yX4QoDiky6ULg2TBlIzbaRS3pKVhZbaiMJ07YH3dubeIeEP9RBr3w@eZmNxNcnl9FrN/g37o5jkHiLNMIZn@@8eAYPoMpTHy9j6PhnGbfUL "Jelly – Try It Online") Returns `[1]` for triangles, `[2]` for rectangles, `[3]` for squares and `[]` for messes ## How it works ``` ỴẈµLe|Ç - Main link. Takes a string S on the left Ỵ - Split S into a list of lines Ẉ - Take the length of each line µ - Use this list of lengths W as the left and right argument: L - Length of W e - This length is in W? This returns 1 for triangles and squares and for messes with one (or more) lines of a length of the number of lines in the mess Ç - Call the helper link on W | - Logical OR Jm0w,ET - Helper link. Takes a list of lengths W on the left J - Replace W with it's indices ([1, 2, ..., len(W)]) m0 - Reflect; [1, 2, ..., len(W), len(W), ..., 2, 1] w - Index of W as a sublist in this array, or 0 This returns a non-zero number for triangles E - Are all elements of W equal? This returns 1 for squares and rectangles , - Pair T - Return the indices of non-zero elements This yields: - [1] for triangles - [2] for rectangles/squares - [] for messes ``` Taking the logical or between these results yields: * `1 | [1] = [1 | 1] = [1]` for triangles * `0 | [2] = [0 | 2] = [2]` for rectangles * `1 | [2] = [1 | 2] = [3]` for squares * `1 | [] = []` or `0 | [] = []` for messes [Answer] ## Javascript 125 bytes ``` _=>(g=(l=_.split('\n').map(a=>a.length)). length)<3?0:(r=l.reduce((a,b)=>a==b?a:0)) ?r==g?2:1:l.reduce((a,b)=>++a==b?a:0)?3:0 0 = Mess 1 = Rectangle 2 = Square 3 = Triangle ``` ``` fa=_=>(g=(l=_.split('\n').map(a=>a.length)).length)<3?0:(r=l.reduce((a,b)=>a==b?a:0))?r==g?2:1:l.reduce((a,b)=>++a==b?a:0)?3:0 var square = `asd asd asd` var rectangle = `asd asd asd asd asd asd` var triangle = `asd asdf asdfg asdfgh` var mess = `asd dasdasd sd dasasd` console.log(fa(square), fa(rectangle), fa(triangle), fa(mess)) ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 83 bytes * Mess: nothing * Square: 0 * Triangle: 1 * Rectangle: 2 ``` ($z)=grep++$$_{"@+"-$_*~-$.}==$.,0,/$/,-1 }{$.<2or$_=$$z{$z>0||$.}?$z%2:@F>1&&2x!$z ``` [Try it online!](https://tio.run/##Dcq7DoIwGAbQnbeQfBK1F9omLMYiE5vP0HghxITYpjqYFnx0fz3zCUOcGqIN0taOcQiMAS6XHSsF3O4jIBdrIbniNWoudLFkyIPxEc4CKSO1ap7/64i0Nvuub3VVmfcKieh8Ky7Xrw@vu388SUyhJ3FqpFZS/QA "Perl 5 – Try It Online") [Answer] # PHP, ~~195~~ 205 bytes ``` <?$a=$argv[1];$r=substr($a,-2,1)=="\n"?strrev($a):$a;foreach(explode("\n",$r)as$l){$s=strlen($l);$x[$s ]=++$i;$m=$i==$s?T:M;}$z=count($x);echo$i*$z>2?$z==1&&key($x)==$i?S:($z==1&&$i>2?R:($i==$z?$m:M)):M;?> ``` The upside down triangle adds an expensive 56 bytes to this! Outputs are S,R,T,M Saved a few bytes thanks to Dom Hastings. [Try it online!](https://tio.run/##LYxNbsIwEIX3OUWFRsguYRGWcQefgA10RxGaBpdYDbZlG5Sm6tXrTqTO6v1880IfSnnRQAgUr49jc1IQMd3fU44CqF5v6kYiLt7cQnMUzYNT2QKpDx8Ndb0wYxj8xYgZqSFKSjDIb0jI@GCcYKdgPEKqTrhagVVwQ7CIkPRru1M/MGHn7y4LGKUyXe/BPsO03WgusFkuP83XXPGD1YdW/KdgmdiznZcmDbd2JyXP6W1VSun4KqqIqln9@pCtd6msL0@p9zGffTDunOmK3v0B "PHP – Try It Online") Fixed a few issues now... Test runs produce this. ``` $_=" $_=" $_"" ;say RESULT:S ============= $_= "no t a squ are ";# RESULT:R ============= $ _= "So this "."". shape; RESULT:T ============= $_="or even, this way !! " RESULT:T ============= as smiley asd A RESULT:M ============= X RESULT:M ============= XX RESULT:M ============= cccc a aa cccc RESULT:M ============= ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 81 bytes ``` {.lines>>.chars.&{($_==.[0],3)[2*(2>.max )+($_ Z- .skip).&{.[0].abs+.Set*2+^2}]}} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wi8nMy@12M5OLzkjsahYT61aQyXe1lYv2iBWx1gz2khLw8hOLzexgktTGyihEKWroFecnVmgCVQIUqOXmFSsrRecWqJlpB1nVBtbW/ufqzixUiENqFhTIS2/iItTKTExMSYPQSjpoIghc4EYKpAE5SJUYOOg6odLQYz5DwA "Perl 6 – Try It Online") Returns `True` for square, `False` for rectangle, `3` for triangle, `Nil` for mess. [Answer] # [Stax](https://github.com/tomtheisen/stax), 39 bytes ``` L{%m~;:-c:u{hJchC; |mb1=-C;%a\sI^^P}M0 ``` [Run and debug online!](https://staxlang.xyz/#c=L%7B%25m%7E%3B%3A-c%3Au%7BhJchC%3B+%0A%7Cmb1%3D-C%3B%25a%5CsI%5E%5EP%7DM0&i=L%7B%25m%7E%3B%3A-c%3Au%7BhJchC%3B+%0A%7Cmb1%3D-C%3B%25a%5CsI%5E%5EP%7DM0%0A%0A%24_%3D%27%0A%24_%3D%22%0A%24_%22%27%0A%3Bsay%0A%0A%24_%3D%22but+it%0Ais+still+a%0Aconsistent%0Ashape%21%22%3B%23%23%0A%0A%24%0A_%3D%0A%22So%0Athis%0A%22.%22%22.%0Ashape%3B%0A%0A%24_%3D%22or%0Aeven,%0Athis%0Away%0A%21%21%0A%22%0A%0Ashape%3B%0A%24_%3D%22or%0Aeven,%0Athis%0Away%0A%21%21%0A%22%0A%0Ashape%3B%0A%0As%0Ah%0Aa%0Ap%0Ae%0A%3B&a=1&m=1) Shortest ASCII-only answer so far. > > 0 - Mess > > 1 - Rectangle > > 2 - Square > > 3 - Triangle > > > > ## Explanation The solution makes use of the following fact: If something is explicitly printed in the execution of the program, no implicit output is generated. Otherwise, the top of stack at the end of the execution is implicitly output. ``` L{%m~;:-c:u{hJchC;|mb1=-C;%a\sI^^P}M0 L Collect all lines in an array {%m Convert each line to its length ~; Make a copy of the length array, put it on the input stack for later use :- Difference between consecutive elements. If the original array has only one line, this will be an empty array c:u Are all elements in the array the same? Empty array returns false { }M0 If last test result is true, execute block If the block is not executed, or is cancelled in the middle, implicitly output 0 hJ The first element of the difference array squared (*) chC Cancel if it is not 0 or 1 ;|m1= Shortest line length (**) is 1 - Test whether this is the same as (*) Includes two cases: a. (*) is 1, and (**) is 1, in which case it is a triangle b. (*) is 0, and (**) is not 1, in which case it is a square or a rectangle C Cancel if last test fails ;% Number of lines a\ [Nr. of lines, (*)] I Get the 0-based index of (**) in the array 0-> Square, 1->Triangle -1(not found) -> Rectangle ^^P Add 2 and print ``` [Answer] # [Haskell](https://www.haskell.org/), ~~113~~ ~~107~~ ~~103~~ 101 bytes ``` ((#)=<<k).map k.lines;k=length;1#x=0;l#x|x==[1..l] ||x==[l,l-1..1]=3;l#x=k[1|z<-[l,x!!0],all(==z)x] ``` [Try it online!](https://tio.run/##vZDBaoQwFEX3fsWbpFAFDdpZalbddmDodFFwpKQSo/gmTE0EGfz22sROp/QHuklyzr1v8dIK00vEpeHHJQxpxIuij9hJnKFn2Glp8p6j1Mq2eUYnnuZIp3nivMwYwyoAmFfCGBNnsopvfYP3ZTZfisT5abNJq1gghpxfoqlaFKTAgeykMSRQkHl4lrUVWqH05sGbw8cohhW3Hl@G7pa/raIV9t6AgPdRMRIEJ9Fp5ztt5SBqC3eggEETJAlcI7fTDsLzaA92eNIuXAsRlISSmFBKj/r74e5fcz08/@R/zG2EVP/zf591g0KZJXl93O@/AA "Haskell – Try It Online") Returns 0, 1, 2 and 3 for mess, rectangle, square and triangle, respectively. *Edit: -2 bytes thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn)!* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~35~~ ~~29~~ 27 bytes Saved 8 bytes thanks to *Magic Octopus Urn* ``` DgV€g©ZU¥ÄP®Y QP®ËJCXY‚1›P* ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fJT3sUdOa9EMro0IPLT3cEnBoXSRXIJA83O3lHBH5qGGW4aOGXQFa//9Hq6vE2yrlF6nrKKinlqXm6YAYJRmZxSC6PLESRCkqgkgl9VgA "05AB1E – Try It Online") `0` = Mess `4` = Triangle `1` = Rectangle `3` = Square [Answer] # [R](https://www.r-project.org/), 101 bytes ``` "if"(var(z<-nchar(y<-scan(,"",,," ","")))==0,"if"(length(y)==z,1,2 ),"if"(all(abs(diff(z))==1),3,4)) ``` > > 1=Square > > 2=Rectangle > > 3=Triangle > > 4=Random > > > > Code cannot deal with 'NEGATIVE ACKNOWLEDGE' (U+0015) or the square in the code above. This byte can be switched to something different if the input requires contains this byte. [Try it online!](https://tio.run/##vZJBa8MwDIXvuu@eaIPaoJZ12y3NYbBrN@huvQw3cxaDcbbIbUn@vKss/8EghHhIvI@HhpTQtaguZlDTbh2aToZxt@bGBEWIRISAhHeota7rR/rf9jb8xE6Noky0pSfQi268V@bE6tu1rZrmg62mZ3rROj181SuQhtJwBRWbESCL9ewKGHqIhQH@O4MZLGB1n9EeT@dYuAiOC47OewFp@sCOow0RuDO/thSifEgwR/IpkXSOATeIm4WiyhlKP4C92EALxVUeoiwBcxEcXt/fPvZHOEqldAM "R – Try It Online") [Answer] # Snails, 29 bytes ``` ada7A .2,lr ?!(t. rw~)z .+~o~ ``` Output key: * **0** - Mess * **3** - Triangle * **6** - Rectangle * **7** - Square It would be 23 bytes without source layout: ``` zA .2,dun!(t.rf~)z.+~o~ ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 119 bytes ``` (x=StringLength/@#~StringSplit~"\n")/.{{1}->3,s~(t=Table)~{ s=Tr[1^x]}:>0,x[[1]]~t~s:>1,(r=Range@s)|Reverse@r:>2,_->3}& ``` Using `Replace` `/.` and pattern matching on the character count by line. `Replace` will kick out the first RHS of a rule that is matched, so the ordering is to test for the 1 character input, then squares, rectangles, triangles, and a fall-through for messes. square=0,rectangle=1,triangle=2,mess=3 [Try it online!](https://tio.run/##NY3bUoMwEIbvfQqbdhRmYhF7BxOGB/DCKb1jaSdtw6HSbU2i0kHy6pjIeLGn//9298x1Lc5cNwc@lmz0OpZp2WD1KrDSdZDOzTRn17bRhgASP1j2fTg8JSuqjKfZhu9b4Zv@TrGNzMNtVwxR8ky7PA@LwmijoiSknmRrjpVIlf@zFl9CKpHKKHmhO3tneBjf7A@dl0Hak8WOAblIQIshBdR1owC/@Q1wNgMEQihZAFrK9tnlHwCyBOISqppfReyoiUHH3HNrfHwCcimcGM8n4BHw76ErQOwUK36zFlfHtnw/2WJX1LF0kgvA/YEMxfgL "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Red](http://www.red-lang.org), 209 bytes ``` func[s][c: copy[]foreach a split s"^/"[append c length? a]d: unique c r: 0 if 1 < l: length? c[if 1 = length? d[r: 2 if(do d)= l[r: 1]]n: 0 v: copy[]loop l[append v n: n + 1]if(v = c)or(v = reverse c)[r: 3]]r] ``` [Try it online!](https://tio.run/##XY/BTsMwEETv@xUbF6lUoEDLLaXiH@BomcrYDrEU2cZ2girUbw@bps0hF2u182Z2HI0e3o1GLqCuhrpziifBVYXKhxMXtY9GqgYlptDajIl9PjEuQzBOo8LWuO/cvKEUusLO2Z/OoIJY4TPaGrf4im01Q4pfdod5oTmROyLvtUe9IWFcbIVwFAD9rUPrfSDperRHUh0@EEfGnuLUxsfLEE1vYqIGmzHnRYgohhCty1jj393xwL66jDaDTZiybVuUoLxLNmXjMqRGBlOw/Wp1BphsV98aRjM9bA37JE@zPspwPAD78JAbm4CVjJVT0n5JleWSo2GB3or6CPQX9zjRv/IERQHsPPwD "Red – Try It Online") `0` Mess `1` Square `2` Rectangle `3` Triangle [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 119 bytes ``` {p=l;l=L[NR]=length($0) D=d}{d=p-l;x=x?x:NR>2?\ d!=D:0}END{print x==1?\ 3:d*d==1?(L[NR]+L[1]==\ NR+1)?2:3:p!=NR}####### ``` [Try it online!](https://tio.run/##JYy7CoMwFED3@xWNddDago8tcpvFbpIhq0oREqo02CBSUyTfnr7OdDjD6de795tBXWqsGy461Gq6LUMUpjFUKN0m0Zx0adEyS7k456wFSbCiqbvwajPzOC07i5h9ekHlQX41@q2Susk6xBa4SLKY5bSghiAXbv/H@/CKwWMG9VTTEZZhhLV/ASEQwBs "AWK – Try It Online") Output: `0` = Square `1` = Rectangle `2` = Triangle `3` = Mess [Answer] # [Ruby](https://www.ruby-lang.org/), ~~115~~ 111 bytes ``` ->s{m=s.split(?\n).map &:size;r=*1..s=m.size;s<2?4:(m|[ ]).size<2?m[0]<2?4:s==m[0]?1:2:r==m.reverse||r==m ?3:4} ``` [Try it online!](https://tio.run/##HYrBDoIwEAXv/YpCiAGjjSCnytoPQWIwltjEYrOLGhS/vRZuM/MePi@j78Bvj/S1QILc3QypOvWZsK3jK0nmow8I61wIAisWpapQpUztVLMmW1IItt41SyeAmVUuC4mBBeqXRtLTNBtXe1n@vONdnVRhaq@NT84QP5CFW79hw80Qe7cjiyIW/wE "Ruby – Try It Online") Anonymous lambda. Outputs: 1. Square 2. Rectangle 3. Triangle 4. Mess [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~125~~ 123 bytes Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for -2 bytes. ``` f(L,n)int**L;{int i,l,c,F=strlen(*L),s=-F;for(l=i=0;i<n;l=c)c =strlen(L[i++]),s+=c-l;s=n>1?s||F<2?~abs(s)+n?0:3:n^F?2:1:0;} ``` [Try it online!](https://tio.run/##bVFNc9owED3bv0JRmqlsiwwYQmYQDjdO3HrEtGOEMJpx1tRr0ukQ8tepJJuBNL5oP/Te076V7OVSnu81yOKwUWSKdaUhf9y9@Le9jS5N67xlCw6BhjoMF@JoItG84JLPE0MrFLBwEXBMenOxLStWJDrpCz0FUSQykP4FtFjqKFoZYJTIXiEwgZfBDN/f59N49pGtkWEQwaw/GU7g53wWTwaTvjid30q9ITmTJWBN5C6rSBgWGhRyYgeBwD/63u0t7rK9wuWKJORIXxUi5YTi70NWKZtVStYZ5IUrjOkmPwnfs3Joou8ZF4Q5m0akL0yYEjAhigLf8/aHGpkbYalXgSOgwW1ZOxY0vb1ZaL1lNIWHDWEPGKSQgnnUINoR0bJPvm9fes00sC9eaoX1oLXy7VeSfrdD24Q2SUqblsDsr/PwPzm@ki0upVA63yRrt2JDu5mUivtOkeFFxKIuQj8aoZ3Gpn5M7WFyjzp7olNqdGOGlpWlqjcF/Fbrj/Fiwt1dI9yp89TqqKrMYV2q3GLN@l3EvIBO1vgLqwv13KJitxt7rB3O93LmPoSTkf3ipoo5GV@r4adq9Kl64mR4rcacDK7Vc3N3Ov8D "C (gcc) – Try It Online") ]
[Question] [ Given a string, find the first word starting with each letter (case insensitive). ### Sample Using `Ferulas flourish in gorgeous gardens.` as input: ``` "Ferulas flourish in gorgeous gardens." ^^^^^^^ ^^ ^^^^^^^^ | | | | | --> is the first word starting with `g` | --> is the first word starting with `i` --> is the first word starting with `f` ``` Then, the output for this sample should be the matched words joined by one single space: ``` "Ferulas in gorgeous" ``` ### Challenge Both input and output must be a string representation, or the closest alternative in your language. Program or function allowed. You can consider a word being at least one of: `lowercase or uppercase letters, digits, underscore`. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins. ### Another samples: ``` input: "Take all first words for each letter... this is a test" output: "Take all first words each letter is" ``` --- ``` input: "Look ^_^ .... There are 3 little dogs :)" output: "Look _ There are 3 dogs" ``` --- ``` input: "...maybe some day 1 plus 2 plus 20 could result in 3" output: "maybe some day 1 plus 2 could result in 3" ``` [Answer] # [Retina](https://github.com/mbuettner/retina/wiki/The-Language), 28 bytes: ``` M!i`\b(\w)(?<!\b\1.+)\w* ¶ ``` * `M!` - Match each work and print all words separated by newlines. * `i` - Ignore case. * `\b(\w)` - Capture first letter of each word * `(?<!\b\1.+)` - After matching the letter, check if there wasn't a previous word starting with the same letter. `\1.+` ensures at least two characters, so we are skipping the current word. * `\w*` - match the rest of the word. The above matches only words - all other characters are removed. * `¶\n` - Replace newlines with spaces. [Try it online!](http://retina.tryitonline.net/#code=TSFpYFxiKFx3KSg_PCFcYlwxLispXHcqCsK2CiA&input=Li4ubWF5YmUgc29tZSBkYXkgMSBwbHVzIDIgcGx1cyAyMCBjb3VsZCByZXN1bHQgaW4gMw) [Answer] ## [Retina](https://github.com/mbuettner/retina), 45 bytes ``` i`\b((\w)\w*)\b(?<=\b\2\w*\b.+) \W+   ^ | $ ``` Simply uses a single regex to remove later words starting with the same `\w` character (case insensitive with the `i` option), converts runs of `\W` to a single space, then removes any leading/trailing space from the result. [Try it online!](http://retina.tryitonline.net/#code=aWBcYigoXHcpXHcqKVxiKD88PVxiXDJcdypcYi4rKQoKXFcrCiAKXiB8ICQK&input=VGhpcyBpcyBhIGxvbmdlciB0ZXN0IHdpdGggc2luZ2xlIGxldHRlciB3b3JkcywgbnVtYmVycyBsaWtlIDIsIDMwMCwgMjAsIC01LCAzIGFuZCA1MiwgYW5kIG1vcmUuIEkgYWxzbyBzdGFydCB0aGlzIHNlY29uZCBzZW50ZW5jZSBhcyBhbiBleGN1c2UgdG8gYWRkIGFub3RoZXIgc2luZ2xlIGxldHRlciB3b3JkLiBvX08gT2ggYm95Lg) Edit: See [@Kobi's answer](https://codegolf.stackexchange.com/a/77273/21487) for a shorter version using `M!`` [Answer] # JavaScript (ES6), ~~73~~ 71 bytes ``` s=>s.match(u=/\w+/g).filter(w=>u[n=parseInt(w[0],36)]?0:u[n]=1).join` ` ``` *Saved 2 bytes thanks to @edc65!* ## Test ``` var solution = s=>s.match(u=/\w+/g).filter(w=>u[n=parseInt(w[0],36)]?0:u[n]=1).join` `; var testCases = [ "Ferulas flourish in gorgeous gardens.", "Take all first words for each letter... this is a test", "Look ^_^ .... There are 3 little dogs :)", "...maybe some day 1 plus 2 plus 20 could result in 3" ]; document.write("<pre>"+testCases.map(t=>t+"\n"+solution(t)).join("\n\n")+"</pre>"); ``` [Answer] # Pyth, 23 bytes ``` J:z"\w+"1jdxDJhM.grhk0J ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=J%3Az%22%5Cw%2B%221jdxDJhM.grhk0J&input=Take%20all%20first%20words%20for%20each%20letter...%20this%20is%20a%20test&test_suite_input=Take%20all%20first%20words%20for%20each%20letter...%20this%20is%20a%20test%0ALook%20%5E_%5E%20....%20There%20are%203%20little%20dogs%20%3A%29%0A...maybe%20some%20day%201%20plus%202%20plus%2020%20could%20result%20in%203&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=J%3Az%22%5Cw%2B%221jdxDJhM.grhk0J&input=Take%20all%20first%20words%20for%20each%20letter...%20this%20is%20a%20test&test_suite=1&test_suite_input=Take%20all%20first%20words%20for%20each%20letter...%20this%20is%20a%20test%0ALook%20%5E_%5E%20....%20There%20are%203%20little%20dogs%20%3A%29%0A...maybe%20some%20day%201%20plus%202%20plus%2020%20could%20result%20in%203&debug=0) `J:z"\w+"1` finds all the words in the input using the regex `\w+` and stores them in `J`. `.grhk0J` groups the words by their lowercase first letter, `hM` takes the first from each group, `xDJ` sorts these words by their index in the input string, and `jd` puts spaces between them. [Answer] # Perl 6, 39 bytes ``` {.words.grep({!%.{.substr(0,1).lc}++})} ``` [Answer] # C, ~~142~~ ~~132~~ 122 bytes 10 bytes lighter thanks to @tucuxi! ``` b[200],k;main(c){for(;~c;isalnum(c)|c==95?k&2?:(k|=!b[c|32]++?k&1?putchar(32):0,7:2),k&4?putchar(c):0:(k&=1))c=getchar();} ``` ~~Prints a trailing space after the last output word.~~ [Answer] # [MATL](https://esolangs.org/wiki/MATL), 23 bytes ``` '\w+'XXtck1Z)t!=XRa~)Zc ``` This borrows [Jakube's idea](https://codegolf.stackexchange.com/a/77275/36398) of using a regexp for removing unwanted characters and splitting at the same time. Input is a string enclosed by single quotes. [**Try it online!**](http://matl.tryitonline.net/#code=J1x3KydYWHRjazFaKXQhPVhSYX4pWmM&input=J1Rha2UgYWxsIGZpcnN0IHdvcmRzIGZvciBlYWNoIGxldHRlci4uLiB0aGlzIGlzIGEgdGVzdCc) ### Explanation ``` '\w+'XX % find words that match this regexp. Gives a cell array t % duplicate c % convert into 2D char array, right-padded with spaces k % make lowercase 1Z) % get first column (starting letter of each word) t!= % duplicate, transpose, test for equality: all combinations XR % set diagonal and below to 0 a~ % true for columns that contain all zeros ) % use as a logical index (filter) of words to keep from the original cell array Zc % join those words by spaces ``` [Answer] # Vim 57 keystrokes ``` :s/[^a-zA-Z_ ]//g<cr>A <cr>ylwv$:s/\%V\c<c-v><c-r>"\h* //eg<c-v><cr>@q<esc>0"qDk@q ``` Explanation: ``` :s/[^a-zA-Z_ ]//g #Remove all invalid chars. A <cr> #Enter insert mode, and enter #a space and a newline at the end ylwv$:s/\\c%V<c-v><c-r>"\h* //eg<c-v><cr>@q<esc> #Enter all of this text on the #next line 0 #Go to the beginning of the line "qD #Delete this line into register #"q" k@q #Run "q" as a macro #Macro ylw #Yank a single letter v$ #Visual selection to end of line :s/ #Substitute regex \%V\c #Only apply to the selection and #ignore case <c-v><c-r>" #Enter the yanked letter \h* #All "Head of word" chars #And a space // #Replace with an empty string eg #Continue the macro if not found #Apply to all matches <c-v><cr> #Enter a <CR> literal @q<esc> #Recursively call the macro ``` I'm really dissapointed by how long this one is. The "Invalid" chars (everything but `a-z`, `A-Z`, `_` and space) really threw me off. I'm sure there's a better way to do this: ``` :s/[^a-zA-Z_ ]//g ``` Since `\h` matches all of that expect for the space, but I can't figure out how to put the metachar in a range. If anyone has tips, I'd love to hear em. [Answer] # Julia, ~~165~~ ~~155~~ ~~151~~ ~~129~~ 102 bytes ``` g(s,d=[])=join(filter(i->i!=0,[(c=lcfirst(w)[1])∈d?0:(d=[d;c];w)for w=split(s,r"\W",keep=1<0)])," ") ``` This is a function that accepts a string and returns a string. Ungolfed: ``` function g(s, d=[]) # Split the string into an array on unwanted characters, then for # each word, if the first letter has been encountered, populate # this element of the array with 0, otherwise note the first letter # and use the word. This results in an array of words and zeros. x = [(c = lcfirst(w)[1]) ∈ d ? 0 : (d = [d; c]; w) for w = split(s, r"\W", keep=1<0)] # Remove the zeros, keeping only the words. Note that this works # even if the word is the string "0" since 0 != "0". z = filter(i -> i != 0, x) # Join into a string and return return join(z, " ") end ``` Saved 53 bytes with help from Sp3000! [Answer] # Jelly, ~~32~~ 31 bytes ``` ØB;”_ e€¢¬œṗf€¢¹ÐfµZḢŒlQi@€$ịj⁶ ``` [Try it online!](http://jelly.tryitonline.net/#code=w5hCO-KAnV8KZeKCrMKiwqzFk-G5l2bigqzCosK5w5BmwrVa4biixZJsUWlA4oKsJOG7i2rigbY&input=&args=IlRha2UgYWxsIGZpcnN0IHdvcmRzIGZvciBlYWNoIGxldHRlci4uLiB0aGlzIGlzIGEgdGVzdCI) [Answer] # **C# (LINQPAD) - 136 128 bytes** ``` var w=Util.ReadLine().Split(' ');string.Join(" ",w.Select(s=>w.First(f=>Regex.IsMatch(""+f[0],"(?i)"+s[0]))).Distinct()).Dump(); ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 40 bytes Code: ``` 94L32+çJžj-DU-ð¡""Kvy¬Xsl©åï>iX®«Uy}\}ðý ``` [Try it online!](http://05ab1e.tryitonline.net/#code=OTRMMzIrw6dKxb5qLURVLcOwwqEiIkt2ecKsWHNswqnDpcOvPmlYwq7Cq1V5fVx9w7DDvQ&input=Li4ubWF5YmUgc29tZSBkYXkgMSBwbHVzIDIgcGx1cyAyMCBjb3VsZCByZXN1bHQgaW4gMw) Explanation: We first generate all characters which should be deleted from the input string using `94L32+ç` ([Try here](http://05ab1e.tryitonline.net/#code=OTRMMzIrw6c&input=)). We join this string using `J` and remove `[a-zA-Z0-9_]` which is stored in žj ([Try here](http://05ab1e.tryitonline.net/#code=xb5q&input=)). We remove all the characters that are in the second string from the first string, which will leave us: ``` !"#$%&'()*+,-./:;<=>?@[\]^`{|}~ ``` That can also be tested [here](http://05ab1e.tryitonline.net/#code=OTRMMzIrw6dKxb5qLQ&input=). We `D`uplicate this and store in to `X` with the `U`-command. We then remove all the characters that are in this string from the input. We then split on whitespaces using `ð¡` and remove all empty strings (using `""K`). We now have [this](http://05ab1e.tryitonline.net/#code=OTRMMzIrw6dKxb5qLURVLcOwwqEiIks&input=Li4ubWF5YmUgc29tZSBkYXkgMSBwbHVzIDIgcGx1czopOikgMjAgY291bGQgcmVzdWx0IGluIDM). This is the *clean* version of the input, which we will work with. We map over each element using `v`. This uses `y` as the string variable. We take the first character of the string using `¬` and push `X`, which contains a string with all *forbidden* characters (`!"#$%&'()*+,-./:;<=>?@[\]^`{|}~`). We check if the `l`owercase version of the first character, (which will also be `©`opied to the register), is in this string using `å`. Covered by this part: `ï>i`, if the first letter doesn't exist in the string of forbidden characters (`X`), we append this letter to the list of forbidden characters (done with `X®«U`) and we push `y` on top of the stack. Finally, when the strings are filtered, we join the stack by spaces with `ðý`. [Answer] # **PHP** Inspired by the use of regex in most of the answers, I originally tried to do this without using regex at all just to show off a neat variation, but the sticking point of not having clean strings as input ruined that idea. Sad. **With function wrapper, 89 bytes** ``` function f($s){foreach(preg_split('/\W/',$s)as$w)$c[lcfirst($w)[0]]++?:$v.=" $w";echo$v;} ``` **Without function wrapper (needing $s pre-declared), 73 bytes** ``` foreach(preg_split('/\W/',$s)as$w)$c[lcfirst($w)[0]]++?:$v.=" $w";echo$v; ``` Explanation: ``` foreach(preg_split('/\W/',$s)as$w)$c[lcfirst($w)[0]]++?:$v.=" $w";echo$v; preg_split('/\w/',$s) Break input on all non-word characters foreach( as$w) Loop through each 'word' lcfirst($w)[0] Take the first letter of the lowercase version of the word $c[ ]++?: Increment an array element with a key of that letter after checking if it's false-y (0) $v.=" $w"; Add the word if the letter wasn't found (if the previous condition evaluated to false) echo$v; Print the new string to screen. ``` My only regret is that I couldn't find a faster way of checking/converting letter case. [Answer] # Python, 103 bytes ``` import re lambda s,d=[]:[w for w in re.findall("\w+",s)if(d.append(w.lower()[0])or d[-1])not in d[:-1]] ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 40 bytes ``` ->s{s.scan(/\w+/).uniq{|x|x.ord|32}*' '} ``` [Try it online!](https://tio.run/##LU7BbsIwFLv3K3wDNhE2epu0HXfakds2ptC@thFpXnkvEVSUX18XpEm2LNmyZUmHcW5e5/WbXtVoZcNy83V@3KxMCu50nS7TxbDUU7m9PSywuM1Diorms@q4H77nd5LkbTY8J3HawQW0LC1xUrRWagpqip09Eqz3aJxoxDkP5goLyFYdPMVIYoxB7JwiwyKSxuKD@Yj9zx7mHu46krySWcK7GD2h5lbxsipy3NvxQFDus2tHPGPw@cH2X55QcfI1hDT5eD9Z/vIQHQed1@EP "Ruby – Try It Online") `String#ord` returns the codepoint of the first character in a string and bitwise or with `32` maps uppercase codepoints to the lowercase ones and `95 (_)` to `127`, while keeping everything else the same. [Answer] ## Lua, 172 Bytes It ended up way longer that I wanted... ``` t={}(...):gsub("[%w_]+",function(w)b=nil for i=1,#t do b=t[i]:sub(1,1):lower()==w:sub(1,1):lower()and 1 or b end t[#t+1]=not b and w or nil end)print(table.concat(t," ")) ``` ### Ungolfed ``` t={} -- initialise the accepted words list (...):gsub("[%w_]+",function(w)-- iterate over each group of alphanumericals and underscores b=nil -- initialise b (boolean->do we have this letter or not) for i=1,#t -- iterate over t do b=t[i]:sub(1,1):lower() -- compare the first char of t's i word ==w:sub(1,1):lower() -- and the first char of the current word and 1 -- if they are equals, set b to 1 or b -- else, don't change it end t[#t+1]=not b and w or nil -- insert w into t if b isn't set end) print(table.concat(t," ")) -- print the content of t separated by spaces ``` [Answer] ## Seriously, 43 bytes ``` 6╙¬▀'_+,;)-@s`;0@Eùk`M┬i;╗;lrZ`i@╜í=`M@░' j ``` [Try it online!](http://seriously.tryitonline.net/#code=NuKVmcKs4paAJ18rLDspLUBzYDswQEVrYE3ilKxpYMO5YE074pWXO2xyWmBpQOKVnMOtPWBNQOKWkScgag&input=Ii4uLm1heWJlIHNvbWUgZGF5IDEgcGx1cyAyIHBsdXMgMjAgY291bGQgcmVzdWx0IGluIDMi) The lack of regex capabilities made this much more difficult than it needed to be. Explanation: ``` 6╙¬▀'_+,;)-@s`;0@Eùk`M┬i;╗;lrZ`i@╜í=`M@░' j 6╙¬▀ push digits in base 62 (uppercase and lowercase letters and numbers) '_+ prepend underscore ,;) push two copies of input, move one to bottom of stack - get all characters in input that are not letters, numbers, or underscores @s split input on all occurrences of non-word characters `;0@Eùk`M for each word: push the first letter (lowercased) ┬i transpose and flatten (TOS is list of first letters, then list of words) ;╗ push a copy of the first letters list to register 0 ;lrZ zip the list of first letters with their positions in the list `i@╜í=`M for each first letter: push 1 if that is the first time the letter has been encountered (first index of the letter matches its own index) else 0 @░ filter words (take words where corresponding element in the previous list is truthy) ' j join on spaces ``` [Answer] ## Ruby 76 Bytes ``` s;f={};s.scan(/(([\w])[\w]*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=!p; h)}.compact.*' ' ``` ### Or with method definition 88 bytes ``` def m s;f={};(s.scan(/((\w)\w*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=1; h)}-[p]).*' ';end ``` Ungolfed and with unit test: ``` def m_long(s) #found - Hash with already found initials f={} #h=hit, i=initial, j=i[0].downcase s.scan(/(([\w\d])[\w\d]*)/).map{|h,i| f[j=i.upcase] ? nil : (f[j] = true; h) }.compact.join(' ') end #true == !p #~ def m(s) #~ f={};s.scan(/(([\w\d])[\w\d]*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=!p; h)}.compact.join' ' #~ end def m s;f={};s.scan(/(([\w\d])[\w\d]*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=!p; h)}.compact.join' ';end #~ s = "Ferulas flourish in gorgeous gardens." #~ p s.split require 'minitest/autorun' class FirstLetterTest < Minitest::Test def test_1 assert_equal("Ferulas in gorgeous",m("Ferulas flourish in gorgeous gardens.")) assert_equal("Ferulas in gorgeous",m_long("Ferulas flourish in gorgeous gardens.")) end def test_2 assert_equal("Take all first words each letter is",m("Take all first words for each letter... this is a test")) assert_equal("Take all first words each letter is",m_long("Take all first words for each letter... this is a test")) end def test_3 assert_equal("Look _ There are 3 dogs",m("Look ^_^ .... There are 3 little dogs :)")) assert_equal("Look _ There are 3 dogs",m_long("Look ^_^ .... There are 3 little dogs :)")) end def test_4 assert_equal("maybe some day 1 plus 2 could result in 3",m("...maybe some day 1 plus 2 plus 20 could result in 3")) assert_equal("maybe some day 1 plus 2 could result in 3",m_long("...maybe some day 1 plus 2 plus 20 could result in 3")) end end ``` [Answer] # grep and awk, 68 56 bytes The script: ``` echo `grep -o '\w*'|awk '!x[tolower(substr($0,1,1))]++'` ``` Explanation: * `grep -o` matches the legal words, printing each on its own line. * `awk` takes the first letter of each line with `substr`, makes it lowercase, and then increments a hashtable entry with that key. If the value was unset before the increment, the line is printed. * `echo ...` turns the lines back into words I previously tried to create a solution without `awk`, using `uniq`, `sort`, `grep` and `bash` but fell just short. History in the edits. Thanks to Dennis for some improvements I missed. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 55 bytes ``` {" "/w@.*'" "_=_*'w:" "\c(c:`c$&2!&48,27\3988544219)?x} ``` [Try it online!](https://ngn.bitbucket.io/k/#eJx1j0FPgzAUgO/8iidZtrEYdICRtTF68uRxt41BhQIN3WraEiCL/nYfmzEz6qFpk/d9X/NKcnTBveme/MUMH+lDuph1BF/bfJ6TLJ9Mg6tpFF8H99twFcd3URQsV95j/+44lhwnm+FDkxJ6mqmGzrOSCUl7OlDtJSOxcZ+5biUzUErVamFqEAeolK64ag1UTBf8YHyXfnMXYzcZA2vWcGBSQim0sdApXWBNaeAsr0Fya7n2fR9sLdA2wMByY7H4p3ghIXz+4UWpBnbpDvyxs665Rg9PCFJYKzkUqjJAPGye0PQHMw7PHbT3bHjlYNQeJTbAEt4krhl8XbeQq1YWoLlppR1XDbH5n/ObTRznE5UqiQw=) * `(c:`c$&2!&48,27\3988544219)` a compressed version of `"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"`, stored in `c` * `c(...)?x` replace all non-alphanumeric/underscore characters with spaces * `w:" "\` split the converted input on spaces, storing in `w` * `=_*'w` build a dictionary mapping the distinct (lowercased) leading characters to their words' position(s) within the input sentence * `" "_` remove/ignore spaces * `w@.*'` retrieve the first word beginning with each distinct character... * `" "/` ...joining them together with spaces (to be implicitly returned) [Answer] # [Perl 5](https://www.perl.org/) `-n`, ~~44~~ 37 bytes ``` /./&&!$k{lc$&}++&&print$_,$"for/\w+/g ``` [Try it online!](https://tio.run/##DcPRCkAwFADQX7m0bmnYg7z4Bo8eRWJY1u6alQf5dZdTx@tga2ZVKsREHLedBT5SIvpgXBRjLtKVguovqTbmluiAYRyg/EG366Bh@ldgTYxWw0LbCU32ko@G3MmF@wA "Perl 5 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), ~~19~~ 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` f/\w+/ üÈÎvÃmÎnU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVM&code=Zi9cdysvCvzIznbDbc5uVQ&input=IkZlcnVsYXMgZmxvdXJpc2ggaW4gZ29yZ2VvdXMgZ2FyZGVucy4i) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=Zi9cdysvCvzIznbDbc5uVQ&footer=VnFT&input=WwoiRmVydWxhcyBmbG91cmlzaCBpbiBnb3JnZW91cyBnYXJkZW5zLiIKIlRha2UgYWxsIGZpcnN0IHdvcmRzIGZvciBlYWNoIGxldHRlci4uLiB0aGlzIGlzIGEgdGVzdCIKIkxvb2sgXl9eIC4uLi4gVGhlcmUgYXJlIDMgbGl0dGxlIGRvZ3MgOikiCiIuLi5tYXliZSBzb21lIGRheSAxIHBsdXMgMiBwbHVzIDIwIGNvdWxkIHJlc3VsdCBpbiAzIgpdLW1S) ``` f/\w+/\nüÈÎvÃmÎnU :Implicit input of string U > "Ferulas flourish in gorgeous gardens." f/\w+/ :Match /\w+/g > ["Ferulas","flourish","in","gorgeous","gardens"] \n :Reassign to U ü :Group and sort by È :Passing each through the following function Î : First character > ["F","f","i","g","g"] v : Lowercase > ["f","f","i","g","g"] à :End function > [["Ferulas","flourish"],["gorgeous","gardens"],["in"]] m :Map Î : First element > ["Ferulas","gorgeous","in"] nU :Sort by index in U > ["Ferulas","in","gorgeous"] :Implicit output joined with spaces > "Ferulas in gorgeous" ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `S`, 16 bytes ``` kr‛ _+↔⇩⌈:vhÞU*' ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=S&code=kr%E2%80%9B%20_%2B%E2%86%94%E2%87%A9%E2%8C%88%3Avh%C3%9EU*%27&inputs=Take%20all%20first%20words%20for%20each%20letter...%20this%20is%20a%20test&header=&footer=) Explanation: ``` kr‛ _+↔ # Remove any non A-Z,a-z,0-9,_, or space chars ⇩ # Lowercase ⌈ # Split on spaces : # Duplicate vh # Get the first letter of each ÞU # Nub Sieve (Unique mask) * # Multiply mask with list of words ' # Remove all empty strings # 'S' flag - join top of stack with spaces and print ``` [Answer] # Python 3.5, 138 bytes: ``` import re;lambda o,t=[]:''.join([y[0]for y in[(u+' ',t.append(u[0].lower()))for u in re.sub('\W+',' ',o).split()if u[0].lower()not in t]]) ``` Basically, what's happening is.. 1. Using a simple regular expression, the program replaces all the characters, except lowercase or uppercase letters, digits, or underscores in the given string with spaces, and then splits the string at those spaces. 2. Then, using list comprehension, create a list that iterates through all the words in the split string, and add the first letters of each word to list "t". 3. In the process, if the current word's first letter is NOT already in the list "t", then that word and a trailing space are added to the current list being created. Otherwise, the list continues on appending the first letters of each word to list "t". 4. Finally, when all words in the split have been iterated through, the words in the new list are joined into a string and returned. [Answer] **PHP 120bytes** ``` function a($s){foreach(preg_split('/\W/',$s)as$w)if(!$o[ucfirst($w[0])]){$o[ucfirst($w[0])]=$w;}return implode(" ",$o);} ``` This generates a bunch of warnings but that's fine. [Answer] # Javascript ES6, ~~108~~ 107 chars ### 107 chars, result string is trimmed ``` r=s=>s.split``.reverse().join`` f=s=>r(r(s).replace(/\b\w*(\w)\b(?=.*\1\b)/gi,'')).replace(/\W+/g,' ').trim() ``` Test: ``` ["Take all first words for each letter... this is a test", "Look ^_^ .... There are 3 little dogs :)", "...maybe some day 1 plus 2 plus 20 could result in 3" ].map(f) + '' == [ "Take all first words each letter is", "Look _ There are 3 dogs", "maybe some day 1 plus 2 could result in 3" ] ``` [Answer] # [Tcl](http://tcl.tk/), 150 bytes ``` proc F {s D\ {}} {lmap w [split $s] {regsub -all \[^\\w] $w "" f if {![dict e $D [set k [string tol [string in $f 0]]]]} {dict se D $k $f}} dict v $D} ``` [Try it online!](https://tio.run/##PVCxboQwDN35ilfE0qGo7W2dTzd1vA2OKgcGIsIFxU7RCfHt1DDUSuToxe/52VK7bZuCr3HBwjiXWNYVixvNhBkFT84KMr5hCdRxvOPNOIeyqMpyviGbkaZoE9tieSkaWwsI2Vl5JBg0SbCPDuLd/9s@kLV4v2lon4PChDOyQfF1TQ7kV0XW7TDBWJL0QiE6w2idj8Fyv6t0PnTkI6MzoaEHp0l6NQNh99fawILZh0Y5PoBM3cORCIU8zyG9ZegxEGJR4rf3A6qfCvn@fe0pqI7eE3R8cYTGd4yvVy0dzfNOYD8qaJ74wOTUwydqH12DQByd7PZOaaLzTVEYxWXf4Lr9AQ "Tcl – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 131 bytes ``` lambda s:' '.join(sorted({w[0].lower():w for w in''.join(c*(c.isalnum()or c in'_ ')for c in s).split()[::-1]}.values(),key=s.find)) ``` [Try it online!](https://tio.run/##VY9Ba8MwDIXv@xW6xR6baddbYNedduyta4sbK4lXxQqWvRDGfnvmjDIoSAih7z2exjn1HHZL@/qxkB0uzoLUFVTmk31QwjGhU9/TYXM0xBNGpesJWo4wgQ/VDWseVWO8WAp5ULocm/V4hkq3twVEGxnJJ6UPdf28Pf6YL0sZRemnK86vYlofnNbLGH1IqlXVG8ZMVqAlztFLv5p0HDvkLNDZ6DCIqbR@@Ffs7RXBEkHroySYODr5i4q26YEwJYzGGEi9FyhlIaGkO4t35iuczicwK7jvMRbH0jso0RMhOO4Ean0nKuhg5wuC8FAIO8MWRiopX25jAw1nchBRMqX1kV0xWH4B "Python 3 – Try It Online") Solution without regex. [Answer] # [Husk](https://github.com/barbuz/Husk), 22 bytes ``` wÖ€₁¹m←ko_←₁ mf§|='_□w ``` [Try it online!](https://tio.run/##yygtzv7/v/zwtEdNax41NR7amfuobUJ2fjyQBHK5ctMOLa@xVY9/NG1h@f///0MSs1MVEnNyFNIyi4pLFMrzi1KKFdLyixRSE5MzFHJSS0pSi/SAQKEkI7NYAYgSFUpSi0sA "Husk – Try It Online") The '\_' requirement is a bit annoying, otherwise a pretty interesting challenge. ## Explanation ``` function ₁: filter nonalphanumerics and split mf§|='_□w w split on spaces mf map and filter each letter in the words by: □ is it alphanumeric? §| or: ='_ is it an underscore? main function: wÖ€₁¹m←ko_←₁ ₁ format the input ko key the words on: _← first letter, lowercased m← map each to first word Ö order by: €₁¹ their index in the formatted input w join back with spaces ``` [Answer] # Python, 93 bytes ``` import re s="" for w in re.findall("\w+",input()): if(a:=w[0].lower())not in s:s+=a;print(w) ``` ]
[Question] [ Infix notation is a method of printing mathematical expressions where each operator sits between its two arguments, such as \$ \left(5 \cdot 4\right) + 3 \$. Prefix notation is a method of printing expressions where operators sit before their arguments. The equivalent of the above is `+*543`. It's a bit harder to understand than infix, but here's a sort of explanation: ``` +*543 # Expression + # Adding *54 # Expression * # The product of 5 # 5 and 4 # 4 3 # And 3 ``` Your challenge is to, given an expression in prefix, convert it to infix notation. You may take input as a string, character array, array of charcodes, etc. The input will contain lowercase letters and digits, and can be assumed to be a valid expression - that is, each operator (letter) has exactly two operands and there is only one value left at the end The output should be a valid expression in infix - that is, it should be an expression in the following recursive grammar: ``` digit := 0-9 operator := a-z expression := digit | (expression operator expression) ``` That is, each expression should be a digit, or two expressions joined by an operator and wrapped in parentheses for unambiguity. ## Example Note: Spaces are for clarity and are optional in the input and output. ``` Expression: x 3 u f 4 3 h 5 9 You could read this as x(3, u(f(4, 3), h(5, 9))) or something. The x is taking 3 and the expression with a u as operands: Result: (3 x ...) Expression: u f 4 3 h 5 9 The u is taking the expression with a f and the expression with an h as operands. Result: (3 x ((...) u (...))) Expression: f 4 3 The f is taking 4 and 3 as operands. Result: (3 x ((4 f 3) u (...))) Expression: h 5 9 The h is taking 5 and 9 as operands. Expression: (3 x ((4 f 3) u (5 h 9))) And that's the result! Spaces are optional. ``` ## Testcases As usual, these are manually created, so comment if I've stuffed these up. ``` a34 -> (3a4) ba567 -> ((5a6)b7) cba1234 -> (((1a2)b3)c4) a1b23 -> (1a(2b3)) a1fcb46d4e95ig6h42kj32l68 -> (1a(((4b6)c(4d(9e5)))f((6g(4h2))i((3j2)k(6l8))))) ``` Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 61 bytes ``` f=lambda S:(s:=next(S:=iter(S)))[:s<"a"]or"("+f(S)+s+f(S)+")" ``` [Try it online!](https://tio.run/##NY5BboMwEEX3nMKa1YySVsI2DqF1LwG7NAsbcHBCAYEXLZenQJvZjOb9p9EffkLTdyIdxmVxujVftjIsz3DKdFd/B8wz7UM9Yk5El2x6BwPXfgSEg1vZYfpbQLAUGgCMkOzlg6EwkiJrEnXaT0yMInuiqLQm5v8OYmw4WUHl6prYcrHj2CBf4YZcaaWqZH1O/E01kj/ugrcqfWqI0ioqUVZ4rpO1oENUN5QNJ/KI4s7pgapNaZu1XFToS3idhtYHhO0JEHP9yALzHSuewWcHdI027o/9nmSzdujpbRh9F3A@zlr3FC2/ "Python 3.8 (pre-release) – Try It Online") This does the conversion in a single linear pass over the input. The tree structure is captured by a recursive scheme where each branch corresponds to an instance of the function. The function logic is then as simple as: Read the next character and return it if it is a numeral. Else store it, then output opening braces call yourself for the first operand, output the stored infix call yourself for the second operand and add the closing braces. To keep track of the position within the input string across all the recursive function calls we convert the input to an iterator. Applying `iter` to an iterator returns the object itself, so it does no harm doing it multiple times. As all copies of the recursive function use the self-same single instance of the iterator the bookkeeping becomes trivial. [Answer] # TypeScript Types, ~~234~~ 206 bytes Saved 28 bytes thanks to tjjfvi! ``` //@ts-ignore type F<E>=E extends`${infer H}${infer T}`?(H extends`${number}`?[H,T]:F<T>extends[infer I,infer U]?F<U>extends[infer J,infer V]?[`(${I}${H}${J})`,V]:0:0):0 type G<E>=F<E>extends[infer H,""]?H:0 ``` [Try it online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAMQB4BRAPgF5zD0APcdRAE0gAMASAb1kQBm6VIQASAX178hIgCriOAfgAUo+kxbtuPRAFcAtgCNhCxQG1RAGlkBdAFxlZlRszaQz04YQCSlzyIBVG0UyAOcNNw9BLwApP2iRADVgsw5lXm9JHgleGPEASg5LZLsABjL8sux8IgBxChoyKhdNd38xSwAiTuDRKswQCBgEFAxqgkIAYQALdABjAGtSAEF1V3ZCSHBUfnhLQgAhNdbN7d3KQmpCeuWLlrdDwkVCTuWAGzfCeGRkVgBCTqEOyEDgAeWmhFY6AAhqh9rwbpRxIRYJBCChwIRwLNNtD9ERoWjeAcFABuTDjIirK4zeZLTrQgDMABZOvtOspGdDmflOpQBsBCEKAHqKSmPGmzRakTqGaEAVgAbAB2NkvZTKeXQxX5QzK3n8kBCwii8WTS5TKX0uZygCMACYWWqORrbdD7brGfk5jy+QLjabcBMACIW2nShm2wyO53KN3Ke2GL0G-0isVBoh0SV0mXQ20CG3MxWsZnoACc8oQiumzPtCwAVoz7W9FQAOWPxjXMww6ubKZmsZRl9Dy-JjgQaxXwfvTD35WAaxn1j0LZSKt6tsdbv1GtNAA) Thanks to [@tjjfvi](https://codegolf.stackexchange.com/users/87606/tjjfvi) for helping me get started with abusing TypeScript's surprisingly powerful type system. This is pretty much the same approach as my Scala answer, just at compile time. At each step, `F` returns one expression and the remainder of the input. First it deconstructs the input into the first character `H` and the rest `T` using `E extends `${infer H}${infer T}`` . Then it checks if the first character of `E` is a digit (`H extends'0'|...|'9'`). If it is, it just returns that first character (a valid infix expression) and `T` in a list (or is it a tuple type?). Otherwise, it finds the next two expressions `I` and `J` and returns the infix expression `(IHJ)` along with the remaining text `V`. `G` exists simply to match on `F`'s output and return the valid expression, as the second part of the output of `F` is an empty string by the end. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 49 bytes ``` s=>(i=0,g=(c=s[i++])=>c>=0?c:'('+g()+c+g()+')')() ``` [Try it online!](https://tio.run/##PY9BbsIwEEX3OYV3/qNARBzHQJHTVU9BkXCMEwwBIxxVSFXPniaodBYjzZunL/2T@TLR3v2tn1/DwQ2NHqKu4PVi1mpYHbc@TXekK1vpxbt94@BpC0rtc3PiBBp6F3trootMs31iCsnmFUNhJCW1KdXyeaI0iuolJbY2ufhzgNwIqguyo2vyWhRPnBuIEU6osbVUB@nWpW/VUYrzqRCdWr00QNaKLOQBa1cSUQOoFvIoiDxQnASdoboVTZPss/7uL6As3jrfg39eOWUXc8OD6Yo9XngK50Sb5L9Y1oT7h7FHYOtnzO1o8r8Txmy4xtC5rAstEMb@DTyNX62Zm7EwZvzQZvgF "JavaScript (Node.js) – Try It Online") [Answer] # x86-16 machine code, ~~23~~ 21 bytes ``` 00000000: ac3c 617c 0e50 b028 aae8 f4ff 58aa e8ef .<a|.P.(....X... 00000010: ffb0 29aa c3 ..).. ``` Listing: ``` P2I: AC LODSB ; AL = next char, SI++ 3C 61 CMP AL, 'a' ; is alpha? 7C 0E JL IS_ARG ; if not, it's an argument 50 PUSH AX ; save operator to stack B0 28 MOV AL, '(' ; load left paren AA STOSB ; write to output E8 0100 CALL P2I ; recursive call for next char 58 POP AX ; restore operator from this call stack AA STOSB ; write to output E8 0100 CALL P2I ; recursive call for next char B0 29 MOV AL, ')' ; load right paren IS_ARG: AA STOSB ; write to output C3 RET ; return to caller ``` Input string at `[SI]`, output to `[DI]`. [![enter image description here](https://i.stack.imgur.com/AeZn9.png)](https://i.stack.imgur.com/AeZn9.png) [Answer] # [Haskell](https://www.haskell.org/), 70 bytes ``` g(a:b)|a<'a'=([a],b)|(c,d)<-g b,(e,f)<-g d=('(':c++a:e++")",f) f=fst.g ``` [Try it online!](https://tio.run/##Rcm9DoIwGIXh3av40qVtKCYURCXAFejkiAxfgQLyEyJ1894rSKLbc97T4NxVfW9tzTBS/I0xRZqwDHOxLFaIksduDUqwSugvy4RRRqPCcTCqHIdwshw7nejZ7Gs7YDtCAgNOV2B3A24K08vczBMMpD@TtZN/uIzANBjOISPoB0QAUXgIjysKhZ7cGnpK@ht0oYKwDKrzoa3DJpDdw5d9eCK5/QA "Haskell – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~96~~ ~~65~~ ~~72~~ 69 bytes Or **[R](https://www.r-project.org/)>=4.1, 62 bytes** by replacing the word `function` with `\`. *-many bytes by changing I/O to vector of char codes.* *-another some bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).* *+7 bytes costed converting from not-so-self-contained function to a program.* *-3 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) - converting back to one (reusable) function.* ``` `/`=function(s,t=0)"if"((a=s[i<<-t*i+1])<58,a,c(40,s/1,a,s/1,41));i=9 ``` [Try it online!](https://tio.run/##hZDNbsIwEITvfQqUXmbbIPAviYh7752eqkrYJgYDSiRieP3USJVoL80eVjva/WakvYy@727tJZlxu9iacO18in2HoUxmSUUMBWDN8BmbZp5e4iv7okZVpS095LIcFiyP9y4Z0Tqaeoxd2vQfKVT4McY1i03/3iUUVsiCiJ5n87cZhJX09O@5s0qvHgCU1eRWE5B3lvHfOQCznJwgP5VnmePiATILnrFJKHgn9U62tYp7fZD8dBT8rKs/RoB0mvLTdqhblTcB0HvIAyeKgDhyOkGfK7rX@A0 "R – Try It Online") Port of [@loopy walt's answer](https://codegolf.stackexchange.com/a/237581/55372). **Explanation** A function takes string `s` and `t` defaulting to `0` (for resetting global variable). The recursive function (named `/` overriding division) takes one character at a time (`a`) incrementing the global counter each time. If the character char code is less then 58, then it's a digit and needs to be returned as is. Otherwise, we surround the character with braces (char codes `40,41`) and recursive calls to our function (with `t=1` to keep `i` as is between calls). The code at the end initiates global counter `i` to a digit (`9` chosen for demonstration purposes). --- Solution shorter for [R](https://www.r-project.org/)>=4.1: ### [R](https://www.r-project.org/), 74 bytes Or **[R](https://www.r-project.org/)>=4.1, 60 bytes** by replacing two `function` occurrences with `\`s. ``` function(s,i=0,f=function(a=s[i<<-i+1])"if"(a<58,a,c(40,f(),a,f(),41)))f() ``` [Try it online!](https://tio.run/##hZDNbsJADITvfQoULmM1SN1fgpT03js9VT14lywsoI0ES18/LKgq7aXxwRpb840ln0Y/pK/@lLsxXJLPcUg417F7qUP3s@Du/BHbdhGfxSdVMVTg1jQ11x66GEFF3roWRFTEGFNeD@85NPhOx6UM6@EtZVSsdFV889nidQbFmp7@tTs2dvkAYNiSW05A3rGQv@8AgiU5RX7qHgsn1QMUDFmwSSh4p@1G9ysTt3an5WGv5NE2f4IA7SyVp22w6s39V7Bb6J0kioDaSzrAHhu61XgF "R – Try It Online") Same as above, but here `i` is "local" for the main function, but "global" for the recursive one. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), ~~95~~ 81 bytes Haven't programmed in Prolog for a while, so this was a fun challenge to do. Prologs ability to handle strings and atoms do not make it easy. Probably suboptimal, but here we go: ``` f(R,[H|T]):-T=[],H<97,R=[H];append(X,Y,T),f(C,X),f(D,Y),flatten([40,C,H,D,41],R). ``` Input and output are both codepoint lists. [Try it online!](https://tio.run/##hY4/D4IwEMV3PgVxapPDCFT8P@GAkwlh0BBCChSskkKgRge/O1Y2opFb3uXe795d3VRlVRjtg3ddjnwIvVcQ4bUR7MIIvO1qAf4u9KINrWsmMnSCMwQYcuTC6SN7OCspqZRMoJDMwAUP9kDMCHw87eqG5fwZyyrmQjXoIEA/3iXW14amq2plw0URp1XG2t50Px2G3lTvsHY4GvAqCHSF/LgzoTaZ9Oa9lHiqaV9AQufO4j@SJtS0xnKomVj2GJKnCXEywlZzXjgXYt2utlU6y8HaGw "Prolog (SWI) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 74 bytes ``` +`([a-z])((([a-z])|(?<-4>\d))*\d)((([a-z])|(?<-7>\d))*\d) ($2$U$1$5) T`L`l ``` [Try it online!](https://tio.run/##K0otycxLNPz/XztBIzpRtypWU0MDyqjRsLfRNbGLSdHU1AISqOLmcHEuDRUjlVAVQxVTTa6QBJ@EnP//E41NuJISTc3MuZKTEg2NgLxEwyQjYyCZlpxkYpZikmppmplulmFilJ1lbJRjZgEA "Retina – Try It Online") Link includes test cases. Explanation: ``` ([a-z])((([a-z])|(?<-4>\d))*\d)((([a-z])|(?<-7>\d))*\d) ``` Match a letter followed by two prefix expressions. A prefix expression is readily identified as being a substring that contains exactly one more digit than letter. ``` ($2$U$1$5) ``` Convert this letter to infix and upper case it to show that it has been converted. ``` +` ``` Keep making replacements until all of the letters have been upper cased. ``` T`L`l ``` Change all the letter back to lower case again. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~62~~ ~~60~~ 54 bytes ``` ->e,i=-1{(f=->c=e[i+=1]{c=~/\d/?c:?(+f[]+c+f[]+?)})[]} ``` Saved 6 more bytes by removing parenthesis and using ternary operator by the hint from Dingus. [Try it online!](https://tio.run/##RY3BjoIwEIbvPsWEvcxE0VBK1U2qp30KlkNbilQJGoFkN8i@Ogsusj20zf/NN/@90d99IXv/YFdO@kGLmfQPRtrYLWWQtEb@bD7TzdG8H3GZxcnSPO8jdRQnXd8uADwVcg/kATwMFSdvNWZaRWI7pRgpQXo7EaNVwGYDMVCMdEjmZapAs3CigUI2sJlkRnORcruP3EnknF3OISvE7n8akWtBBnmKexsRUYYoTshzRuQQwzOjC4piR@MZtnZrq0wO6RUerrw19Qrs182a2qaPofFuq6aoQUIRP2kyZMNTTWCcUK6y4H1MEry1L3/tymr8daCbGk7XemB/2kw8aMrCVtXcI@f2hS3TRf8L "Ruby – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) -p, 51 bytes ``` s/(\D) (\S+) (\S+)/ ($2$1$3)/||s/.\b/ $&/ until/^ / ``` [Try it online!](https://tio.run/##K0gtyjH9/79YXyPGRVNBIyZYG0rqK2ioGKkYqhhr6tfUFOvrxSTpK6io6SuU5pVk5ujHKej//59obMKVlGhqZs6VnJRoaATkJRomGRkr0AMArUpLTjIxSzFJtTTNTDfLMDHKzjI2yjGz@JdfUJKZn1f8X7cAAA "Perl 5 – Try It Online") Uses regexp substitutions and treat the $\_ string as an array where the first element is the input, or what is left of it while processing, and the rest of the array elements is the working stack. Commands to see it's behavior on the last test case: ``` INP=a1fcb46d4e95ig6h42kj32l68 #which is the last test case echo $INP|perl -plE'say,s/(\D) (\S+) (\S+)/ ($2$1$3)/||s/.\b/ $&/ until/^ /' a1fcb46d4e95ig6h42kj32l68 a1fcb46d4e95ig6h42kj32l6 8 a1fcb46d4e95ig6h42kj32l 6 8 a1fcb46d4e95ig6h42kj32 (6l8) a1fcb46d4e95ig6h42kj3 2 (6l8) a1fcb46d4e95ig6h42kj 3 2 (6l8) a1fcb46d4e95ig6h42k (3j2) (6l8) a1fcb46d4e95ig6h42 ((3j2)k(6l8)) a1fcb46d4e95ig6h4 2 ((3j2)k(6l8)) a1fcb46d4e95ig6h 4 2 ((3j2)k(6l8)) a1fcb46d4e95ig6 (4h2) ((3j2)k(6l8)) a1fcb46d4e95ig 6 (4h2) ((3j2)k(6l8)) a1fcb46d4e95i (6g(4h2)) ((3j2)k(6l8)) a1fcb46d4e95 ((6g(4h2))i((3j2)k(6l8))) a1fcb46d4e9 5 ((6g(4h2))i((3j2)k(6l8))) a1fcb46d4e 9 5 ((6g(4h2))i((3j2)k(6l8))) a1fcb46d4 (9e5) ((6g(4h2))i((3j2)k(6l8))) a1fcb46d 4 (9e5) ((6g(4h2))i((3j2)k(6l8))) a1fcb46 (4d(9e5)) ((6g(4h2))i((3j2)k(6l8))) a1fcb4 6 (4d(9e5)) ((6g(4h2))i((3j2)k(6l8))) a1fcb 4 6 (4d(9e5)) ((6g(4h2))i((3j2)k(6l8))) a1fc (4b6) (4d(9e5)) ((6g(4h2))i((3j2)k(6l8))) a1f ((4b6)c(4d(9e5))) ((6g(4h2))i((3j2)k(6l8))) a1 (((4b6)c(4d(9e5)))f((6g(4h2))i((3j2)k(6l8)))) a 1 (((4b6)c(4d(9e5)))f((6g(4h2))i((3j2)k(6l8)))) (1a(((4b6)c(4d(9e5)))f((6g(4h2))i((3j2)k(6l8))))) ``` [Answer] # [Rust](https://www.rust-lang.org/), 117 bytes ``` fn f(s:&mut std::str::Chars)->String{let c=s.next().unwrap();if c<'a'{c.into()}else{format!("({}{}{})",f(s),c,f(s))}} ``` Takes a mutable reference to a character iterator and returns a string. Requires Rust 1.46+. [Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&code=%0Afn%20f(s%3A%26mut%20std%3A%3Astr%3A%3AChars)-%3EString%7Blet%20c%3Ds.next().unwrap()%3Bif%20c%3C%27a%27%7Bc.into()%7Delse%7Bformat!(%22(%7B%7D%7B%7D%7B%7D)%22%2Cf(s)%2Cc%2Cf(s))%7D%7D%0A%0A%2F%2F%20Run%20testcases%0Afn%20main()%20%7B%0A%20%20%20%20let%20testcases%20%3D%20%22a34%20-%3E%20(3a4)%0Aba567%20-%3E%20((5a6)b7)%0Acba1234%20-%3E%20(((1a2)b3)c4)%0Aa1b23%20-%3E%20(1a(2b3))%0Aa1fcb46d4e95ig6h42kj32l68%20-%3E%20(1a(((4b6)c(4d(9e5)))f((6g(4h2))i((3j2)k(6l8)))))%22%3B%0A%20%20%20%20for%20line%20in%20testcases.lines()%20%7B%0A%20%20%20%20%20%20let%20(input%2C%20expected)%20%3D%20parse_input(line)%3B%0A%20%20%20%20%20%20let%20result%20%3D%20f(%26mut%20input.chars())%3B%0A%20%20%20%20%20%20println!(%22%7B%7D%20-%3E%20%7B%7D%22%2C%20input%2C%20result)%3B%0A%20%20%20%20%20%20assert_eq!(result%2C%20expected)%3B%0A%20%20%20%20%7D%0A%7D%0A%20%20%20%20%0Afn%20parse_input(line%3A%20%26str)%20-%3E%20(String%2CString)%20%7B%0A%20%20%20%20let%20parts%3A%20Vec%3C_%3E%20%3D%20line.split(%22%20-%3E%20%22).collect()%3B%0A%20%20%20%20(%0A%20%20%20%20%20%20%20%20parts%5B0%5D.into()%2C%0A%20%20%20%20%20%20%20%20parts%5B1%5D.into()%2C%0A%20%20%20%20)%0A%7D) ### Ungolfed ``` fn f(iterator: &mut std::str::Chars) -> String { // Get next character let c = iterator.next().unwrap(); // If it's a digit if c < 'a' { c.into() // convert the sole digit character into a string } // Otherwise else { // Build infix string with two recursive calls for the operands format!("({}{}{})", f(iterator), c, f(iterator)) } } ``` [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 44 bytes ``` f(a:b++c)|a>'9'='(':f b++a:f c++")" f[a]=[a] ``` [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NI9EqSVs7WbMm0U7dUt1WXUPdKk0BKJIIpJK1tZU0lbjSohNjbYH4f25iZp6CrUKaglKiYVpykolZikmqpWlmulmGiVF2lrFRjpmF0n8A "Curry (PAKCS) – Try It Online") [Answer] # [Lexurgy](https://www.lexurgy.com/sc), 164 bytes ``` class d {\0,\1,\2,\3,\4,\5,\6,\7,\8,\9} a propagate: {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}$1 {(\( []+ \)),@d}$2 {(\( []+ \)),@d}$3=>\( $2 $1 $3 \) ``` Explanation: ``` class d {\0,\1,\2,\3,\4,\5,\6,\7,\8,\9} # define digits a propagate: # while the input changed last iteration... # match an op {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}$1 # match left expr {(\( []+ \)),@d}$2 # match right expr {(\( []+ \)),@d}$3 # put parens, swap op and left =>\( $2 $1 $3 \) ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 91 bytes ``` Object f(java.util.Iterator<Character>s){var c=s.next();return c<97?c:"("+f(s)+c+f(s)+")";} ``` [Try it online!](https://tio.run/##VVA7b8IwEN75FadISLYAS4QQyrNDpw5VB7pVHS7GAYe8ZF9QK8Rvd@0SVe3gO913/h52gRecFIeza7us1BJkidbCC@oargOAHrWE5Nul0Qeo/I7tyej6@P4BaI6W/1wFyBsD7IImgLD6twIIuCbYBljIExrLuKiwfWtes4JJmOyABZhLLjQpg9QYxtd/2EbZrgwKOdP0u9l/WVKVaDoSrc9EOYuGNqgN7bCOxsFu3FN7zm1wP/dHOW@vJHnRwn@F6EiX4rn33zz5QCj9tLP8GjLIrRW1@iSfzCjqTA1ys1w8ylXEolHOLB/Je4t4tL65m3M4S1yG83ThZIbT2E84zeKZr7nMkvSQqOVcH9NTEp@LWVymD98 "Java (JDK) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~71~~ 70 bytes -1 thanks to [AZTECCO](https://codegolf.stackexchange.com/questions/237574/convert-prefix-to-infix/237616?noredirect=1#comment539038_237616) ``` f(char*s){s=putchar(*s+!(*s++>60?f("("),s=f(s):1))>60?f(s)+!f(")"):s;} ``` [Try it online!](https://tio.run/##RY/RbsIwDEWfyVcES5Ni0gnahrARyj5k4yENDWRjBdXdy6p@e5dCpb1Y19fX1rF7Pjk3DF64s20WhB0Vt592bMSC5Hwscq9Xb16AAEyo8IJwmyI@TEI5jyME3JLph28baoEdux/jrXs/8IJ3DGyuIGFQ2rXejMKVNs0enk3LLP/3fHVUU8im3pVKH1X1ug4nfVbZ12eeXfQLsN4wf224CHXLQ7EyYUfht7p60TpcTvLOgCZIiRFhdmtiOKLu@RN91JBEuHBAw2bj0iTj5yQAouxZP/wB "C (gcc) – Try It Online") Relies on summands evaluating from left to right. Outputs to stdout. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes ``` If[t=##2;#>60,##&[40,#0@t,#,#0@t,41],#]& ``` [Try it online!](https://tio.run/##VchBC4IwGIDhuz9jH3haoHOuIpSBEHQL6iYevs0trVQYu4n@9VV46vQ@vAP6zgzoe43BFuFia18AsBOUIqEAcc2/SaSnsIWnDYUmDlfXj76GXXl201B16FB746qpNXK2Ut6n/wdLE683jeM6RwQzTmhEFOZi/4NWmLLtYapYtsFqxUXLzTHvH6Lj7PXM2FscSLSEDw "Wolfram Language (Mathematica) – Try It Online") Input and output a sequence of character codes. ### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 37 bytes ``` If[t=##2;#>60,40 .#0@t.#.#0@t. 41,#]& ``` [Try it online!](https://tio.run/##VYtBC4IwGIbv/grZoEOY6JyrCGUgBEGHoG7i4dvccpUKa7fIv74KT52eh@fl7cF1qgdnJHhd@IOuXYEx2eGSJRFNwhgn3MV4RkjTCDcLf7JmcDVelXs79lUHFqRTthpbxZdH83Sca84v4//yPU5nCcP0ChBkFEUBEpCz9U@kgJTMDVJBslm0FJS1VG1zc2UdJfdbRh5sg4K3/wA "Wolfram Language (Mathematica) – Try It Online") Outputs a `Dot` of character codes instead. [Answer] # Scala, 57 bytes ``` s=>{def g:Any={val n=s.next;if(n>58)s"($g$n$g)"else n};g} ``` [Try it online!](https://scastie.scala-lang.org/DylOh9yeSFWNzgNzefzY0w) Takes an iterator of characters instead of a string so it can save its position. ## Without an iterator, 118 bytes ``` f(_)._1 def f(s:String):(Any,String)=if(s(0)<58)s.splitAt(1)else{val(a,t)=f(s.tail);val(b,u)=f(t);s"($a${s(0)}$b)"->u} ``` [Try it online!](https://scastie.scala-lang.org/QGm9zd8YTgOsWY6A61XxHA) [Answer] # [Haskell](https://www.haskell.org/), 63 bytes (or 69\*) Below, `a` is Haskell's IO monad computation of type `IO ()` which, when executed, reads the expression from `stdin` and outputs the result to `stdout`. ``` a=getChar>>=(putStr#) p#c|c<'a'=p[c]|1<2=p"(">>a>>p[c]>>a>>p")" ``` [Try it online!](https://tio.run/##ZVDBaoNAEL3vVwymED0YiDG2DXEPDS0EWnLIsZQwrlu12eyKu1IC@Xe7rloo3cNjZt6bfcMrUZ@5EF11qVVj4HjVhl8W@wP4lX4@vARkJHZKmkaJxZuSmIPfSsG1DjpMC252JTaUpn7dmqNpZgGpZ@zGtnOcp/U7@7gtt1Fae75HKVLaT4bCC7yulaYS1m2zAYtPSgkIaV/6wW9BJhFTModM5VdIIVcE7NOlakV@0kbVsA2dws2H@/7QvtukFP59FxBywUqOR1hD140ek9rFAXeTMTo89aZjAhCGsC@kajiYkoPk36KSHJilkBneuIUholcJntfhKiYZrpN7wjJcRrbDZRatLH6yLE7ymD@uqyIp4@j8tYpE8kB@AA "Haskell – Try It Online") ### Ungolfed code ``` main = a >> putStrLn "" a :: IO () a = do c <- getChar -- read a character c putStr # c -- if c is an operator, process its arguments (#) :: (String -> IO ()) -> Char -> IO () p # c | c < 'a' = p[c] -- the character is a number | otherwise = do -- the character is an operator p "(" -- print "(" to stdout a -- read the left subexpression and output it in the required format p [c] -- print the operator to stdout a -- read the right subexpression and output it in the required format p ")" -- print ")" to stdout ``` ### \*Disclaimer I am not sure if the standard code golf rules permit answers being Haskell's IO monads of type `IO ()`. In [this meta answer](https://codegolf.meta.stackexchange.com/a/11935), it was stated that computations of type `IO a` which read `stdin` and produce a value of type `a` are allowed. Should the `IO ()` type be unacceptable, I shall replace my answer with this 69 byte entry with computation of type `IO String` – [try it online!](https://tio.run/##ZVDRaoMwFH3PV1xKQUUs1Fq3WfVhZYPCRh/6OEaJSVpd00SSSCn0313M7GAsD4dzcu6953JrrE@M8745t1IZ2F21YefZZgt@o1@2rwEajbUURkk@e5cCU/A7wZnWQY@LIzPrGquyLA7oAORGcg97Rdsp9kE@b/M8Lqhc8TzCKzXAYEw938t4GJJMheEkmPSdMA23mVkGFp@l5BCVA/WDX4LuRUQKCpWkVyiASgT26Vp2nO61kS3kkatw/z9b/rF911mW8G9cgNAZN2JcwgY6NWbcq91RYHoPxkJfmBoysdP7gY4XgSiCzVFIxcDUDAS78EYwINbCxDDlGtrO7Ix6E@OkHi8SVOFl@oBIheexVXhexQuLB1IlKU3Y07I5pnUSn74WMU8f0Tc "Haskell – Try It Online"). I asked for a clarification in [this comment](https://codegolf.stackexchange.com/questions/237574/convert-prefix-to-infix/237817#comment539295_237574). [Answer] # [Python](https://www.python.org), ~~146~~ ~~139~~ 84 bytes ``` lambda x,s=[]:[(s:=s+[n if n<":"else"("+s.pop()+n+s.pop()+")"])for n in x[::-1]][-1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3Q3ISc5NSEhUqdIpto2OtojWKrWyLtaPzFDLTFPJslKyUUnOKU5U0lLSL9QryCzQ0tfPgLCVNpVjNtPwiBaDiPIWKaCsrXcPY2GggATVbtaAoM69EI01DKdEwLTnJxCzFJNXSNDPdLMPEKDvL2CjHzEJJUxOieMECCA0A) *¯55 thanks to @emanresuA* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 54 bytes ``` ⊞υ⟦⟧FS¿№βι⊞υ⟦ι⟧«⊞§υ±¹ιW⁼³L§υ±¹⊞§υ±²⪫()⪫⮌⁺⟦⊟§υ±¹⟧⊟υω»⊟υ ``` [Try it online!](https://tio.run/##dY@xbsIwEIZn/BQnprOUDoQ0apUJoQ4ghKIyIgYTLonBsmlsA1LFs7txRVkKy@n0/fr@01Wt6CojVAilty36BNYbXrDadIAzffRu5TqpG@QcZA04NV473CYge3A3ZFRIWYJvNvilEzfTO7rEdEmNcIQjzqNVsMG5lYoAP768UBbHCSxIN@6Jw//u/E/T2Dg3UuMQ@fC2ftKJOktYKm9xXZrj49pNAjHzPHac@1mwKyv7Tx3eeBGCGNXVNst3Gb2/yiZvs/SwH6cqfwsvJ/UD "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υ⟦⟧ ``` Start with no expression. ``` FS ``` Loop over the input characters. ``` ¿№βι⊞υ⟦ι⟧ ``` If it's a letter then begin a new operation. ``` « ``` Otherwise: ``` ⊞§υ±¹ι ``` Push this operand to the current operation. ``` W⁼³L§υ±¹ ``` While the current operation has both of its operands, ... ``` ⊞§υ±²⪫()⪫⮌⁺⟦⊟§υ±¹⟧⊟υω ``` Convert it to infix and push it to its parent operation, which becomes the new current operation. ``` »⊟υ ``` Output the final infix code. [Answer] # [Pip](https://github.com/dloscutoff/pip), 34 bytes ``` c:POacGT9?pJ J[b:REacREa@>#:bDCp]c ``` Takes the prefix expression as a command-line argument. [Replit!](https://replit.com/@dloscutoff/pip) Here's the closest I can get with TIO: [Try it online!](https://tio.run/##K8gs@F9gpaShqfQ/2SrAPzHZPcTSvsBLwSs6yUojLVEzGUg42ClbJbk4F2jGJv///z/RMMnIGAA "Pip – Try It Online") ### Explanation Recursive program; parses the first prefix expression from its input and returns its infix representation. If the input starts with a digit, the expression is just that single digit. Otherwise, the first character is an operator and its operands are the results of recursively parsing twice. ``` c:POacGT9?pJ J[b:REacREa@>#:bDCp]c a Current prefix expression, possibly including some extra trailing characters PO Pop the first character c: and store it in local variable c cGT9 Is c greater than "9" (string comparison)? ? If so, it's a letter: [ ] Make a list containing the following: 1) REa Call the program recursively on the portion of the input after the (popped) first character b: and assign the result to local variable b 2) c The popped first character (the operator) 3) RE Call the program recursively on a@> the portion of the input after this index... #: Length of bDCp b from earlier with all parentheses deleted J Join that list into a single string pJ Join "()" on that string Otherwise, c is a number: c Return the number ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` è▼2╖X!ú▬Ie╓ƒû≈²O┬ ``` [Run and debug it](https://staxlang.xyz/#p=8a1f32b75821a3164965d69f96f7fd4fc2&i=a34%0Aba567%0Acba1234%0Aa1b23%0Aa1fcb46d4e95ig6h42kj32l68&a=1&m=2) [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 38 36 [bytes](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` {𝕩{'9'(1⌽")("∾𝕊∾˜𝕊∾⊢)⍟<𝕗⊑˜i+↩1}i←¯1} ``` [Try it here.](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge/Cdlal7JzknKDHijL0iKSgi4oi+8J2ViuKIvsuc8J2ViuKIvuKKoinijZ888J2Vl+KKkcucaSvihqkxfWnihpDCrzF9CgpGwqgiYTM0IuKAvyJiYTU2NyLigL8iY2JhMTIzNCLigL8iYTFiMjMi4oC/ImExZmNiNDZkNGU5NWlnNmg0MmtqMzJsNjgiCg==) How it works: The outer function simply makes a counter `i` and passes the input `𝕩` to the inner function as `𝕗`. ``` {'9'(1⌽")("∾𝕊∾˜𝕊∾⊢)⍟<𝕗⊑˜i+↩1} # Inner function i+↩1 # Increment i, 𝕗⊑˜ # and use it to index into the input '9'( )⍟< # if the code point is greater than '9' 𝕊∾⊢ # recurse and prepend the result 𝕊∾˜ # recurse and append the result 1⌽")("∾ # wrap with parentheses ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 33 bytes ``` V_Q?-1/GN=Y+YN=Y+YjN[+\(.)Y+.)Y\) ``` [Try it online!](https://tio.run/##K6gsyfj/Pyw@0F7XUN/dzzZSOxJMZPlFa8do6GlGagNxjOb//0qJhmnJSSZmKSaplqaZ6WYZJkbZWcZGOWYWSgA "Pyth – Try It Online") ``` # Q = eval(input()) # G = "abcdefghijklmnopqrstuvwxyz" # Y = [] V_Q # for N in reversed(Q): ?-1/GN # if N in G: =Y+YN # Y.append(N) # else: jN[+\(.)Y+.)Y\) # X = N.join(['(' + Y.pop(), Y.pop() + ')']) =Y+Y # Y.append(X) ``` ]
[Question] [ Let's start with the natural numbers ``` [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,55,56,57,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,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100... ``` Now we will make a new list, replacing each natural number `n` with a countdown from `n` to `1`. ``` [1,2,1,3,2,1,4,3,2,1,5,4,3,2,1,6,5,4,3,2,1,7,6,5,4,3,2,1,8,7,6,5,4,3,2,1,9,8,7,6,5,4,3,2,1,10,9,8,7,6,5,4,3,2,1,11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1,13,12,11,10,9,8,7,6,5,4,3,2,1,14,13,12,11,10,9,8,7,6.. ``` Now we will repeat the process. ``` [1,2,1,1,3,2,1,2,1,1,4,3,2,1,3,2,1,2,1,1,5,4,3,2,1,4,3,2,1,3,2,1,2,1,1,6,5,4,3,2,1,5,4,3,2,1,4,3,2,1,3,2,1,2,1,1,7,6,5,4,3,2,1,6,5,4,3,2,1,5,4,3,2,1,4,3,2,1,3,2,1,2,1,1,8,7,6,5,4,3,2,1,7,6,5,4,3,2,1,6.. ``` And now we will do it a third time: ``` [1,2,1,1,1,3,2,1,2,1,1,2,1,1,1,4,3,2,1,3,2,1,2,1,1,3,2,1,2,1,1,2,1,1,1,5,4,3,2,1,4,3,2,1,3,2,1,2,1,1,4,3,2,1,3,2,1,2,1,1,3,2,1,2,1,1,2,1,1,1,6,5,4,3,2,1,5,4,3,2,1,4,3,2,1,3,2,1,2,1,1,5,4,3,2,1,4,3,2,1... ``` This is the **triple countdown sequence**. Your task is to implement the triple countdown sequence. You may either take input and give the value of the sequence at that index, or you may simply output the terms starting from the beginning without stop.1 This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being the goal. --- 1: Both zero and one indexing are permitted. Outputting the terms without halt includes lazy structures which can produce an infinite number of terms. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 bytes Returns the *n*th number in the series. ``` ⊢⊃1(∊…¨⍨)⍣3⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HXokddzYYajzq6HjUsO7TiUe8KzUe9i40f9W7@n/aobcKj3j6g/KPeNY96txxab/yobeKjvqnBQc5AMsTDM/h/moIhV5qCERAbA7EJEJsCsRkQmwOxBRBbArGhAQA "APL (Dyalog Extended) – Try It Online") `⊢` the argument `⊃` picks the element from `1(`…`)⍣3⍳` repeat thrice with 1 as constant left argument and **i**ndices 1 through *n* as initial right argument:  `∊` **e**nlist (flatten)  `…` the sequence   `¨` for each    `⍨` with swapped arguments, i.e. counting down from that number to 1 [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` ∞3FLí˜ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8Yzefw2tPz/n/HwA "05AB1E – Try It Online") Infinitely outputs, thanks to Kevin Crujisen # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` L3FLí˜ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fx9jN5/Da03P@/zc0AAA "05AB1E – Try It Online") I doubt it could be beaten [Answer] # [Haskell](https://www.haskell.org/), ~~34~~ ~~33~~ 32 bytes -1 byte thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)! -1 byte thanks to [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger)! ``` [1..]>>=f>>=f>>=f f x=[x,x-1..1] ``` [Try it online!](https://tio.run/##y0gszk7NyfmfbhvzP9pQTy/Wzs42DYa50hQqbKMrdCp0gTKGsf9zEzPzbAuKMvNKFNL//0tOy0lML/6vm1xQAAA "Haskell – Try It Online") [Answer] # [jq](https://stedolan.github.io/jq/), 50 bytes ``` def f:[range(.)+1]|reverse[]; 1|while(1;.+1)|f|f|f ``` [Try it online!](https://tio.run/##yyr8/z8lNU0hzSq6KDEvPVVDT1PbMLamKLUstag4NTrWmsuwpjwjMydVw9BaT9tQsyYNBP///5dfUJKZn1f8XzcPAA "jq – Try It Online") funny how similar the second line is to the Zsh answer. -1 from ovs. [Answer] # [Zsh](https://www.zsh.org/), 37 bytes ``` c()xargs -i seq {} -1 1 seq inf|c|c|c ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwcLqpaUlaboWN1WTNTQrEovSixV0MxWKUwsVqmsVdA0VDLlA7My8tJpkEIQoXlVbk5GamKKgq2IIEVgabWhgELsAwgEA) Full program which outputs infinitely, one per line (ATO link includes a wrapper to halt after N terms). "Implicit" "list" "flattening" FTW! (Zsh doesn't actually have any of these features - it's just text!) `c` is a function that outputs the `seq`uence from `{}` to `1` (with a step of `-1`) for each `{}` in the input (`xargs -i`). Then output "all" integers and pipe that to `c` three times. [Answer] # [JavaScript (V8)](https://v8.dev/), 60 bytes ``` for(a=1;;a++)for(i=a;--i;)for(j=i;--j;)for(k=j;--k;)print(k) ``` [Try it online!](https://tio.run/##JcfBCoAwCADQ35kMD90C8WMkCFRow8Z@31a92zOZch@hfeDcM88WRXgjklrhjbIQotIXY12xP8624gQ99BrFIfMB "JavaScript (V8) – Try It Online") Boring trivial solution. [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` !4¡ṁṫN ``` [Try it online!](https://tio.run/##yygtzv7/X9Hk0MKHOxsf7lzt9/8/AA "Husk – Try It Online") outputs an infinite list. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes ``` Do[Print[0;],{,∞},#,#,#]&@{,,1,-1} ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/98lPzqgKDOvJNrAOlanWudRx7xaHWUQjFVzqNbRMdTRNaz9/x8A "Wolfram Language (Mathematica) – Try It Online") Prints elements indefinitely. --- A somewhat more interesting solution which generalizes to \$n\$-countdown sequences: ### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 48 bytes ``` Nest[gArray[g,#,{#,1}]&,Print,3]@i~Do~{i,∞} ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/98vtbgkOv39pIWORUWJldHpOso61co6hrWxajoBRZl5JTrGsQ6ZdS75ddWZOo865tX@/w8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 33 bytes Outputs terms without stopping! ``` filter s{$_..1} for(){++$x|s|s|s} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/f8/LTOnJLVIobhaJV5Pz7CWKy2/SMNapUI3J9VUs1pbW6WiphgEa/9z/QcA "PowerShell Core – Try It Online") *Note: the linked TIO limits the output* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` r1)⁺⁺Fị@ ``` [Try it online!](https://tio.run/##y0rNyan8/7/IUPNR4y4gcnu4u9vh/@H2R01r/v83MgAA "Jelly – Try It Online") Because it is extremely cumbersome to produce infinite output in Jelly, it instead applies countdown 3 times to the input's range and outputs the input-th item. The part without indexing (6 bytes) ties with [05AB1E's equivalent](https://codegolf.stackexchange.com/a/235530/78410). ``` r1)⁺⁺Fị@ Monadic main link. Input = n r1) [x,x-1..1] for each number x (autorange) ⁺⁺ Do the above; do the above (no autorange) Fị@ Flatten and get the nth item ``` [Answer] # Scala, 60 bytes ``` Stream.from(1)flatMap>flatMap>flatMap> def> =(_:Int)to(1,-1) ``` [Try it in Scastie!](https://scastie.scala-lang.org/jfpbO2ekQre7BbIOSmxdGg) ~~A less trivial solution should be coming soon.~~ `>` is a function that takes an `Int` and returns a range going from that number to 1. We then take an infinite `Stream` starting at 1, and apply `>` to each of those numbers thrice, flattening each time. [Answer] # [Raku](http://raku.org/), 33 bytes ``` (1..*,{.flatmap:{$_...1}}...*)[3] ``` [Try it online!](https://tio.run/##K0gtyjH7n1up4JCoYPtfw1BPT0unWi8tJ7EkN7HAqlolXk9Pz7C2FkhqaUYbx/63VihOBCmOjjM0MIj9DwA "Perl 6 – Try It Online") This is a lazy list of countdown sequences, where the first element is the list of natural numbers, the second is the countdown sequence, the third is the double countdown sequence, and the fourth is the triple countdown sequence, et cetera. The triple countdown sequence is the one at index `3`, which is returned. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 45 bytes ``` Flatten[r@r@r@Range@#][[#]]& r=Range[#,1,-1]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773y0nsaQkNS@6yAEEgxLz0lMdlGOjo5VjY9W4imzBAtHKOoY6uoaxav8DijLzShT0HdL1oUrNDP7/BwA "Wolfram Language (Mathematica) – Try It Online") -23 bytes from @att [Answer] # [R](https://www.r-project.org/), ~~59~~ 51 bytes ``` `[`=`for`;while(F<-F+1)i[F:1,j[i:1,k[j:1,show(k)]]] ``` [Try it online!](https://tio.run/##K/r/PyE6wTYhLb8owbo8IzMnVcPNRtdN21AzM9rNylAnKzoTSGZHZwHJ4oz8co1szdjY2P//AQ "R – Try It Online") Prints the resulting sequence infinitely. --- Less boring: ### [R](https://www.r-project.org/), 68 bytes ``` `!`=unlist;s=sapply;while(F<-F+1)cat(!s(!s(F:1,seq,,-1),seq,,-1),"") ``` [Try it online!](https://tio.run/##K/r/P0ExwbY0LyezuMS62LY4saAgp9K6PCMzJ1XDzUbXTdtQMzmxREOxGITcrAx1ilMLdXR0DTURDCUlzf//AQ "R – Try It Online") [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 101 bytes ``` #include<cstdio> int a,x,y,z;main(){for(;;)for(x=a++;x--;)for(y=x;y--;)for(z=y;z;)printf("%d,",z--);} ``` [Try it online!](https://tio.run/##Sy4o0E1PTv7/XzkzLzmnNCXVJrm4JCUz344rM69EIVGnQqdSp8o6NzEzT0OzOi2/SMPaWhNEVdgmamtbV@jqQriVthXWlTBOlW2ldZW1ZkER0Ig0DSXVFB0lnSpdXU3r2v//AQ "C++ (gcc) – Try It Online") [Answer] # [Factor](https://factorcode.org/) + `combinators.extras lists lists.lazy`, 58 bytes ``` [ 1 lfrom [ [ 1 [a,b] >list ] lmap-lazy lconcat ] thrice ] ``` Running in the listener, as `lmap-lazy` postdates build 1525, the one TIO uses. Note that output has been limited to 30 so I could actually take the screenshot. This limitation is not present in the code itself. [![enter image description here](https://i.stack.imgur.com/1Bay9.png)](https://i.stack.imgur.com/1Bay9.png) ## Explanation It's a quotation (anonymous function) that returns an infinite lazy list of the triple countdown sequence. * `1 lfrom` An infinite lazy list of the natural numbers. * `[ ... ] thrice` Apply a quotation (to the natural numbers) three times. * `[ ... ] lmap-lazy` Use a quotation to map over a lazy list. * `1 [a,b] >list` Create a list from an input number to one. e.g. `5` -> `L{ 5 4 3 2 1 }` * `lconcat` Concatenate a list of lists into a single list. [Answer] # [C (gcc)](https://gcc.gnu.org/), 69 bytes Nested Ternary operator solution. `a`, `b` and `c` are the triple countdown state from fastest to slowest, and `d` is the increasing count. `a` is printed for every step in the countdown. (make that a+1 thanks to AZTECCO Thanks to AZTECCO for -10 bytes!! And -2 more!!! It took me an embarrassingly long time to figure out what's going on with the last suggestion, that's some serious golfing. ``` a,b,c,d;main(){for(;;a=!a?b=!b?c-=c?1:--d:b-1:a-1)printf("%d,",a+1);} ``` [Try it online!](https://tio.run/##BcHBCoAgDADQb1EIlLbDrg7xW@bE8JCFdIu@fb2neKiaCVRQaHzKmCG@/VqBWbKTUrOrRTFroYTYUkVKghTvNebTg98aeJCdIn9mPw "C (gcc) – Try It Online") [Answer] # [Swift](https://swift.org/), 103 bytes ``` let a:([Int])->[Int]={$0.flatMap{(1...$0).reversed()}};(1...).forEach{a(a(a([$0]))).forEach{print($0)}} ``` Functional programming in Swift, excepting the `print` call, which obviously is non-pure. `a` is a closure that converts an array of integers to an array of their countdown, which is called three times for every number. [Try it online!](https://tio.run/##Ky7PTCsx@f8/J7VEIdFKI9ozryRWU9cOTNtWqxjopeUklvgmFlRrGOrp6akYaOoVpZalFhWnpmho1tZag0U19dLyi1wTkzOqEzVAMFrFIFZTEyFaUJSZV6IB1Ftb@/8/AA "Swift – Try It Online") [Answer] # [Nibbles](http://golfscript.com/nibbles), 6 bytes ``` <$/, 3,~.@\, ``` explanation ``` <$ # first int input elements / # fold ,3 # [1,2,3] (any list of length 3 would work) ,~ # [1,2,...inf] (initial value to fold) .@ # map on accumulator \, # reverse of list from 1 to # implicit $ (the element of list to map) ``` [Answer] # [Python 3](https://docs.python.org/3/), 72 bytes ``` def c(x,i):i>0<x!=(print(x),c(x-1,i),c(x-1,i-1)) i=1 while 1:c(i,2);i+=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFZo0InU9Mq087ApkLRVqOgKDOvRKNCUwcormsIlIExdA01NbkybQ25yjMyc1IVDK2SNTJ1jDStM7VtDf//BwA "Python 3 – Try It Online") -19 bytes thanks to Wheat Wizard by using even more recursion -1 byte thanks to ovs [Answer] # [JavaScript (V8)](https://v8.dev/), 51 bytes ``` e=f=>i=>{for(;--i;)f(i)};e(_=>e(e(e(print)))(-_))`` ``` [Try it online!](https://tio.run/##FcIxCoAwDAXQ6@QP2YWSXqUtkkActNTSRTx7RN472mr3PrxPXluEikl2yY9dgxKzJxg53qRUJCv9@vBzAiAuQK0RHw "JavaScript (V8) – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` )╒3æ╒mx─§ ``` Outputs the 0-based value. [Try it online.](https://tio.run/##y00syUjPz0n7/1/z0dRJxoeXAcncikdTGg4t///fgMuQy4jLmMuEyxDINOUyNwAA) **Explanation:** ``` ) # Increase the (implicit) input-integer by 1 (work-around for input 0) ╒ # Pop and push a list in the range [1,input+1] 3æ # Loop 3 times, using four characters as inner code-block: ╒ # Convert each integer in the list to a [1,n] ranged list m # Map over each list: x # Reverse the list ─ # Flatten the list of lists § # After the loop, get the value at the (implicit) input as index # (after which the entire stack is output implicitly as result) ``` [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~132~~ ~~123~~ ~~114~~ ~~113~~ 112 bytes ``` #include<argp.h> main(int a,int b){if(a<2)for(;;)main(2,a++);while(--b)if(a<4)main(a+1,b);else printf("%d,",b);} ``` [Try it online!](https://tio.run/##Sy4o0E1PTv7/XzkzLzmnNCXVJrEovUAvw44rNzEzTyMzr0QhUQdEJmlWZ6ZpJNoYaablF2lYW2uC5Y10ErW1Na3LMzJzUjV0dZM0wWpMIJKJ2oY6SZrWqTnFqQoFRUBD0jSUVFN0lECCtf//AwA "C++ (gcc) – Try It Online") Thanks to @wheat-wizard for tip on removing all whitespace [Answer] # [Julia 1.0](http://julialang.org/), 56 bytes ``` ~i=i:-1:1 !i=[.~i...;] for i=1:-1%UInt println.(!!!i)end ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/vy7TNtNK19DKkEsx0zZary5TT0/POpYrLb9IIdPWECijGuqZV6JQUJSZV5KTp6ehqKiYqZmal/L/PwA "Julia 1.0 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) There's gotta be a better way than this. Outputs the `n`th term, 0-indexed. ``` gÈc!õ1}g3NËôÄ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z8hjIfUxfWczTsv0xA&input=MjU) [Answer] # [Perl 5](https://www.perl.org/), 48 bytes ``` sub d{sub c{map{reverse 1..$_}@_}sub{c c c++$i}} ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhpRpEJlfnJhZUF6WWpRYVpyoY6umpxNc6xNcCpaqTFYBQW1sls7b2f0FRZl6JBlCpQrWSSryOUq1Ciq6dhqamQnlGZg5Q338A "Perl 5 – Try It Online") Returns an anonymous sub that can be called repeatedly to obtain the next list of items in the sequence. Ungolfed and commented: ``` sub d { sub c { # This is where the magic happens. c(1) returns (1), c(2) returns (2, 1). # c(1, 2, 3) returns (1, 2, 1, 3, 2, 1) return map {reverse 1 .. $_} @_; } # 3 nested calls to c() to get the triple countdown return sub{c(c(c(++$i)))}; } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 48 bytes ``` x=0 loop{x-=1;eval"(x...0).map{|x|"*3+"p -x}}}"} ``` [Try it online!](https://tio.run/##KypNqvz/v8LWgCsnP7@gukLX1tA6tSwxR0mjQk9Pz0BTLzexoLqmokZJy1hbqUBBt6K2tlap9v9/AA "Ruby – Try It Online") * outputs infinitely We eval "(x...0).map{|x|"\*3 which becomes a depth 3 loop x is decremented thus negative so that we can use range x..0 Then we put -x [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` ɾṘ3(vɾf)Ṙ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C9%BE%E1%B9%983%28v%C9%BEf%29%E1%B9%98&inputs=5&header=&footer=) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` Nθ≔⁰ηW›θLυ«≦⊖ηF…η⁰F…κ⁰F…λ⁰⊞υμ»I±§υ⊖θ ``` [Try it online!](https://tio.run/##ZY7NCsIwEITP7VPkuIEI9eKlp6IghVqKbxDbNSmmac2PCuKzx5R6KLi3GeabnVZy045chVDqybvaDxc0cKd5WljbCw0ZIzKqp@wVEjga5G4OMFKhFk6Cp5SSd5qc@PQjDtgaHFA77BY2uY6GwJlrgSAZySKwcm5/jlqcxttYz8gQKz5pY3rtYM@tgxpFHAGFK3WHrzmyehm3z5eHsN2FzUN9AQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs the 1-indexed `n`th value. Explanation: Based on @AZTECCO's answer, generates the triple countup sequence for the negated natural numbers, and then negates the final value to produce the desired result. ``` Nθ ``` Input `n`. ``` ≔⁰η ``` Start with no terms. ``` W›θLυ« ``` Repeat until we have at least `n` terms. ``` ≦⊖η ``` Get the next negated natural number. ``` F…η⁰F…κ⁰F…λ⁰⊞υμ ``` Generate the triple countup for that number. ``` »I±§υ⊖θ ``` Output the `n`th term, negating to give the desired result. [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 14 bytes ``` r1{m{ro^p}}3E! ``` [Try it online!](https://tio.run/##SyotykktLixN/f@/yLA6t7ooP66gttbYVfH/fwA "Burlesque – Try It Online") ``` r1 # Range 1..inf { m{ # Apply to each ro # Range from 1..N ^p # Push in reverse } } 3E! # Run 3 times ``` ]
[Question] [ [Halley's Comet](https://en.wikipedia.org/wiki/Halley%27s_Comet) is the only comet that may appear (i.e. become visible to the naked eye on Earth) twice in a human lifetime. The orbital period of Halley's Comet is not constant: it has varied between 75 to 79 Earth years since the first definite apparition was recorded in 240 BCE. This variability is mainly driven by gravitational interactions between the comet and the planets of the Solar System. For the three millennia up to the year 3000, Halley's Comet appeared, or is projected to appear, in the following years: 66, 141, 218, 295, 374, 451, 530, 607, 684, 760, 837, 912, 989, 1066, 1145, 1222, 1301, 1378, 1456, 1531, 1607, 1682, 1758, 1835, 1910, 1986, 2061, 2134, 2209, 2284, 2358, 2430, 2504, 2579, 2653, 2726, 2795, 2863, 2931, 3000 Apparitions beyond 2134 predicted using this [orbit simulator](http://orbitsimulator.com/gravitySimulatorCloud/simulations/1452654910254_halley.html). The simulations account for gravitational perturbations due to the planets but not for other effects, such as changes in the comet's outgassing rate, that also affect its orbit. See [here](https://forum.cosmoquest.org/showthread.php?164509-Future-apparitions-of-Comet-Halley) for further discussion. ### Task Write a program or function that takes as input a positive integer up to 3000 (inclusive), representing a year, and outputs/returns the number of years until the next apparition of Halley's Comet. In other words, if the input year is \$y\$ and Halley's Comet next appears in year \$y\_\text{H}\ge y\$, find \$y\_\text{H}-y\$. The shortest code (in bytes) in each language wins. ### Test cases ``` 1 -> 65 1066 -> 0 1067 -> 78 1986 -> 0 1987 -> 74 2021 -> 40 ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 74 bytes ``` n=>Buffer("BKMMOMOMMLMKMMOMOMNKLKLMKLKIKKJHJKJIEDDE").every(c=>(n-=c)>0)-n ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1s6pNC0ttUhDycnb19cfCH19fKEsP28fbyDHx9vT29vLw8vby9PVxcVVSVMvtSy1qFIj2dZOI0/XNlnTzkBTN@9/cn5ecX5Oql5OfrpGmoaCgoKhpqaCvr6CmSkXqpShgZkZRErBAFPKHCJlboEuZWmBU5elBUyXiQKanJGBEdQdJgb/AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` n => // n = input year Buffer( // build a buffer consisting of "BKMM...EDDE" // the year deltas encoded as ASCII codes ) // 'B' -> 66, + 'K' (75) -> 141, etc. .every(c => // for each value c in there: (n -= c) // subtract c from n > 0 // and go on while the result is positive ) // end of every(), which yields false - n // return -n ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 35 bytes Uses second-order differences to reconstruct the years, which is 1 byte shorter than [first-order differences](https://tio.run/##AUUAuv9vc2FiaWX//@KAojnDisO6w4FEZVRjw4zigJrFkynDjsSARcWhy4bDjuKAojEy0LI2OCsuwqU2NitJLS7OlGT//zIwMjE). ``` •6?É@fô]öÔMƵ4^-•7в4-.¥75+.¥66+I-.Δd ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcMiM/vDnQ5ph7fEHt52eIrvsa0mcbpAUfMLm0x09Q4tNTfVBpJmZtqeunrnpqT8/29kYGQIAA "05AB1E – Try It Online") ``` •6...-• # compressed integer 7в # convert to base 7 4- # subtract 4 from each .¥ # un-delta: cumulative sum with a 0 prepended 75+ # add 75 to each; this is now the list of years between appearances .¥ # un-delta 66+ # add 66 to each; this is now the list of years of appearances I- # subtract the input year .Δd # find the first non-negative integer ``` [Try it with step-by-step output!](https://tio.run/##jZHBSsNAEIbvPsVPrjallnQDBdGrBx9BYZOdNAvNbtidrXgQvHrvEwi@gKgPYMCj@Ay@SIxWWhotdI7DN//8/4z1MtPUtp@39@KkuTstmqeL5qVZnr89J5dx10WU26p25D0paMM0IzdFNDiOosFB@vGI7eposyDHYItMekK6hpO4z/qQsZM5I0HhbAWSebnGh68PfT6YWNGc5RR5qMJcsl4QfKhwpbmExAid0ZqMIrWxODnsqUilkE6@De6/75cR4j8xIf6Ine3OyiV1d6wD45rk5pTD96W62R4ptFE/eKGdZxhrYkOzVereJ9p2PBoffQE) The part `.¥75+.¥66+` can be written with a loop at the same length as `„KBÇv.¥y+}`. [Answer] # [R](https://www.r-project.org/), ~~87~~ 81 bytes ``` (z=cumsum(utf8ToInt("BKMMOMOMMLMKMMOMOMNKLKLMKLKIKKJHJKJIEDDE"))-scan())[z>=0][1] ``` [Try it online!](https://tio.run/##K/r/X6PKNrk0t7g0V6O0JM0iJN8zr0RDycnb19cfCH19fKEsP28fbyDHx9vT29vLw8vby9PVxcVVSVNTtzg5MU9DUzO6ys7WIDbaMPa/kYGR4X8A "R – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~45~~ 44 bytes ``` 66 75'#AeXj=*pq5 Oe>3-u'F7Za4-,hYs]i-t0<~)X< ``` [Try it online!](https://tio.run/##y00syfn/38xMwdxUXdkxNSLLVqug0FTBP9XOWLdU3c08KtFEVycjsjg2U7fEwKZOM8Lm/38jAyNDAA) Or [verify all test cases](https://tio.run/##y00syfmf8N/MTMHcVF3ZMTUiy1aroNBUwT/Vzli3VN3NPCrRRFcnI7I4NlO3xMCmTjPC5r9LVEXIf0MuQwMzMxBhzmVoaWEGIsy5jAyMDAE). ### Explanation This uses the *second*-order consecutive differences to compress the list of years. ``` 66 % Push 66 75 % Push 75 '#AeXj=*pq5 Oe>3-u' % Push this string F7Za % Uncompress from base94 (printable ASCII except quote) to base 7 4- % Subtract 4. This is the 2nd-order difference of the list of years , % Do twice h % Concatenate (first time with 75, second time with 66) Ys % Cumulative sum ] % End i- % Subtract input element-wise t % Duplicate 0<~ % Logical index of non-negative values ) % Apply index to keep only non-negative values X< % Minimum. Implicitly display ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 73 bytes ``` $,=EDDEIJKJHJKKIKLKMLKLKNMOMOMMKMLMMOMOMMKB;$_-=ord chop$,while$_>0;s/-// ``` [Try it online!](https://tio.run/##K0gtyjH9/19Fx9bVxcXV08vby8PL29vT28fb1wdI@Pn6A6EvkOMLZTlZq8Tr2uYXpSgkZ@QXqOiUZ2TmpKrE2xlYF@vr6uv//2/IZWbIZWhpYcb1L7@gJDM/r/i/rq@pnoGhwX/dghwA "Perl 5 – Try It Online") Uses the popular ASCII encoding but puts the first appearance (year 66) at the right side. [Answer] # [J](http://jsoftware.com/), 61 bytes ``` (3+/\@u:'BKMMOMOMMLMKMMOMOMNKLKLMKLKIKKJHJKJIEDDE')&(]-~I.{[) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NYy19WMcSq3Unbx9ff2B0NfHF8ry8/bxBnJ8vD29vb08vLy9PF1dXFzVNdU0YnXrPPWqozX/a3JxpSZn5CuYmSrYKqQpAIEhRABoA0jA0MDMDCJgbgETMEdVYWkBU2ECE4CqMIGoMDIwMuT6DwA "J – Try It Online") Noticed I independently came up with the same long constant Arnauld used in his answer, which is 66 prepended to the differences of the years, converted to Unicode code points `u:`. The J code then converts back to a list of numbers `3 u:`, and scan sums those numbers `+/\@` to recover the original list of comet years. We then find the "insert before" index `I.` of the program input within the list of comet years, and subtract the program input `]-~` from the actual comet list value at that same index `I.{[`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~85~~ ~~42~~ 41 bytes ``` -hg#Qt.u+NYCM+\B."BOÅ>+‘¸h`bʹ¹dtg"Z ``` [Try it online!](https://tio.run/##K6gsyfj/XzcjXTmwRK9U2y/S2Vc7xklPycmf/3CrnfahiYd2ZCQksR/uOrTz0E7hFL6S9HqlqP//jQyMDAE "Pyth – Try It Online") --- Managed to shed 44 bytes by using [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s delta string. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 80 bytes ``` -Fold[If[#>0,#-#2,#]&,#,36^^9cyu7y4a7m84jq6pihqeoy2jutbhh4~IntegerDigits~15+65]& ``` [Try it online!](https://tio.run/##HczBCoMgAIDhu68hdJmBurI6LHYYg26DHaPANU1j2Wp2kDFf3UWXj//0j9wqMXKrOx7kKcTX6fWsK1nDEiMYQ4pgEyGIjqxti86tmUt4NubJMLO3VrOYHB1W@1Aq8ZWxohfLRffafjxJDyxtonBbtLE1jEt53k7@3nHjv4AgQDBju9lmkbPdrSmmBPzCHw "Wolfram Language (Mathematica) – Try It Online") The comet should be visible near its periapsis. Unfortunately, [`CometData`](https://reference.wolfram.com/language/ref/CometData.html) only includes the dates of the previous and next periapses (5 Feb 1986 and 31 May 2061). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` I⌊Φ⁻EφΣE…”$↷↥CⅉWF3⊖n↧JNω∕υ³*H↨{W”⊕ι℅λN¬‹ι⁰ ``` [Try it online!](https://tio.run/##LY1NDsIgGESvQrr6SDDRbt3Z1kiB1sQTIMWUhNKGHxNPj9Q4s3lvNqNm6dUqbc53b1yERoYIwjizpAWuxkbtd00BhNzgRdCj7Ds2H2V1M68bVBcmxFgquPjTwDgrwhllrL/1rKdd23YVQdQprxftop7AYEzQ6CfjpAWL8a7UbSkOaXmW292HNQLXIYAh6Ih/OedcH@tTPrztFw "Charcoal – Try It Online") Link is to verbose version of code. Also uses @Arnauld's string, although I didn't realise until I read @Jonah's answer. Explanation: ``` φ Predefined variable 1000 (shorter than 40) E Map over implicit range ”...” Compressed form of @Arnauld's string … Truncate to length ι Current index ⊕ Incremented E Map over characters λ Current character ℅ Take the ordinal Σ Summed ⁻ Vectorised subtract N Input year Φ Filter where ι Current value ¬‹ ⁰ Is non-negative ⌊ Take the minimum I Cast to string Implicitly print ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 47 bytes ``` -⁰ḟ≥⁰∫m+66ΘB14B95mo-30c"(p_45Ux2|!uvrA(C$TDL3W ``` [Try it online!](https://tio.run/##yygtzv7/X/dR44aHO@Y/6lwKZDzqWJ2rbWZ2boaToYmTpWluvq6xQbKSRkG8iWlohVGNYmlZkaOGs0qIi49xuML///@NDIwMAQ "Husk – Try It Online") No built-in numeric compression in [Husk](https://github.com/barbuz/Husk), so we encode the differences between Halley years as printable ASCII values. Halley year differences are then reconstructed by subtracting 30 from the ASCII values, converting to base 95, getting base 14 digits and adding 66. The Halley years are the cumulative sum of this: altogether `∫m+66ΘB14B95mo-30c"(p_45Ux2|!uvrA(C$TDL3W` (where `"(p_45Ux2|!uvrA(C$TDL3W "` is the encoding string). We then just retrive the first element greater-or-equal to the input (`ḟ≥⁰`), and subtract the input from this (`-⁰`). [Answer] # [Zsh](https://www.zsh.org/), 78 bytes ``` for ((a=-$1;a<0;a+=##$s[++i]))s=BKMMOMOMMLMKMMOMOMNKLKLMKLKIKKJHJKJIEDDE;<<<$a ``` [Try it online!](https://tio.run/##hVNNb9pAEL37V4xipGC@RDlic0gapBID6aGHSlUkL/aAVzK7rndoSqP@djrrdUnaAFnLnzPz9s28518mP6zbwfNhrStot8Wk3/oQimgYiu7E91vmW7crH4PATG7jxeKBj8V80Twt43nML/N4Fsf3n@7j@9n07m4aRlHUEoff4VMuC4QKRQbfw0zDGlr2rtDzxlF0Pf36eX6zvPkye1hee957uw8GAwfcZIJdYXMeVxAcv9vlw8e@oT2zsEWF1qXnAm4fuLx8kEqSFIU0CIlIgDRQjvy13FEPFG4EYea9LrHMLyK6mVgwaaBAYxhRKBh6l6m4/o8oBgkScyRkqJJqcxaCR3iqtbTCLSoGkgm0DYmKDAiCIchtWchUUrEPTmOyLHx9fIO5YVqWDyNSDmkuKpESVqDXlu0pLN8/N6i/WKnOsNSSeardduXAeGT0Av8Gl61zXgCRZa6eZ8cyvDN356bad7aYCSkoK8vG1nqdzlITdjpjmDmnFHuYQc6GT5xizqv8FATjGqZKoG/lIxYMzL8Cwgo5H9kPWQ/4UodWOtu7ntGzBuYkm5qMWTT@p5SmnN@DAdzuCAyriv@X1b63dsOfmO7Ysc0@dYyrqwzSQuzY46/z23bDKxRpDpKHLEhqdQUluyRw5J44X3G/ttB6UapGlxqrZ@MpO5t/lZdww4u7NuIHwghWe0IzOIyGo6H3Bw "Zsh – Try It Online") I've had this answer prepared since this question was in the sandbox and I'm annoyed I missed it being posted Explanation: ``` for ((a=-$1;a<0;a+=##$s[++i]))s=...;<<<$a for (( ; ; )) ; # C-style for loop a=-$1; # initialise `a` to the input, negated a<0; # while `a` is less than 0 s=...; # set `s` to the string ++i # increment `i` (starts at 0 implicitly) $s[ ] # get the `i`th character of `s` ## # get the codepoint number of that character a+= # add that to `a` ;<<<$a # then print `a` ``` **Note**: Initially I had `s=...;for ((...)):;<<<$r` - setting s to the string beforehand, and the body of the loop being `:` (do nothing). But since the body of the loop is executed before the third clause of the loop (the "each iteration" part), and we only use `s` in that clause, we can put `s` in the body to save 2 bytes. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 37 bytes ``` ɾ»«Ẏ⅛Ṁß)∞'₌›ṫh⁰ḟ†ṙ←⁰»12τ68+¦0p66+$Fhε ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvsK7wqvhuo7ihZvhuYDDnyniiJ4n4oKM4oC64bmraOKBsOG4n+KAoOG5meKGkOKBsMK7MTLPhDY4K8KmMHA2NiskRmjOtSIsIiIsIjY3Il0=) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 71 bytes ``` •1Ò}MKX…иv½ι„qā·&à©Dà|ãвìkPn…(l2ßrÏyO;¬VÕÏcw÷©ûëтÎBʒNdãA₄ΩΓ•3001вʒI@}αW ``` [Try it online!](https://tio.run/##AXwAg/9vc2FiaWX//@KAojHDkn1NS1jigKbQuHbCvc654oCeccSBwrcmw6DCqUTDoHzDo9Cyw6xrUG7igKYobDLDn3LDj3lPO8KsVsOVw49jd8O3wqnDu8Or0YLDjkLKkk5kw6NB4oKEzqnOk@KAojMwMDHQssqSSUB9zrFX//8x "05AB1E – Try It Online") I know there's a shorter 05AB1E answer, but this uses a different method, so I thought it'd be interesting to see the comparison in byte lengths. ## Explained ``` •...•3001в # Pushed compressed list of all years ʒI@} # Keep only those >= the input year αW # Push the smallest absolute difference amongst those values ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “¡AMzⱮ⁽ƑẸÑ[NṀtR“¦Ṛ’b8+"6FŻ+66ÄḟḶḢ_ ``` **[Try it online!](https://tio.run/##AUwAs/9qZWxsef//4oCcwqFBTXrisa7igb3GkeG6uMORW07huYB0UuKAnMKm4bma4oCZYjgrIjZGxbsrNjbDhOG4n@G4tuG4ol////8xMDY3 "Jelly – Try It Online")** ### How? ``` “...“¦Ṛ’b8+"6FŻ+66ÄḟḶḢ_ - Link: year “...“¦Ṛ’ - list of base 250 integers = [18853782274514630143915309466833, 1683] b8 - convert to base 8 = [[3, 5, 5, 7, ..., 2, 1], [3, 2, 2, 3]] 6 - six +" - zip (implicitly wrapped 6 = [6]) with addition = [[9,11,11,13, ..., 8, 7], [3, 2, 2, 3]] F - flatten = [ 9,11,11,13, ..., 8, 7, 3, 2, 2, 3] Ż - prepend zero = [ 0, 9,11,11,13, ..., 8, 7, 3, 2, 2, 3] +66 - add 66 = [66,75,77,77,79, ...,74,73, 69,68,68,69] Ä - cumulative sums = [66,141,218,295,374, ...,2653,2726,2795,2863,2931,3000] Ḷ - lowered range (year) = [0,1,2,...,year-1] ḟ - filter discard - e.g. if year = 2860 then [2863,2931,3000] Ḣ - head 2863 _ - subtract (year) 3 ``` --- FWIW a port of [ovs's](https://codegolf.stackexchange.com/users/64121/ovs) [05AB1E answer](https://codegolf.stackexchange.com/a/217252/53748) using the second-difference (and also using the filter-out-lowered range technique above) is also 34: ``` “¬V>ƭṘḌƘH*O⁵i²Ọ’b7_4ÄŻ+75ÄŻ+66ḟḶḢ_ ``` [Answer] # [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), ~~266~~ ~~263~~ ~~262~~ 204 bytes ``` mod H is pr LIST{Nat}. op n : Nat ~> Nat . vars A B C : Nat . eq n(A)= n(A 66 5710855311372188087909795024940117969860147607). eq n(A B C)= if A > B then n(A(B +(C & 15)+ 68)(C >> 4))else sd(A,B)fi . endm ``` ### Example Session ``` Maude> red n(1) . --- Ex: 65 result NzNat: 65 Maude> red n(1066) . --- Ex: 0 result Zero: 0 Maude> red n(1067) . --- Ex: 78 result NzNat: 78 Maude> red n(1986) . --- Ex: 0 result Zero: 0 Maude> red n(2021) . --- Ex: 40 result NzNat: 40 Maude> red n(3000) . --- Ex: 0 result Zero: 0 ``` ### Ungolfed ``` mod H is pr LIST{Nat} . op n : Nat ~> Nat . vars A B C : Nat . eq n(A) = n(A 66 5710855311372188087909795024940117969860147607) . eq n(A B C) = if A > B then n(A (B + (C & 15) + 68) (C >> 4)) else sd(A, B) fi . endm ``` The answer is obtained by reducing the function `n`, which takes the input year. The large number encodes the differences between successive years (e.g., 141 - 66 = 75) *minus* 68, packed into a bitstring with 4 bits per value. --- Shaved off 3 bytes by replacing two conditional equations with a single equation using `if_then_else_fi`. Saved one more byte by deduplicating a long enough repeated sublist using a condition. Saved 58 bytes by encoding the year differences as a bitstring (and a few other tweaks). [Answer] # [Python 2](https://docs.python.org/2/), 83 bytes ``` f=lambda y,t=0x46ba1298ab6f2234037bc64abb247ba8e61402:f(y-t%14-66,t/14)if y>0else-y ``` [Try it online!](https://tio.run/##PY3RjoMgFETf@Yr7sqkm0AJlUZvov0DFLAkqkbtJ@Xor3Y1vc@eemYkZf9ZF7vvUBzPb0UCm2POX0tYI2bXG6knKu@L3xj61MtZK1VjTOi0Ul4@pygy/hGJaU7wJVfsJ8sBdSI7l3c9x3RBSToRM6wbBLw78UoxrwtEvDwLHHrhXdE90I/Qwm1j5BemHvaYYPFYXNlzq@kA3l34DHtQxW@64Hejp9mcPLaUlRf@fOwAIYAPobyK41kUCL7IpsmmJ6NrT7do/VwGRXH5yir8B "Python 2 – Try It Online") Stores the differences between the years (minus 66) as digits in a base-14 number `t`. Repeatedly subtracts the differences from the given year `y` until we gets a non-positive number (overshoot), in which case the answer is `-y`. ]
[Question] [ Given a list of positive integers, find the number of triangles we can form such that their side lengths are represented by three distinct entries of the input list. (Inspiration comes from [CR](https://codereview.stackexchange.com/questions/226885/counting-the-triangles-that-can-be-formed-from-segments-of-given-lengths).) ### Details * A triangle can be formed if *all* permutations of the three side lengths \$a,b,c\$ satisfy the *strict* triangle inequality $$a + b > c.$$ (This means \$a+b > c\$, \$a+c>b\$ and \$b+c>a\$ must all hold.) * The three side lengths \$a,b,c\$ must appear at distinct positions in the list, but do not necessarily have to be pairwise distinct. * The order of the three numbers in the input list does not matter. If we consider a list `a` and the three numbers `a[i], a[j], a[k]` (where `i,j,k` are pairwise different), then `(a[i],a[j],a[k]), (a[i],a[k],a[j]), (a[j], a[i], a[k])` etc. all are considered as the *same* triangle. * The input list can assumed to contain at least 3 entries. * You can assume that the input list is sorted in ascending order. ### Examples A small test program can be found here on [Try it online!](https://tio.run/##ZY/NDoIwEITvPMV4MRgWIupRfQS9eCMctrXSxlISWuOFd8eKPzHxMpkvO/un2V@VteModdd5tYbFDlVqZzMmRBWTygUGqwLaWLTKNUHHXI6SwNjmqJZF0dYEMQFn5QvlhOKFdWL8qTfsGquQMgmKQ3fgTGAfk/M5RCaj5aeVGUcrEndrheqPl0@jn857X1AduqCNazAgPDd9PyD8rAp10rJxsc24oHqWAanX3R0F/qcX6BWfF@NYlbSiNW3qBw "Haskell – Try It Online") ``` Input, Output: [1,2,3] 0 [1,1,1] 1 [1,1,1,1] 4 [1,2,3,4] 1 [3,4,5,7] 3 [1,42,69,666,1000000] 0 [12,23,34,45,56,67,78,89] 34 [1,2,3,4,5,6,7,8,9,10] 50 ``` For the input of `[1,2,3,...,n-1,n]` this is [A002623](http://oeis.org/A002623). For the input of `[1,1,...,1]` (length `n`) this is [A000292](http://oeis.org/A000292). For the input of the first `n` Fibonacci numbers ([A000045](http://oeis.org/A000045)) this is [A000004](http://oeis.org/A000004). [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~8~~ 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) Thanks to [recursive](https://codegolf.stackexchange.com/users/527/recursive) for -1! ``` é═rê÷┐↨ ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=82cd7288f6bf17&i=[1+2+3]%0A[1+1+1]%0A[1+2+3+4]%0A[3+4+5+7]%0A[1+42+69+666+1000000]%0A[12+23+34+45+56+67+78+89]%0A[1+2+3+4+5+6+7+8+9+10]&a=1&m=2) ### Unpacked (8 bytes) and explanation: ``` r3SFE+<+ r Reverse 3S All length-3 combinations F For each combination: E Explode: [5,4,3] -> 3 4 5, with 3 atop the stack + Add the two shorter sides < Long side is shorter? 0 or 1 + Add result to total ``` That's a neat trick. If you have a sequence of instructions that will always result in 0 or 1 and you need to count the items from an array that yield the truthy result at the end of your program, `F..+` is a byte shorter than `{..f%`. Assumes the initial list is sorted ascending. Without this assumption, stick an `o` at the beginning for 8 bytes. [Answer] # [R](https://www.r-project.org/), ~~62~~ ~~52~~ ~~40~~ 34 bytes ``` sum(c(1,1,-1)%*%combn(scan(),3)>0) ``` [Try it online!](https://tio.run/##K/r/v7g0VyNZw1DHUEfXUFNVSzU5PzcpT6M4OTFPQ1PHWNPOQPO/oZGCkbGCsYmCiamCqZmCmbmCuYWCheV/AA "R – Try It Online") Port of [Luis Mendo's Octave solution](https://codegolf.stackexchange.com/a/190966/67312) Since `a<=b<=c`, the triangle condition is equivalent to `a+b-c>0`. The `a+b-c` is succinctly captured by the matrix product `[1,1,-1] * X`, where `X` is the 3-combinations of the input array. There were a lot of suggestions for improvements made by 3 different people in the comments: * [Robert S.](https://codegolf.stackexchange.com/users/81727/robert-s) for [suggesting `scan`](https://tio.run/##BcFLCoAgEADQq8xyhtz4N@gm4qKEoIUjZMLc3t571xqzYe3tYhz1ZCRl1T25fk9nFJJsyyFZl02yKURLGzAWrAPnwQcIEWKCtK8f). * [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder) for suggesting [improvements to the triangle inequality](https://tio.run/##PYnbCoMwEETf@xU@ZssU6ibZKNgvEcE2ECiYCG0F/z6mN2dezpx55FB1pyqHJfnXfU5qwtiPFz/HW6LnEhUfp14jXtehe0NRA@WgvKrB0ESHL5fuXDzMbxWChds/w5AWIoL6/Mn/YbCGNjAWViAOrkHTEuUN) and [this odd one](https://tio.run/##K/r/P8e2ODkxT0PTOiE6wTY5Pzcpz7q4NFfDSCsn2lgnNSfWBkQDRWI1/1tYKphbKJiZK5iaKZiYKhibKBgZKxga/QcA) which requires the input to be in *descending* order (which just goes to show how important a flexible input format is). * and finally [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy) for the following: # [R](https://www.r-project.org/), 40 bytes ``` y=combn(scan(),3);sum(y[3,]<y[1,]+y[2,]) ``` [Try it online!](https://tio.run/##K/r/v9I2OT83KU@jODkxT0NTx1jTurg0V6My2lgn1qYy2lAnVrsy2kgnVvO/oZGCkbGCsYmCiamCqZmCmbmCuYWCheV/AA "R – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 49 bytes ``` ([]%) [c,b,a]%l|a+b>c=1 p%(h:l)=(h:p)%l+p%l _%_=0 ``` [Try it online!](https://tio.run/##LcVNCsIwEEDhfU4xCwMNHcH@VyFeJIYyDcYWp2WwLj27sQt58L2JtuedOUV7S5nz2igXcETymj@Uj9dgCyU6my5s7K4YzbloVoMe7CktNK9gQV7z@oYDLCQQ9ztXlFhWWNVYN9i02HbY9difPYIr8J/36Rsi02NLxyDyAw "Haskell – Try It Online") Recursively generates all subsequences of `l` (reversed), and checks which length-3 ones form triangles. **50 bytes** ``` f l=sum[1|[a,b,c]<-filter(>0)<$>mapM(:[0])l,a+b>c] ``` [Try it online!](https://tio.run/##LcpNDoIwEEDhq8yCBcQhofxroDfwBJMuSkO1cUoaijvPbmVh3uLbvKeOr5U5JQs8x7cn8SGNCxo1ldbxse65rIopk16He36jShWM@rJIo5LXboMZwu62AzI4D7CnRKLGusGmxbbDrsd@wGHE8aoQSOA/pdLXWNaPmEoTwg8 "Haskell – Try It Online") The same idea, generating the subsequences with `mapM`, by mapping each value in `l` either to itself (include) or `0` (exclude). **50 bytes** ``` ([]%) p%(b:t)=sum[1|c<-t,a<-p,a+b>c]+(b:p)%t _%_=0 ``` [Try it online!](https://tio.run/##Lcm9DsIgFEDhvU/BIElJL4n0X1N8ESQNJaKN0NwIbj672MGc4RvOw8Tnzfvs5DWXSlNWIC2Xc2IyvoMSHzvxBGbiCKZaLlZX@0RGUzHTWR5zMOtGJMHXuiVyIMEgcbtKiRrqBpoW2g66HvoBhhHGkwaiBPzTOn@t8@YeM7eIPw "Haskell – Try It Online") Tries every partition point to take the middle element `b`. **51 bytes** ``` f(a:t)=f t+sum[1|b:r<-scanr(:)[]t,c<-r,a+b>c] f _=0 ``` [Try it online!](https://tio.run/##LcVLDsIgEADQvaeYhYs2nSbSv6R4EULMlIg2AiGAO88uujBv8R6UnjdrSzEV8VwLA7lJLyfZe@NxbZMmHyteS5VRr21EaraLVgcDV3EqjnYPAkLcfYYjOApgfkvJOux67AccRhwnnGacF1zOCkEy/FOqfLSxdE@l1SF8AQ "Haskell – Try It Online") The function `q=scanr(:)[]` generates the list of suffixes. A lot of trouble comes from needing to consider including equal elements the right number of times. **52 bytes** ``` q=scanr(:)[] f l=sum[1|a:r<-q l,b:s<-q r,c<-s,a+b>c] ``` [Try it online!](https://tio.run/##LcZNDsIgEEDhvaeYhQuNw4L@S4oXISymxGpTIJTRnWcXNTFv8b078Xr1vpRNs6OYD@po7G4Gr/kZjHyRyqPYwOOk@DcZ3SgY6TRdnC2BlggaUl7iA/YQKMH81RhZYVVj3WDTYtth12M/4HC2CEbiP2vL282eblyES@kD "Haskell – Try It Online") The helper function `q=scanr(:)[]` generates the list of suffixes. **57 bytes** ``` import Data.List f l=sum[1|[a,b,c]<-subsequences l,a+b>c] ``` [Try it online!](https://tio.run/##LcW9DsIgEADg3ae4wc2rCf03sU6OvgFhOAgoKVTs0c1nFx3MN3wP4tmGUIqP6blmuFKm481z3jkIE29Rirck1GjUueJNs31tdjGWISAd9MWoEskvMEFa/ZJhD5ESuN9SihrrBpsW2w67HvsBhxHHk0KQAv@UKh/jAt25VCalLw "Haskell – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes ``` {⊇Ṫ.k+>~t}ᶜ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv/pRV/vDnav0srXt6kpqH26b8/9/tEK0oY6RjnGsDpAGQjAN5OuYAFlAUsdUxxwsZmKkY2apY2ZmpmNoAAYgUSMdI2MdYxMdE1MdUzMdM3MdcwsdC0uEGUDdZjrmOhY6lkBdsQqxAA "Brachylog – Try It Online") I may have forgotten to take advantage of the sorted input in my old solution: # [Brachylog](https://github.com/JCumin/Brachylog), ~~18~~ ~~17~~ 15 bytes ``` {⊇Ṫ¬{p.k+≤~t}}ᶜ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv/pRV/vDnasOraku0MvWftS5pK6ktvbhtjn//0crRBvqGOkYx@oAaSAE00C@jgmQBSR1THXMwWImRjpmljpmZmY6hgZgABI10jEy1jE20TEx1TE10zEz1zG30LGwRJgB1G2mY65joWMJ1BWrEAsA "Brachylog – Try It Online") ``` { }ᶜ The output is the number of ways in which ⊇ a sublist of the input can be selected Ṫ with three elements ¬{ } such that it is not possible to show that p for some permutation of the sublist k+ the sum of the first two elements ≤ is less than or equal to . ~t} the third element. ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 35 bytes ``` +*.combinations(3).flat.grep(*+*>*) ``` [Try it online!](https://tio.run/##TYtNCoMwGETXzSlcuMgXh1ATTRRpr1LSokXwJ6gbKT17GmwXZRbzeMz4dhlMGPck7ZJLyIR8zOO9n9zWz9PKNclucJt8Lq3nIhNXQaFhnJ14DgVNOCjmR9GhODg2StivV1AaukBRojQwFrZCVf9/4tbAokKN/EyM5Og8f6UdT28kV7e/qWHhAw "Perl 6 – Try It Online") # Explanation It's a Whatever code, i. e. a concise notation for lambda functions (that works only in very simple cases). Each `*` is a placeholder for one argument. So we take the list of lengths (that appears at the first `*`), make all combinations of 3 elements (they always come out in the same order as in the original list, so that means the combinations are sorted too), flatten the list, and then take the list 3-by-3, and filter (`grep`) only those triplets that satisfy `*+*>*`, i. e. that the sum of the first two arguments is greater than the third. That gives all the triplets, and we finally count them with forcing numeric context with a `+`. (Of course we need to test it only for the case of "sum of two smaller > the largest". If this holds, the other hold trivially, if this does not, the triplet does not denote correct triangle lengths and we don't need to look further.) [Answer] # [Python 3](https://docs.python.org/3/), 73 bytes ``` lambda l:sum(a+b>c for a,b,c in combinations(l,3)) from itertools import* ``` [Try it online!](https://tio.run/##TZDBboMwEETv/oo94nYOgMFAJPIjaVQZYlQkgxF2pPbr6UKjpLuXfTvakcfLT/zys9qG9mNzZupuhtwp3KfEvHfnnga/kkGHnsaZej9142zi6OeQOCgpxbD6icZo1@i9CzROi1/j2xZtiJ@9CTZQSxeRXDLkUFdQKnEQN1P2INZQPJlnlKiY1UMvcugGWmtk6VEvpxy5gipQlCg1dIWqRt3st8V/czbUqFCjYQtWy1SKqxB7PAey34vto73tIV9PPwni8vfIGYbEyQNNCBz2b9s@D0H8H/vy5SW3Xw "Python 3 – Try It Online") This is the first naive, brute-force approach that comes to my mind. I'll update the post if I find a shorter solution using a different approach. Note that since the input is sorted, the tuple \$(a,b,c)\$ is also in the ascending order so it suffices to only check whether \$a+b>c\$ holds. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 55 bytes ``` \d+ * L$`_+ $<' %L$w`(,_+)\b.*\1(_*)\b(?<=^_+\2,.*) _ _ ``` [Try it online!](https://tio.run/##NYu9CsIwGEX37zlSTJNLyZfmr1BxdOkjBBOlDi4OIvj4MQhyuXDOcF739@N55TbIc21516RoE7VoEuuBhk18qkTRY75NKrMsqpM8rcdL0dliUiMVKq0xLGZi9NGP4agfHrG7w4IQwMYQW9gZs4Pz8AEhIiak5R/1ICAi9YDNFw "Retina – Try It Online") Link includes test cases, but with the values in the 5th case reduced to allow it to finish today. Assumes sorted input. Explanation: Regexes don't really like matching more than one thing. A normal regex would be able to find all of the values that could be a shortest leg of a triangle. Retina's `v` option doesn't help here, except to avoid a lookahead. However Retina's `w` option is slightly more helpful, as it would be able to find both the shortest and longest leg at the same time. That's not enough for this challenge though, as there might be multiple middle legs. ``` \d+ * ``` Convert the input to unary. ``` L$`_+ ``` For each input number... ``` $<' ``` ... create a line that's the original array truncated to start at that number. `$'` normally means the string after the match, but the `<` modifies it to mean the string after the previous separator, avoiding wasting 2 bytes on `$&`. Each line therefore represents all potential solutions using that number as the shortest leg. ``` %L$w`(,_+)\b.*\1(_*)\b(?<=^_+\2,.*) _ ``` For each of those lines, find all possible middle and longest legs, but ensuring that the difference is less than the first leg. Output a `_` for each matching combination of legs. ``` _ ``` Count the total number of triangles found. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ ~~10~~ 9 bytes My first time using 05AB1E! Thanks to [Grimmy](https://codegolf.stackexchange.com/users/6484/) for -1! ``` 3.Æʒ`α›}g ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fWO9w26lJCec2PmrYVZv@/3@0oZGOkbGOsYmOiamOqZmOmbmOuYWOhWUsAA "05AB1E – Try It Online") or [test suite](https://tio.run/##yy9OTMpM/V9W@d9Y73DbqUkJ5zY@athVm/5f5390tKGOkY5xrA6QBkIwDeTrmABZQFLHVMccLGZipGNmqWNmZqZjaAAGIFEjHSNjHWMTHRNTHVMzHTNzHXMLHQtLhBlA3WY65joWOpZAXbGxAA) A direct port of my Stax answer. Get all combinations of three entries and count those that could possibly form triangles. It's that counting part that really got me. I spend a load of bytes there. Bound to be some rookie mistake there. ``` 3.Æʒ`α›}g 3.Æ List of length-3 combinations ʒ }g Count truthy results under operation: ` Push the two shorter sides, then the long one α Absolute difference (negated subtraction in this case) › Remaining short side is longer? ``` [Answer] # [Python 2](https://docs.python.org/2/), 72 bytes ``` f=lambda l,p=[]:l>[]and(p==p[:2]<[sum(p)]>l)+f(l[1:],p)+f(l[1:],p+l[:1]) ``` [Try it online!](https://tio.run/##TYxBCoMwFET3nsJlUmfRxBg1VC8S/sJipUJMQ6uUnj6NLZTOh8/jwUx4rdeblzFOnRuW8zjkDqGzZFxvafAjC10XrJF0so9tYYFT73gxMWeFIYQ/LJw1gnh8Xmd3yYUJ99mvbGKzD9vKOOfRCkiUlGcJ0n0hGSjKbPqoUNPulIRuobWGOH6yWwlZolRQFSoNXaNu0LT020htjRoN2tTaNR2qNw "Python 2 – Try It Online") **73 bytes** ``` lambda l:sum(a+b>c for j,b in enumerate(l)for a in l[:j]for c in l[j+1:]) ``` [Try it online!](https://tio.run/##PYxNCoMwFIT3niLLpM6iiRp/oL2IzSJaRSVGsUrp6dOkQufBMPPBvPWzD4sVrr89nNFz89TEVK9jpjpu7i3pl41MaMhoSWePudv03lHDAtYBmrqaVGjt2aaYV4q59zCajvBq3Ua7056Odj12yhhzNYdAokjkg78zeIJURbV3ZMhVYKmALCGlBL/@FKiASJCkSDNkEjJHXqAo1f@HX0vkKFD6VcDqkn0B "Python 2 – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/) / MATLAB, 33 bytes ``` @(x)sum(nchoosek(x,3)*[1;1;-1]>0) ``` [Try it online!](https://tio.run/##VYzNCsIwEITvPklSxtD8bRJKxfcoOUhpEURzqErfPi7VHty5fDPDThmfl/dU514pVc9ilcvrLh7jtZRluokVVjaD7nR31PnUyjqLQcPAZnnYkLUjp3BfwwCPsDfOgBKICLrd7lcYGAvr4Dw8gQJCREx/ezxDCIhI/Jtl/QA) [Answer] # JavaScript (ES6), 63 bytes ``` f=([v,...a],p=[])=>v?(!p[2]&p[0]+p[1]>v)+f(a,p)+f(a,[...p,v]):0 ``` [Try it online!](https://tio.run/##jY5BDoIwFET3ngI3pg0jlNIWMEEP0vwFUTAaI42YXh8bNW4Q48zib17en3Pjm2F/O7n7@tof2nHsamY9kiRpCK62xOut37Gls5JWzgqKnc1o63ncsQbudWzAHTzxjRj3/XXoL21y6Y@sYzaDRE7RJJxHaRqJxQQPncWzxTc7FP2JBxQaxQyeT@1KwlQwxiATz9Cv7RIyR66gNLSBKVCUKCt629XM@LDIoECJKjyhj16L8QE "JavaScript (Node.js) – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 66 bytes ``` for a;z=$y&&for b (${@:2+y++})for c (${@:3+z++})((t+=c<a+b)) <<<$t ``` [Try it online!](https://tio.run/##qyrO@J@moanxPy2/SCHRuspWpVJNDcROUtBQqXawMtKu1Nau1QSJJENEjLWrQCIaGiXatsk2idpJmppcNjY2KiX/NbnSFAwhEMGCso0UjBVMECwFUwUzBXMFCwVLBUMDqGKQhClQyND4PwA "Zsh – Try It Online") Relatively straightforward, taking advantage of the sorted input, and incrementing in the `for` header (the increment happens once per *parent* loop). ``` for a;{ z=$y for b (${@:2+y++});{ # subarray starting at element after $a for c (${@:3+z++}) # subarray starting at element after $b ((t+=c<a+b)) } } ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 bytes ``` *1sm>sPded.cQ3 ``` [Try it online!](https://tio.run/##K6gsyfj/X8uwONeuOCAlNUUvOdD4//9oQyMdI2MdYxMdE1MdUzMdM3MdcwsdC8tYAA "Pyth – Try It Online") ``` .cQ3 # All combinations of length 3 from Q (input), sorted in ascending order m # map over that lambda d: sPd # sum(d[:-1]) > ed # > d[-1] s # sum all of those (uses the fact that True = 1) *1 # multiply by 1 so it doesn't output True if there's only one triangle ``` Alternative (also 14 bytes): ``` lfTm>sPded.cQ3 ``` [Answer] # [C (clang)](http://clang.llvm.org/), 83 bytes ``` x,y,q;f(*a,z){for(x=y=q=0;z;q+=z>1&a[x-=x?1:2-y--]+a[y]>a[z])y=y>1?y:--z;return q;} ``` [Try it online!](https://tio.run/##dZHRboIwFIbveYrGZAvM00ihFLQp3my3ewEkhigsJhsThglgfHbXtQzEsfYG/n5/z@n5d3j3nuRv10NeoS2JYnEm4IB74YsFspGhZEfLciuZdLLb00D1gdbpjy418MBXuqt1T/PUAbYExhgQWy1dSzNMMQ44LrgUqAceA@aDH0Cw1HdRDfo3xWUhBj4EsJRXKsrrrgv6zrve6bWGBgqemU8JtNY5@yzNWjSiEDZveTEXbUgek6jGol6TlYMbjON5EjVxmERtbDWiCcm6WWHc8jKtTmWOCn5Rw/tIDrlpobNhHEv5nyFz1o0SiRA97BEyUVof012V7uVkrU0@g8zcEnAti488P70OHtKjzl9Uz34KlvoY/g1kgN0epvfwVEqDcehe5nNn/Ce6m6q0dzMIJh80znOwekNhX55MzG00uaFQoN9nHE/Vlznb5AirjV5en5H@lqAEkFxdrDY3Ltdv "C (clang) – Try It Online") Saved 1 thanks to @ceilingcat [Answer] # Excel VBA, ~~171~~ ~~164~~ 152 bytes *-26 bytes thanks to TaylorScott* ``` Sub z t=[A:A] u=UBound(t) For i=1To u-2 For j=i+1To u-1 For k=j+1To u a=t(i,1):b=t(j,1):c=t(k,1) r=r-(a+b>c)*(b+c>a)*(c+a>b) Next k,j,i Debug.?r End Sub ``` Input is in the range `A:A` of the active sheet. Output is to the immediate window. Since this looks at every combination of every cell in a column that's 220 cells tall (which is nearly 260 combinations), this code is... not fast. You could make it *much* faster but at the expense of bytes. [Answer] # Java 8, ~~131~~ ~~130~~ 126 bytes ``` a->{int r=0,i=a.length,j,k,I,J,K;for(;i-->0;)for(I=a[j=i];j-->0;)for(J=a[k=j];k-->0;r+=I+J>K&I+K>J&J+K>I?1:0)K=a[k];return r;} ``` Straightforward approach. The triangle check is the same as [my answer for the *Is this a triangle?* challenge](https://codegolf.stackexchange.com/a/199374/52210). -4 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##RVHBjoIwEL37FY0HA2EgiAhqA5vNnoCsF4@EQxerW8BiSnFjCN/OFtTYJm@mrzPte5mC3IhZHMshr0jToG/CeDdDiHFJxYnkFO3H40SgXFOYZojoWHH9TEEjiWQ52iOOgoGYYTfWicAGFhCrovwsf6GAEiKIIcGnWmiYmWZoY33Mo4CkRcAyXLy5WHFlUGS4nDhhBJERh8kiMpIwXsQKo4/lztaTsS7DgspWcCRwP@BR0LX9qZSgp65bzY7oojxpBykYP6cZ0R9@xq9uRCBJG/lFGrrj9A9N9tKs65bgwKoHFdV@xWembsBVmUJYgz9xrgPeFjzPg6U9rZF1wFnBygV3DWsPPB/8DWy27zdUtwc@bGCruvpen3QhdLg3kl6supXWVWmWFdcKNSSrlayyPoUg98aS9cOP9pKvG/Mdmhvcyt/Uc0r98A8) **Explanation:** ``` a->{ // Method with integer-array parameter and integer return-type int r=0, // Result-integer, starting at 0 i=a.length,j,k, // Index-integers I,J,K; // Temp-integers for(;i-->0;) // Loop `i` in the range (length,0]: for(I=a[j=i]; // Set `I` to the `i`th value j-->0;) // Inner loop `j` in the range (i,0]: for(J=a[k=j]; // Set `J` to the `j`'th value k-->0 // Inner loop `k` in the range (j,0]: ; // After every iteration: r+= // Increase the result by: I+J>K&I+K>J&J+K>I? // If `I`, `J`, and `K` form a triangle: 1 // Increase the result by 1 : // Else: 0) // Keep the result the same by increasing with 0 K=a[k]; // Set `K` to the `k`'th value return r;} // After the nested loops, return the result ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` IΣ⭆θ⭆…θκ⭆…θμ›⁺νλι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0VyO4BMhP900s0CjUUUBwfPNzUkAi2ZrYRHOBou5FqYklqUUaATmlxRp5Ogo5QLFMTQiw/v8/OtrQSMfIWMfYRMfEVMfUTMfMXMfcQsfCMjb2v25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Assumes sorted input. Explanation: ``` θ Input array ⭆ Map over elements and join θ Input array … Truncated to length κ Outer index ⭆ Map over elements and join θ Input array … Truncated to length μ Inner index ⭆ Map over elements and join ν Innermost value ⁺ Plus λ Inner value › Is greater than ι Outer value Σ Take the digital sum I Cast to string for implicit print ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` à3 ËÌÑ<Dx ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=4DMgy8zRPER4&input=WzEyLDIzLDM0LDQ1LDU2LDY3LDc4LDg5XQ) ``` à3 ®o <Zx ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=4DMgrm8gPFp4&input=WzEyLDIzLDM0LDQ1LDU2LDY3LDc4LDg5XQ) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~37~~ 35 bytes ``` Tr@Boole[2#3<+##&@@@#~Subsets~{3}]& ``` [Try it online!](https://tio.run/##TYxBCoMwFET3XiPgplNak/gToS2hJyi0O3Fhi6JQK2i6knj1NOqm8xfzePCnK21TdaVtX6Wvz/4xmGvfv6ucM3HaMRYbY9h8/z7Hyo7zJFwR@9vQfmzO9pfasCI@mCmaEnAIhwXCbRAM5IKhkEJtVnJQBiJCclyzag4uICRkipRACkpDZ387YYCgoJGFPxc5/wM "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 41 bytes ``` ->l{l.combination(3).count{|a,b,c|c<a+b}} ``` [Try it online!](https://tio.run/##NUzLCsIwELz7FR4Vx2KTdNOA@iMhh6RQKPRFaQ@S9NvjWnAHdh4ws2zhk9tXvr/72BfNNIRu9Gs3jRd5ZbuNa0weAU1qnv4W9j1bW0JAOjAzDmYPxYo/KugjUwJkQEQoH8f9UgEhIRVUhYpAGrpGbRxO/xGuEzRqGK45Vwx@jmlJ87m1i9vzFw "Ruby – Try It Online") [Answer] # Perl 5 (`-p`), ~~55~~ 52 bytes using regex backtracking, -3 bytes thanks to @Cows quack using `^` instead of `(?!)` to fail and backtrack. ``` $d='(\d++)';$_=/$d.* $d.* $d(?{$n++if$1+$2>$3})^/+$n ``` or ``` $_=/(\d++).* (\d++).* (\d++)(?{$n++if$1+$2>$3})^/+$n ``` [TIO](https://tio.run/##NYvNCsIwEITvfYo5LLQ1aM3fpqVUX0T0UoVCmwb1IuKrG0PVGWaGXfjC@TraOD3It5H6Li8OvRBl3tKpq6jfrPCrYv8kL8RwISlI7Ui/ymMlyMcooaAzieRvL5t@MFkKLFy6jQI3YGbI7aJMKigNbWAsLIMdXI26@bOJYzjUaBLxnsN9mP0trsfwAQ) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` œc3+>ƭ/€S ``` [Try it online!](https://tio.run/##y0rNyan8///o5GRjbbtja/UfNa0J/v//v6GRjpGxjrGJjompjqmZjpm5jrmFjoUlAA "Jelly – Try It Online") A monadic link taking a sorted list of integers as its argument and returning the number of triangles. ## Explanation ``` œc3 | Combinations of length 3 ƭ/€ | Reduce each using each of the following in turn: + | - Add > | - Greater than S | Sum (counts the 1s) ``` Alternative 9s: ``` œc3Ṫ€<§ƊS œc3Ṫ<SƊ€S ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 123 bytes ``` for a;do for((i=2;i<=$#;i++)){ b=${!i};for((j=$[i+1];j<=$#;j++)){ c=${!j};T=$[T+(a<b+c&b<a+c&c<a+b)];};};shift;done;echo $T ``` [Try it online!](https://tio.run/##JY3LCsMgFER/xVIpBlcxz3L1L9yVLNQmqIsKTXfBb7@9TRkYBs6B8W6PiFt5MwfPwmgIkYyCpA2/QpKyaQ7mDT8uqcJJs@GPJNsF8qnkvxJ@Sq5giVopnPYy3Lx21IHaNwtUyh7T9qGj1wpriIVxi4itQtVh12M/4DDiOOE043z/Ag "Bash – Try It Online") A fun one. [Answer] # [J](http://jsoftware.com/), 40 bytes ``` 1#.](+/*/@(->])])@#~2(#~3=1&#.)@#:@i.@^# ``` [Try it online!](https://tio.run/##VY3LDoIwEEX3fMWNTQRUCn1NgQTTxMSVK/e4MRJ14x/w67VSDNpJF/dk7pmnX/F0QNcixQ4V2vALjsP5dPSC8T7blpvSZcW@z/vcsVFmbFSdWDMeUuse3F2Yz5Pkdr2/QrXDAAEJFYGYQZgI9AK@SCwl6IjUhEKEgf1XawlqQEQQ1fTmxiyWkOoTtIEhkIWtUTeIS6b6PRXcBIsaTVDBvwE "J – Try It Online") [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 6 bytes ``` SƆ$đ+< ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FiuCj7WpHJmobbOkOCm5GCq44GZJtKGOkY5xLBeQBkIYDWUBZXRMgCwgqWOqYw4WMzHSMbPUMTMz0zE0AAOQqJGOkbGOsYmOiamOqZmOmbmOuYWOhSXCDKBuMx1zHQsdS6CuWIjlAA) ``` SƆ$đ+< S Find a subset of the input Ɔ Split the subset into the last element and the rest $đ Check if the rest has exactly two elements + Add these two elements < Check if the last element is less than the sum ``` `-n` counts the number of solutions. [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 181 bytes ``` S =TABLE() R X =X + 1 S<X> =INPUT :S(R) I I =J =K =I + 1 LT(I,X) :F(O) J J =K =J + 1 LT(J,X) :F(I) K K =K + 1 LT(K,X - 1) :F(J) T =T + 1 GT(S<I> + S<J>,S<K>) :(K) O OUTPUT =T END ``` [Try it online!](https://tio.run/##Nc4/D4IwEIfh@e5T3NhGHPgrkpZEI5q2BAwtSWdnI4PfP7Uobpd73uH3fi2P5VmEAJakO537jnGcwJP0tKMUwQrfklTDfXbQWDZxVKBIapImvtcGesdU4jk0VzZy1PAz/Te9meJowKy2gUk87Sn9ouYILi5YjW6OWaHaeFuh28QK08aIGY4jjLOLU2KJ3XAJIc0wyzEvsCixrLA64KHG@vgB "SNOBOL4 (CSNOBOL4) – Try It Online") Brute force \$O(n^3)\$ algorithm. Takes input as a newline separated list and outputs the number of triangles, or an empty line for `0`. This is probably allowable since SNOBOL treats the empty string as `0` for numerical calculations. [Answer] # [Scala](http://www.scala-lang.org/), 280 bytes 280 bytes, it can be golfed much more. --- Golfed version. [Try it online!](https://tio.run/##dVLLbtswELzrK/ZkcGFasONHYiU00PZUoD0VySUIAoqiEhY0JYhU0dTQt7tLKk2awCHEh3Z2ZpcjeSWtPJp923QBfHzJVWOtVsE0Lt/3QZZW55@6Tj597utad1nWlD8Jhu/SODgcK12DYq746gK3xTfjwy0d73A8vrzfCVMzJ8QcY4ilBVFbryECO5t780eP4GtYiAXafC/bkXA/Mg6sbjpmrmY2N64ySnt8MtpWh1/SwqOwzOBlPAZh86prWmamC7ykJmcLHjDJPRbFPQ6YhyYK57WVIWg3ZPE2N@zNPWgVii25RXKmd@GgJHWX@pG85ArFTk7LnZpM5FTtysmkpE0OR4AotieXmOwefAHJxNsfoTPugXTh2pkAAg4Z0Ej9ah@@kLinaNJPCMB4@QWHMw5L5DBH/h6JD6Z5isNhdQKMYQ5rDueYdN8zV0TdbGluNkSep3GqOqWdkdaSxFaktqbszTmpXnC42Ebp1YddpfKUT@mUvY1liLCeY8rHLG30sYEx6wMH/bulX09XCFezV7vw2cPRxaYPbR@NvYkcfEak97oL7B8oXqQ4jNIj8l@JkTlkcQ7Hvw) ``` def c(n:Int,l:List[Int]):List[List[Int]]=if(n==0)List(List())else if(n>l.size)List()else if(n==1)l.map(List(_))else{(for(i<-l.indices)yield{val h=l(i);val t=l.drop(i+1);c(n-1,t).map(h::_)}).toList.flatten} def V(l:List[Int]):Int=c(3,l).count{case List(a,b,c)=>a+b>c&&a+c>b&&b+c>a} ``` Ungolfed version. [Try it online!](https://tio.run/##dVNNb9swDL37V/BUWJhqpM1HG2MusO40YDvt41IUgWzLmTZZMiR5WDfkt2cUnRhOkwVxHIqPj8@PtK@EFvu9ajvrAvgYZZXVWlZBWZO1fRClltk758TLY9800iUn2D4ojQUmOKuzRyfFT59tksSWP5ABPgll4G8CUMsGKtuWyojIm5ocPpjAQfuQw0flwxOGz@zwfzx4hoLKAVQDqYGigBkjTEo/jFFSai8PiIdImXn1Rx5wZwjkuGGEakU30GymPEM/gLSxDlIFb68JrEytKukZvCip6xEF8Eto@C5FjVIRlyp2kglC6SGT1c52yPcG24@QE0/gGm44VTDSRqx5DpsjfseyYKPirNEiBGnofJfEazS5N@Gb0Kr@4pQwWy19emYy3kZjo8iJCo@Jqag5zWgQMIVl1Gi0oRLoHHkpOJQcKgbFAwh82BJHUsHVFQUVBmUMykMgzp@gxZ1Jhdv6HGjrnj4Hp8w26v5q1KnwIH14j62jaup@nB0FaOYthznjuDT8dSZ@GV2XajgsLiTjMYclhztGvK8rF1i6WuO1WmHxjD6XuiPsFrnmSLZAtiWiV3fIes/hfh2pF/9VRe0Rj3BEr2MbLFjOhgmxhG60uXHsHOTvDl9EWbO4x6NdbBxcdNH2oesDDf7i8hzXT3gvXUiP8GIk5zA0GzKTpmwy3t1@/w8) ``` import scala.collection.mutable.ArrayBuffer import scala.util.control.Breaks._ object Main { def combination(n: Int, lst: List[Int]): List[List[Int]] = { if (n == 0) List(List()) else if (n > lst.size) List() else if (n == 1) lst.map(List(_)) else { (for (i <- lst.indices) yield { val head = lst(i) val tail = lst.drop(i + 1) combination(n - 1, tail).map(head :: _) }).toList.flatten } } def countValidTriangles(lst: List[Int]): Int = { val combinations = combination(3, lst) combinations.count { case List(a, b, c) => a + b > c && a + c > b && b + c > a } } def main(args: Array[String]): Unit = { val testCases = List( (List(1, 2, 3), 0), (List(1, 1, 1), 1), (List(1, 2, 3, 4), 1), (List(3, 4, 5, 7), 3), (List(1, 42, 69, 666, 1000000), 0), (List(12, 23, 34, 45, 56, 67, 78, 89), 34), (List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 50) ) for ((lst, expected) <- testCases) { val output = countValidTriangles(lst) assert(output == expected, (lst, output, expected)) } } } ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 49 bytes ``` f=([v,...x],a,b)=>v?f(x,a,b)+(b?a+b>v:f(x,v,a)):0 ``` [Try it online!](https://tio.run/##jY5BDoIwEEX3noJlG75QSmmBBDgI6aIgGA0BI6bh9ojEuEGMfzaTycubfzXWjPX9cnsc@@HUzHObkdLC87xJw6CiWW6Llkzr7pKqMG6V2/R1sTCUpmyuh34cusbrhjNpSRmAI9TOJpQ6vu@wwwZfZhcPDt/sEPpPfEERQe3g4dYuOGQCKSUCtkb/6s7BQ4QCIkIkIRVUjDjRb7vYKb80klCIkSxP9EcfsfkJ "JavaScript (Node.js) – Try It Online") [Answer] # [Uiua](https://www.uiua.org/), 27 bytes (SBCS) ``` /+≡(|1<+/∘⇌)≐▽▽=3≡/+.⋯⇡ⁿ⧻,2 ``` [Try it online!](https://www.uiua.org/pad?src=VHJpYW5nbGVzIOKGkCAvK-KJoSh8MSA8Ky_iiJjih4wp4omQ4pa94pa9PTPiiaEvKy7ii6_ih6Higb_ip7ssMgoKVHJpYW5nbGVzIFsxIDIgM10gICAgICAgICAgICAgICAgICAgIyBFeHBlY3RlZDogMApUcmlhbmdsZXMgWzEgMSAxXSAgICAgICAgICAgICAgICAgICAjIEV4cGVjdGVkOiAxClRyaWFuZ2xlcyBbMSAxIDEgMV0gICAgICAgICAgICAgICAgICMgRXhwZWN0ZWQ6IDQKVHJpYW5nbGVzIFsxIDIgMyA0XSAgICAgICAgICAgICAgICAgIyBFeHBlY3RlZDogMQpUcmlhbmdsZXMgWzMgNCA1IDddICAgICAgICAgICAgICAgICAjIEV4cGVjdGVkOiAzClRyaWFuZ2xlcyBbMSA0MiA2OSA2NjYgMTAwMDAwMF0gICAgICMgRXhwZWN0ZWQ6IDAKVHJpYW5nbGVzIFsxMiAyMyAzNCA0NSA1NiA2NyA3OCA4OV0gIyBFeHBlY3RlZDogMzQKVHJpYW5nbGVzIFsxIDIgMyA0IDUgNiA3IDggOSAxMF0gICAgIyBFeHBlY3RlZDogNTAK) **Explanation** ``` ≐▽▽=3≡/+.⋯⇡ⁿ⧻,2 # Get all length 3 combinations 2 # Put 2 on the stack , # Copy the array onto the stack ⧻ # Get the length of the array ⁿ # Raise 2 to the power of the length ⇡ # Create an array of all natural numbers less than the result ⋯ # Convert to binary . # Copy the result ≡/+ # For each binary number, add up the bits =3 # Check which add up to three ▽ # Keep rows of the binary array where the number of 1s is 3 ≐▽ # For each of the remaining binary numbers, # keep items in the original array /+≡(|1<+/∘⇌) # Calculate number of triangles ≡(|1 ) # For each row in the resulting array: ⇌ # Reverse the array /∘ # Put the items onto the stack + # Add the first two numbers < # Check if the third number is less than the result /+ # Add up all the triangles ``` As part of this, I made the combinations part generic. This might be useful for future golfing. If someone can find a shorter way of doing this part, it may help many people. ``` ≐▽▽=⊙(≡/+.⋯⇡ⁿ⧻,2) ``` [Try it online!](https://www.uiua.org/pad?src=Q29tYmluYXRpb25zIOKGkCDiiZDilr3ilr094oqZKOKJoS8rLuKLr-KHoeKBv-KnuywyKQoKQ29tYmluYXRpb25zIDMgM180XzVfNwpDb21iaW5hdGlvbnMgNCA5XzhfNF83XzFfNgo=) ]
[Question] [ ## Challenge Given a three digit octal permissions number, output the permissions that it grants. ## chmod On UNIX OSes file permissions are changed using the `chmod` command. There are few different ways of using chmod, but the one we will focus on today is using octal permissions. The three digits in the permissions number represent a different person: * The first digit represents the permissions for the **user** * The second digit represents the permissions for the **group** * The last digit represents the permissions for **others** Next, each digit represents a permission as shown below in: ``` Key: number | permission 7 | Read Write and Execute 6 | Read and Write 5 | Read and Execute 4 | Read only 3 | Write and Execute 2 | Write only 1 | Execute only 0 | None ``` ## Input The input will be the three digit number as a string, e.g.: ``` 133 ``` or ``` 007 ``` This will be passed either via STDIN or via function arguments. ## Output Your output should be the different permissions for each of the user, the group and the others. You must display this information like so: ``` User: ddd Group: ddd Others: ddd ``` Where there are three spaces after `User`, two spaces after `Group` and one space after `Others`. You replace `ddd` with the permissions information. Your output may be to STDOUT or as a returned string. ## Examples **Input:** 666 **Output:** ``` User: Read and Write Group: Read and Write Others: Read and Write ``` --- **Input:** 042 **Output:** ``` User: None Group: Read only Others: Write only ``` --- **Input:** 644 **Output:** ``` User: Read and Write Group: Read only Others: Read only ``` ## Winning The shortest code in bytes wins. [Answer] ## Javascript (ES6), ~~165~~ 161 bytes ``` n=>[0,1,2].map(i=>(s='User: 3Group: 68Others:58None576Read48Write476Execute475and4576only'.split(/(\d+)/))[i*2]+s[n[i]*2+1].replace(/./g,c=>' '+s[c*2])).join` ` ``` *Edit: +1 byte to fulfill the "no tab" rule* ### Examples ``` let f = n=>[0,1,2].map(i=>(s='User: 3Group: 68Others:58None576Read48Write476Execute475and4576only'.split(/(\d+)/))[i*2]+s[n[i]*2+1].replace(/./g,c=>' '+s[c*2])).join` ` console.log(f("666")); console.log(f("042")); console.log(f("644")); console.log(f("137")); ``` [Answer] ## GNU sed, ~~187 163~~ 158 (157+1) bytes Run with *-r* (ERE regexp). File contains no trailing newline. ``` s/(.)(.)/User: \1\nGroup: \2\nOthers: /g s/[4-7]/Read &/g s/[2367]/Write &/g s/[1357]/Execute &/g s/(\w) (\w+) [1-7]/\1 and \2/g s/[1-7]/only/g s/0/None/g ``` [Answer] # C# 214 Bytes ``` string h(string y){string e="Execute ",r="Read ",w="Write ",O="Only",a="and ";var z=new[]{"None",e+O,w+O,w+a+e,r+O,r+a+e,r+a+w,r+w+a+e};return$"User: {z[y[0]-'0']}\nGroup: {z[y[1]-'0']}\nOthers: {z[y[2]-'0']}";} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~100 91~~ 85 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ~~Almost certainly golfable - 91 bytes, what?!~~ **8 months and 6 wisdom bytes!** - 1. more string compression; - 2. remove the post-ordinal decrement by 48 since indexing is modular; - 3. use better tacit chaining). -9 bytes with the kind help of @Lynn running string compressions for me ``` ,“£ɱ~» Ñ ṖK,“ and”,Ṫ LĿK 7RBUT€Uị“ØJƓ“¥Ị£“¤/¡»Ç€“¡*g»ṭ “ṖŒhJ"ỵd¡»ḲðJ4_⁶ẋ⁸,"j€”:ż⁹Oị¢¤Y ``` Test it at **[TryItOnline](https://tio.run/##y0rNyan8/1/nUcOcQ4tPbqw7tJvr8ESuhzuneYOEFBLzUh41zNV5uHMVl8@R/d5c5kFOoSGPmtaEPtzdDZQ/PMPr2GSQ1qUPd3cdWgxiLdE/tPDQ7sPtQEUg7kKt9EO7H@5cywXkAE09OinDS@nh7q0pIEUPd2w6vMHr4c5Zjxq3PdzV/ahxh45SFljfXKujex417vQH2nJo0aElkf///1cyMDFSAgA)** How? ``` ,“£ɱ~» - Link 1: pair with the string "Only" Ñ - Link 2: call next link ṖK,“ and”,Ṫ - Link 3: insert " and" between the last two elements of x Ṗ - x[:-1] K - join with spaces “ and” - the string " and" Ṫ - x[-1] , , - pair LĿK - Link 4: call appropriate link and add missing spaces L - length Ŀ - call link at that index K - join the result with spaces 7RBUT€Uị“ØJƓ“¥Ị£“¤/¡»Ç€“¡*g»ṭ - Link 5: construct all 8 cases 7R - range of 7: [1,2,3,4,5,6,7] B - binary (vectorises): [[1],[1,0],[1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]] U - reverse (vectorises): [[1],[0,1],[1,1],[0,0,1],[1,0,1],[0,1,1],[1,1,1]] T€ - indexes of truthy values for each: [[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] U - reverse (vectorises): [[1],[2],[2,1],[3],[3, 1],[3,2],[3,2,1]] “ØJƓ“¥Ị£“¤/¡» - list of strings: ["Execute","Write","Read"] ị - item at index (vectorises): [["Execute"],["Write"],["Write","Execute"],["Read"],["Read","Execute",["Read","Write"],["Read","Write","Execute"]] Ç€ - call the previous link for each “¡*g» - the string "None" ṭ - tack (Jelly is 1-based so the 8th item will be indexed as 0) “ṖŒhJ"ỵd¡»ḲðJṚ⁶ẋ⁸,"j€”:ż⁹Oị¢¤Y - Main Link: parse input and make the result. e.g.: "042" “ṖŒhJ"ỵd¡» - dictionary compression of "User Group Others" Ḳ - split at spaces -> ["User","Group","Others"] ð - dyadic chain separation, call that g (input as right) J - range of length of g -> [1,2,3] Ṛ - reverse -> [3,2,1] ⁶ - literal space ẋ - repeat -> [" "," "," "] ⁸ - chain's left argument, g " - zip with: , - pair -> [["User"," "],["Group"," "],["Others"," "]] ”: - literal ':' j€ - join for €ach -> ["User: ","Group: ","Others: "] ¤ - nilad followed by link(s) as a nilad: ⁹ - chain's right argument, the input string -> "042" O - cast to ordinal (vectorises) -> [48, 52, 50] ¢ - call last link (5) as a nilad -> ["Execute Only","Write Only","Write and Execute","Read Only","Read and Execute","Read and Write","Read Write and Execute","None"] ị - index into (1-based & modular) -> ["None","Read Only","Write Only"] ż - zip together -> [["User: ","None"],["Group: ","Read Only"],["Others: ","Write Only"]] Y - join with line feeds -> ["User: ","None",'\n',"Group: ","Read Only",'\n',"Others: ","Write Only"] - implicit print: >>>User: None >>>Group: Read Only >>>Others: Write Only ``` [Answer] # Octave, 185 bytes ``` @(n)fprintf('User: %s\nGroup: %s\nOthers: %s',{'Read Write and Execute','Read and Write','Read and Execute','Read only','Write and Execute','Write only','Execute only','None'}{56-n}) ``` Create anonymous function that takes the input as a string: '042'. Convert it to an array: `(56-'042)' = [0 4 2]`. Use this as multiple cell indices to index the cell array with `Read Write and Execute','Read and Write', ...`. Uses `fprintf` to output the three strings, with the appropriate categories: `User:` , `Group:` and `Others:` . I tried finding a way to store `Execute`, `Write`, `Read` as separate words and concatenate as needed, but this turned out longer than the naive approach. **Examples:** ``` 1> f('000') User: None Group: None Others: None 2> f('042') User: None Group: Read only Others: Write only ``` [**Try it online.**](https://ideone.com/VpSVW6) [Answer] ## PowerShell v2+, ~~189~~ 168 bytes ``` [char[]]$args[0]|%{('User','Group','Others')[$i++]+":`t"+('None','Read','Write','Execute','only','and')[(0,(3,4),(2,4),(2,5,3),(1,4),(1,5,3),(1,5,2),(1,2,5,3))[$_-48]]} ``` Loops through the input `$args[0]` as a `char`-array. Each iteration, we index into an array with `$i++` (defaults to `0`) to select `User`, `Group`, or `Others`, concatenate that with a colon and a tab, and concatenate that with another array index. Here's the magic. We implicitly cast the `char` to an `int` and subtract `48` (i.e., turning ASCII `48` (`"0"`) into `0`), choosing the appropriate wording as an array of `int`s. That array is subsequently used as the index into the `'None','Read','Write','Execute','only','and'` array. Since the default [`$ofs`](https://technet.microsoft.com/en-us/library/hh847796.aspx) (Output Field Separator) is a space, this correctly inserts spaces between the array elements when stringified (which happens when it concatenates to the left). These three strings are left on the pipeline, and output via implicit `Write-Output` happens at program completion. ### Example ``` PS C:\Tools\Scripts\golfing> .\decode-the-chmod.ps1 '123' User: Execute only Group: Write only Others: Write and Execute ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~89~~ 87 bytes ``` ”‚Ý:‚Ù:ˆ†:”ð¡v”Šª0ÍÃ20‡í20‡í1ÍÃ0‚Ø20‚Ø1ÍÃ0‚Ø1‡í0‚؇í1ÍÔ2ð'€É«:1ð'€ƒ«:0ð«¡¹Nèèð3N-×ìyì, ``` ~~Summons the **Cthulhu** encoding.~~ Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=4oCd4oCaw5064oCaw5k6y4bigKA64oCdw7DCoXbigJ3FoMKqMMONw4MyMOKAocOtMjDigKHDrTHDjcODMOKAmsOYMjDigJrDmDHDjcODMOKAmsOYMeKAocOtMOKAmsOY4oChw60xw43Dg-KAnTLDsCfigqzDicKrOjHDsCfigqzGksKrOjDDsMKrwqHCuU7DqMOow7AzTi3Dl8OsecOsLA&input=MDQy) [Answer] ## [Straw](http://github.com/tuxcrafting/straw), 193 bytes ``` ((01234567)((None)(Execute only)(Write only)(Write and Execute)(Read only)(Read and Execute)(Read and Write)(Read Write and Execute)))::~<:{-¢(User: ),+> >}:{-¢(Group: ),+> >}-¢(Others: ),+> ``` [Try it online](http://straw.tryitonline.net/#code=KCgwMTIzNDU2NykoKE5vbmUpKEV4ZWN1dGUgb25seSkoV3JpdGUgb25seSkoV3JpdGUgYW5kIEV4ZWN1dGUpKFJlYWQgb25seSkoUmVhZCBhbmQgRXhlY3V0ZSkoUmVhZCBhbmQgV3JpdGUpKFJlYWQgV3JpdGUgYW5kIEV4ZWN1dGUpKSk6On48OnstwqIoVXNlcjogICApLCs-Cj59OnstwqIoR3JvdXA6ICApLCs-Cj59LcKiKE90aGVyczogKSwrPg&input=) Push 3 times a conversion table on the first stack, switch to the second stack, convert each number using the conversation table and print. [Answer] # Haskell, 186 Bytes ``` s=zip(words"7654 6 7632 753 7531 0 421")(words"Read and Write and Execute None only") m c=mapM_(\(x,y)->putStrLn(x++unwords[b|(a,b)<-s,elem y a]))$zip["User: ","Group: ","Others: "]c ``` Example: ``` Prelude> :r [1 of 1] Compiling Main ( decCh.hs, interpreted ) Ok, modules loaded: Main. *Main> m "654" User: Read and Write Group: Read and Execute Others: Read only ``` Only Prelude used. Am I doing this right? Ungolfed: ``` s = zip (words "7654 6 7632 753 7531 0 421") (words "Read and Write and Execute None only") ps y = unwords [b|(a,b)<-s,elem y a] -- build permissions string pp (x,y) = putStrLn $ x ++ ps y -- print user + permission m c = let up = zip ["User: ","Group: ","Others: "] c -- pair user and permission in mapM_ pp up --print each ``` [Answer] # Python 2, ~~190~~ 185 bytes ``` def f(i): r,w,a,x,o,g="Read ","Write ","and ","Execute ","only",["User: ","Group: ","Others:"];p=["None",x+o,w+o,w+a+x,r+o,r+a+x,r+a+w,r+w+a+x] for z in 0,1,2:print g[z],p[int(i[z])] ``` Leaves a trailing space if Execute or Write are at the end of the line but I didn't see that this wasn't allowed. **EDIT** Saved 5 bytes by changing range(3) to 0,1,2 and checking byte count on my Linux laptop instead of my Windows one (\n = \r\n or the other way round. I can never remember which). [Answer] # Python 2, ~~240~~ ~~239~~ ~~238~~ ~~237~~ 228 bytes I thought I’d finally give this cold golf thing a go. ~~Hopefully trailing whitespace is allowed.~~ (fixed, and in the process saved a byte) ``` i=0 def a(b): for d in 4,2,1: if b&d:yield('Execute','Write','Read')[d/2] for k in raw_input(): b,q=list(a(int(k))),' and';e=len(b) if e:b[~e/2]+=(' only',q,q)[e-1] print'UGOsrteohrue:pr :s :'[i::3],' '.join(b)or None;i+=1 ``` [Answer] **PHP, ~~169~~ 159 bytes** ``` foreach([User,Group,Others]as$i=>$u){echo" $u: ";for($n=[5,33,34,66,35,67,131,531][$i]];$n;$n>>=3)echo["and",Execute,Write,Read,only,None][$n&7]," ";} ``` takes string as command line argument: `php -r '<code>' <argument>`, prints a leading newline instead of a trailing one Thanks to Jörg for pointing out my bugs - and for the `\t`. # PHP, 169 bytes with the new restriction: (tab character forbidden) ``` foreach(['User: ','Group: ','Others:']as$i=>$u){echo" $u";for($n=[5,33,34,66,35,67,131,531][$argv[1][$i]];$n;$n>>=3)echo' ',['and',Read,Write,Execute,only,None][$n&7];} ``` This is 1 byte shorter than with `str_pad`, because of the additional blank it would require. **breakdown** ``` foreach([User,Group,Others]as$i=>$u) { echo"\n$u:\t"; // print newline, who, blanks for($n=[5,33,34,66,35,67,131,531] // octal values for words indexes [$argv[1][$i]] // (last word=highest digit) ;$n;$n>>=3) // while value has bits left echo['and',Execute,Write,Read,only,None][$n&7]," "; // print that word } ``` To create the array for `$n`, use this: ``` $b=[[5],[1,4],[2,4],[2,0,1],[3,4],[3,0,1],[3,0,2],[3,2,0,1]]; foreach($b as$i=>$a){for($v=$j=0;$a;$j+=3)$v+=array_shift($a)<<$j;echo"$v,";} ``` [Answer] # bash - ~~221~~ 213 bytes `GNU bash, version 4.3.46` ``` l=("User: " "Group: " "Others: ") o=\ only;a=" and ";x=Execute;w=Write;r=Read b=(None "$x$o" "$w$o" "$w$a$x" "$r$o" "$r$a$x" "$r$a$w" "$r $w$a$x") for c in `echo $1|grep -o .`;{ echo "${l[$((z++))]}${b[$c]}";} ``` Unclear if this can be condensed any further, at least not without fundamentally changing the approach here (splitting up input and using it as an index to the array `${b}` that holds the corresponding strings). [Answer] # Java 7, ~~300~~ 284 bytes ``` String c(String s){char[]a=s.toCharArray();return"User: "+f(a[0])+"Group: "+f(a[1])+"Others: "+f(a[2]);}String f(int i){return new String[]{"None","Execute only","Write only","Write and Execute","Read only","Read and Execute","Read and Write","Read Write and Execute"}[i%48]+"\n";} ``` Direct approach for now. Will try to come up with a more generic approach to reuse the words. **Ungolfed & test cases:** [Try it here.](https://ideone.com/TKs7ZT) ``` class M{ static String c(String s){ char[] a = s.toCharArray(); return "User: " + f(a[0]) + "Group: " + f(a[1]) + "Others: " + f(a[2]); } static String f(int i){ return new String[]{ "None", "Execute only", "Write only", "Write and Execute", "Read only", "Read and Execute", "Read and Write", "Read Write and Execute" } [i % 48] + "\n"; } public static void main(String[] a){ System.out.println(c("666")); System.out.println(c("042")); System.out.println(c("644")); } } ``` **Output:** ``` User: Read and Write Group: Read and Write Others: Read and Write User: None Group: Read only Others: Write only User: Read and Write Group: Read only Others: Read only ``` [Answer] # Groovy, ~~217~~ ~~207~~ 205 bytes ``` def c(m){def i=0,e='Execute',w='Write',r='Read',o=' only',a=' and ';m.each{println(['User: ','Group: ','Others: '][i++]+['None',"$e$o","$w$o","$w$a$e","$r$o","$r$a$e","$r$a$w","$r $w$a$e"][it as int])}} ``` ungolfed: ``` def c(m) { def i=0,e='Execute',w='Write',r='Read',o=' only',a=' and '; m.each{ println(['User: ','Group: ','Others: '][i++]+['None',"$e$o","$w$o","$w$a$e","$r$o","$r$a$e","$r$a$w","$r $w$a$e"][it as int]) } } ``` [Answer] # Mathematica, 211 bytes ``` {r,w,e,o,a}={"Read ","Write ","Execute ","only ","and "};""<>Transpose@{{"User: ","Group: ","Others: "},"None"[{e,o},{w,o},{w,a,e},{r,o},{r,a,e},{r,a,w},{r,w,a,e}][[#]]&/@IntegerDigits[#,10,3],"\n"&~Array~3}& ``` A straightforward implementation (probably easily beatable): doesn't compute anything, just hard-codes each possible output. Input is an integer; outputs each line with a trailing space, and a trailing newline overall. `IntegerDigits[#,10,3]` gives the three digits of the input (even if there are leading zeros). Each digit indicates an argument of the "function" ``` "None"[{e,o},{w,o},{w,a,e},{r,o},{r,a,e},{r,a,w},{r,w,a,e}] ``` with 0 indicating the function name itself. `""<>` concatenates all the strings in a list (of lists). `"\n"&~Array~3` produces the three newlines. [Answer] # Java 7, 278 Golfed: ``` String f(String i){String o="";for(int n=0;n<i.length();)o+=(n<1?"User: ":n<2?"Group: ":"Others: ")+new String[]{"None","Execute only","Write only","Write and Execute","Read only","Read and Execute","Read and Write","Read Write and Execute"}[i.charAt(n++)-48]+"\n";return o;} ``` Ungolfed: ``` String f(String i) { String o = ""; for (int n = 0; n < i.length();) o += (n < 1 ? "User: " : n < 2 ? "Group: " : "Others: ") + new String[] { "None", "Execute only", "Write only", "Write and Execute", "Read only", "Read and Execute", "Read and Write", "Read Write and Execute" }[i.charAt(n++) - 48] + "\n"; return o; } ``` Output: ``` User: Read and Write Group: Read and Write Others: Read and Write User: None Group: Read only Others: Write only User: Read and Write Group: Read only Others: Read only ``` [Answer] # Python 3.5, 3.6 - 235 232 228 216 bytes (should work on all Python 3.x) So the input is on STDIN here (saves an import ☺). ``` a=input() r=range for i in r(3): p=int(a[i]);x=[["Read","Write","Execute"][j]for j in r(3)if 4>>j&p] if x[1:]:x[-1:-1]="and", if len(x)==1:x+="only", print(["User: ","Group: ","Others:"][i]," ".join(x)or"None") ``` Making use of tuples, omitting spaces where possible and operator precedence where you would normally put parentheses to make your intentions clear. Sample usage: ``` $ echo -n '666' | python3 golf2.py User: Read and Write Group: Read and Write Others: Read and Write $ echo -n '644' | python3 golf2.py User: Read and Write Group: Read only Others: Read only $ echo '042' | python3 golf2.py User: None Group: Read only Others: Write only $ echo '123' | python3 golf2.py User: Execute only Group: Write only Others: Write and Execute $ echo -n '777' | python3 golf2.py User: Read Write and Execute Group: Read Write and Execute Others: Read Write and Execute ``` Un-golfed: ``` input_perms = list(map(int, input())) entities = ["User", "Group", "Others"] perm_names = ["Read", "Write", "Execute"] for i in range(3): bits = input_perms[i] perms = [ perm_names[j] for j in range(3) if (1 << (2-j)) & bits ] if len(perms) > 1: perms.insert(-1, "and") if len(perms) == 1: perms.append("only") print("{:7} {}".format( entities[i]+":", " ".join(perms) or "None" )) ``` [Answer] ## Batch, 280 bytes ``` @echo off set/pc= call:l "User: " %c:~0,1% call:l "Group: " %c:~1,1% call:l "Others: " %c:~2,1% exit/b :l for %%s in (None.0 Execute.1 Write.2 "Write and Execute.3" Read.4 "Read and Execute.5" "Read and Write.6" "Read Write and Execute.7") do if %%~xs==.%2 echo %~1%%~ns ``` Hardcoding the strings was 47 bytes shorter than trying to piece them together. Would have been 267 bytes if tabs were legal. [Answer] # C# ~~307~~ ~~241~~ 210 bytes `string X(string s){var z="User: ,Group: ,Others:,5,34,14,123,04,023,021,0123,Read,Write,and,Execute,only,None".Split(',');return string.Join("\n",s.Zip(z,(a,b)=>b+z[a-45].Aggregate("",(x,y)=>x+" "+z[y-37])));}` Formatted ``` string X(string s) { var z = "User: ,Group: ,Others:,5,34,14,123,04,023,021,0123,Read,Write,and,Execute,only,None".Split(','); return string.Join("\n", s.Zip(z, (a, b) => b + z[a - 45].Aggregate("", (x, y) => x + " " + z[y - 37]))); } ``` [Answer] # C#, 322 337 348 bytes That's for sure not the shortest version, but I tried solving this problem using bitwise operators since the `chmod` values are actually bit flags. Also C# is probably not the best golfing language :D ``` string P(string s){Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");return a.Count>1?string.Join(" ",a.Take(a.Count-1))+" and "+a.Last():a.Count>0?a.First()+" only":"none";};return string.Join("\n",(new[]{"User: ","Group: ","Others: "}).Select((c,i)=>c+X(s[i]-'0')));} ``` ungolfed: (with comments) ``` string P(string s) { // Function that determines the permissions represented by a single digit (e.g. 4 => "Read only") Func<int, string> X = p => { var a = new List<string>(); // temporary storage for set permissions if ((p & 4) > 0) a.Add("Read"); // Read bit set if ((p & 2) > 0) a.Add("Write"); // Write bit set if ((p & 1) > 0) a.Add("Execute"); // Execute bit set // actually just Output formatting ... Takes a lot of bytes *grr* return a.Count > 1 ? string.Join(" ", a.Take(a.Count - 1)) + " and " + a.Last() : a.Count > 0 ? a.First() + " only" : "none"; }; // Actual result: return string.Join("\n", (new[] { "User: ", "Group: ", "Others: " }) .Select((c, i) => c + X(s[i] - '0'))); // Map "User, .." to its permissions by using above function } ``` This is my first time code golfing, so please tell me, if I did anyting wrong :) # EDIT 1: Saved some bytes by replacing `s[i]-'0'` by `s[i]&7` (at the very end) and saving list count into variable: ``` string P(string s){Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");var c=a.Count;return c>1?string.Join(" ",a.Take(c-1))+" and "+a.Last():c>0?a[0]+" only":"none";};return string.Join("\n",(new[]{"User: ","Group: ","Others: "}).Select((c,i)=>c+X(s[i]&7)));} ``` # EDIT 2: Changed to lambda expression: ``` s=>{Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");var c=a.Count;return c>1?string.Join(" ",a.Take(c-1))+" and "+a.Last():c>0?a[0]+" only":"none";};return string.Join("\n",(new[]{"User: ","Group: ","Others: "}).Select((c,i)=>c+X(s[i]&7)));} ``` [Answer] # Javascript, 213 209 208 188 186 bytes ``` function(d){a=" and ";r="Read";w="Write";e="Execute";v=";";o=" only";c=["None",e+o,w+o,w+a+e,r+o,r+a+e,r+a+w,r+" "+w+a+e];return"User: "+c[d[0]]+"\nGroup: "+c[d[1]]+"\nOthers: "+c[d[2]]} ``` Saved 20 bytes thanks to Dada! [Answer] # Visual Basic, 606 Bytes ``` imports System.Collections module h sub main() Dim i As String=console.readline() Dim s=new Stack(new String(){"Others: ","Group: ","User: "}) for each j as Char in i dim t=new Stack() if((asc(j) MOD 2)=1)then t.push("Execute") if(asc(j)=50 or asc(j)=51 or asc(j)=54 or asc(j)=55)then t.push("Write") if(asc(J)>51)then t.push("Read") if t.count=3 then w(s.pop+t.pop+" "+t.pop+" and "+t.pop) else if t.count=2 then w(s.pop+t.pop+" and "+t.pop) else if t.count=0 then w(s.pop+"None") else w(s.pop+t.pop+" only") end if end if end if next end sub sub w(s As String) console.writeline(s) end sub end module ``` [Answer] # Crystal, 200 194 Bytes ``` def m(y)y=y.chars.map &.to_i a=" and " o=" only" r="Read" w="Write" x="Execute" c=["None",x+o,w+o,w+a+x,r+o,r+a+x,r+a+w,r+" "+w+a+x] "User: "+c[y[0]]+" Group: "+c[y[1]]+" Others: "+c[y[2]]end ``` returns the resulting string for a given octal-sequence as a string. e.g.: `m("670")` results to: `User: Read and Write\nGroup: Read Write and Execute\nOthers: None`. [Try it online](https://tio.run/##NcnBC4IwFMfx@/6K8Q6hTMQ6FAg7RreCIDrIiDEXCrrJ20T3168ldXg/vnyewuC8HGJs9ZuOWcgDD6XqJLpylBPdld6@eiI5UGlaCsSmsmYIQJDDXcsWyMLhib3XQFYO51Wr@duKN3C1RkOxMlss20m2FpgKfyXZkhYosO0nCDycxprSJKoJTSUEA3JBO0/13/ab3Xyn0dU/OwihTRsn7I3PxgyOpwryPH4A). [Answer] # C#, 371 bytes ``` public String[] a = {"none","Execute only","Write only","Write and Execute","Read only","Read and Execute","Read and Write","Read Write and Execute"}; public String pA(int i){return a[i];} public int d(int n,int i){ n=n/Math.pow(10,i); return n%=10; } public void main(int i){ Console.Write("User:\t{0}\nGroup:\t{1},Others:\t{2}",pA(d(i,0)),pA(d(i,1)),pA(d(i,2)); } ``` [Answer] ## Python 3.5 - ~~370~~ ~~294~~ 243 bytes Golfed: ``` import sys a=lambda o: [print(('User: ','Group: ','Others:')[n],('None','Execute only','Write only','Write and Execute','Read only','Read and Execute','Read and Write','Read Write and Execute')[int(o[n])]) for n in range(0,3)] a(sys.argv[1]) ``` Size check: ``` $ du -b OctalToHuman.py 243 OctalToHuman.py ``` Un-golfed: ``` #!/usr/bin/env python3 from sys import argv as ARGS types = ('User: ', 'Group: ', 'Others:') perms = ('None','Execute only','Write only','Write and Execute','Read only','Read and Execute','Read and Write','Read Write and Execute') def convert(octal_string): for n in range(0,3): print(types[n], perms[int(octal_string[n])]) if __name__ == '__main__': convert(ARGS[1]) ``` Sample output: ``` $ python ./OctalToHuman.py 666 User: Read and Write Group: Read and Write Others: Read and Write ``` ``` $ python ./OctalToHuman.py 042 User: None Group: Read only Others: Write only ``` ``` $ python ./OctalToHuman.py 644 User: Read and Write Group: Read only Others: Read only ``` [Answer] # F#, ~~204~~ 203 Bytes *my first golf, so do please forgive any mistakes ;)* The golfed version (based 1:1 on [pinkfloydx33's answer](https://codegolf.stackexchange.com/a/93119/47341)): ``` fun(y:string)->let e,r,w,o,a="Execute ","Read ","Write ","only","and ";let z=["None";e+o;w+o;w+a+e;r+o;r+a+e;r+a+w;r+w+a+e;];let(!-)a=z.[int y.[a]-48];sprintf"User: %s\nGroup: %s\nOthers: %s"!-0!-1!-2 ``` The ungolfed version: ``` fun (y : string) -> let e, r, w, o, a = "Execute ", "Read ", "Write ", "only", "and " let z = [ "None"; e + o; w + o; w + a + e; r + o; r + a + e; r + a + w; r + w + a + e; ] let (!-) a = z.[int(y.[a]) - 48] sprintf "User: %s\nGroup: %s\nOthers: %s" !-0 !-1 !-2 ``` Example usage: ``` let k = ...... // function definition goes here printf"%s"<|k"755" printf"%s"<|k"042" // etc ... ``` --- **This is solely to check, whether I could 'improve' [pinkfloydx33's answer](https://codegolf.stackexchange.com/a/93119/47341) - I do not take any credit for the algorithm** [Answer] # PHP ,199 Bytes ``` foreach([User,Group,Others]as$i=>$u){$a=[];foreach([Read,Write,Execute]as$k=>$s)if($argv[1][$i]&4>>$k)$a[]=$s;$a[]=($x=array_pop($a))?$a?"and $x":"$x only":None;echo str_pad("\n$u:",9).join(" ",$a);} ``` PHP ,189 Bytes with \t ``` foreach([User,Group,Others]as$i=>$u){$a=[];foreach([Read,Write,Execute]as$k=>$s)if($argv[1][$i]&4>>$k)$a[]=$s;$a[]=($x=array_pop($a))?$a?"and $x":"$x only":None;echo"\n$u:\t".join(" ",$a);} ``` [Answer] # Python 3, 191 bytes ``` def d(n):a,b,c,d,e=' and ',' only',"Execute","Write","Read";l=["None",c+b,d+b,d+a+c,e+b,e+a+c,e+a+d,e+" "+d+a+c];y,u,i=map(int,n);return"User: %s\nGroup: %s\nOthers: %s\n"%(l[y],l[u],l[i]) ``` ungolfed ``` def d(n): a,b,c,d,e=' and ',' only',"Execute","Write","Read" l=["None",c+b,d+b,d+a+c,e+b,e+a+c,e+a+d,e+" "+d+a+c] y,u,i=map(int,n) return"User: %s\nGroup: %s\nOthers: %s\n"%(l[y],l[u],l[i]) ``` [Answer] ## Javascript (ES6), 159 bytes ``` a=>`User: ${(b=[' None',(c=' Execute')+(d=' only'),(e=' Write')+d,f=e+(g=' and')+c,(h=' Read')+d,h+g+c,h+g+e,h+f])[a[0]]}\nGroup: ${b[a[1]]}\nOthers:`+b[a[2]] ``` --- Example: ``` (a=>`User: ${(b=[' None',(c=' Execute')+(d=' only'),(e=' Write')+d,f=e+(g=' and')+c,(h=' Read')+d,h+g+c,h+g+e,h+f])[a[0]]}\nGroup: ${b[a[1]]}\nOthers:`+b[a[2]])("042") ``` ]
[Question] [ Following the fine tradition of questions such as [Find the largest prime whose length, sum and product is prime](https://codegolf.stackexchange.com/questions/35441/find-the-largest-prime-whose-length-sum-and-product-is-prime?rq=1) , this is a variant on a largest prime challenge. **Input** Your code should not take any input. **Definition** We say a prime `p` is `good` if `p-1` has exactly `2` distinct prime factors. **Output** Your code should output the absolute difference between consecutive good primes `q` and `p` so that `|q-p|` is as large as possible and `q` is the smallest good prime larger than `p`. You may output any number of good pairs and your last output will be taken as the score. **Example** The sequence of the first 55 good primes is <https://oeis.org/A067466> . **Score** Your score is simply `|q-p|` for the pair of good primes you output. **Languages and libraries** You can use any language or library you like (that wasn't designed for this challenge) *except* for any library functions for primality testing or factoring integers. However, for the purposes of scoring I will run your code on my machine so please provide clear instructions for how to run it on Ubuntu. **My Machine** The timings will be run on my machine. This is a standard Ubuntu install on an 8GB AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code. # Details * I will kill your code after 2 minutes unless it starts to run out of memory before that. It should therefore make sure to output something before the cut off. * You may not use any external source of primes. * You may use probabilistic prime testing methods although I am told by Mego that with good tables, Miller-Rabin can test up to 341,550,071,728,321 (or even higher) deterministically. See also <http://miller-rabin.appspot.com/> . **Best entries that check all integers from 1** * **756** by cat in **Go** * **756** by El'endia Starman in **Python** * **1932** by Adnan in **C#** (using mono 3.2.8) * **2640** by yeti in **Python** (using pypy 4.01) * **2754** by Reto Koradi in **C++** * **3486** by Peter Taylor in **Java** * **3900** by primo in **RPython** (using pypy 4.01) * **4176** by The Coder in **Java** **Best entries that may skip a large number of integers to find a large gap** * **14226** by Reto Koradi in **C++** * **22596** by primo in **RPython** (using pypy 4.01). Record reached after 5 seconds! [Answer] ## Probably 4032, mixed Atkin-Bernstein sieve and "deterministic" Miller-Rabin ### Wheel factorisation and good primes It's highly obvious that with the exceptions of 2, 3, and 5, every prime is coprime to 2\*3\*5 = 60. There are 16 equivalence classes modulo 60 which are coprime to 60, so any primality test only needs to check those 16 cases. However, when we're looking for "good" primes we can thin the herd even more. If `gcd(x, 60) = 1`, we find that in most cases `gcd(x-1, 60)` is either 6 or 10. There are 6 values of `x` for which it is 2: ``` 17, 23, 29, 47, 53, 59 ``` Therefore we can precompute the "good" primes of the form `2^a 3^b + 1` and `2^a 5^b + 1` and merge them into the result of a prime generator which only considers 10% of numbers as even *potential* primes. ### Implementation notes Since I already had a Java implementation of the Atkin-Bernstein sieve lying around, and that already uses a wheel as a key component, it seemed natural to strip out the unnecessary spokes and adapt the code. I originally tried using a producer-consumer architecture to exploit the 8 cores, but memory management was too messy. To test whether a prime is a "good" prime, I'm using a "deterministic" Miller-Rabin test (which really means a Miller-Rabin test which someone else has pre-checked against a list generated deterministically). This can certainly be rewritten to also use Atkin-Bernstein, with some caching to cover the ranges corresponding to sqrt, cbrt, etc., but I'm not sure whether it would be an improvement (because it would be testing lots of numbers which I don't need to test), so that's an experiment for another day. On my fairly old computer this runs to ``` 987417437 - 987413849 = 3588 1123404923 - 1123401023 = 3900 1196634239 - 1196630297 = 3942 1247118179 - 1247114147 = 4032 ``` in pretty much exactly 2 minutes, and then ``` 1964330609 - 1964326433 = 4176 2055062753 - 2055058529 = 4224 2160258917 - 2160254627 = 4290 ``` at 3:10, 3:20, and 3:30 respectively. ``` import java.util.*; public class PPCG65876 { public static void main(String[] args) { long[] specials = genSpecials(); int nextSpecialIdx = 0; long nextSpecial = specials[nextSpecialIdx]; long p = 59; long bestGap = 2; for (long L = 1; true; L += B) { long[][] buf = new long[6][B >> 6]; int[] Lmodqq = new int[qqtab.length]; for (int i = 0; i < Lmodqq.length; i++) Lmodqq[i] = (int)(L % qqtab[i]); for (long[] arr : buf) Arrays.fill(arr, -1); // TODO Can probably get a minor optimisation by inverting this for (int[] parms : elliptic) traceElliptic(buf[parms[0]], parms[1], parms[2], parms[3] - L, parms[4], parms[5], Lmodqq, totients[parms[0]]); for (int[] parms : hyperbolic) traceHyperbolic(buf[parms[0]], parms[1], parms[2], parms[3] - L, Lmodqq, totients[parms[0]]); // We need to filter down to squarefree numbers. long pg_base = L * M; squarefreeMid(buf, invTotients, pg_base, 247, 1, 38); squarefreeMid(buf, invTotients, pg_base, 253, 1, 38); squarefreeMid(buf, invTotients, pg_base, 257, 1, 38); squarefreeMid(buf, invTotients, pg_base, 263, 1, 38); squarefreeMid(buf, invTotients, pg_base, 241, 0, 2); squarefreeMid(buf, invTotients, pg_base, 251, 0, 2); squarefreeMid(buf, invTotients, pg_base, 259, 0, 2); squarefreeMid(buf, invTotients, pg_base, 269, 0, 2); // Turn bitmasks into primes long[] page = new long[150000]; // TODO This can almost certainly be smaller long[] transpose = new long[6]; for (int j = 0, off = 0; j < (B >> 6); j++) { // Reduce cache locality problems by transposing. for (int k = 0; k < 6; k++) transpose[k] = buf[k][j]; for (long mask = 1L; mask != 0; mask <<= 1) { for (int k = 0; k < 6; k++) { if ((transpose[k] & mask) == 0) page[off++] = pg_base + totients[k]; } pg_base += M; } } // Insert specials and look for gaps. for (long q : page) { if (q == 0) break; // Do we need to insert one or more specials? while (nextSpecial < q) { if (nextSpecial - p > bestGap) { bestGap = nextSpecial - p; System.out.format("%d - %d = %d\n", nextSpecial, p, bestGap); } p = nextSpecial; nextSpecial = specials[++nextSpecialIdx]; } if (isGood(q)) { if (q - p > bestGap) { bestGap = q - p; System.out.format("%d - %d = %d\n", q, p, bestGap); } p = q; } } } } static long[] genSpecials() { // 2^a 3^b + 1 or 2^a 5^b + 1 List<Long> tmp = new LinkedList<Long>(); for (long threes = 3; threes <= 4052555153018976267L; threes *= 3) { for (long t = threes; t > 0; t <<= 1) tmp.add(t + 1); } for (long fives = 5; fives <= 7450580596923828125L; fives *= 5) { for (long f = fives; f > 0; f <<= 1) tmp.add(f + 1); } // Filter down to primes Iterator<Long> it = tmp.iterator(); while (it.hasNext()) { long next = it.next(); if (next < 60 || next > 341550071728321L || !isPrime(next)) it.remove(); } Collections.sort(tmp); long[] specials = new long[tmp.size()]; for (int i = 0; i < tmp.size(); i++) specials[i] = tmp.get(i); return specials; } private static boolean isGood(long p) { long d = p - 1; while ((d & 1) == 0) d >>= 1; if (d == 1) return false; // Is d a prime power? if (d % 3 == 0 || d % 5 == 0) { // Because of the way the filters before this one work, nothing should reach here. throw new RuntimeException("Should be unreachable"); } // TODO Is it preferable to reuse the Atkin-Bernstein code, caching pages which correspond // to the possible power candidates? if (isPrime(d)) return true; for (int a = (d % 60 == 1 || d % 60 == 49) ? 2 : 3; (1L << a) < d; a++) { long r = (long)(0.5 + Math.pow(d, 1. / a)); if (d == (long)(0.5 + Math.pow(r, a)) && isPrime(r)) return true; } return false; } /*--------------------------------------------------- Deterministic Miller-Rabin ---------------------------------------------------*/ public static boolean isPrime(int x) { // See isPrime(long). We pick bases which are known to work for the entire range of int. // Special case for the bases. if (x == 2 || x == 7 || x == 61) return true; int d = x - 1; int s = 0; while ((d & 1) == 0) { s++; d >>= 1; } // TODO Can be optimised if (!isSPRP(2, d, s, x)) return false; if (!isSPRP(7, d, s, x)) return false; if (!isSPRP(61, d, s, x)) return false; return true; } private static boolean isSPRP(int b, int d, int s, int x /* == d << s */) { int l = modPow(b, d, x); if (l == 1 || l == x - 1) return true; for (int r = 1; r < s; r++) { l = modPow(l, 2, x); if (l == x - 1) return true; if (l == 1) return false; } return false; } public static int modPow(int a, int b, int c) { int accum = 1; while (b > 0) { if ((b & 1) == 1) accum = (int)(accum * (long)a % c); a = (int)(a * (long)a % c); b >>= 1; } return accum; } public static boolean isPrime(long x) { if (x < Integer.MAX_VALUE) return isPrime((int)x); long d = x - 1; int s = 0; while ((d & 1) == 0) { s++; d >>= 1; } // TODO Can be optimised // If b^d == 1 (mod x) or (b^d)^(2^r) == -1 (mod x) for some r < s then we pass for base b. // We select bases according to Jaeschke, Gerhard (1993), "On strong pseudoprimes to several bases", Mathematics of Computation 61 (204): 915–926, doi:10.2307/2153262 // TODO Would it be better to use a set of 5 bases from http://miller-rabin.appspot.com/ ? if (!isSPRP(2, d, s, x)) return false; if (!isSPRP(3, d, s, x)) return false; if (!isSPRP(5, d, s, x)) return false; if (!isSPRP(7, d, s, x)) return false; if (x < 3215031751L) return true; if (!isSPRP(11, d, s, x)) return false; if (x < 2152302898747L) return true; if (!isSPRP(13, d, s, x)) return false; if (x < 3474749660383L) return true; if (!isSPRP(17, d, s, x)) return false; if (x < 341550071728321L) return true; throw new IllegalArgumentException("Overflow"); } private static boolean isSPRP(long b, long d, int s, long x /* == d << s */) { if (b * (double)x > Long.MAX_VALUE) throw new IllegalArgumentException("Overflow"); // TODO Work out more precise page bounds long l = modPow(b, d, x); if (l == 1 || l == x - 1) return true; for (int r = 1; r < s; r++) { l = modPow(l, 2, x); if (l == x - 1) return true; if (l == 1) return false; } return false; } /** * Computes a^b (mod c). We assume c &lt; 2^62. */ public static long modPow(long a, long b, long c) { long accum = 1; while (b > 0) { if ((b & 1) == 1) accum = prodMod(accum, a, c); a = prodMod(a, a, c); b >>= 1; } return accum; } /** * Computes a*b (mod c). We assume c &lt; 2^62. */ private static long prodMod(long a, long b, long c) { // The naive product would require 128-bit integers. // Consider a = (A << 32) + B, b = (C << 31) + D. Different shifts chosen deliberately. // Then ab = (AC << 63) + (AD << 32) + (BC << 31) + BD with intermediate values remaining in 63 bits. long AC = (a >> 32) * (b >> 31) % c; long AD = (a >> 32) * (b & ((1L << 31) - 1)) % c; long BC = (a & ((1L << 32) - 1)) * (b >> 31) % c; long BD = (a & ((1L << 32) - 1)) * (b & ((1L << 31) - 1)) % c; long t = AC; for (int i = 0; i < 31; i++) { t = (t + t) % c; } // t = (AC << 31) t = (t + AD) % c; t = (t + t) % c; t = (t + BC) % c; // t = (AC << 32) + (AD << 1) + BC for (int i = 0; i < 31; i++) { t = (t + t) % c; } // t = (AC << 63) + (AD << 32) + (BC << 31) return (t + BD) % c; } /*--------------------------------------------------- Atkin-Bernstein ---------------------------------------------------*/ // Page size. private static final int B = 1001 << 6; // Wheel modulus for sharding between binary quadratic forms. private static final int M = 60; // Squares of primes 5 < q < 240 private static final int[] qqtab = new int[] { 49, 121, 169, 289, 361, 529, 841, 961, 1369, 1681, 1849, 2209, 2809, 3481, 3721, 4489, 5041, 5329, 6241, 6889, 7921, 9409, 10201, 10609, 11449, 11881, 12769, 16129, 17161, 18769, 19321, 22201, 22801, 24649, 26569, 27889, 29929, 32041, 32761, 36481, 37249, 38809, 39601, 44521, 49729, 51529, 52441, 54289, 57121 }; // If a_i == q^{-2} (mod 60) is the reciprocal of qq[i], qq60tab[i] = qq[i] + (1 - a_i * qq[i]) / 60 private static int[] qq60tab = new int[] { 9, 119, 31, 53, 355, 97, 827, 945, 251, 1653, 339, 405, 515, 3423, 3659, 823, 4957, 977, 6137, 1263, 7789, 1725, 10031, 1945, 2099, 11683, 2341, 2957, 16875, 3441, 18999, 21831, 22421, 4519, 4871, 5113, 5487, 31507, 32215, 35873, 6829, 7115, 38941, 43779, 9117, 9447, 51567, 9953, 56169 }; /** * Produces a set of parameters for traceElliptic to find solutions to ax^2 + cy^2 == d (mod M). * @param d The target residue. * @param a Binary quadratic form parameter. * @param c Binary quadratic form parameter. */ private static List<int[]> initElliptic(final int[] invTotients, final int d, final int a, final int c) { List<int[]> rv = new ArrayList<int[]>(); // The basic idea is that we maintain an invariant of the form // M k = a x^2 + c y^2 - d // Therefore we increment x in steps F such that // a((x + F)^2 - x^2) == 0 (mod M) // and similarly for y in steps G. int F = computeIncrement(a, M), G = computeIncrement(c, M); for (int f = 1; f <= F; f++) { for (int g = 1; g <= G; g++) { if ((a*f*f + c*g*g - d) % M == 0) { rv.add(new int[] { invTotients[d], (2*f + F)*a*F/M, (2*g + G)*c*G/M, (a*f*f + c*g*g - d)/M, 2*a*F*F/M, 2*c*G*G/M }); } } } return rv; } private static int computeIncrement(int a, int M) { // Find smallest F such that M | 2aF and M | aF^2 int l = M / gcd(M, 2 * a); for (int F = l; true; F += l) { if (a*F*F % M == 0) return F; } } public static int gcd(int a, int b) { while (b != 0) { int t = b; b = a % b; a = t; } return a; } // NB This is generalised somewhat from primegen's implementation. private static void traceElliptic(final long[] buf, int x, int y, long start, final int cF2, final int cG2, final int[] Lmodqq, final int d) { // Bring the annular segment into the range of ints. start += 1000000000; while (start < 0) { start += x; x += cF2; } start -= 1000000000; int i = (int)start; while (i < B) { i += x; x += cF2; } while (true) { x -= cF2; if (x <= cF2 >> 1) { // It makes no sense that doing this in here should perform well, but empirically it does much better than // only eliminating the squares once. squarefreeTiny(buf, Lmodqq, d); return; } i -= x; while (i < 0) { i += y; y += cG2; } int i0 = i, y0 = y; while (i < B) { buf[i >> 6] ^= 1L << i; i += y; y += cG2; } i = i0; y = y0; } } // This only handles 3x^2 - y^2, and is closer to a direct port of primegen. private static void traceHyperbolic(final long[] a, int x, int y, long start, final int[] Lmodqq, final int d) { x += 5; y += 15; // Bring the segment into the range of ints. start += 1000000000; while (start < 0) { start += x; x += 10; } start -= 1000000000; int i = (int)start; while (i < 0) { i += x; x += 10; } while (true) { x += 10; while (i >= B) { if (x <= y) { squarefreeTiny(a, Lmodqq, d); return; } i -= y; y += 30; } int i0 = i, y0 = y; while (i >= 0 && y < x) { a[i >> 6] ^= 1L << i; i -= y; y += 30; } i = i0 + x - 10; y = y0; } } private static void squarefreeTiny(final long[] a, final int[] Lmodqq, final int d) { for (int j = 0; j < qqtab.length; ++j) { int qq = qqtab[j]; int k = qq - 1 - ((Lmodqq[j] + qq60tab[j] * d - 1) % qq); while (k < B) { a[k >> 6] |= 1L << k; k += qq; } } } private static void squarefreeMid(long[][] buf, int[] invTotients, final long base, int q, int dqq, int di) { int qq = q * q; q = M * q + (M * M / 4); while (qq < M * B) { int i = qq - (int)(base % qq); if ((i & 1) == 0) i += qq; if (i < M * B) { int qqhigh = ((qq / M) << 1) + dqq; int ilow = i % M; int ihigh = i / M; while (ihigh < B) { int n = invTotients[ilow]; if (n >= 0) buf[n][ihigh >> 6] |= 1L << ihigh; ilow += di; ihigh += qqhigh; if (ilow >= M) { ilow -= M; ihigh += 1; } } } qq += q; q += M * M / 2; } squarefreebig(buf, invTotients, base, q, qq); } private static void squarefreebig(long[][] buf, int[] invTotients, final long base, int q, long qq) { long bound = base + M * B; while (qq < bound) { long i = qq - (base % qq); if ((i & 1) == 0) i += qq; if (i < M * B) { int pos = (int)i; int n = invTotients[pos % M]; if (n >= 0) { int ihigh = pos / M; buf[n][ihigh >> 6] |= 1L << ihigh; } } qq += q; q += M * M / 2; } } // The relevant totients of M - those which only have one forced prime factor. static final int[] totients = new int[] { 17, 23, 29, 47, 53, 59 }; private static final int[] invTotients; // Parameters for tracing the hyperbolic BQF used for 59+60Z. private static final int[][] hyperbolic = new int[][] { {5, 1, 2, -1}, {5, 1, 8, -2}, {5, 1, 22, -9}, {5, 1, 28, -14}, {5, 4, 7, -1}, {5, 4, 13, -3}, {5, 4, 17, -5}, {5, 4, 23, -9}, {5, 5, 4, 0}, {5, 5, 14, -3}, {5, 5, 16, -4}, {5, 5, 26, -11}, {5, 6, 7, 0}, {5, 6, 13, -2}, {5, 6, 17, -4}, {5, 6, 23, -8}, {5, 9, 2, 3}, {5, 9, 8, 2}, {5, 9, 22, -5}, {5, 9, 28, -10}, {5, 10, 1, 4}, {5, 10, 11, 2}, {5, 10, 19, -2}, {5, 10, 29, -10} }; // Parameters for tracing the elliptic BQFs used for all totients except 11 and 59. private static final int[][] elliptic; static { invTotients = new int[M]; Arrays.fill(invTotients, -1); for (int i = 0; i < totients.length; i++) invTotients[totients[i]] = i; // Calculate the parameters for tracing the elliptic BQFs from a table of the BQF used for each totient. // E.g. for 17+60Z we use 5x^2 + 3y^2. int[][] bqfs = new int[][] { {17, 5, 3}, {23, 5, 3}, {29, 4, 1}, {47, 5, 3}, {53, 5, 3} }; List<int[]> parmSets = new ArrayList<int[]>(); for (int[] bqf : bqfs) parmSets.addAll(initElliptic(invTotients, bqf[0], bqf[1], bqf[2])); elliptic = parmSets.toArray(new int[0][]); } } ``` Save as `PPCG65876.java`, compile as `javac PPCG65876.java`, and run as `java -Xmx1G PPCG65876`. [Answer] # RPython (PyPy 4.0.1), 4032 [RPython](http://pypy.readthedocs.org/en/latest/coding-guide.html#our-runtime-interpreter-is-rpython) is a restricted subset of Python, which can be translated to C and then compiled using the RPython Toolchain. Its expressed purpose is to aid in the creation of language interpreters, but it can also be used to compile simple programs. To compile, [download](http://pypy.org/download.html) the current PyPy source (PyPy 4.0.1), and run the following: ``` $ pypy /pypy-4.0.1-src/rpython/bin/rpython --opt=3 good-primes.py ``` The resulting executable will be named `good-primes-c` or similar in the current working directory. --- **Implementation Notes** The prime number generator `primes` is an unbounded Sieve of Eratosthenes, which uses a wheel to avoid any multiples of *2*, *3*, *5*, or *7*. It also calls itself recursively to generate the next value to use for marking. I'm quite satisfied with this generator. Line profiling reveals that the slowest two lines are: ``` 37> n += o 38> if n not in sieve: ``` so I don't think there's much room for improvement, other than perhaps using a larger wheel. For the "goodness" check, first all factors of two are removed from *n-1*, using a bit-twiddling hack to find largest power of two which is a divisor `(n-1 & 1-n)`. Because *p-1* is necessarily even for any prime *p > 2*, it follows that *2* must be one of the distinct prime factors. What remains is sent to the `is_prime_power` function, which does what its name implies. Checking if a value is a prime power is "nearly free", since it is done simultaneously with the primality check, with at most *O(logpn)* operations, where *p* is the smallest prime factor of *n*. Trial division might seem a bit naïve, but by my testing it is the fastest method for values less than *232*. I do save a bit by reusing the wheel from the sieve. In particular: ``` 59> while p*p < n: 60> for o in offsets: ``` by iterating over a wheel of length 48, the `p*p < n` check will be skipped thousands of times, at the low, low price of no more than 48 additional modulo operations. It also skips over 77% of all candidates, rather than 50% by taking only odds. The last few outputs are: ``` 3588 (987417437 - 987413849) 60.469000s 3900 (1123404923 - 1123401023) 70.828000s 3942 (1196634239 - 1196630297) 76.594000s 4032 (1247118179 - 1247114147) 80.625000s 4176 (1964330609 - 1964326433) 143.047000s 4224 (2055062753 - 2055058529) 151.562000s ``` The code is also valid Python, and should reach 3588 ~ 3900 when run with a recent PyPy interpreter. --- ``` # primes less than 212 small_primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,101,103,107,109,113,127,131,137,139,149,151, 157,163,167,173,179,181,191,193,197,199,211] # pre-calced sieve of eratosthenes for n = 2, 3, 5, 7 # distances between sieve values, starting from 211 offsets = [ 10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2,10, 2] # tabulated, mod 105 dindices =[ 0,10, 2, 0, 4, 0, 0, 0, 8, 0, 0, 2, 0, 4, 0, 0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 6, 0, 0, 2, 0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 4, 2, 0, 6, 6, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 4, 2, 0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 6, 2, 0, 6, 0, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 4, 8, 0, 0, 2, 0,10, 0, 0, 4, 0, 0, 0, 2, 0, 4, 2] def primes(start = 0): for n in small_primes[start:]: yield n pg = primes(6) p = pg.next() q = p*p sieve = {221: 13, 253: 11} n = 211 while True: for o in offsets: n += o stp = sieve.pop(n, 0) if stp: nxt = n/stp nxt += dindices[nxt%105] while nxt*stp in sieve: nxt += dindices[nxt%105] sieve[nxt*stp] = stp else: if n < q: yield n else: sieve[q + dindices[p%105]*p] = p p = pg.next() q = p*p def is_prime_power(n): for p in small_primes: if n%p == 0: n /= p while n%p == 0: n /= p return n == 1 p = 211 while p*p < n: for o in offsets: p += o if n%p == 0: n /= p while n%p == 0: n /= p return n == 1 return n > 1 def main(argv): from time import time t0 = time() m = 0 p = q = 7 pgen = primes(3) for n in pgen: d = (n-1 & 1-n) if is_prime_power(n/d): p, q = q, n if q-p > m: m = q-p print m, "(%d - %d) %fs"%(q, p, time()-t0) return 0 def target(*args): return main, None if __name__ == '__main__': from sys import argv main(argv) ``` --- ## RPython (PyPy 4.0.1), 22596 This submission is slightly different than the others posted so far, in that it doesn't check all good primes, but instead makes relatively large jumps. One disadvantage of doing this is that sieves cannot be used [[I stand corrected?]](https://codegolf.stackexchange.com/posts/comments/160711?noredirect=1), so one has to rely entirely on primality testing which in practice is quite a bit slower. There's also a happy medium to be found between the rate of growth, and the number of values checked each time. Smaller values are much faster to check, but larger values are more likely to have larger gaps. To appease the math gods, I've decided to follow a Fibonacci-like sequence, having the next starting point as the sum of the previous two. If no new records are found after checking 10 pairs, the script moves on the the next. The last few outputs are: ``` 6420 (12519586667324027 - 12519586667317607) 0.364000s 6720 (707871808582625903 - 707871808582619183) 0.721000s 8880 (626872872579606869 - 626872872579597989) 0.995000s 10146 (1206929709956703809 - 1206929709956693663) 4.858000s 22596 (918415168400717543 - 918415168400694947) 8.797000s ``` When compiled, 64-bit integers are used, although it is assumed in a few places that two integers may be added without overflow, so in practice only 63 are usable. Upon reaching 62 significant bits, the current value is halved twice, to avoid overflow in the calculation. The result is that the script shuffles through values on the *260 - 262* range. Not surpassing native integer precision also makes the script faster when interpreted. The following PARI/GP script can be used to confirm this result: ``` isgoodprime(n) = isprime(n) && omega(n-1)==2 for(n = 918415168400694947, 918415168400717543, { if(isgoodprime(n), print(n" is a good prime")) }) ``` --- ``` try: from rpython.rlib.rarithmetic import r_int64 from rpython.rtyper.lltypesystem.lltype import SignedLongLongLong from rpython.translator.c.primitive import PrimitiveType # check if the compiler supports long long longs if SignedLongLongLong in PrimitiveType: from rpython.rlib.rarithmetic import r_longlonglong def mul_mod(a, b, m): return r_int64(r_longlonglong(a)*b%m) else: from rpython.rlib.rbigint import rbigint def mul_mod(a, b, m): biga = rbigint.fromrarith_int(a) bigb = rbigint.fromrarith_int(b) bigm = rbigint.fromrarith_int(m) return biga.mul(bigb).mod(bigm).tolonglong() # modular exponentiation b**e (mod m) def pow_mod(b, e, m): r = 1 while e: if e&1: r = mul_mod(b, r, m) e >>= 1 b = mul_mod(b, b, m) return r except: import sys r_int64 = int if sys.maxint == 2147483647: mul_mod = lambda a, b, m: a*b%m else: mul_mod = lambda a, b, m: int(a*b%m) pow_mod = pow # legendre symbol (a|m) # note: returns m-1 if a is a non-residue, instead of -1 def legendre(a, m): return pow_mod(a, (m-1) >> 1, m) # strong probable prime def is_sprp(n, b=2): if n < 2: return False d = n-1 s = 0 while d&1 == 0: s += 1 d >>= 1 x = pow_mod(b, d, n) if x == 1 or x == n-1: return True for r in xrange(1, s): x = mul_mod(x, x, n) if x == 1: return False elif x == n-1: return True return False # lucas probable prime # assumes D = 1 (mod 4), (D|n) = -1 def is_lucas_prp(n, D): Q = (1-D) >> 2 # n+1 = 2**r*s where s is odd s = n+1 r = 0 while s&1 == 0: r += 1 s >>= 1 # calculate the bit reversal of (odd) s # e.g. 19 (10011) <=> 25 (11001) t = r_int64(0) while s: if s&1: t += 1 s -= 1 else: t <<= 1 s >>= 1 # use the same bit reversal process to calculate the sth Lucas number # keep track of q = Q**n as we go U = 0 V = 2 q = 1 # mod_inv(2, n) inv_2 = (n+1) >> 1 while t: if t&1: # U, V of n+1 U, V = mul_mod(inv_2, U + V, n), mul_mod(inv_2, V + mul_mod(D, U, n), n) q = mul_mod(q, Q, n) t -= 1 else: # U, V of n*2 U, V = mul_mod(U, V, n), (mul_mod(V, V, n) - 2 * q) % n q = mul_mod(q, q, n) t >>= 1 # double s until we have the 2**r*sth Lucas number while r: U, V = mul_mod(U, V, n), (mul_mod(V, V, n) - 2 * q) % n q = mul_mod(q, q, n) r -= 1 # primality check # if n is prime, n divides the n+1st Lucas number, given the assumptions return U == 0 # primes less than 212 small_primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,101,103,107,109,113,127,131,137,139,149,151, 157,163,167,173,179,181,191,193,197,199,211] # pre-calced sieve of eratosthenes for n = 2, 3, 5, 7 indices = [ 1, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,101,103, 107,109,113,121,127,131,137,139,143,149,151,157, 163,167,169,173,179,181,187,191,193,197,199,209] # distances between sieve values offsets = [ 10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2,10, 2] bit_lengths = [ 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF, 0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF, 0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF] max_int = 2147483647 # returns the index of x in a sorted list a # or the index of the next larger item if x is not present # i.e. the proper insertion point for x in a def binary_search(a, x): s = 0 e = len(a) m = e >> 1 while m != e: if a[m] < x: s = m m = (s + e + 1) >> 1 else: e = m m = (s + e) >> 1 return m def log2(n): hi = n >> 32 if hi: return binary_search(bit_lengths, hi) + 32 return binary_search(bit_lengths, n) # integer sqrt of n def isqrt(n): c = n*4/3 d = log2(c) a = d>>1 if d&1: x = r_int64(1) << a y = (x + (n >> a)) >> 1 else: x = (r_int64(3) << a) >> 2 y = (x + (c >> a)) >> 1 if x != y: x = y y = (x + n/x) >> 1 while y < x: x = y y = (x + n/x) >> 1 return x # integer cbrt of n def icbrt(n): d = log2(n) if d%3 == 2: x = r_int64(3) << d/3-1 else: x = r_int64(1) << d/3 y = (2*x + n/(x*x))/3 if x != y: x = y y = (2*x + n/(x*x))/3 while y < x: x = y y = (2*x + n/(x*x))/3 return x ## Baillie-PSW ## # this is technically a probabalistic test, but there are no known pseudoprimes def is_bpsw(n): if not is_sprp(n, 2): return False # idea shamelessly stolen from Mathmatica's PrimeQ # if n is a 2-sprp and a 3-sprp, n is necessarily square-free if not is_sprp(n, 3): return False a = 5 s = 2 # if n is a perfect square, this will never terminate while legendre(a, n) != n-1: s = -s a = s-a return is_lucas_prp(n, a) # an 'almost certain' primality check def is_prime(n): if n < 212: m = binary_search(small_primes, n) return n == small_primes[m] for p in small_primes: if n%p == 0: return False # if n is a 32-bit integer, perform full trial division if n <= max_int: p = 211 while p*p < n: for o in offsets: p += o if n%p == 0: return False return True return is_bpsw(n) # next prime strictly larger than n def next_prime(n): if n < 2: return 2 # first odd larger than n n = (n + 1) | 1 if n < 212: m = binary_search(small_primes, n) return small_primes[m] # find our position in the sieve rotation via binary search x = int(n%210) m = binary_search(indices, x) i = r_int64(n + (indices[m] - x)) # adjust offsets offs = offsets[m:] + offsets[:m] while True: for o in offs: if is_prime(i): return i i += o # true if n is a prime power > 0 def is_prime_power(n): if n > 1: for p in small_primes: if n%p == 0: n /= p while n%p == 0: n /= p return n == 1 r = isqrt(n) if r*r == n: return is_prime_power(r) s = icbrt(n) if s*s*s == n: return is_prime_power(s) p = r_int64(211) while p*p < r: for o in offsets: p += o if n%p == 0: n /= p while n%p == 0: n /= p return n == 1 if n <= max_int: while p*p < n: for o in offsets: p += o if n%p == 0: return False return True return is_bpsw(n) return False def next_good_prime(n): n = next_prime(n) d = (n-1 & 1-n) while not is_prime_power(n/d): n = next_prime(n) d = (n-1 & 1-n) return n def main(argv): from time import time t0 = time() if len(argv) > 1: n = r_int64(int(argv[1])) else: n = r_int64(7) if len(argv) > 2: limit = int(argv[2]) else: limit = 10 m = 0 e = 1 q = n try: while True: e += 1 p, q = q, next_good_prime(q) if q-p > m: m = q-p print m, "(%d - %d) %fs"%(q, p, time()-t0) n, q = p, n+p if log2(q) > 61: q >>= 2 e = 1 q = next_good_prime(q) elif e > limit: n, q = p, n+p if log2(q) > 61: q >>= 2 e = 1 q = next_good_prime(q) except KeyboardInterrupt: pass return 0 def target(*args): return main, None if __name__ == '__main__': from sys import argv main(argv) ``` [Answer] # C++, 2754 (all values, brute force primality test) This is brute force, but it's a start before our resident mathematicians might get to work with something more efficient. I can add some more explanation if necessary, but it's probably very obvious from the code. Since if `p` is a prime other than 2, we know that `p - 1` is even, and one of the two factors is always 2. So we enumerate the primes, reduce `p - 1` by all factors 2, and check that the remaining value is either a prime, or that all its factors are the same prime. Code: ``` #include <stdint.h> #include <vector> #include <iostream> int main() { std::vector<uint64_t> primes; uint64_t prevGoodVal = 0; uint64_t maxDiff = 0; for (uint64_t val = 3; ; val += 2) { bool isPrime = true; std::vector<uint64_t>::const_iterator itFact = primes.begin(); while (itFact != primes.end()) { uint64_t fact = *itFact; if (fact * fact > val) { break; } if (!(val % fact)) { isPrime = false; break; } ++itFact; } if (!isPrime) { continue; } primes.push_back(val); uint64_t rem = val; --rem; while (!(rem & 1)) { rem >>= 1; } if (rem == 1) { continue; } bool isGood = true; itFact = primes.begin(); while (itFact != primes.end()) { uint64_t fact = *itFact; if (fact * fact > rem) { break; } if (!(rem % fact)) { while (rem > fact) { rem /= fact; if (rem % fact) { break; } } isGood = (rem == fact); break; } ++itFact; } if (isGood) { if (prevGoodVal) { uint64_t diff = val - prevGoodVal; if (diff > maxDiff) { maxDiff = diff; std::cout << maxDiff << " (" << val << " - " << prevGoodVal << ")" << std::endl; } } prevGoodVal = val; } } return 0; } ``` The program prints the difference as well as the corresponding two good primes any time a new maximum difference is found. Sample output from the test run on my machine, where the reported value of 2754 is found after about 1:20 minutes: ``` 4 (11 - 7) 6 (19 - 13) 8 (37 - 29) 14 (73 - 59) 24 (137 - 113) 30 (227 - 197) 32 (433 - 401) 48 (557 - 509) 50 (769 - 719) 54 (1283 - 1229) 60 (1697 - 1637) 90 (1823 - 1733) 108 (2417 - 2309) 120 (3329 - 3209) 126 (4673 - 4547) 132 (5639 - 5507) 186 (7433 - 7247) 222 (8369 - 8147) 258 (16487 - 16229) 270 (32507 - 32237) 294 (34157 - 33863) 306 (35879 - 35573) 324 (59393 - 59069) 546 (60293 - 59747) 570 (145823 - 145253) 588 (181157 - 180569) 756 (222059 - 221303) 780 (282617 - 281837) 930 (509513 - 508583) 1044 (1046807 - 1045763) 1050 (1713599 - 1712549) 1080 (1949639 - 1948559) 1140 (2338823 - 2337683) 1596 (3800999 - 3799403) 1686 (6249743 - 6248057) 1932 (12464909 - 12462977) 2040 (30291749 - 30289709) 2160 (31641773 - 31639613) 2190 (34808447 - 34806257) 2610 (78199097 - 78196487) 2640 (105072497 - 105069857) 2754 (114949007 - 114946253) ^C real 1m20.233s user 1m20.153s sys 0m0.048s ``` [Answer] # C++, 14226 (high values only, Miller-Rabin test) Posting this separately because it is entirely different from my initial solution, and I did not want to completely replace a post that had gotten a number of upvotes. Thanks to @primo for pointing out a problem with the original version. There was an overflow for large numbers in the prime number test. This takes advantage of some insights that have been gained during the evolution of other solutions. The main observations are: * Since the results clearly show that the gaps get larger as the primes themselves get larger, there is no point in bothering with small primes. Exploring large prime values is much more effective. * Probabilistic prime testing is required for primes of this size. Based on this, the method employed here is fairly simple: * For primality testing, the Miller-Rabin test is used. The implementation is based on the pseudo code on the [wikpedia page](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test). With the bases used, it will deliver correct values up to 3825123056546413051 (see OEIS [A014233](http://oeis.org/A014233)), which is plenty for the range of values used here. * To determine if primes are good primes, the powers of 2 are stripped. Factorizing the remaining value would be very expensive, but is unnecessary. Instead, I calculate the much fewer possible roots using double math, and see if any of them produces an integer that is in fact the correct root. * Math is mostly using 64-bit unsigned values, with 128-bit unsigned values needed for some temporary values in the primality test. * Since I use double math for the roots, and a double can exactly represent integers of at most 53 bits, the maximum size that can safely be handled by this code is 54 bits (the number converted to double is at most half the size of the prime). * Since 54 bits was the maximum size for the number I was confident using, I start with a number that is somewhat smaller than the maximum 54-bit number. The code does report larger gaps for even larger start values, and they are *probably* correct, but I can't be as sure. Results: ``` 1266 (16888498602640739 - 16888498602639473) 1470 (16888498602645563 - 16888498602644093) 2772 (16888498602651629 - 16888498602648857) 2862 (16888498602655829 - 16888498602652967) 3120 (16888498602675053 - 16888498602671933) 3756 (16888498602685769 - 16888498602682013) 4374 (16888498602696257 - 16888498602691883) 5220 (16888498602745493 - 16888498602740273) 5382 (16888498603424039 - 16888498603418657) 5592 (16888498603511279 - 16888498603505687) 5940 (16888498603720697 - 16888498603714757) 6204 (16888498605020837 - 16888498605014633) 6594 (16888498605999017 - 16888498605992423) 14226 (16888498608108539 - 16888498608094313) ^C real 0m26.335s user 0m26.312s sys 0m0.008s ``` Code: ``` #include <stdint.h> #include <cmath> #include <iostream> uint64_t intRoot(uint64_t a, int p) { double e = 1.0 / static_cast<double>(p); double dRoot = pow(a, e); return static_cast<uint64_t>(dRoot + 0.5); } uint64_t intPow(uint64_t a, int e) { uint64_t r = 1; while (e) { if (e & 1) { r *= a; } e >>= 1; a *= a; } return r; } uint64_t modPow(uint64_t a, uint64_t e, uint64_t m) { uint64_t r = 1; a %= m; while (e) { if (e & 1) { __uint128_t t = r; t *= a; t %= m; r = t; } e >>= 1; __uint128_t t = a; t *= a; t %= m; a = t; } return r; } bool isPrime(uint64_t n) { const uint64_t a[] = {2, 3, 5, 7, 11, 13, 17, 19, 23}; if (n < 2) { return false; } for (int k = 0; k < 9; ++k) { if (n == a[k]) { return true; } if (n % a[k] == 0) { return false; } } int r = __builtin_ctzll(n - 1); uint64_t d = (n - 1) >> r; for (int k = 0; k < 9; ++k) { uint64_t x = modPow(a[k], d, n); if (x == 1 || x == n - 1) { continue; } bool comp = true; for (int i = 0; i < r - 1; ++i) { x = modPow(x, 2, n); if (x == 1) { return false; } if (x == n - 1) { comp = false; break; } } if (comp) { return false; } } return true; } int main() { uint64_t prevGoodVal = 0; uint64_t maxDiff = 0; for (uint64_t val = (1ull << 54) - (1ull << 50) + 1; ; val += 2) { if (isPrime(val)) { uint64_t d = static_cast<double>((val - 1) >> __builtin_ctzll(val - 1)); bool isGood = false; if (isPrime(d)) { isGood = true; } else { for (int e = 2; ; ++e) { uint64_t r = intRoot(d, e); if (r < 3) { break; } if (intPow(r, e) == d && isPrime(r)) { isGood = true; break; } } } if (isGood) { if (prevGoodVal) { uint64_t diff = val - prevGoodVal; if (diff > maxDiff) { maxDiff = diff; std::cout << maxDiff << " (" << val << " - " << prevGoodVal << ")" << std::endl; } } prevGoodVal = val; } } } return 0; } ``` [Answer] # PyPy-2.4.0 # Python-2 The `x` file~~s~~ ... Episode: *"Look mom! Not a single division!"* ;-) ``` M = g = 0 B = L = {} n = 2 while 1: if n in L: B = P = L[n] del L[n] else: if len(B) == 2: if g: m = n - g if M < m: M = m print n, g, m g = n P = [n] for p in P: npp = n + p if npp in L: if p not in L[npp]: L[npp] += [p] else: L[npp] = [p] n += 1 ``` I tested it on Debian8 with PyPy-2.4.0 and Python2 started like: ``` timeout 2m pypy -O x timeout 2m python2 -O x ``` If there is really plenty of RAM, the `del L[n]` line may be deleted. --- The basic prime number generator is this: ``` L = {} n = 2 while 1: if n in L: P = L[n] del L[n] else: print n P = [n] for p in P: npp = n + p if npp in L: if p not in L[npp]: L[npp] += [p] else: L[npp] = [p] n += 1 ``` It basically does exactly what the sieve of Eratosthenes does but in a different order. `L` is dictionary but can be seen as list (tape) of lists of numbers. Nonexistent cells `L[n]` are interpreted as `n` has no known prime divisiors up to now. The `while` loop does a prime or not prime decission on each turn for `L[n]`. * If `L[n]` exists (same as `n in L`), `P = L[n]` is a list of distinct prime divisors of `n`. So `n` is not a prime. * If `L[n]` does not exist, no prime divisor was found. So `n` must be prime then with `P = [n]` being the known divisor. Now `P` is the list of known prime divisors for both cases. The `for p in P` loop moves every entry of `P` forward by the distance of it's value on the tape of numbers. This is how the divisors jump on the tape and this is the reason why these jumping numbers have to be prime. New numbers only get on the tape by the `else` decission above and those are numbers with no known divisors other than them self. Nonprimes never get into these lists `L[n]`. The primes jumping on the list are all distinct because every number `n` is looked at only once and only is added as divisor (if not prime:) `0` or (if prime:) `1` times. Known prime divisors only will move forward but never get duplicated. So `L[n]` always will hold distinct prime divisors or will be empty. --- Back to the upper program for the good primes gaps: ``` if n in L: B = P = L[n] ``` ...keeps the prime divisors of `n` in `B` when `n` is known not to be prime. If `n` is recognised to be prime, `B` holds the list of prime divisors of the previous loop pass looking at `n-1`: ``` else: if len(B) == 2: ``` ...so `len(B) == 2` means `n - 1` has two distinct prime divisors. ``` if g: m = n - g if M < m: M = m print n, g, m g = n ``` `g` just remembers the last seen good prime before the new one, `M` is the length of the previous maximum good prime gap and `m` the length of the newly found gap. --- Happy end. [Answer] # C#, probably 1932 I did find out that, the faster your algorithm is for finding primes, the better your score. I'm also pretty sure that my algorithm is not the most optimal method for prime searching. ``` using System; using System.Collections.Generic; namespace GoodPrimes { class Program { static void Main(string[] args) { int[] list_of_primes = new int[168]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997}; bool is_last_prime = false; int last_prime = 0; int max_value = 0; int old_max_value = 1000000; int old_min_value = 3; HashSet<int> primeSet = new HashSet<int>(); primeSet.Add(2); int X = 0; Console.WriteLine("Initialize primes until " + old_max_value); for (int i = old_min_value; i < old_max_value; i++) { if (IsPrime(i, primeSet)) primeSet.Add(i); } old_min_value = old_max_value; for (int i = 3; ; i += 2) { if (i > old_max_value) { old_max_value += 500000; Console.WriteLine("Initialize primes until " + old_max_value); for (int j = old_min_value; j < old_max_value; j++) { for(int k = 0; k < list_of_primes.Length; k++) if(j % list_of_primes[k] == 0 && j > list_of_primes[k]) continue; if (IsPrime(j, primeSet)) primeSet.Add(j); } old_min_value = old_max_value; } if (primeSet.Contains(i)) { is_last_prime = false; X = (i - 1) / 2; while (X % 2 == 0) X = X / 2; if (IsPrime(X, primeSet)) is_last_prime = true; for (int j = 3; j < i; j++) { if (j % 2 == 0 && j > 2) continue; if (j % 3 == 0 && j > 3) continue; if (j % 5 == 0 && j > 5) continue; if (j % 7 == 0 && j > 7) continue; if (j % 11 == 0 && j > 11) continue; if (j % 13 == 0 && j > 13) continue; if (j % 17 == 0 && j > 17) continue; if (X % j == 0 || is_last_prime) { while (X % j == 0) X = X / j; if ((primeSet.Contains(j) && X == 1) || is_last_prime) { while (X % j == 0) X = X / j; if (X == 1 || is_last_prime) { if (i - last_prime > max_value) { max_value = i - last_prime; Console.WriteLine("New max value: " + max_value.ToString() + " (" + i.ToString() + "-" + last_prime.ToString() + ")"); } last_prime = i; } } break; } } } } Console.ReadLine(); } private static bool IsPrime(int i, HashSet<int> j) { if (i == 2) return true; for (int m = 2; m < Math.Sqrt(System.Convert.ToDouble(i)) + 1; m++) { if (j.Contains(m)) { if (m % 2 == 0 && m > 2) continue; if (m % 3 == 0 && m > 3) continue; if (m % 5 == 0 && m > 5) continue; if (m % 7 == 0 && m > 7) continue; if (m % 11 == 0 && m > 11) continue; if (m % 13 == 0 && m > 13) continue; if (m % 17 == 0 && m > 17) continue; if (i % m == 0) return false; } } return true; } } } ``` [Answer] ## Python 3, 546 ...in two minutes on my machine, which I think is significantly less powerful than yours. ``` def getPrimes_parallelized(): #uses sieve of Sundaram yield 2 yield 3 P = [[4,1]] i = 2 while 1: if P[0][0] <= i: while P[0][0] <= i: P[0][0] += 2*P[0][1]+1 P.sort() elif P[0][0] > i: yield 2*i+1 P.append([2*(i+i*i), i]) P.sort() i += 1 def goodPrimes(x): P = getPrimes_parallelized() primes = [] for p in P: primes.append(p) n = p-1 factors = [] for p2 in primes: if n%p2 == 0: factors.append(p2) while n%p2 == 0: n //= p2 if len(factors) > x: break if len(factors) <= x: yield p maxdiff = 0 GP = goodPrimes(2) p1 = next(GP) gp = next(GP) gps = [(p1,gp)] while 1: if gp-p1 > maxdiff: maxdiff = gp-p1 print("p: %d, q: %d, |q-p|: %d" % (p1,gp,gp-p1)) p1,gp = gp,next(GP) ``` I probably *could* make this more efficient by optimizing for the `x=2` case, but eh. Good enough. :P [Answer] # Go, probably 756 For shame! I'm such a novice that I only naively reused some old code and expected it to work and be fast! If I reimplemented this and actually built it around good primes, it would be so much faster, but alas, I am learning. (I'll probably answer again tomorrow with a fully rebuilt solution that is purpose-built.) ``` package main import "fmt" func mkPrime(ch chan<- int) { for i := 2; ; i++ { ch <- i // Send 'i' to channel 'ch'. } } // Copy the values from channel 'in' to channel 'out', // removing those divisible by 'prime'. func filterPrm(in <-chan int, out chan<- int, prime int) { for { i := <-in // Receive value from 'in'. if i%prime != 0 { out <- i // Send 'i' to 'out'. } } } func mkPFac(max int, ch chan<- int) { ch <- 2 for i := 3; i <= max; i += 2 { ch <- i } ch <- -1 // signal that the limit is reached } // Copy the values from channel 'in' to channel 'out', // removing those divisible by 'prime'. func filterPFac(in <-chan int, out chan<- int, prime int) { for i := <-in; i != -1; i = <-in { if i%prime != 0 { out <- i } } out <- -1 } func calcPFactors(numToFac int) []int { rv := []int{} ch := make(chan int) go mkPFac(numToFac, ch) for prime := <-ch; (prime != -1) && (numToFac > 1); prime = <-ch { for numToFac%prime == 0 { numToFac = numToFac / prime rv = append(rv, prime) } ch1 := make(chan int) go filterPFac(ch, ch1, prime) ch = ch1 } return rv } func rmDup(list []int) []int { var nlist []int for _, e := range list { if !isIn(e, nlist) { nlist = append(nlist, e) } } return nlist } func isIn(a int, list []int) bool { for _, b := range list { if b == a { return true } } return false } // The prime sieve: Daisy-chain Filter processes. func main() { var diff, prev, high int ch := make(chan int) // Create a new channel. go mkPrime(ch) // Launch Generate goroutine. for i := 0; i < 10000000000; i++ { prime := <-ch list := rmDup(calcPFactors(prime - 1)) if len(list) == 2 { //fmt.Println(list, prime) diff = prime - prev //fmt.Println(diff) prev = prime if diff > high { high = diff fmt.Println(high) } } ch1 := make(chan int) go filterPrm(ch, ch1, prime) ch = ch1 } } ``` Uses concurrency, obviously. [Answer] ## Java, 4224 (99.29 s) ## Heavily Customized Sieve of Eratosthenes with advantage of BitSet ``` import java.util.BitSet; public class LargeGoodPrimeGap { // Use this to find upto Large Gap of 4032 - Max 4032 found in 55.17 s // static int limit = 125_00_00_000; // Use this to find upto Large Gap of 4224 - Max 4224 found in 99.29 s static int limit = Integer.MAX_VALUE - 1; // BitSet is highly efficient against boolean[] when Billion numbers were involved // BitSet uses only 1 bit for each number // boolean[] uses 8 bits aka 1 byte for each number which will produce memory issues for large numbers static BitSet primes = new BitSet(limit + 1); static int limitSqrt = (int) Math.ceil(Math.sqrt(limit)); static int maxAllowLimit = Integer.MAX_VALUE - 1; static long start = System.nanoTime(); public static void main(String[] args) { genPrimes(); findGoodPrimesLargeGap(); } // Generate Primes by Sieve of Eratosthenes // Sieve of Eratosthenes is much efficient than Sieve of Atkins as // Sieve of Atkins involes Division, Modulus, Multiplication, Subtraction, Addition but // Sieve of Eratosthenes involves only addition and multiplication static void genPrimes() { // Check if the Given limit exceeds the Permitted Limit 2147483646 (Integer.MAX_VALUE - 1) // If the limit exceeded, Out the Error Message and Exit the Program if ( limit > maxAllowLimit ) { System.err.printf(String.format("Limit %d should not be Greater than Max Limit %d", limit, maxAllowLimit)); System.exit(0); } // Mark numbers from 2 to limit + 1 as Prime primes.set(2, limit + 1); // Now all Values in primes will be true except 0 and 1, // True represents prime number // False represents not prime number // Set the First Prime number int prime = 2; // Set the First multiple of prime int multiple = prime; // Reduce the limit by 1 if limit == Interger.MAX_VALUE - 1 to prevent // Integer overflow on multiple variable int evenLimit = limit == Integer.MAX_VALUE - 1 ? limit - 1 : limit; // Mark all Even Numbers as Not Prime except 2 while ( (multiple += prime) <= evenLimit ) { primes.clear(multiple); } // If evenLimit != limit, set last even number as Not Prime if ( evenLimit != limit ) { primes.clear(limit); } int primeAdd; // Set odd multiples of each Prime as not Prime; // prime <= limitSqrt -> Check Current Prime <= SQRT(limit) // prime = primes.nextSetBit(prime + 1) -> Assign the next True (aka Prime) value as Current Prime // ^ - Above initialisation is highly efficient as Next True check is only based on bits // prime > 0 -> To handle -ve values returned by above True check if no more True is to be found for ( prime = 3; prime > 0 && prime <= limitSqrt; prime = primes.nextSetBit(prime + 1) ) { // All Prime Numbers except 2 were odd numbers // Adding a Prime number with itself will result in an Even number, // but all the Even numbers were already marked as not Prime. // So every odd multiple (3rd, 5th, 7th, ...) of Current Prime will only be marked as not Prime // and skipping all the even multiples (2nd, 4th, 6th, ...) // This reduces the time for prime calculation by ~50% when comparing with all multiples marking primeAdd = prime + prime; // multiple = prime * prime -> Unmarked Prime will appear only from this number as previous values // are already marked as Non Prime by previous prime multiples // multiple += primeAdd -> Increases the multiple by multiple + (CurrentPrime x 2) which will // always be a odd multiple (5th, 7th, 9th, ...) for ( multiple = prime * prime; multiple <= limit && multiple > 0; multiple += primeAdd ) { // Clear or False the multiple if it True primes.clear(multiple); } } double end = (System.nanoTime() - start) / 1000000000.0; System.out.printf("Total Primes upto %d = %d in %.2f s", limit, primes.cardinality(), end); } static void findGoodPrimesLargeGap() { int prevGP = 7; int prevDiff = 0; for ( int i = 11; i <= limit && i > 0; i = primes.nextSetBit(i + 1) ) { int gp = i - 1; int distPrimes = 0; for ( int j = 2; j <= limitSqrt && distPrimes < 3 && j > 0; j = primes.nextSetBit(j + 1) ) { if ( gp % j == 0 ) { ++distPrimes; while ( gp % j == 0 ) { gp = gp / j; } if ( gp <= 1 ) { break; } } if ( primes.get(gp) ) { ++distPrimes; break; } } if ( distPrimes == 2 ) { int currDiff = i - prevGP; if ( currDiff > prevDiff ) { System.out.println( String.format("(%d - %d) %d (%.2f s)", i, prevGP, prevDiff = currDiff, (System.nanoTime() - start) / 1000000000.0)); } prevGP = i; } } } } ``` Time taken is dependent on the Max Limit of the Prime numbers which are going be calculated. For ``` static int limit = Integer.MAX_VALUE - 1; ``` --- ``` Total Primes upto 2147483646 = 105097564 in 17.65 s (11 - 7) 4 (17.71 s) (19 - 13) 6 (17.71 s) (37 - 29) 8 (17.71 s) (73 - 59) 14 (17.71 s) (137 - 113) 24 (17.71 s) (227 - 197) 30 (17.71 s) (433 - 401) 32 (17.71 s) (557 - 509) 48 (17.71 s) (769 - 719) 50 (17.71 s) (1283 - 1229) 54 (17.71 s) (1697 - 1637) 60 (17.71 s) (1823 - 1733) 90 (17.71 s) (2417 - 2309) 108 (17.71 s) (3329 - 3209) 120 (17.71 s) (4673 - 4547) 126 (17.71 s) (5639 - 5507) 132 (17.71 s) (7433 - 7247) 186 (17.71 s) (8369 - 8147) 222 (17.71 s) (16487 - 16229) 258 (17.71 s) (32507 - 32237) 270 (17.72 s) (34157 - 33863) 294 (17.72 s) (35879 - 35573) 306 (17.72 s) (59393 - 59069) 324 (17.72 s) (60293 - 59747) 546 (17.72 s) (145823 - 145253) 570 (17.73 s) (181157 - 180569) 588 (17.73 s) (222059 - 221303) 756 (17.73 s) (282617 - 281837) 780 (17.73 s) (509513 - 508583) 930 (17.74 s) (1046807 - 1045763) 1044 (17.75 s) (1713599 - 1712549) 1050 (17.77 s) (1949639 - 1948559) 1080 (17.77 s) (2338823 - 2337683) 1140 (17.78 s) (3800999 - 3799403) 1596 (17.80 s) (6249743 - 6248057) 1686 (17.85 s) (12464909 - 12462977) 1932 (17.96 s) (30291749 - 30289709) 2040 (18.31 s) (31641773 - 31639613) 2160 (18.34 s) (34808447 - 34806257) 2190 (18.41 s) (78199097 - 78196487) 2610 (19.40 s) (105072497 - 105069857) 2640 (20.07 s) (114949007 - 114946253) 2754 (20.32 s) (246225989 - 246223127) 2862 (24.01 s) (255910223 - 255907313) 2910 (24.31 s) (371348513 - 371345567) 2946 (27.97 s) (447523757 - 447520673) 3084 (30.50 s) (466558553 - 466555373) 3180 (31.15 s) (575713847 - 575710649) 3198 (35.00 s) (606802529 - 606799289) 3240 (36.13 s) (784554983 - 784551653) 3330 (42.89 s) (873632213 - 873628727) 3486 (46.39 s) (987417437 - 987413849) 3588 (50.97 s) (1123404923 - 1123401023) 3900 (56.60 s) (1196634239 - 1196630297) 3942 (59.70 s) (1247118179 - 1247114147) 4032 (61.88 s) (1964330609 - 1964326433) 4176 (94.89 s) (2055062753 - 2055058529) 4224 (99.29 s) ``` [Answer] # Python 3, 1464 With help from [Lembik](https://codegolf.stackexchange.com/users/9206/lembik), whose idea was to just check for the first two good primes after a power of two and when found immediately move on to the next power of two. If someone can use this as a jumping point, feel free. A portion of my results are below after running this in IDLE. The code follows. Credit to [primo](https://codegolf.stackexchange.com/users/4098/primo) as I grabbed their list of small primes for this code. **Edit:** I have edited the code to fit the actual specifications of the problem (two distinct prime divisors not *exactly* two distinct prime divisors), and I implemented not moving on to the next power of two until the good primes the program has found have a gap larger than that of the *last* two good primes it found. I should also give credit to [Peter Taylor](https://codegolf.stackexchange.com/users/194/peter-taylor), as I used his idea that good primes could only be a few values mod 60. Again, I have run this on a slow computer in IDLE, so the results may be faster in something like PyPy, but I have not been able to check. A sample of my results (p, q, q-p, time): ``` 8392997 8393999 1002 2.6750288009643555 16814663 16815713 1050 7.312098026275635 33560573 33561653 1080 8.546097755432129 67118027 67119323 1296 10.886202335357666 134245373 134246753 1380 20.37420392036438 268522349 268523813 1464 59.23987054824829 536929187 536931047 1860 95.36681914329529 ``` My code: ``` from time import time small_primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,101,103,107,109,113,127,131,137,139,149,151, 157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239] def good(n=0): end = n or 100 time0 = time() x,y = 0,0 recent_max = 0 for i in range(2,end): two = 2**i for j in range(two+3,2*two,2): m=j%60 if not(m==17or m==23or m==29or m==47or m==53or m==59): continue comp = 0 for p in small_primes: if j % p == 0 and j != p: comp = 1 break for p in range(241,int(pow(j,.5))+1,2): if j % p == 0 and j != p: comp = 1 break if comp: continue d = j-1 & 1-j if is_prime_power((j-1)/d): x,y = y,j if x and y and y-x > recent_max: print(x,y,y-x,time()-time0) recent_max = y-x x,y=0,0 break def is_prime_power(n): for p in small_primes: if n%p == 0: n //= p while n % p == 0: n //= p return n == 1 for p in range(241,int(pow(n,.5))+1,2): if n%p == 0: n //= p while n % p == 0: n //= p return n == 1 return n > 1 good() ``` [Answer] # Go: All Integers: 5112 ``` max |q-p| 5112 q 4278566879 p 4278561767 ``` `good.go`: ``` // Find the largest gap between good primes // https://codegolf.stackexchange.com/questions/65876/ // // We say a prime p is good if p-1 has exactly 2 distinct prime factors. // // Your code should output the absolute difference between consecutive // good primes q and p so that |q-p| is as large as possible and // q is the smallest good prime larger than p. You may output any number of // good pairs and your last output will be taken as the score. // // The timings will be run on a standard Ubuntu install on // an 8GB AMD FX-8350 eight-core processor. // http://products.amd.com/en-us/search/CPU/AMD-FX-Series/AMD-FX-8-Core-Black-Edition/FX-8350/92 // // I will kill your code after 2 minutes unless it starts to // run out of memory before that. It should therefore make sure to // output something before the cut off. // // A067466 Primes p such there are 2 distinct prime factors in p-1. // https://oeis.org/A067466 // // 7, 11, 13, 19, 23, 29, 37, 41, 47, 53, 59, 73, 83, 89, 97, 101, 107, ... // // peterSO: max |q-p| 5112 q 4278566879 p 4278561767 // https://codegolf.stackexchange.com/a/73770/51537 // // p is a good prime number, if // // p-1 = x**a * y**b // // Where p is a prime number, x and y are are distinct prime numbers, // and a and b are positive integers. // // For p > 2, p is odd and (p-1) is even. Therefore, either x or y = 2. package main import ( "fmt" "math" "runtime" "time" ) var start = time.Now() const ( primality = 0x80 prime = 0x00 notprime = 0x80 distinct = 0x7F ) func oddPrimes(n uint64) (sieve []uint8) { // odd prime numbers sieve = make([]uint8, (n+1)/2) sieve[0] = notprime p := uint64(3) for i := p * p; i <= n; i = p * p { for j := i; j <= n; j += 2 * p { sieve[j/2] = notprime } for p += 2; sieve[p/2] == notprime; p += 2 { } } return sieve } func maxGoodGap(n uint64) { // odd prime numbers sieve := oddPrimes(n) // good prime numbers fmt.Println("|q-p|", " = ", "q", "-", "p", ":", "t") m := ((n + 1) + 1) / 2 var max, px, qx uint64 for i, s := range sieve { if s == prime { p := 2*uint64(i) + 1 if p < m { // distinct odd prime number factors for j := p + 2*p; j <= m; j += 2 * p { sieve[j/2]++ } } // Remove factors of 2 from p-1. p1 := p - 1 for ; p1&1 == 0; p1 >>= 1 { } // Does p-1 have exactly 2 distinct prime factors? // That is, one distinct prime factor other than 2. if sieve[p1/2]&distinct <= 1 { // maximum consecutive good prime gap px, qx = qx, p if max < qx-px { max = qx - px if px != 0 { fmt.Println(max, " = ", qx, "-", px, " : ", time.Since(start)) } } } } } } func init() { runtime.GOMAXPROCS(1) } func main() { // Two minutes: max |q-p| 5112 q 4278566879 p 4278561767 var n uint64 = math.MaxUint32 // 4294967295 fmt.Println("n =", n) maxGoodGap(n) fmt.Println("n =", n, "real =", time.Since(start)) } ``` Output: ``` $ go build good.go && ./good n = 4294967295 |q-p| = q - p : t 4 = 11 - 7 : 18.997478838s 6 = 29 - 23 : 19.425839298s 8 = 37 - 29 : 19.5924487s 14 = 73 - 59 : 20.351329953s 24 = 137 - 113 : 21.339752269s 30 = 227 - 197 : 22.310449147s 32 = 433 - 401 : 23.511560468s 48 = 557 - 509 : 23.904677275s 50 = 769 - 719 : 24.518310365s 54 = 1283 - 1229 : 25.350700584s 60 = 1697 - 1637 : 25.782520338s 90 = 1823 - 1733 : 25.883049102s 108 = 2417 - 2309 : 26.300049556s 120 = 3329 - 3209 : 26.735575056s 126 = 4673 - 4547 : 27.190597227s 132 = 5639 - 5507 : 27.420936586s 186 = 7433 - 7247 : 27.761805597s 222 = 8369 - 8147 : 27.909656781s 258 = 16487 - 16229 : 28.710626512s 270 = 32507 - 32237 : 29.469193619s 294 = 34157 - 33863 : 29.525197303s 306 = 35879 - 35573 : 29.578355515s 324 = 59393 - 59069 : 30.11620771s 546 = 60293 - 59747 : 30.131928104s 570 = 145823 - 145253 : 31.014864294s 588 = 181157 - 180569 : 31.223246627s 756 = 222059 - 221303 : 31.415507367s 780 = 282617 - 281837 : 31.640006297s 930 = 509513 - 508583 : 32.169485481s 1044 = 1046807 - 1045763 : 32.783669616s 1050 = 1713599 - 1712549 : 33.186784964s 1080 = 1949639 - 1948559 : 33.290533456s 1140 = 2338823 - 2337683 : 33.434568615s 1596 = 3800999 - 3799403 : 33.810580195s 1686 = 6249743 - 6248057 : 34.183678793s 1932 = 12464909 - 12462977 : 34.683651976s 2040 = 30291749 - 30289709 : 35.296022077s 2160 = 31641773 - 31639613 : 35.325773748s 2190 = 34808447 - 34806257 : 35.390646164s 2610 = 78199097 - 78196487 : 35.878632519s 2640 = 105072497 - 105069857 : 36.018381898s 2754 = 114949007 - 114946253 : 36.058571726s 2862 = 246225989 - 246223127 : 36.337844257s 2910 = 255910223 - 255907313 : 36.351442541s 2946 = 371348513 - 371345567 : 36.504506082s 3084 = 447523757 - 447520673 : 36.60250012s 3180 = 466558553 - 466555373 : 36.626346413s 3198 = 575713847 - 575710649 : 36.761306175s 3240 = 606802529 - 606799289 : 36.799984807s 3330 = 784554983 - 784551653 : 37.014430956s 3486 = 873632213 - 873628727 : 37.121270926s 3588 = 987417437 - 987413849 : 37.25618423s 3900 = 1123404923 - 1123401023 : 37.417362803s 3942 = 1196634239 - 1196630297 : 37.504784859s 4032 = 1247118179 - 1247114147 : 37.565187304s 4176 = 1964330609 - 1964326433 : 38.39652816s 4224 = 2055062753 - 2055058529 : 38.502515034s 4290 = 2160258917 - 2160254627 : 38.625633674s 4626 = 2773400633 - 2773396007 : 39.324109323s 5112 = 4278566879 - 4278561767 : 41.022658954s n = 4294967295 real = 41.041491885s $ ``` For comparison: peterSO max 5112 in 41.04s versus The Coder max 4176 in 51.97s. [Coder: max |q-p| 4176 q 1964330609 p 1964326433](https://codegolf.stackexchange.com/a/66915) Output: ``` $ javac coder.java && java -Xmx1G coder Total Primes upto 2147483646 = 105097564 in 11.61 s (11 - 7) 4 (11.64 s) << SNIP >> (1247118179 - 1247114147) 4032 (34.86 s) (1964330609 - 1964326433) 4176 (51.97 s) $ ``` ]
[Question] [ What general tips do you have for golfing in Go? I'm new to Code Golfing and looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Go. Please keep to one tip per answer. [Answer] Inspired by @EMBLEM's answer [here](https://codegolf.stackexchange.com/a/75569/53406). You can put a package's functions in the global namespace when you import them like so: ``` package main import ."fmt" func main() { Printf("Hello World!") } ``` [Answer] Named return values can save a few bytes. For example: ``` func x()string{ r:="" //Do stuff return r} ``` You can save 3 bytes with ``` func x()(r string){ //Do stuff return} ``` It's more useful if you need to declare multiple variables at the start of your function. [Answer] You can name packages whatever you like when you import them. ``` package main import f "fmt" func main() { f.Printf("Hello World\n") } ``` Learned this [here](https://stackoverflow.com/a/1727139/3161525). [Answer] If you need to compare many different values to a single one, it may be more space-efficient to use a `switch` with a single case. ``` if x==1||x==2||x==3||x==4{} switch x{case 1,2,3,4:} ``` [Answer] Go compiler has predefined `print` and `println` functions that don't require importing fmt, so instead of this. ``` package main import."fmt" func main(){Printf(`Hello World `)} ``` You can write this. ``` package main func main(){print(`Hello World `)} ``` Note that this outputs to STDERR. [Answer] Go has different operator precedence for bit operations, `<<`, `>>`, `&`, etc. usually have lower precedence than `+` and `-` in most languages, but in Go they have the same precedence as `*` and `/`. ``` Precedence Operator 5 * / % << >> & &^ 4 + - | ^ 3 == != < <= > >= 2 && 1 || ``` This could be used to save some parentheses. Most languages: ``` (a&b)*c ``` Go: ``` a&b*c ``` [Answer] A lot of stuff in the for range loop is optional. Standard version: ``` for i,v:=range a{ // Do stuff } ``` If `i`, `v` has already been defined and can be overwritten: ``` for i,v=range a{ // Do stuff } ``` If you don't care about value: ``` for i:=range a{ // Do stuff } ``` If you don't care about value and `i` has already been defined: ``` for i=range a{ // Do stuff } ``` If you don't care about index or value: ``` for range a{ // Do stuff } ``` If you want an infinite loop: ``` for{ // Do stuff } ``` [Answer] Need a string to contain a newline? Don't write `\n`, create a raw string with backquotes and put a literal newline in it. ``` s:="\n" // 7 bytes s:=` ` // 6 bytes ``` [Answer] Declaring Multiple Variables: ``` i,s:=0,"" var(i int;s string) ``` Int From String Conversion: (limited but sometimes helpful) ``` n:=byte("9"[0])-48 // actual type is uint8 n,_:=strconv.Atoi("9") ``` And Vice Versa ``` s:=string(9+48) s:=strconv.Itoa(9) ``` [Answer] ### When looping a constant `n` times, `for-range` is shorter up to `n <= 5` If you need to loop a constant number of times, a `for range"..."{}` loop (where `...` is `n` characters) is shorter than a 3-part for loop up to `n <= 5` iterations. The two loop forms are equivalent at `n == 5`: ``` for range`|||||`{} for i:=0;i<5;i++{} ``` Past `n > 5`, use a 3-part loop. [Answer] You can put any number of opening braces on one line, but a line that contains opening braces may contain at most one closing brace. Correct: ``` func main(){if true{switch{case 1==1:for{break }}}} ``` Also correct: ``` func main(){if true{switch{case 1==1:for{break} }}} ``` Also correct: ``` func main(){if true{switch{case 1==1:for{ break}}}} ``` Incorrect: ``` func main() { if true{for{break}} } ``` [Answer] Since [an allowable output format is writing to reference arguments](https://codegolf.meta.stackexchange.com/a/4942/88456), it may save bytes to pass a pointer instead of returning a value. ``` func f(a,b string)string{if g(a)>g(b){return a};return b} func f(a,b string, s*string){s=&b;if g(a)>g(b){s=&a}} ``` [Answer] If you're using a C-style 3-part for-loop, if your loop variable isn't dependent on something outside of its scope for its initialization, declare it with your other variable declarations to save a byte. In these examples, `i` is initialized independently of `a` ``` func f(){a:=3;for i:=0;i<a;i++{}} // vs func f(){a,i:=3,0;for;i<a;i++{}} ``` [Answer] When taking a single character substring from a string and want to keep it as a string, use string slices to not get a rune: ``` string(s[0]) // 12 bytes s[:1] // 4 bytes string(s[10]) // 13 bytes s[10:11] // 8 bytes string(s[100]) // 14 bytes s[100:101] // 10 bytes string(s[1000]) // 15 bytes s[1000:1001] // 12 bytes string(s[10000]) // 16 bytes s[10000:10001] // 14 bytes ``` This method is shorter than `string(s[index])` up to getting from index `100000` and above, but indexing strings of that size are rare. [Answer] Don't declare variables in the `for`'s init statement: ``` for i:=0;i<n;i++{...} ``` By declaring it outside you may save a byte when you need a variable outside of it beacause you can now assign to it (`=`) instead of declaring it (`:=`): ``` i:=0 for;i<n;i++{...} i=0 for;i<n;i++{...} ``` You might even save a byte if you're not using the `for`'s post-statement by removing the semicolons [Answer] Make full use of Go's first-class functions by assigning long library function names to one-letter variables. ``` import."strings" r:=Replace ``` [Answer] # Shuffle elements with `rand.Perm` I discovered `math/rand.Perm` the other day, which returns a slice of integers from 0 to `n`, shuffled. ### For strings Given an input string `k`, and you need to return a string, and we have that string as a named return, `Perm` is shorter because you don't need to real with the boilerplate for `Shuffle` or the swapping: ``` Shuffle(len(k),func(i,j int){k[i],k[j]=k[j],k[i]}) // 48 bytes for i:=range k{j:=Intn(i);k[i],k[j]=k[j],k[i]} // 44 bytes, -4, no separate string needed for i:=range Perm(len(k)){e+=k[i:i+1]} // 36 bytes, -12 ``` ### For slices Assuming the same conditions as above but with a slice, it is still shorter: ``` Shuffle(len(k),func(i,j int){k[i],k[j]=k[j],k[i]}) // 48 bytes for i:=range k{j:=Intn(i);k[i],k[j]=k[j],k[i]} // 44 bytes, -4, no separate slice needed for i:=range Perm(len(k)){e=append(e,k[i])} // 41 bytes, -7 ``` [Answer] ## Use `min` and `max` to clamp values (Go 1.21+) Say you have 2 comparables `l` and `h`, where you must satisfy `l <= h`. It is 1 byte shorter to use the builtins than an if-statement. ``` // assuming l,h := n, 0 if h<l{h=l} h=max(h,l) if l>h{l=h} l=min(h,l) // and the opposite l,h := 0, n if h>l{h=l} h=min(h,l) if l<h{l=h} l=max(h,l) ``` ]
[Question] [ In this challenge, you will be given a text block, and you need to perform reflection on the text. # Input: 1. A string to be reflected. The text may *not* be supplied as an array whose elements are the lines of text. For example, `"ab\ncd"` and `['a','b','\n','c','d']` are allowed, but `['ab','cd']` or `[['a','b'],['c','d']]` are not. You can assume that all of the lines have the same number of characters (padded with whitespace where needed). 2. A boolean where `True` indicates Y reflection and `False` indicates X reflection The two inputs can be passed in any order. # Output: The reflected string. The characters do not change, only their position. The resulting image block should be aligned to the top left (the first row and column must each contain a non-whitespace character). Trailing whitespace (on any of the lines) is allowed. # Test cases: ``` False o / --|/ | / \ / o /|-- | \ / ``` --- ``` True o / --|/ | / \ / \ | --|/ o / ``` --- ``` True text text ``` --- ``` False text txet ``` --- ``` True P P C G G C P P ``` --- ``` False P P C G P P C G ``` --- ``` True abcde fghij kl mn opqrs tuvwx tuvwx opqrs kl mn fghij abcde ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so answer with the shortest answer in your favorite language! [Answer] ## C#, ~~168~~ ~~144~~ ~~141~~ 120 Bytes ``` using System.Linq;i=>y=>string.Join("\n",y?i.Split('\n').Reverse():i.Split('\n').Select(x=>string.Concat(x.Reverse()))); ``` New version utilizes the obvious string.Join overload that takes an IEnumerable, the first solution was using it inadvertently I was just able to use it for the else side of the ternary as well. ### Update: New version is an anonymous lambda and uses currying to save 21 bytes total. This changes usage to be `f("text")(false)` where f is the anonymous function. ### Ungolfed: ``` using System.Linq; //Using currying to save one byte input => IsYReflect => //Lambda makes return implicit string.Join("\n", IsYReflect //Y Reflect, just need to reverse the array ? input.Split('\n').Reverse() //X Reflect, reverse each line into an IEnumerable : input.Split('\n').Select(x => string.Concat(x.Reverse()))); ``` [Answer] ## Pyke, 7 bytes ``` !I_)ncX ``` [Try it here!](http://pyke.catbus.co.uk/?code=%21I_%29ncX&input=1%0A%22++o+%2F%5Cn--%7C%2F+%5Cn++%7C++%5Cn+%2F+%5C%5C+%22&warnings=0) ``` !I ) - if not boolean: _ - input = reversed(input) nc - input.split("\n") X - splat(input) - (print lines backwards) ``` [Answer] # Brainfuck, ~~143~~ ~~140~~ 131 bytes ``` ,[,[---------->+<[>-]>[->]<,]<[[<]>[++++++++++.>]++++++++++.<[<]<]],[---------->+<[++++++++++>-]>[-<<[.<]++++++++++.[>]>>]<,]<[.<] ``` Beat~~s~~ C#. The challenge was easy enough for Brainfuck, and I apparently was tired enough to just have to do it. Takes the boolean as a `0x00` (falsy) or any other (truthy) byte in the start of the input, then a rectangle-padded string. Outputs a trailing newline for the Y flip, and none for the X flip. Requires an interpreter that supports memory locations to the left of the start (unsure if still required) and gives EOF as `0x00`. One such interpreter is [here](http://www.iamcal.com/misc/bf_debug/). Obviously doesn't support null bytes in the input because of that. The code has a lot of blocks with 10 `+`'s or `-`'s; those can probably be reduced. ### Commented version ``` , get mode [ check truthy input ,[ loop thru input ---------- subtract newline >+ set flag < go back to char [ was not newline > move to flag - reset flag ] > move to flag or one past flag [ hit flag; was newline - reset flag > skip a cell ] < go to next position , read next input ] < find end of line [ loop thru lines [<]> find start of line [ loop thru line ++++++++++ add newline back . print this cell > go to next cell ] ++++++++++ change to newline . print newline <[<]< find end of previous line ] ] ,[ loop thru any input left ---------- subtract newline >+ set flag < go back to char [ was not newline ++++++++++ add newline back > move to flag - reset flag ] > move to flag or one past flag [ hit flag; was newline - clear flag < go back to char < go back to line chars [ loop thru line . print this cell < go to previous cell ] ++++++++++. print newline [>]>> find empty cell ] < go to next position , read next input ] < go to line [ loop thru line . print this cell < go to previous cell ] ``` [Answer] # 32-bit x86 machine code, 76 bytes In hex: ``` 31c031c9495789f7fcf2aef7d15192b00a89f7f2ae5829f7f7f787f95f4b89c3741287d94b534b8a041eaa75f95b01dea4e2f2c348f7e101c6b00a5651f3a4595e29ce4f4b0f44c3aa75f0c3 ``` Input: `EBX`: direction flag (0/1), `ESI`: input string, `EDI`: output buffer. Input is required to be rectangular. ``` 0: 31 c0 xor eax,eax ;EAX=0 2: 31 c9 xor ecx,ecx 4: 49 dec ecx ;ECX=(uint)-1 5: 57 push edi 6: 89 f7 mov edi,esi 8: fc cld 9: f2 ae repne scasb ;Scan input string for terminating NULL b: f7 d1 not ecx ;ECX==<input string length (including NULL)> d: 51 push ecx e: 92 xchg edx,eax ;EDX=0 f: b0 0a mov al,0x0a ;'\n' 11: 89 f7 mov edi,esi 13: f2 ae repne scasb ;Scan input string for the first newline 15: 58 pop eax ;EAX==<input string length (including NULL)> 16: 29 f7 sub edi,esi ;EDI==<single line length (including '\n')> 18: f7 f7 div edi ;EAX==<# of lines> 1a: 87 f9 xchg ecx,edi ;ECX=EDI 1c: 5f pop edi ;EDI=<dest buffer> 1d: 4b dec ebx ;Test input flag (0/1) 1e: 89 c3 mov ebx,eax ;EBX=<# of lines> 20: 74 12 je _vertical 22: 87 d9 xchg ecx,ebx ;Horisontal flip, exchange ECX & EBX so we can use LOOP 24: 4b dec ebx ;EBX=<single line length (excluding '\n')> _hfouter: 25: 53 push ebx _hfinner: 26: 4b dec ebx ;Decrement inner loop counter 27: 8a 04 1e mov al,[esi+ebx] ;AL=ESI[EBX] 2a: aa stosb ;*EDI++=AL 2b: 75 f9 jne _hfinner ;EBX==0 => break 2d: 5b pop ebx 2e: 01 de add esi,ebx ;*ESI=='\n' (\0 on the last line) 30: a4 movsb ;*EDI++=*ESI++, ESI now points to the next line 31: e2 f2 loop _hfouter ;--ECX==0 => break 33: c3 ret ;Nothing more to do here _vertical: 34: 48 dec eax ;# of strings less one 35: f7 e1 mul ecx ;Line length (including '\n') 37: 01 c6 add esi,eax ;ESI+=ECX*(EAX-1), ESI now points to the beginning of the last line 39: b0 0a mov al,0x0a ;'\n' _vfloop: 3b: 56 push esi 3c: 51 push ecx 3d: f3 a4 rep movsb ;Copy the whole line to the output including newline/NULL at the end 3f: 59 pop ecx 40: 5e pop esi 41: 29 ce sub esi,ecx ;Set ESI to the beginning of the previous line 43: 4f dec edi ;*EDI=='\n' (0 on the first iteration), should overwrite it with correct value 44: 4b dec ebx ;Decrement loop counter 45: 0f 44 c3 cmove eax,ebx ;if (EBX==0) EAX=EBX, this clears EAX on the last iteration 48: aa stosb ;*EDI++=EBX?'\n':0 49: 75 f0 jne _vfloop ;EBX==0 => break 4b: c3 ret ``` [Answer] ## Haskell, ~~51~~ ~~49~~ 45 bytes ``` r=reverse f b=unlines.last(map r:[r|b]).lines ``` Usage example: ``` f True "abc\ndef\nghi\njkl" "jkl\nghi\ndef\nabc\n" f False "abc\ndef\nghi\njkl" "cba\nfed\nihg\nlkj\n" ``` Split into lines, either reverse the lines (True) or reverse each line (False) and join into a single string again. In case of a `True` input, `map r:[r|b]` is a list of two functions `[<reverse each line>, <reverse lines>]` and for a `False` input a list with one function `[<reverse each line>]`. `last` picks the last element of this list. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṣ⁷ṚU⁴?j⁷ ``` [Try it here.](http://jelly.tryitonline.net/#code=4bmj4oG34bmaVeKBtD9q4oG3&input=MA&args=YWJjCmRlZgpnaGk+MQ) ``` ṣ⁷ Split over newlines. ṚU⁴? If ⁴ (2nd argument), then Ṛ (reverse rank ∞), else U (reverse rank 1). j⁷ Join with newlines. ``` [Answer] # Python, 56 bytes ``` lambda s,r:'\n'.join(s[::2*bool(r)-1].split('\n')[::-1]) ``` Call with a string `s` and any truthy/falsey value `r`. [Answer] # Python 3.5, 61 bytes: ``` lambda f,j:[print(r[::-1])for r in j[::[1,-1][f]].split('\n')] ``` A simple anonymous lambda function that assumes rectangular input. Call it by by first naming the function, and then calling it wrapped inside `print()`. In other words, if the function were named `H`, call it like `print(H(<Bool value>, <String>))`, where `<Bool Value>` is any true or false value (i.e. `0/1`, `true/false`, etc.) and `<String>` is the input string. [See it in Action! (repl.it)](https://repl.it/CbmC/2) Here is another version with the same length that also assumes rectangular input, but this time a *named* function, i.e. you don't have to name it first nor wrap it inside `print()`: ``` def J(f,j):[print(r[::-1])for r in j[::[1,-1][f]].split('\n')] ``` Simply call this one like`J(<Bool Value>,<String>)`. [See this in Action! (repl.it)](https://repl.it/CbmK/0) However, I'm not the one to stop there. Although we are allowed to assume rectangular input, I also created a version that does *not* assume that type of input. Therefore, it will space-pad all of the lines to the same length based on the line with the maximum length if and only if the `<Bool>` input is `False`, as only a X-reflection will result in the string being "flipped". Now, without further ado, here is the non-rectangular assuming version with a length of **~~134~~ 129 bytes** in the form of a normal function: ``` def J(f,j):print('\n'.join([' '*((max([len(i)for i in j.split('\n')])-len(r))*(not f))+r[::-1]for r in j[::[1,-1][f]].split('\n')])) ``` [See this Last One in Action! (repl.it)](https://repl.it/CbmV/1) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~26~~ ~~24~~ 16 bytes ``` t1,?h@nr~@nw|hrw ``` Expects a list containing the string and the boolean `1` or `0`, e.g. ``` run_from_file('code.bl',["P | P | C | G":1]). ``` ### Explanation ``` t1, If the tail of the input is 1 ?h@n Split the string on \n r Reverse the resulting list ~@n Join the list of strings with \n w Write to STDOUT | Or hr Reverse the string w Write to STDOUT ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` 10&Ybc2i-&P ``` [**Try it online!**](http://matl.tryitonline.net/#code=MTAmWWJjaX5RJlA&input=WycgJywgJyAnLCAnbycsICcgJywgJy8nLCAnICcsIDEwLCAnLScsICctJywgJ3wnLCAnLycsIDEwLCAnICcsICcgJywgJ3wnLCAnICcsIDEwLCAnICcsICcvJywgJyAnLCAnXCddCjE) The **first input** is the multiline string. Since MATL doesn't recognize `\n` as linefeed, the multiline string should be defined as a concatenation of substrings, or individual characters, and `10` (ASCII for line feed, which is interpreted as a character). Concatenation in MATL is `[... ...]` or `[..., ...]` (commas are optional). So for example, input can be as follows (concatenation of a string, linefeed, and another string): ``` ['first line' 10 'second'] ``` or equivalently (concatenation of individual characters) ``` ['f' 'i' 'r' 's' 't' ' ' 'l' 'i' 'n' 'e' 10 's' 'e' 'c' 'o' 'n' 'd'] ``` or (same with commas) ``` ['f', 'i', 'r', 's', 't', ' ', 'l', 'i', 'n', 'e', 10, 's', 'e', 'c', 'o', 'n', 'd'] ``` The **second input** can be entered as `1`/`0` or equivalently as `T`/`F` for `true`/`false` respectively. ### Explanation ``` 10 % Push 10 (ASCII for linefeed) &Yb % Take input string implicitly. Split at linefeeds. Gives a cell array c % Convert to a 2D char array, right-padding with spaces i~Q % Input Boolean value. Negate and add 1. Gives 1/2 for true/false resp. &P % Flip along that dimension (1: vertically; 2: horizontally). Display implicitly ``` [Answer] # Julia, 59 bytes ``` x\y=(y=split(y,' ');! =reverse;join(x?!y:[!a for a=y],' ')) ``` [Try it online!](http://julia.tryitonline.net/#code=eFx5PSh5PXNwbGl0KHksJwonKTshID1yZXZlcnNlO2pvaW4oeD8heTpbIWEgZm9yIGE9eV0sJwonKSkKcHJpbnQodHJ1ZVwiYWJjZGUKZmdoaWoKa2wgbW4Kb3BxcnMKdHV2d3giKQ&input=) [Answer] # Pyth, 10 bytes ``` j?Q_.z_M.z ``` [Test suite.](http://pyth.herokuapp.com/?code=j%3FQ_.z_M.z&test_suite=1&test_suite_input=True%0Aab%0Acd%0AFalse%0Aab%0Acd%0A&debug=0&input_size=3) ``` j?Q_.z_M.z first line evaluated as Q, all other lines as .z ?Q if Q: _.z yield reverse(.z) _M.z else: yield map(reverse, .z) j join by newlines ``` [Answer] ## Perl, 35 bytes **34 bytes code + 1 for `-n`.** Requires the input lines be padded with spaces. 13 (!) bytes saved thanks to @[Dada](https://codegolf.stackexchange.com/users/55508/dada). ``` print/T/?reverse<>:map~~reverse,<> ``` ### Usage ``` perl -ne 'print/T/?reverse<>:map~~reverse,<>' <<< 'False o / --|/ | / \ ' / o /|-- | \ / perl -ne 'print/T/?reverse<>:map~~reverse,<>' <<< 'True o / --|/ | / \ ' / \ | --|/ o / ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~9~~ ~~11~~ 9 bytes (SBCS) Fixed answer ~~but only had to add 2 bytes~~ and kept it the same length thanks to @[Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m) ``` ⌽[⎕]⎕FMT⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862tP@P@rZGw0UigViN98QIPkfKPy/CKgAyA51DlYwNObKL8pMz8xLzFEAiiqoKyjkK@ir6xTpqOvq1ugrgFkKCjUKUJa@QoyCOpe6P1SPOlw3l3pIUWlJRqU6VxpCzJBL3S0xpxhV0AAA "APL (Dyalog Unicode) – Try It Online") Takes a character vector using `\r` as a separator through STDIN first, then 1 or 0. Requires 0-indexing. `⎕` accepts input. `⎕FMT` formats it into a character matrix because of `\r`. `⌽[⎕]` reflects that over either the x- or y-axis, depending on the second input. With 0-indexing, `⌽[0]` or just `⌽` reflects over the x-axis, `⌽[1]` or `⊖` over the y-axis. [Answer] # Bash + common linux utils, 16 ``` (($1))&&tac||rev ``` Boolean value (zero or non-zero) passed as a command-line parameter. I/O of text block via STDIN/STDOUT. Assumes that all lines are the same length, as [indicated in the comments](https://codegolf.stackexchange.com/questions/85363/ascii-art-reflection#comment209483_85363). [Answer] # C (Ansi), 193 Bytes ## Golfed: ``` i,y,x;main(g,o,p)char**o;{p=(o[1][0]=='t');while(o[2][++i]!='\n');p?y=(strlen(o[2])-1)/i:(x=i);do do printf("%c",o[2][x+y*i]);while(p?++x<i:x-->0);while(p?x=0,y--:++y<(x=i-1,strlen(o[2])/i));} ``` ## Ungolfed: ``` i,y,x; main(g,o,p)char**o;{ p=(o[1][0]=='t'); while(o[2][++i]!='\n'); p?y=(strlen(o[2])-1)/i:(x=i); do{ do{ printf("%c",o[2][x+y*i]); }while(p?++x<i:x-->0); }while(p?x=0,y--:++y<(x=i-1,strlen(o[2])/i)); } ``` ## Usage: ### Compilation Arguments: ``` gcc -O3 -ansi ``` ### Example Input: Input is a t or not t for true of false followed by a newspace lead and trailed string. ``` ./reverseString t " truck ducky quack moose " ``` ### Example Output: ``` moose quack ducky truck ``` [Answer] # JavaScript (ES 6) 83 bytes ``` (c,b)=>(p=c.split` `)&&(b?p.reverse():p.map(a=>a.split``.reverse().join``)).join` ` ``` --- ``` f=(c,b)=>(p=c.split` `)&&(b?p.reverse():p.map(a=>a.split``.reverse().join``)).join` ` f("abcde\nfghij\nkl mn\nopqrs\ntuvwx",1) c=" o / --|/ | / \ "; f(c,1) " / \ | --|/ o / " f(c,0) "/ o /|-- | \ / " ``` [Answer] # J, 29 bytes ``` }:@,@(,.&LF@{|."1,:|.)>@cutLF ``` LHS input is the boolean where 0 is false and 1 is true. RHS is the string input. [Answer] # Java 99 bytes ``` public String[] reverse(String[]a){ int i=-1,j=a.length; for(;++i<--j;){ String b=a[i]; a[i]=a[j]; a[j]=b; } return a; } ``` Golfed: ``` String[] e(String[]a){int i=-1,j=a.length;for(;++i<--j;){String b=a[i];a[i]=a[j];a[j]=b;}return a;} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` U|XiRë€R}» ``` # Explanation ``` U Remove the first input line and store it in variable X | Aggregate the rest of the input into an array XiR If x is true, revert the array ë€R Else revert each element } End if » Join everything with newlines and implicitly display ``` [Try it online!](https://tio.run/nexus/05ab1e#@x9aE5EZdHj1o6Y1QbWHdv//b8iVmJScksqVlp6RmcWVnaOQm8eVX1BYVMxVUlpWXgEA "05AB1E – TIO Nexus") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes ``` θ¿η‖↓‖ ``` Link is to verbose version of code. [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRKNQUyEzTSNDUyEoNS0nNblEw8olvzxPUyE1pzgVJvb/f7SSgkK@gn5Mnq5uDZBUUKgBEvoKMTFKOoax/3VzygA "Charcoal – Try It Online") [Answer] ## Mathematica, 70 bytes ``` If[#,Reverse,StringReverse]@ImportString[#2,l="Lines"]~ExportString~l& ``` Anonymous function, takes a boolean value as first argument (explicitly `True` or `False` in Mathematica) and the (multiline) string as the second argument. Imports the string as a list of strings corresponding to the lines of the multiline string (the string is NOT passed to the function as an array). If `True`, reverse the list. If `False` `StringReverse` the list, which automatically is applied to each element in turn. Then export the list as a string, where each element is a new line. [Answer] # JavaScript (ES6), 76 ``` s=>b=>(s=s.split` `,b?s.reverse():s.map(r=>[...r].reverse().join``)).join` ` ``` ``` F=s=>b=>(s=s.split` `,b?s.reverse():s.map(r=>[...r].reverse().join``)).join` ` function test() { var rows=I.value, r // Trim trailing newlines, pad to blank rows=rows.split('\n') while(!(r=rows.pop())); rows.push(r) var maxlen=Math.max(...rows.map(r=>r.length)) rows=rows.map(r=>r+' '.repeat(maxlen-r.length)).join`\n` var t1=F(rows)(false) var t2=F(rows)(true) O.textContent = 'False\n'+t1+'\n\nTrue\n'+t2 } test() ``` ``` #I { width:50%; height:10em } ``` ``` <textarea id=I> o / --|/ | / \ </textarea> <button onclick=test()>Go</button> <pre id=O></pre> ``` [Answer] # Vim, 33 bytes Changed previous V answer to Vim. Any V answer would be way different, so it wasn't really fair. ``` DgJ:if@" g/^/m0 el se ri en cG" ``` [Try it online!](https://tio.run/nexus/v#@@@S7mWVmeagxJWuH6efa8CVmsNVnKpQlMmVmseV7C6kxPH/vyGXgkK@gj6Xrm6NvgKQXaMAJPUVYhQA "V – TIO Nexus") Hexdump ``` 00000000: 4467 4a3a 6966 4022 0a67 2f5e 2f6d 300a DgJ:if@".g/^/m0. 00000010: 656c 0a73 6520 7269 0a65 6e0a 6347 1222 el.se ri.en.cG." 00000020: 08 . ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` |ćiRëí}» ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/5kh7ZtDh1YfX1h7a/f@/AZeCQr6CPpeubo2@ApBdowAk9RViFAA "05AB1E – Try It Online") ``` |ćiRëí}» # full program » # join... | # list of lines in input... ć # excluding the first element... R # reversed... i # if... ć # first element of... | # list of lines in input... i # is truthy... ë # else... í # with each element in list reversed... » # by newlines } # end if statement # implicit output ``` ]
[Question] [ If you are unfamiliar with hacker typer, see [hackertyper.net](http://hackertyper.net). In short, it is a program that outputs one chunk of a code base per keystroke for comedic effect. BUT, the hackertyper.net version is far too easy to implement. It simply outputs three characters at a time from an *arbitrary* piece of code. For this challenge, a program must output its own source code, and print one *space delimited* chunk of code per keystroke. ## Details * One cannot hard code a file name for the program; it must determine its name dynamically. If the program compiles to an executable, it may append the standard file extension to the name of the executable (excluding the .exe if using Windows) and assume that the source file is within the executable's directory. For example, if a C executable is named "hacker", it should pull its source code from a file named "hacker.c" in its same directory. If a compiled program has an extension, it should be dropped before determining the name of its source code ("typer.exe" -> "typer.cs"). * Programs must contain at least 5 spaces, with at least one character between each space. This means that the smallest possible size for this challenge is 9 bytes. The spaces do not have to be crucial to the functioning of the program. * Any formatting (indentation, new lines, etc.) must be maintained in the output. This formatting may either be printed with the code that proceeds it or follows it, what matters is that the formatting be maintained. * Avoid using comments to satisfy the 5 space requirement unless there is no other way to implement the spaces in your language of choice. **EDIT**: New lines can be used in place of, or in addition to, spaces as chunk separators. [Answer] ### HTML & JavaScript, 123 ``` <head></head><body onload="s=(a=document.all)[i=0].innerHTML" onkeyup="a[2].textContent += s.split(/(?= )/)[i++%6]"></body> ``` This works similarly to hacker typer, but with its own source code. Let me know if I've misunderstood the rules. And here's a styled version (170 characters): ``` <head></head> <body style="background:#000;color:lime" onload="s=(a=document.all)[i=0].innerHTML" onkeyup="a[3].textContent+=s.split(/(?=\s)/)[i++%6]"> <pre></pre></body> ``` I've made a [**demo**](http://jsbin.com/pejexu/1/). It's modified because JS Bin adds a lot of extra code, but the general idea is the same. [Answer] ### bash, 51 58 ``` for w in $(<$0);do read -sn 1;printf -- "$w ";done ``` [Answer] # Perl + Term::ReadKey, 56 bytes ``` use Term'ReadKey;ReadMode 4;open 0;ReadKey,print for <0> ``` Thanks to [ThisSuitIsBlackNot](https://codegolf.stackexchange.com/a/37373) for the original inspiration, and to [primo](https://codegolf.stackexchange.com/questions/37333/create-a-hacker-typer-program-that-renders-its-own-source-code/37381#comment85029_37381) for suggesting `open 0` and `<0>`. Note that the newline after `for` is actually unnecessary, except that I need to include one extra newline *somewhere* to bring the whitespace count up to the specified minimum of five. Also note that, like ThisSuitIsBlackNot's submission, this program requires the [Term::ReadKey](http://search.cpan.org/perldoc?Term%3A%3AReadKey) module from CPAN. On Debian / Ubuntu Linux, this module, if not already present, can be easily installed with the command `sudo apt-get install libterm-readkey-perl`. Also, to save a few characters, this program does not restore the input mode to normal on exit, so you may find yourself unable to see what you're typing afterwards. Executing the shell command `stty sane` or `reset` should fix that. This issue could be fixed, at the cost of 10 extra bytes, with: ``` use Term'ReadKey;ReadMode 4;open 0;ReadKey,print for<0>;ReadMode 0 ``` --- ## Bonus: Pure quine, 81 bytes ``` $_=q{use Term'ReadKey;ReadMode 4;ReadKey,say for split$/, "\$_=q{$_};eval"};eval ``` Again, the newline after the comma is only needed to meet the five whitespace minimum. Unlike the 56-byte program above, this version doesn't actually need to read its own source code, since it's based on a quine — specifically, on this quine: ``` $_=q{say"\$_=q{$_};eval"};eval ``` The nice thing about this quine is that it can easily carry an arbitrary "payload" within the `q{ }` block, without having to repeat it. While it can't quite beat `<0>` in shortness, it does get pretty close. Note: This program uses the Perl 5.10+ `say` feature, and thus needs to be invoked with the `-M5.010` (or `-E`) command line switch. Per established consensus on meta, such switches used to enable modern language features [do not count as extra characters](http://meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions). The shortest solution I can find without `say` is 83 bytes: ``` $_=q{use Term'ReadKey;ReadMode 4;ReadKey,print for split/^/, "\$_=q{$_};eval"};eval ``` Both of these can also be made more terminal-friendly by (joining the last two lines and) inserting: ``` ;ReadMode 0 ``` before the last `}`. [Answer] # Python 3 - 124 bytes - 7 spaces --- Code: ``` from curses import* s=initscr();noecho() for x in open(__file__).read().split(" "):s.getch();s.addstr(x+" ") echo();endwin() ``` Ungolfed: ``` from curses import* # init curses screen=initscr() noecho() # split code into spaces code = open(__file__).read().split(" ") for x in code: # wait for keypress screen.getch() # print a bit screen.addstr(x+" ") # deactivate curses echo() endwin() ``` Styled version: ``` from curses import* s=initscr();noecho();start_color();init_pair(2,COLOR_GREEN,COLOR_BLACK) for x in open(__file__).read().split(" "):s.getch();s.addstr(x+" ",color_pair(2)) echo();endwin() ``` [Answer] # Ruby, 85, 71 ``` require"io/console";f=File.open __FILE__;loop{STDIN.raw &:getc;print f.read(3)||exit} ``` Too bad that `IO#raw` is not part of the standard library. ### Improvement ``` require"io/console";24.times{|q|STDIN.raw &:getc;$><<IO.read($0,3,q*3)} ``` This one eliminates the call to Kernel#exit and uses global variables to shorten the code. [Answer] # Befunge - 21 ``` ~ $ g , 1 +:54*`#@_:0 ``` I'm fairly pleased with this, as I just found out about Befunge. If you don't mind "typing" into a popup window, you can run it [here](http://www.bedroomlan.org/tools/befunge-93-playground) or [here](https://www.ashleymills.com/befunge_applet_full) until I find a better online interpreter. [Answer] ## Powershell, 89 ``` (gc $MyInvocation.MyCommand.Path).split(" ")|%{$l+="$_ ";write-host "$l";read-host ;cls} ``` [Answer] ## Python 3 - 299 ``` a="""from curses import* s=initscr() raw() noecho() for x in e: s.getch() s.addstr(x+' ') nocbreak() echo() endwin() """;b="""e=(a+'a=#%s#;b=#%s#;%s'%(a,b,b.replace('#','""''"',4))+'exec(a)').split(' ') """;e=('a="""%s""";b="""%s""";%s'%(a,b,b.replace('#','""''"',4))+'exec(a)').split(' ') exec(a) ``` Its a quine. Shortened from 507 by using `exec` and moving some statements around. [Answer] # C, 211 186 bytes My solution in C using the curses library. It may be longer than the other C solution, but it is a quine. Although not required by the question, it's still pretty nice. It also works quite nicely: ``` #define R(x)#x #define T(x)R(x) #define S(p)char*s="#define R(x)#x\n#define T(x)R(x)\n#define S(p)"p"\nS(T(S(p)))";main(){initscr();noecho();while(*s)if(~getch())addch(*s++);} S(T(S(p))) ``` A more readable version with some comments and stuff: ``` #define R(x)#x /* macros to convert the source code in S into a C-string */ #define T(x)R(x) #define S(p) char*s="#define R(x)#x\n" \ "#define T(x)R(x)\n" \ "#define S(p) " p "\n" \ "S(T(S(p)))";\ main(){\ initscr();\ noecho(); /* don't echo input */ \ while(*s)\ if(~getch()) /*true if character has been typed */ \ addch(*s++);\ } S(T(S(p))) ``` compile with: ``` gcc -o h h.c -lncurses ``` [Answer] # C - 136 135 132 bytes (Windows only) ``` *fopen();**v;b[ 1<<20];main(p,q){v=q; strcpy(b,*v);strcat(b,".c") ;for(*v=fopen(b,"r");~fscanf(*v,"%s",b);printf("%s ",b))getch();} ``` Note: there is a space at the end of the program, which probably won't show up. I can't guarantee this program will work on a single computer other than my own as it is awesomely hacky. Things would have been a lot simpler back when everyone only had 32-bit machines. Then I would not need to worry about `sizeof(int*)` being 8 (which it definitely is; I printed it out to make sure) while `sizeof(int)` is 4. Happily, the name of the executable is stored in the first string in argv. ~~However, putting a pointer as an argument to a function means that I have to explicitly specify the type of ALL the arguments to the function--meaning I would have to type `int` twice--a huge waste of characters.~~ Fortunately I found a workaround. I had the second argument to main, `q`, be just another int. Then assigning `q` to a variable of type `int**` somehow managed to grab all the necessary bytes from the stack. I was unsuccessful in finding any such tricks to interpret the return type of `fopen` as a pointer without declaring the function. Edit: Noticed I should use `~fscanf(*v,"%s",b)` instead of `fscanf(*v,"%s",b)>0` since the return is -1 when EOF is reached. [Answer] # Perl - 87 bytes ``` #!/usr/bin/perl -040 use Term::ReadKey;open F,$0;ReadMode 3;print''.<F>while ReadKey 0 ``` I didn't see anything in the rules about what to do once the file has been read to the end, so it simply sits waiting for input after printing the last chunk. [Answer] node.js with LiveScript: ``` #!/usr/local/bin/lsc console.log <| require \fs .readFileSync __filename, encoding: \utf8 ``` asynchronous version: ``` #!/usr/local/bin/lsc require \fs .readFile __filename, encoding: \utf8, -> console.log &1 ``` [Answer] # Cobra - 147 ``` class P def main while 1,for a in File.readLines(CobraCore.exePath[:-4]+'.cobra'),print if('[Console.readKey]'and (Console.cursorLeft=0)<1,a,'')* ``` `CobraCore.exePath` is so useful! [Answer] # Javascript ES6, 154 **Firefox 154**: ``` (a= (i=1,b="(a= "+a+")()",s="") => {window.onkeydown=()=>{clear();i=b.indexOf(" ",i+1),d=b.slice(0,i<0?b.length:i);console.log(s+d);if(i<0){i=0,s+=d}}})() ``` **Chrome 175**: ``` ( a= function (i,s){b="( a= "+a+")()";c=console,window.onkeydown=function(){c.clear();s=s||"",i=b.indexOf(" ",i+1),d=b.slice(0,i<0?b.length:i);c.log(s+d);if(i<0){i=0,s+=d}}})() ``` **Both 274**: ``` ( a= function (i,s){b="( a= "+a+")()";c=console,window.onkeydown=function(){(clear)?clear():c.clear?c.clear():0;s=s||"",i=b.indexOf(" ",i+1),d=b.slice(0,i<0?b.length:i);c.log(s+d);if(i<0){i=0,s+=d}}})() ``` **Ungolfed** (chrome): ``` ( a= function (i,s){ // starting index | undefined, output string b="( a= "+a+")()"; // get a string representation of the function c=console, window.onkeydown=function(){ // on each key down event c.clear(); // clear the output s=s||""; i=b.indexOf(" ",i+1); // get the index of next space d=b.slice(0,i<0?b.length:i);// get the string part wanted c.log(s+d); // print the string if(i<0){ i=0, // reset counters s+=d // adding the string to the main output } } })() ``` Has two versions, because Chrome does not handle arrow function and the console is not cleared with the same method The Firefox one work with firebug, it seem that the default developer console can't be cleared from a script. [Answer] ## C, 248 characters **True quine** Only works in unix, in windows it would be implemented using \_getch. ``` main(){char *p="main(){char *p=\"%s\",s[400];sprintf(s,p,p);system(\"stty raw\");for(p=s;*p!=0;putchar(*p++))getchar();system(\"stty cooked\");}",s[400];sprintf(s,p,p);system("stty raw");for(p=s;*p!=0;putchar(*p++))getchar();system("stty cooked");} ``` [Answer] # Groovy - 379 ``` import java.nio.file.* Path p = Paths.get(System.getProperty("user.dir")) DirectoryStream<Path> f = Files.newDirectoryStream(p,"*.groovy") try{for(e in f){read(e.toAbsolutePath().toString())}} catch(Exception e){ } finally{f.close()} void read(String x){ def s = new File(x).text for(e in s.replace("%n"," %n").split(" ")) print e + " " Thread.sleep(200) } ``` Since there is no `getch()` or equivalent in Java and Java-esque languages like Groovy... basically my code doesn't handle keypresses. That's all :D [Answer] # HTML and Javascript, 232 bytes ``` <body><script>var n=0;var f=function (){document.onkeypress=function(){document.body.innerHTML+=("&lt;body>&lt;script>var n=0;var f="+f.toString()+"f()&lt;/script>&lt;/body>").split(" ")[n]+" ";n++;}};f()</script></body> ``` The traditional Javascript quine, but modified. JSFiddle [here](http://jsfiddle.net/fog3vc1z/). [Answer] # SmileBASIC, ~~79~~ 75 bytes ``` LOAD"PRG1:"+PRGNAME$() PRGEDIT 1 @L IF BUTTON(2)THEN?PRGGET$(); WAIT GOTO@L ``` ~~It's very easy to get a specific LINE of a program in SmileBASIC, so I just put the spaces before each line break.~~ I thought I was so clever, putting the spaces before each line break, but apparently we're allowed to use line breaks instead of spaces... Explanation: ``` LOAD "PRG1:"+PRGNAME$() 'load the code into slot 1 so we can easily read 1 line at a time PRGEDIT 1 'Edit slot 1 @LOOP IF BUTTON(2) THEN 'When a button is pressed... PRINT PRGGET$(); 'get a line of code and print it WAIT 'delay so we don't detect the same press multiple times in a single frame. GOTO @LOOP ``` ]
[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/19196/edit). Closed 3 years ago. The community reviewed whether to reopen this question 8 months ago and left it closed: > > Original close reason(s) were not resolved > > > [Improve this question](/posts/19196/edit) Given two arbitrary numbers A,B. Print number B as a Digital LED Pattern where A is the scale. input: ``` 1 2320451640799518 ``` ouput: ``` _ _ _ _ _ _ _ _ _ _ _ _ _| _| _|| ||_||_ ||_ |_|| | ||_||_||_ ||_| |_ _||_ |_| | _| ||_| ||_| | | | _| ||_| ``` input: ``` 2 23 ``` ouput: ``` __ __ | | __| __| | | |__ __| ``` **Rules:** * Use **STDIN/STDOUT** for **input/output** * Code with most up-votes wins. In case of Tie, shortest code will be accepted * Most up voted Answer will be accepted at 01/02/2014 (Accepted [this answer](https://codegolf.stackexchange.com/questions/19196/transform-number-into-7-segment-display-pattern/19269#19269) with highest 12 votes) [Answer] # Commodore 64 BASIC [PETSCII](http://en.wikipedia.org/wiki/PETSCII) art rules :) ![LIST](https://i.stack.imgur.com/PH6Cu.png) Output: ![RUN](https://i.stack.imgur.com/jj5XP.png) [Answer] # Python 3, ~~286 282~~ 280 Yeah I golfed this one. Nice challenge! ``` n,x=input().split() n=int(n) l=lambda s:"".join(s)+"\n" h=lambda s:s.replace(*"! ")*~-n+s.replace(*"!_") print(l(" "+"_ "[c in"14"]*n+" "for c in x)+h(l("| "[c in"1237"]+n*"! "[c in"017"]+"| "[c in"56"]for c in x))+h(l(" |"[c in"0268"]+n*"! "[c in"1479"]+"| "[c=="2"]for c in x))) ``` --- Also, here's a Python 2 version weighing in at only 273 bytes! Not updating this one any more with further golfed original source. This was created when the original source was 282 bytes (Python 3 version). ``` exec'eJxdzE0OgjAQhuE9pxhn1VIlFhHUpCdRQlAx1NShAYwsOLzgD4irSd758tC8UWX6SDTZe824V1mju+uQ0lQz4o5RJr0dzylUO0TvWmhiFRd4IHTy8VV5ZWZNesqYizNA7jJaSC4mOUHu2LJjwTAEFJgA7k+gCWWAsUuii5eihD5Bw0XOul07bPxVhLGgl/9OS9mXcbIOMf4BPgK037kfbv4EGUTbgVAK/SnwBAs+TpU='.decode('base64').decode('zip') ``` This may be cheating, so I'm adding it separately. Let me know whether this is considered valid or not. [Answer] ## Haskell (389 chars) The solution uses 7 arrays, one for each segment of the array, using the names from this image: ![8 segment display](https://i.stack.imgur.com/G2Z8a.png) . The value `a !! 4` will be the character that should be displayed at that a position for the number 4. The values are multiplied by the scale where appropriate (using `r` and `rp` for replication), and finally printed out. ### The code ``` a="_ __ _____" b="||||| |||" c="|| |||||||" d="_ __ __ _ " e="| | | | " f="| ||| ||" g=" _____ __" r=replicate cm=concatMap s=(' ':).(++" ") dd w n=[[t n],rp$m f b n,[o g f b n],rp$m e c n,[o d e c n]] where rp=r$w-1 t=cm(s.r w.(a!!)) q f s x y=cm(\n->x!!n:r w(f s n)++[y!!n]) o=q(!!) m=q const ' ' go a=unlines$concat$dd(read$a!!0)$map(read.(:[]))$a!!1 main=interact$go.words ``` ## Example usage ``` echo '1 2320451640799518' | runhaskell ./digit_led.hs _ _ _ _ _ _ _ _ _ _ _ _ _| _| _|| ||_||_ ||_ |_|| | ||_||_||_ ||_| |_ _||_ |_| | _| ||_| ||_| | | | _| ||_| ``` [Answer] # C, 249 226 chars Golfed solution in C: ``` int x,y,g,s,q;main(){char*c,i[99];for(scanf("%d %98s",&s,i);y<2*s+1;++y,puts(""))for(c=i;*c;++c)for(x=0;x<s+2;++x)q=(y+s-1)/s*3+(x+s-1)/s,g=(x%(s+1))*(y%s)?7:q<3?~q%2*7:q-2,putchar("_|_||_| "["zG<lMfvH~N"[*c-48]+1>>g&1?g:7]);} ``` With added whitespace: ``` int x, y, g, s, q; main() { char *c, i[99]; for (scanf("%d %98s", &s, i); y < 2 * s + 1; ++y, puts("")) for (c = i; *c; ++c) for (x = 0; x < s + 2; ++x) q = (y + s - 1) / s * 3 + (x + s - 1) / s, g = (x % (s + 1)) * (y % s) ? 7 : q < 3 ? ~q % 2 * 7 : q - 2, putchar("_|_||_| "["zG<lMfvH~N"[*c - 48] + 1 >> g & 1 ? g : 7]); } ``` Notes: * At most 99 digits are printed * Behavior is undefined if the input is not well formed (e.g. contains non-digits, or scale is < 1) * Should be legal C89 code I will provide an explanation of how it works, should anyone care. [Answer] # Ruby 2.0 Quick and (not so) naive ruby implementation. ``` V,H = ' |',' _' l = gets.split s = l[0].to_i o = Array.new 1+s*2, '' l[1].each_char {|c| m = "{H=mNgwI\x7FO"[c.to_i].ord o[0] += " #{H[m[0]]*s} " o[s] += "#{V[m[1]]}#{H[m[2]]*s}#{V[m[3]]}" o[s*2] += "#{V[m[4]]}#{H[m[5]]*s}#{V[m[6]]}" } (s-1).times { |i| o[i+1] = o[s].gsub '_', ' ' o[s+i+1] = o[s*2].gsub '_', ' ' } o.each {|r| puts r} ``` Quick explanation: I first declare the strings representing on and off digits for horizontal and vertical bars. Then I read scale and the digits. I then declare an array of the necessary size to store enough lines for the given scale. The weird string is actually a mapping of 7-bits values representing which LEDs to switch on for each digit. Next, for each digit, I fill the output array from top to bottom, taking into account horizontal scaling. The final loop is to fill the rows that only have vertical bars, which can just be generated from the middle and bottom rows by removing horizontal bars. Finally, I print the output array ! [Answer] Python 2.6 with no imports. I'd say that the attractiveness of this solution is the use of templates. Unfortunately I think that's why I had such a hard time compacting it. ``` def numbers(scale, number): def single(yay, wall, digit): walls = ('1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111010') return yay if int(walls[digit][wall]) else ' ' def expand_one(char, digit): characters = '_||_||_' translated = single(characters[char], char, digit) if char % 3: return translated return translated * scale def expand_template(template, digit): out = '' for c in template: if c == '.': out += ' ' * scale elif c == ' ': out += c else: out += expand_one(int(c), digit) return out def repeated_expand_template(template, n): print ''.join(expand_template(template, int(d)) for d in n) repeated_expand_template(' 0 ', number) for _ in range(scale - 1): repeated_expand_template('1.2', number) repeated_expand_template('132', number) for _ in range(scale - 1): repeated_expand_template('4.5', number) repeated_expand_template('465', number) scale, number = raw_input().split() numbers(int(scale), number) ``` And a bit shorter (308 characters): ``` s,n=raw_input().split();s=int(s) for e in('0 0 ','11.2','0132','14.5','0465'):print '\n'.join(''.join(''.join(([' ','_||_||_'[int(c)]][int(bin(1098931065668123279354)[7*int(d)+int(c)+2])]*(s,1,1)[int(c)%3])if ord(c)>46 else c for c in e[1:].replace('.',' '*s))for d in n) for _ in range((1,s-1)[int(e[0])])) ``` [Answer] (Edit: This solution is now invalid because the semantics of the `銻` instruction has changed. I didn’t realise that I’d already made use of the instruction when I changed it. You can, however, fix ths program by simply changing it to the newer instruction `壹`.) # ~~[Sclipting](http://esolangs.org/wiki/Sclipting) — 85 characters~~ ``` 겠合글坼銻標⓷가殲갰復묽땸민뫝뜵깉걈밂⓶各가⓵겐上⓷감嚙긇밌⓶掘⓶감嚙눖밂⓶掘⓷合⓶감嚙긇밌⓶掘⓷合⓸⓸替❶終⓶丟終❶눠替눐終①貶復⓶⓷終丟併눐替글①復終눠替뇰①復終⓶丟 ``` --- ① ## Input: ``` 1 1024856359701 ``` ## Output: ``` _ _ _ _ _ _ _ _ _ _ || | _||_||_||_ |_ _||_ |_| || | | ||_||_ ||_| _||_| _| _| | ||_| | ``` --- ② ## Input: ``` 2 47474747 ``` ## Output: ``` __ __ __ __ | | || | || | || | | |__| ||__| ||__| ||__| | | | | | | | | | | | | | | | | | ``` [Answer] # C# (480 443 chars) ``` namespace System{using z=String;using w=Console;class P{static void Main(){var t=w.ReadLine().Split(' ');var s=int.Parse(t[0]);z b="17",d=b+23,e=b+3459,f="56",g=e+2680;Action<z,z,z,int>q=(l,m,r,n)=>{for(int i=1;i<n;i++){foreach(var c in t[1]){h(c,l);for(int j=0;j<s;j++)h(c,m,"_");h(c,r);}w.Write("\n");}};q(g,"14",g,2);q(d,g,f,s);q(d,b+0,f,2);q(e,g,"2",s);q(e,b+49,"2",2);}static void h(char x,z m,z y="|"){w.Write(m.Contains(""+x)?" ":y);}}} ``` Extended version: ``` using System; using System.Linq; namespace Segments { internal class Program { static void Main() { var scale = int.Parse(Console.ReadLine()); var input = Console.ReadLine(); PrintLine(input, "", "14", "", 2); PrintLine(input,"1237", "", "56", scale); PrintLine(input,"1237", "170", "56", 2); PrintLine(input,"134579", "", "2", scale); PrintLine(input,"134579", "147", "2", 2); } static void PrintLine(string input, string leftMatch, string middleMatch, string rightMatch, int scale) { for (int i = 1; i < scale; i++) { foreach (var c in input) { PrintDigitLine(c, leftMatch, '|', 1); PrintDigitLine(c, middleMatch, "_", scale); PrintDigitLine(c, rightMatch, '|', 1); } Console.Write("\n"); } } private static void PrintDigitLine(char digit, string match, char charToPrint, int) { for (int i = 0; i < n; i++) Console.Write(match.Contains(digit) || match == "" ? ' ' : charToPrint); } } } ``` My idea was to split the task up into 5 horizontal lines, which in turn are split up in a left, right and middle part for each character. [Answer] I guess there are very shorter solutions, but since this is not code-golf I'm quite satisfied! This PHP script will take two numbers `a`, `b` from STDIN and echo `b` in LED format, at `a` size. ``` fscanf(STDIN, "%d %d", $a, $b); //Didn't test this line, but it should be ok. $space=str_repeat("&nbsp;", $a); $top = $topLeft = $topRight = $mid = $botLeft = $botRight = $bot = array(); for ($i=0; $i<count($b); $i++) { $top[$i] = $topLeft[$i] = $topRight[$i] = $mid[$i] = $botLeft[$i] = $botRight[$i] = $bot[$i] = true; switch ($b[$i]) { case 0: $mid[$i] = false; break; case 1: $top[$i] = $topLeft[$i] = $mid[$i] = $botLeft[$i] = $bot[$i] = false; break; case 2: $topLeft[$i] = $botRight[$i] = false; break; case 3: $topLeft[$i] = $botLeft[$i] = false; break; case 4: $top[$i] = $botLeft[$i] = $bot[$i] = false; break; case 5: $topRight[$i] = $botLeft[$i] = false; break; case 6: $topRight[$i] = false; break; case 7: $topLeft[$i] = $mid[$i] = $botLeft[$i] = $bot[$i] = false; break; case 9: $botLeft[$i] = false; break; } } horizontal($top); vertical($topLeft, $topRight); horizontal($mid); vertical($botLeft, $botRight); horizontal($bot); function horizontal($position) { global $a, $b, $space; for ($i=0;$i<count($b);$i++) { if ($position[$i]) echo "&nbsp;".str_repeat("-", $a)."&nbsp;"; else echo "&nbsp;".$space."&nbsp;"; } echo "<br />"; } function vertical($positionLeft, $positionRight) { global $a, $b, $space; for ($j=0;$j<$a;$j++) { for ($i=0;$i<count($b);$i++) { if ($positionLeft[$i]) { echo "|".$space; if ($positionRight[$i]) echo "|;"; else echo "&nbsp;"; } else { echo "&nbsp;".$space; if ($positionRight[$i]) echo "|"; else echo "&nbsp;"; } } echo "<br />"; } } ``` **EDIT:** Looking at the previous output example, I wrongly supposed that space between digits should be as large as the `a` size. This has been fixed with the OP's declaration that no space is needed. [Answer] ## C#, 435 359 473 bytes **EDITS:** * Removed redundant code. Reduced byte size of comparisons. * Converted to a stand-alone application using standard in for input. Here's the golfed code (with added line breaks and whitespace): ``` using C=System.Console; class P{ static void Main(){ var a=C.ReadLine().Split(' '); D(int.Parse(a[0]),a[1]); } static void D(int r,string n){ int i,j; string s="",v="|",w=" ",x=new string('_',r),y=new string(' ',r),z="\n"; foreach(var c in n)s+=w+(F(0,c)?x:y)+w+w; for(j=1;j<6;j+=3) for(i=r;i-->0;){ s+=z; foreach(var c in n)s+=(F(j,c)?v:w)+(i<1&&F(j+1,c)?x:y)+(F(j+2,c)?v:w)+w; } C.Write(s+z); } static bool F(int i,char c){ return(new[]{1005,881,892,927,325,365,1019}[i]&1<<(int)c-48)>0; } } ``` [Answer] ## C (~~561~~ 492 bytes) Author is frmar. He sent me his answer last week (he has not yet created his account). ### 492 bytes but a bit more obfuscated: ``` #include<stdio.h> #include<ctype.h> #include<stdlib.h> #define C(x) ((_[*n-'0'])>>s)&m&x #define P putchar unsigned _[]={476,144,372,436,184,428,492,148,508,188}; void p(int a,char*n,unsigned m,int s) {for(;isdigit(*n);++n){P(C(1)?'|':' '); for(int i=0;i<a;++i)P(C(4)?'_':' '); P(C(2)?'|':' ');} P('\n');} void l(int a,char*b){p(a,b,7,0);int i=1; for(;i<a;++i)p(a,b,3,3);p(a,b,7,3);i=1; for(;i<a;++i)p(a,b,3,6);p(a,b,7,6);} int main(int c,char**v){l(c>1?atoi(v[1]):1,c>2?v[2]:"0123456789");} ``` ### Previous version using 561 bytes: ``` #include<stdio.h> #include<ctype.h> #define C(x) ((((*n-'0')[_])>>s)&m&x) const unsigned _[]={476,144,372,436,184,428,492,148,508,188}; void p(int a,const char*n,unsigned m,int s) { for(;isdigit(*n);++n) { putchar(C(1)?'|':' '); const char c=C(4)?'_':' '; for(int i=0;i<a;++i) putchar(c); putchar(C(2)?'|':' '); } putchar('\n'); } void l(int a,const char*b) { p(a,b,7,0); for(int i=1;i<a;++i)p(a,b,3,3);p(a,b,7,3); for(int i=1;i<a;++i)p(a,b,3,6);p(a,b,7,6); } #include<stdlib.h> int main(int c,char**v){l(c>1?atoi(v[1]):1,c>2?v[2]:"0123456789");} ``` ### Original version from frmar (623 bytes): ``` #include<stdio.h> #include<ctype.h> const unsigned int _[]={476,144,372,436,184,428,492,148,508,188}; void p(int a,const char*n,unsigned int m,int s) { for(;isdigit(*n);++n) { #define C(x) ((((*n-'0')[_])>>s)&m&x) putchar(C(1)?'|':' '); const char c=C(4)?'_':' '; for(int i=0;i<a;++i) putchar(c); putchar(C(2)?'|':' '); } putchar('\n'); } void print_as_led(int a,const char*b) { p(a,b,7,0); for(int i=1;i<a;++i)p(a,b,3,3);p(a,b,7,3); for(int i=1;i<a;++i)p(a,b,3,6);p(a,b,7,6); } #include<stdlib.h> int main(int argc,char**argv){print_as_led(argc>1?atoi(argv[1]):1,argc>2?argv[2]:"0123456789");} ``` ### Compilation: ``` $ gcc -std=c99 -Wall print_as_led.c ``` ### Examples using default `0123456789` number but different sizes: ``` $ ./a.out _ _ _ _ _ _ _ _ | | | _| _||_||_ |_ ||_||_| |_| ||_ _| | _||_| ||_| | $ ./a.out 2 __ __ __ __ __ __ __ __ | | | | || || | || || | | | | __| __||__||__ |__ ||__||__| | | || | | || | || | | |__| ||__ __| | __||__| ||__| | $ ./a.out 3 ___ ___ ___ ___ ___ ___ ___ ___ | | | | || || | || || | | | | | || || | || || | | | | ___| ___||___||___ |___ ||___||___| | | || | | || | || | | | | || | | || | || | | |___| ||___ ___| | ___||___| ||___| | ``` ### Other examples: ``` $ ./a.out 1 42 _ |_| _| ||_ $ ./a.out 2 42 __ | | | |__| __| || ||__ $ ./a.out 3 42 ___ | | | | | | |___| ___| || || ||___ ``` ### Larger sizes: ``` $ ./a.out 4 42 ____ | | | | | | | | | |____| ____| || || || ||____ $ ./a.out 5 42 _____ | | | | | | | | | | | | |_____| _____| || || || || ||_____ ``` [Answer] # Perl + FIGlet + BRA\*: 54 characters ``` while(<>){($n,$x)=split;print(`figlet -f 7seg$n $x`);} ``` I figured this would be quite easy to do with [FIGlet](http://www.figlet.org/), but there didn't appear to be any suitable fonts for this purpose. So I made some :-) * [7seg1.flf](http://pastebin.com/Tr0ScP4E) * [7seg2.flf](http://pastebin.com/5KT5qiDF) * [7seg3.flf](http://pastebin.com/AzLjxbyQ) Here's how it looks on the terminal: ``` $ perl ./led.pl 1 234 _ _ _| _||_| |_ _| | 2 345 __ __ || || __||__||__ | | | __| | __| 3 456 ___ ___ | || | | || | |___||___ |___ | || | | || | | ___||___| ``` \*BRA: blatant rule abuse [Answer] # PERL,   261 244 187   166 chars Little bit of bitwise encoding philosophy rulez :-) ``` ($n,$a)=split/ /;sub c{$_=$a;y/0-9/Gl+%<UWm7=/;s/./(substr" _ _|_| |_ |",2*ord($&)>>$_[0]&$_[1],3)=~s|.\K.|$&x$n|er/ge;print y/_/ /r x($n-1).$_}c 0,2;c 4,14;c 1,14 ``` Code with whitespace added: ``` ($n,$a)=split/ /; sub c{ $_=$a; y/0-9/Gl+%<UWm7=/; s/./(substr" _ _|_| |_ |",2*ord($&)>>$_[0]&$_[1],3)=~s|.\K.|$&x$n|er/ge; print y/_/ /r x($n-1).$_ } c 0,2; c 4,14; c 1,14 ``` Perl has to be invoked with `-n`: ``` $ perl -n digitize.zoom.pl 1 12304597 _ _ _ _ _ _ | _| _| | | |_| |_ |_| | | |_ _| |_| | _| | | 2 0784 __ __ __ | | | | | | | | | | |__| |__| | | | | | | |__| | |__| | 3 789 ___ ___ ___ | | | | | | | | | | | |___| |___| | | | | | | | | | |___| | ``` Notes: * Everything about how digits are displayed is encoded in the string `Gl+%<UWm7=` :-) One character corresponds to one digit, encoded are 3 positions of 3 consecutive characters within the `" _ _|_| |_ |"` string. * Numbers are constructed in 3 lines, line by line. Each of the 3 lines corresponds to one call to sub-routine `c`, which also accomplishes vertical zooming for second and third line. * Horizontal zooming is done at the end of sub-routine `c`. --- My `sed` program cannot zoom, but it looks a lot nicer, doesn't it? :-) ``` s/./\0 /g h s/[14]/ /g s/[2305-9]/ _ /g p g s/[17]/ |/g s/[23]/ _|/g s/[489]/|_|/g s/[56]/|_ /g s/0/| |/g p g s/[147]/ |/g s/2/|_ /g s/[359]/ _|/g s/[680]/|_|/g ``` Pretty much the idea my PERL script uses, but in PERL it's a lot uglier. Note that for my sed program I prefered to use `9` which has the underscore in the last line, to be like reversed 6. [Answer] ## C#, 386 382 364 chars / 374 bytes (UTF-8) and (lots? of) room for improvement... ``` using System.Linq;using C=System.Console;class P{static void Main(string[] args){var s=C.ReadLine();for(int l=0;l<5;l++){for(int j=0;j<s.Length;j++)C.Write(string.Join("",Enumerable.Range(0,3).Select(i=>{var x=l*3+i;return((x&1)>0?((((System.Text.Encoding.Unicode.GetBytes("⑷浝欮╻潿")[(byte)s[j]-48]>>x/2)&1)==1)?(x-1%3>0?"|":"-"):" "):" ");}))+" ");C.WriteLine();}}} ``` **EDIT** Crap... I missed the "scale" part ![CRAP](https://i.stack.imgur.com/0FwyK.gif) I'll give it another shot if I get around to it.. [Answer] # J - 147 95 characters Added required scaling: ``` 1!:2&2,./(([1 s 0 s=:1 :(':';'y#"(2-m)~(m{$y)$1,x'))"2(3 :'(y{(5 3$&,0&,.)"1@#:l)}d')@"."0@":)/".]1!:1]1[l=:>:a.i.'v#\Z9jnQ~z'[d=:' ',:5 3$' - | |' ``` Annotated version: ``` NB. Digit array (2 x 5 x 3) first is blank, second is filled. d=:' ',:5 3$' - | |' NB. Bits to selector (taking into account that all "usefull" bits are separated with 0 bits, looking at the 5 x 3 grid) bts =: 5 3 $&, (0&,.) NB. list of character bits. l=: 119 36 93 91 58 107 111 82 127 123 NB. golfing using ascii range l=: >:a.i.'v#\Z9jnQ~z' NB. scaling function NB. scaling in 1 direction involves inserting copies of the middle segments: NB. from y, copy the middle segments, 1 x 1 x 1 for rank 2 and 1 x 1 for rank 1 NB. Usage: scale (rank s) segment s=: 1 : (':';'y#"(2-m)~(m{$y)$1,x') NB. scale first along columns, then along rows, apply only to rank 2 (planes) b=:([1 s 0 s)"2 NB. Get one number by using amend with a selection array (0 is blank, 1 is filled) NB. get the y'th plane from the array of 10 x 5 x 3 selector bits, use those to index d with. g=: 3 : '(y { (bts"1 #: l)) } d' NB. from right to left: read stdin, convert number string to numbers, NB. use the left for scaling, and split the right in digits,then apply g, NB. then paste them together so the numbers appear next to each other. NB. Put this result on stdout 1!:2&2,./(b g@"."0@":)/".]1!:1] ``` Example: ``` 1 0123456789 - - - - - - - - | || | || || | || || | - - - - - - - | || | | | || | || | | - - - - - - - 2 123 -- -- | | | | | | -- -- | | | | | | -- -- ``` [Answer] # Ruby,126 ASCII characters ``` ->n,x{(n*2).downto(0){|i|x.bytes{|c|z='u"ik:[]b}{'[c-48].ord+2>>i/n*3&7 print' |'[z/2%2],(z%2>i%n ??_:' ')*n,' |'[z/4]} puts}} ``` Each digit is encoded as a bitmap in thirds thus, with each third represented by an octal digit. ``` |_| 8^2 (left and right never used! only the 1's bit used!) |_| 8^1 (4*right+2*left+1*bottom) |_| 8^0 (4*right+2*left+1*bottom) ``` As all digits have either the 64's bit or 32's bit set, the range is 044 octal to 177 octal. Unfortunately 177 is the nonprintable DEL character, so the magic string contains the numbers 2 below the required bitmap code, and we have to add 2 back on in the function. **Ungolfed in test program** ``` f=->n,x{ (n*2).downto(0){|i| #1 top line, n middle lines, n bottom lines x.bytes{|c| #iterate through bytes z='u"ik:[]b}{'[c-48].ord+2>>i/n*3&7 #find octal code for current 1/3 digit print' |'[z/2%2],(z%2>i%n ??_:' ')*n,' |'[z/4]#print left,right and bottom } #z%2>i%n only true on bottom row of 3rd where i%n=0 (print _'s) and octal code has 1's bit set puts #print a newline to finish line } } n=gets.to_i #size x=gets.chop #number taken in string form f[n,x] ``` **Output** ``` C:\Users\steve>ruby 7seg.txt 4 0123456789 ____ ____ ____ ____ ____ ____ ____ ____ | | | | || || | || || | | | | | || || | || || | | | | | || || | || || | | | | ____| ____||____||____ |____ ||____||____| | | || | | || | || | | | | || | | || | || | | | | || | | || | || | | |____| ||____ ____| | ____||____| ||____| ____| ``` [Answer] ## Perl 6, ~~284~~ ~~241~~ 237 ``` my (\a,\n)=split " ",slurp.trim;my @p=n.comb;sub g(\b,\c){for @p {my $h=:36(b);$h+>=3*$_;for ^3 {my \e=$_==1;print " |_".substr($h%2&&(c+!e)&&1+e,1)x a**e;$h+>=1}};say ""};for <52N98I 0 HMTVAD 1 AZRXEV 1> ->\s,\q{g(s,0)for 2..a*q;g(s,1)} ``` Previous solutions: ``` my (\a,\n)=slurp.trim.split: " ";my @p=n.comb;sub g(\b,\c){for @p {my $h=b;$h+>=3*$_;for ^3 {my \e=$_==1;print " |_".substr($h%2&&(c+!e)&&1+e,1)x a**e;$h+>=1}};say ""};for 306775170,0,1066270117,1,664751335,1 ->\s,\q{g(s,0)for 2..a*q;g(s,1)} my (\a,\n)=slurp.trim.split: " ";my @p=n.comb;my &f={print $^b.substr(3*$_,1)~($^c??$b.substr(3*$_+1,1)!!" ")x a~$b.substr(3*$_+2,1)for @p;say ""};for (" _ _ _ "~" _ "x 5,0,"| | | _| _||_||_ |_ ||_||_|",1,"|_| ||_ _| | _||_| ||_| |",1) ->\s,\q{f(s,0)for 2..a*q;f(s,1)} ``` ]
[Question] [ In this question I will talk about programs as strings, this is strings of bytes, not characters. How your resultant program is rendered or displayed is not important to this challenge, only how it appears in memory matters. A [pristine program](https://codegolf.stackexchange.com/questions/63433/programming-a-pristine-world) is a program \$S\$ that when run does not error, however it will error whenever a continuous substring of size \$n\$, where \$1\leq n < \left|S\right|\$, is removed. A filthy program is the opposite, it is a program \$S\$ that when run *does* error, however whenever a continuous substring of size \$n\$, where \$1\leq n < \left|S\right|\$, is removed, it does not error. For this challenge an error is non-empty output to STDERR. Your challenge is to write a filthy program that uses as many unique bytes as possible. This means you will get one point for every unique byte that appears in your code with a larger score being better. The maximum score is thus 256. [Answer] # [Unary](https://esolangs.org/wiki/Unary), 14 bytes ``` 123456789ABCDE ``` This encodes the brainfuck program `[`, which errors due to unmatched brackets. Removing bytes will result in `>`, `<`, `+`, `-`, `.`, `,` or the empty program, which are valid brainfuck programs. [Answer] # [R](https://www.r-project.org/), 3 bytes ``` qrt ``` [Try it online!](https://tio.run/##K/r/v7Co5P9/AA "R – Try It Online") A name of an object is a valid program in R. `qrt` is not the name of anything, so it returns an error. `q` is the quit function `qr` is the QR decomposition function `rt` is the t distribution sampling function `qt` is the t distribution inverse CDF `t` is the transpose function [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~4 5 6 7 8 10~~ 11 bytes ``` “a”;⁽PFð+µU ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5zERw1zrR817g1wO7xB@9DW0P//AQ "Jelly – Try It Online") [Verify it.](https://tio.run/##dVG9TsMwEN79FJYYkihRlYitKJUY2hGxMJWqCs0VjBw7ctyKbmVnY0Jq34GFgYEFnoS8SGrHpm4o3JDcXb4f@0u5knecnTYznkPqeV693mT1entWP35cjr5ew8@3K7Vt5oIX@B4oXWFSlFxIM0xhmVGs6wRntOCV1P2xxvf7S4IsUZICEJJxqpuefvgBQoyzoRBcVDjFMQLXojkXuJKZYhKGRcZuwafAfH3gIEyCPtKWGgQsd5CWESaRg5rVIA4sRZf@MpWCFAXkyk2P436Lm@DQjEq1P9kTpFg5ti4B1YJKxXV5@Ieq0XgS7AnwMINSdgXsVcMUJ519KQiTHakDHVpBV8XF1xFCyMh418yL1E3UH1ZZk7l1HcRGxYLOb/gS8E8c2trierjePimm87WMC/4PfPOsjfZp/QqnDcWEgYfti3DWER4tKP1L8ugEDphzqFQO0jDskZtmBw) Tries to add a string with an integer. Some of the possible subprograms: `“a”` is a string literal. `“a` is the same string literal. `“` is the empty string. `“a”;` concatenates "a" with itself. ...too many to enumerate them all. [Answer] # Polyglot, 3 bytes ``` 1 2 ``` Works in: * JavaScript * Ruby * R * Octave * GHCi * Julia In JavaScript, throws *SyntaxError: unexpected token: numeric literal* or a similar error. All other strings are valid numeric literals (**1**, **2**, or **12**). --- In GHCi this throws ``` <interactive>:1:1: error: • Non type-variable argument in the constraint: Num (t1 -> t2) (Use FlexibleContexts to permit this) • When checking the inferred type it :: forall t1 t2. (Num t1, Num (t1 -> t2)) => t2 ``` This is because it tries to apply `1` to `2` as a function, however it cannot. When any part of this is removed it simply becomes a numeric literal. [Answer] # [Python 2](https://docs.python.org/2/), 2 bytes ### Unexpected character after line continuation character ``` \0 ``` `\` followed by any of `123456789 #` [Try it online!](https://tio.run/##RYw9CoAwDIX3niJbFgdxFDyJdZCYYkHa0lTQ09coBZf398FLd9ljGGqluLHABDNa22OnqvIGXIyLGV4OPnwuo4GUfShfM1DyrQvwxdSWhlFOIhZBo5A4lfFHbvUHth/EWh8 "Python 2 – Try It Online") ### Invalid octal number ``` 08 ``` `0` followed by any of `89` [Try it online!](https://tio.run/##RYwxCoAwEAT7vOK6bSzETsGXiIWcJwYkCbkI@voYJWCxLDsDG@60e9flzH4VpZEmtD0atCVvYzabj/Rasu5rHQyFaF36lqEU70JILuFKqoaezKIKUyRLSMOvtsUeqD9Azg8 "Python 2 – Try It Online") ### Unexpected Indent ``` 0 ``` or `\t` followed by any of `123456789\` [Try it online!](https://tio.run/##RYwxCsMwFEN3n0KbliztGOhJQobw80MNxTb@LiSndx1j6CCE3gOlq7xjeNYqcVfDCwvx4ES03M3VHTHjtvCht80OKftQ@nIo@WoEeqoMMjTtK6JmdE2KpjL/1bH5D8cPWesP "Python 2 – Try It Online") [Answer] # [Python 2/3](https://docs.python.org), 3 bytes ``` 4\f2 ``` OR ``` 4\x0c2 ``` [Try it online!](https://tio.run/##bZBNb4MwDIbv@RUWvYCK0Fb21Uo9UKSddpp2zCUNRqBFCXLCtP56lgAb3YaVSNHj145fdxfXGL0bhgprwE@UvRNnhbFNDgx8RFH0iq4nDW0Nrmkt@LPoQJoKMy8axY4uU1WIIPJt2PSW2LklR1PLZ6EssivwRj2yDbwY8w61IchBNoKEdEg284lie9qW4wREhjIodBVY6mlahJuWYBvTqwqEUnBG@BCqrTLGgj2LgmSTx7M1BUeIuOOa15xgc3uzy@/uHx6f9pxPdsIEBbQa1DJ5YKc/7JuXKzyE35w27nq7o48EhB//N50Y/9di3ucsXC8uk8NaHXTUahcTdjT/mzD2s4ph@AI) In python "\f" is the same as "\x0c" and is a [form feed](https://en.wikipedia.org/wiki/Page_break#Form_feed) character. This means that it indicates for a printer to go to the next line. If a python expression starts or ends with `\f`, it is basically ignored so `\f2` is a valid expression. The `4` and `2` can be any number 0-9. However, for the first byte to be `0` is only valid in Python 2.7.15, as `02` was made a legal declaration of `2`. So the expression itself fails with a Syntax Error, because there are two numbers separated by a whitespace. However, any shortening either puts `\f` at the beginning or end, where it doesn't matter, or it creates `42` which is valid. (It is worth noting that in IDLE this file opens looking like "42".) Form feed explanation source: <https://stackoverflow.com/a/26184126> [Answer] # [Dyalog APL](https://www.dyalog.com/), 5 bytes ([SBCS](https://github.com/abrudz/SBCS)) ``` ~≢0 1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v@5R5yIDBcP//wE "APL (Dyalog Unicode) – Try It Online") or [test all the possible programs](https://tio.run/##XVLbbtNAEH33V4yKVANNlKTcI0Dc7/c7CFGZZBtMnTi1HUoIqVBBke14K1oE5YVb2opQISEIUaASQkr@5PxImI3fkLzenZkzZ88crVG2kvmqYdmFIeQ7MizLnhP5rKaCKeN@Li@mCw/MhzNWsWSXZx3Xqzyae1x9Avk1nZncsXPX7j179yFsHT5y9NjxEydPnT5z9tz5CxcvXb5y9dr1Gzdv3b6DcBVRL4Xo713IZ/sRrB1AsH4QwUf4bfifkxOD3mAFfgj5cx6NJTReQXaw0tyOyEcUIlxA@Bz@F/gbCNcRrj1NQH6H/AG5DNmEDBD9QfgG8gOi35CvIRchNxB8QtAa/Noyfg/@KmQPzRdovERjGYsMea/xyMQJ4lE0T7jeKKhpRGkW2ILsZlWJlBGiWPaqlLPzgkyXXM8xSgVB41SyPXLEbMV0RJ4bi26BOXRFZpYKNKYTK@0mSB/L6oqXslniWxNKRrig4KQLx7G5W9WnVF5p73LwP86t5HLCdXWtrk2bliccLta2Qm7y129zz7YU/@pDJVKJmOcZ0pTR49FUVisbjufGU7KjiVSNG2r9b5kJ3nl1FE1HRZtJRTUK1SF2ox6TjOj6babgrP82TbEaSh9iDPFLGMHqCjK6T1NuK9uX1BMb/gM "APL (Dyalog Unicode) – Try It Online") There sure are better boring answers, but this is the best non-boring one I've found SBCS is required as Dyalog Classic seems to always have output in STDERR, making it unusable. [Answer] # [Zsh](https://www.zsh.org/), 2 bytes ``` :# ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhaLrJQhDCgfJg4A) Zsh is very good at producing errors, so this challenge is very hard. * `:` on its own is command which does nothing * `#` is a comment * `:#` is a single command, which doesn't exist, and therefore errors. (`#` is only a comment when it's at the start of a word) ]
[Question] [ Your input is a list/sequence/vector/array of 5-255 positive integers, not necessarily unique. You may assume whatever input format is most suitable, and that each integer (as well as the quantity of integers) is chosen uniformly at random from the range 5-255. The goal is to output the same list, in the same (or equivalent) format, but sorted into increasing (nondecreasing) order. A common early exercise in learning a language. Submissions to include: 1. An answer which works correctly and achieves the goal; and 2. A second answer which contains an annoying bug. Between 1% and 10% of the time, the output needs to be a list in the correct format and containing the correct elements, but *in the wrong order* (any order except correctly sorted). The rest of the time, the program must work correctly and achieve the goal. The two answers must have [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) one; that is, we can get one from the other by deleting one byte, or adding one byte, or changing one byte. Scoring as usual in code-golf (based on the shorter of your two answers), with usual loopholes forbidden. 10% bonus (decrease to score) if the annoying bug is input-independent, i.e. using the same input again doesn't reproduce the bug (except between 1% and 10% of the time). [Answer] # [Python 3](https://docs.python.org/3/), 36 bytes ## Bug-free version, 37 bytes ``` lambda l:sorted(l,reverse=l[-9:]==[]) ``` [Try it online!](https://tio.run/##bY7BCsIwEETv@Yq1pwRrrUoPBnLxN2qRaFMNpEnZpoKI3x4TK3jxtLAzb2aGh785uwudOAYj@3MrwfDRoVctNTmqu8JRCVOv9rwRom5Y0P0QZUBpW9eTi5usBwElIZ1D0KBtkq6KbsqScQImivVsLtLR1tMq31YVgwScfsBfE2sIYIzoqGEE5raliK@FgO9MZIQMmJDsMF05PF/r2J0VMb6Xnn4YxsIb "Python 3 – Try It Online") ## Annoying version, 36 bytes ``` lambda l:sorted(l,reverse=l[9:]==[]) ``` [Try it online!](https://tio.run/##bY7NCsIwEITv@xRrTwmWWpUeDOTia9Qi0aY1kJ@SpoKIzx5TK3jxtLAz38wMj3Bzdh87fopamEsrULPR@SBbonMv79KPkuv6wBrO64ZGZYakohe2dQaubrIBOZYAnfOoUNlZ6iXZliVlgDqJ9WIu5qNsIFW@qyqKM3D@AX9NtAH0KaIjmgIubWueXiuO35WeAgx@RrLj1DN8vjapOytSvBGBfBhK4xs "Python 3 – Try It Online") This depends on the input and therefore does not qualify for the bonus. It has a probability of around 2% to fail. It fails when the input length is lower then 10. Combined with [LyricLy's answer](https://codegolf.stackexchange.com/a/147094/64121) this gets 34 bytes: ``` lambda l:sorted(l)[::l[9:]>[]or 1] lambda l:sorted(l)[::l[9:]>[]or-1] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5\*0.9 = 4.5 bytes **Working solution** ``` {TLΩi ``` [Try it online!](https://tio.run/##MzBNTDJM/W9oYOD2vzrE59zKzP@1Ov@jjXTMzHWMjXTMdQyNjHVMTICUjmksAA "05AB1E – Try It Online") **Explanation** ``` { # sort input TL # push the range [1 ... 10] Ω # pick a random number in the range i # if true (equal to 1), do nothing ``` **Solution containing the bug** Gives the wrong solution 10% of the time (independent on input). ``` {TLΩiR ``` [Try it online!](https://tio.run/##MzBNTDJM/W9oYOD2vzrE59zKzKD/tTr/o410zMx1jI10zHUMjYx1TEyAlI5pLAA "05AB1E – Try It Online") **Explanation** Same as the working solution, except it reverses the list if the number picked is true. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 \* (100% - 10%) = 6.3 bytes ``` Ṣ¹⁵X:¤¡ ``` [Try it online!](https://tio.run/##y0rNyan8///hzkWHdj5q3BphdWjJoYX/wx/u6j6x3ehwu7fKo6Y1kf//R1vqKBjqKBjpKBgDGQYGQKY5iGVqEAsA "Jelly – Try It Online") Buggy version: ``` ṢẊ⁵X:¤¡ ``` [Try it online!](https://tio.run/##y0rNyan8///hzkUPd3U9atwaYXVoyaGF/8Mf7uo@sd3ocLu3yqOmNZH//0db6igY6igY6SgYAxkGBkCmOYhlahALAA "Jelly – Try It Online") In both links, there's a test harness that will run the code 100 times, each time with the list you give as the argument, and then return the results. The probability of each input length is: ``` 0.1 - 0.1/(length!) ``` So for length 1 there's a 0% probability, for length 2 5%, for length 3 8.83̅%, for length 4 9.583̅% etc. until length ∞ which has a 10% probability. [Answer] # Python 3, score ~~58~~ 57 - 10% = 51.3 Saved a byte thanks to ovs. ### Bug-free version, 57 bytes ``` lambda m:sorted(m)[::random()>.1or 1] from random import* ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHXqji/qCQ1RSNXM9rKqigxLyU/V0PTTs8wv0jXMJYrrSg/VwEiqpCZWwBUqvW/oCgzr0QjTSPaUEfBREfBXEfBCMiI1dT8DwA "Python 3 – Try It Online") ### Bugged version, 57 bytes ``` lambda m:sorted(m)[::random()>.1or-1] from random import* ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHXqji/qCQ1RSNXM9rKqigxLyU/V0PTTs8wv0jBMJYrrSg/VwEiqpCZWwBUqvW/oCgzr0QjTSPaUEfBREfBXEfBCMiI1dT8DwA "Python 3 – Try It Online") I decided to try a solution that uses the bonus. It doesn't beat the other Python answer, but I had fun thinking it up. [Answer] # C, 71\*0.9 = 63.9 bytes **Bug-free:** ``` c(int*a,int*b){return*a-*b;}f(a,n)int*a;{if(rand()%1<9)qsort(a,n,4,c);} ``` [Try it online!](https://tio.run/##hVDBaoNAFLz7FYMQ2GdW0LSRtqv00l4baHMLOZhVyx6iVje9iN9udzdioRD6Dg9mZ9/MeyPDTymnSTJV6yDntp9o6Ep96eogD4OTGCuW85ocLwZVsS6vC0arOH2kr77ptKX5PZckxum7UQV02WtG3uDBlJmDPsTJUThYNR2sF1QWCag0TgTWa0WOtKUP6ogMW6wxG222kfCuw0xzxAnN0MrILOJojdb/6sPi0XbmT8X81V0BnztLEgurKjC3RYqWzLj8pdrMElc8ut5edM8knuEjxNtuj4/d@/71xceTe5mRUR89zy52zlW9ZNO7C7U6lywiunHC5uFvQi5eozj9AA) **Buggy:** ``` c(int*a,int*b){return*a-*b;}f(a,n)int*a;{if(rand()%10<9)qsort(a,n,4,c);} ``` [Try it online!](https://tio.run/##hVDBaoNAFLz7FYMQ2GdW0LSRtqv00l4baHMLOZhVyx6iVje9iN9udzdioRD6Dg9mZ9/MeyPDTymnSTJV6yDntp9o6Ep96eogD4OTGCuW85ocLwZVsS6vC0arOEof6atvOm15fs8liXH6blQBXfaakTd4MGUGoQ9xchQOVk0HawaVRQIqjROB9VqRI23pgzoiwxZrzE6bbSS86zDTHHFCM7QyMos4WqP1v/qweLSd@VMxf3VXwOfOksTCqgrMbZGiJTMuf6k2s8QVj663F90ziWf4CPG22@Nj975/ffHx5F5mZNRHz7OLnXNVL9n07kKtziWLiG6csHn4m5CL1yhOPw) [Answer] # [Groovy](http://groovy-lang.org/), 31 bytes **Bugged solution:** ``` {a->a.sort()[a[9]?0..-1:-1..0]} ``` **Working solution:** ``` {a->a.sort()[a[0]?0..-1:-1..0]} ``` The Groovy subscript operator (the `getAt` method) returns null for lists if the index is bigger than the size. So if there's a ninth element it'll stay the same as the sorted list, but if not (1.99203187% chance) it'll be reversed. However there will always be a first element because the list's size is always bigger than or equal to 5. So the 0 in `a[0]` could be swapped with 1, 2, 3 or 4. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes This is 26.1 bytes with the bonus, but I'm not entirely sure I earn the bonus; on already-sorted input, both versions always produce sorted output. ## Bug-free version (29 bytes) ``` If[RandomReal[]<0.,#,Sort@#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d8zLTooMS8lPzcoNTEnOtbGQE9HWSc4v6jEQTlW7T9UzjOvJDU9tSi62lTHyNS0VgeraCwQ/AcA "Wolfram Language (Mathematica) – Try It Online") ## Annoying version (30 bytes) ``` If[RandomReal[]<0.1,#,Sort@#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d8zLTooMS8lPzcoNTEnOtbGQM9QR1knOL@oxEE5Vu0/VNIzryQ1PbUoutpUx8jUtFYHq2gsEPwHAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # PHP, 70 bytes ## Bug-free version, 70 bytes ``` <?unset($argv[0]);((rand(1,9)?"":r).sort)($argv);echo join(" ",$argv); ``` [Try it online!](https://tio.run/##K8go@P/fxr40rzi1REMlsSi9LNogVtNaQ6MoMS9Fw1DHUtNeScmqSFOvOL@oRBOiQtM6NTkjXyErPzNPQ0lBSQcq@P//fyPT/4Zm/02BNJBhavjf2Oy/pSVQ6F9@QUlmfl7xf908AA) ## Bugged version, 70 bytes ``` <?unset($argv[0]);((rand(0,9)?"":r).sort)($argv);echo join(" ",$argv); ``` [Try it online!](https://tio.run/##K8go@P/fxr40rzi1REMlsSi9LNogVtNaQ6MoMS9Fw0DHUtNeScmqSFOvOL@oRBOiQtM6NTkjXyErPzNPQ0lBSQcq@P//fyPT/4Zm/02BNJBhavjf2Oy/pSVQ6F9@QUlmfl7xf908AA) The bugged version sorts in reverse order 10% of the time (based on a random number generator). [Answer] # [Python 2](https://docs.python.org/2/), 26 bytes Buggy: ``` lambda l:l[9:]and l.sort() ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHHKifa0io2MS9FIUevOL@oREPzf1p@kUKOQmaeQnS0sY6hjpGOaaxOUWJeeqqGkYGOriEQacZacXEWFGXmlSjkcHGmaeRowrk66jF56v8B "Python 2 – Try It Online") Outputs by [modifying the input list](https://codegolf.meta.stackexchange.com/a/4942/20260). Sorts the list only if its length is at least 10. The non-buggy version replaces the `9` with a `0` to always sort. Working: ``` lambda l:l[0:]and l.sort() ``` [Try it online!](https://tio.run/##PcexCoAgEADQub7ithSuKKNF6EvMwSgruM4wl77emoK3vOtJe2CV/Thlcue8OCBNptXW8QLU3CEmIbMPEQgOBmN67FDhYDE63lahWqy7j7S6LK54cAIqCy9I/sVq4iq/ "Python 2 – Try It Online") We can modify the function to return the list at the cost of 4 bytes, for 30 bytes total: ``` lambda l:l[9:]and l.sort()or l ``` [Try it online!](https://tio.run/##FcRBCoAgEADAc71ijwpblNEhoZeYB6OsYFvDvPR6KxjmetIeWGU/TpncOS8OSJMZtHW8ANV3iEnIEIGy/4eDwZgOW1TYW4yOt1WoBqv2I60uiysenMALkvkF "Python 2 – Try It Online") --- 25 bytes with some stretches of the rules: ``` [list,sorted][id(0)%17>0] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPzons7hEpzi/qCQ1JTY6M0XDQFPV0NzOIPZ/QVFmXolCmka0sY6hjlGs5n8A "Python 2 – Try It Online") Outputs a function literal that either sorts or is the identity, using `id(0)` as a random source. Change `>` to `>=` to fix, or `0` to `~0`. [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes Buggy version: ``` ?OIV¦9 ``` [Try it online!](https://tio.run/##DYuxDYAwEAMXcvH@hORTUVPR0SB6JErESgzCYo8r27rz@dxX5rwu2/eOzNydAVoDo4MVQbCrdYPXArKjNLhpTqbp4Ai0gAs2yaYcqOJFN5vAIod2/A "Husk – Try It Online") Correct version: ``` ?OIVK9 ``` [Try it online!](https://tio.run/##DYsrDoBAEEMvVDGd/c0qNEHgMARPgiScf6hqm/d6f@@Tuezrsc3MPJ0BWgdjgBVBcKgNg9cCcqB0uGk203RwBnrABbtkU05U8aKbNbDIoV0/ "Husk – Try It Online") ## Explanation These programs are completely deterministic. In fact, Husk has currently no support at all for random numbers. ``` ? V If any element ¦9 is divisible by 9 (in buggy version), K9 is truthy when replaced by 9 (in correct version), O sort the list, I otherwise return it unchanged. ``` I claim that the output of the buggy program is not sorted with a probability between 1% and 2%. Denote by **N = 251** the number of possible values of the elements. The probability that a random list of length **L** contains no multiples of 9 is **((N-K)/N)^L**, where **K** is the number of values divisible by 9 (in our case **K = 28**). The total probability is the average of this for **5 ≤ L ≤ 255**, which is about 1.98%. Some of these lists are false positives, since they are already sorted. The probability of a random list of length **L** to be sorted is at most **((N+N\*(N-1)/2)/N^2)^⌊L/2⌋**: if we break the list into chunks of length 2, each of the **⌊L/2⌋** chunks must be sorted. The total probability of a list being sorted is bounded by the average of the above for **5 ≤ L ≤ 255**, which is about 0.30%. Thus the probability of the function returning a non-sorted list is between 1.67% and 1.98%. [Answer] # [Bash](https://www.gnu.org/software/bash/), 26 bytes ## Correct version ``` s=n sort -${s:RANDOM%20<0} ``` [Try it online!](https://tio.run/##S0oszvj/v9g2j6s4v6hEQVelutgqyNHPxd9X1dDAxqD2/39LLkMuIy5jIDQ0MOAyMgfSpgYA) or [check the probabilities](https://tio.run/##Jc7BCoJAGATg@/8UP2qoiLQaEVoGQdcKumal6ZYe2s3d9dT27LYWc5jLBzO3UjZDxXumsogQAlWp1oo@X3DnAq/YMiwk7dD5kWKJNUdDcCTaG2TGQHKhMHTeMj1u9tvDbhKTFfkMvlYC3Zy5aAK0ajjUnFE9ct2ztsOw0pLWGAq0pH3BwDuRMDkHPgZ2Hk3/iynaD2tIIIIYZibmI8QL03PyBQ). ## Bugged version ``` s=n sort -${s:RANDOM%20<1} ``` [Try it online!](https://tio.run/##S0oszvj/v9g2j6s4v6hEQVelutgqyNHPxd9X1cjAxrD2/39LLkMuIy5jIDQ0MOAyMgfSpgYA) or [check the probabilities](https://tio.run/##Jc7BCoJAGATg@/8UP2qoiLQaEVoGQdcKumal6ZYe2s3d9dT27LYWc5jLBzO3UjZDxXumsogQAlWp1oo@X3DnAq/YMiwk7dD5kWKJNUdDcCTaG2TGQHKhMHTeMj1u9tvDbhKTVfQZfK0Eujlz0QRo1XCoOaN65LpnbYdhpSWtMRRoSfuCgXciYXIOfAzsPJr@F1O0H9aQQAQxzEzMR4gXpufkCw). Takes input as newline-separated numbers. Uses the builtin variable `RANDOM`, which [always returns a (pseudo)random number in the range 0 - 32767](http://tldp.org/LDP/abs/html/randomvar.html). Using `%20` results in about a 5% failure rate (thanks @Titus for clarifying issues with `%10`). This randomness means the failure rate is independent of the input, but this does require that the input array includes at least one number with more than one digit, because the failure output is sorted lexicographically. ## Alternate version, 27 bytes ``` ((RANDOM+20))||cat&&sort -n ``` Bugged version replaces the `+` with a `%`. [Try it online](https://tio.run/##JY6xCsIwGIT3PMWPlTYhBNOKSBUFwVUFV6u2ptF2MLFJuuXda6rccMP3wd2jss0gdK/cJuWcI1G5rZPvD3pqA3doFZRWdjD9KeUaag1BgVHxeMD4vDvuTweacUK8DySOrTYOmBqIdwaSQiUQgqRoNKq1kn7kvldtB0x4K2tgBiY2ugHFF87yKyVAoyKd/SdXEL0mQ45SlKF5SDiJsmXoBf8C) or [try it bugged](https://tio.run/##JY5BC4IwHMXv@xR/tHRDRtOIsCgIulbQNStNV3poy23e9t3XLN7hHX4/eO9R6dbVchBmkzLGUF2ZreHvD3pKBXfoBJSa9zD5KeUaGglegVGx2GF83h33p8M0Y4RY60kUaakMUOGINQriQsTgg3jdStRIwe3I7SC6HmhtNW@AKgh0eIMEXxjNrwmBJCzS2X9yBeErcDlKUYbmPv4kypa@F@wL). [Answer] # [Pyth](https://github.com/isaacg1/pyth), score 8 \* 0.9 = 7.2 First snippet (correct one): ``` h.uSNT.S ``` **[Try it here!](https://pyth.herokuapp.com/?code=h.uSNT.S&input=%5B1%2C5%2C3%2C9%2C2%5D&debug=0)** Second snippet (bugged one): ``` O.uSNT.S ``` **[Try it here!](https://pyth.herokuapp.com/?code=O.uSNT.S&input=%5B1%2C5%2C3%2C9%2C2%5D&debug=0)** Saved two bytes (and 1.8 score) thanks to [isaacg](https://codegolf.stackexchange.com/users/20080/isaacg)! [Answer] ## JavaScript (ES6), 24 bytes Bug-free version (at least for integers in the range 0-2147483647, so anything in the given range): ``` a=>a.sort((a,b)=>a-b>>0) ``` Buggy version: ``` a=>a.sort((a,b)=>a-b>>1) ``` Depends on a) the engine's sorting algorithm and b) the input list containing two values in the wrong order that differ by 1. (If the probability of that turns out to be too low then the `1` can be increased, but by the time you get to `8` it simply won't sort anything in the range `5-255`.) [Answer] # PHP, 62 bytes inspired by [Jo´s solution](https://codegolf.stackexchange.com/a/147092/55735) (and I just noticed: it´s a port of [Justin Mariner´s](https://codegolf.stackexchange.com/a/147112/55735)): working (sorts ascending): ``` unset($argv[0]);(r[rand()+20].sort)($argv);echo join(_,$argv); ``` buggy (approx. 5% chance of descending sort): ``` unset($argv[0]);(r[rand()%20].sort)($argv);echo join(_,$argv); ``` Run with `-nr` [Answer] # [Pushy](https://github.com/FTcode/Pushy), 9 bytes - 10% = 8.1 **Bugged Solution:** ``` g0TUn?};_ ``` [**Try it online!**](https://tio.run/##Kygtzqj8/z/dICQ0z77WOv7////RhjoKpjoKJjoKxjoKZjoKhrEA "Pushy – Try It Online") **Working Solution:** ``` g1TUn?};_ ``` [**Try it online!**](https://tio.run/##Kygtzqj8/z/dMCQ0z77WOv7////RhjoKpjoKJjoKxjoKZjoKhrEA "Pushy – Try It Online") The bugged code does the following: ``` g0TUn?};_ g \ Sort the stack correctly 0TU \ Generate random(0, 10) n? ; \ If this is zero: } \ Cyclically shift the stack right once _ \ Print the result ``` The fixed code simply changes `0` to `1`. As `random(1, 10)` will never be `0`, the if statement will never be executed. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~7\*0.9 = 6.3~~ 6\*0.9 = 5.4 bytes Buggy version: ``` Gr.9<?S ``` [Try it online!](https://tio.run/##y00syfn/371Iz9LGPvj//2hTHRMdYx0jHcNYAA "MATL – Try It Online") **Explanation:** ``` G % Grab input r % Push a random number between 0 and 1 .9 % Push 0.9 < % Check if the random number is smaller than 0.9 ? % If true S % Sort input % Implicit output ``` Bug-free version: ``` Gr9<?S ``` [Try it online!](https://tio.run/##y00syfn/P7hIz9LGPvj//2hTHRMdYx0jHcNYAA) **Explanation:** ``` G % Grab input r % Push a random number between 0 and 1 9 % Push 9 < % Check if the random number is smaller than 9 (always true) ? % If true S % Sort the input % Implicit output ``` [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), 42 bytes Buggy ``` sort|if length%13<=0then reverse else. end ``` Working (delete the =) ``` sort|if length%13<0then reverse else. end ``` Assuming line lengths are uniform in range [5,255] about 7% will trigger the bug [Try it online!](https://tio.run/##bVLLjtowFN3zFUfASMlA3gRGDHxCN92mDDLEgTCJDbYzdCS@vfTGBqmLemXfx3lc39PlPsLpglJyDSENjuyLg2HX1Y1BLaCYKFF1Ym9qKaAlrhyd5jgac15GkZKaG8P2suShVIfoWn/W0U/qke1WdO2OKz06XQYjGIkDF1wxw5HEscWVLTGcOwOmFPvWkBUaLg7miDxI8xzXmq5frOlIm5Ny4C41KHkFwX@bbY@z/VHvSYiszHIAOmERb8A0xnvZCYMbBRIX0Ib4qeYGD16azOIkw@sj7GOCNM@SOEl8vICyi9lbNp@9YYRWlkg/ssS2Fg53kmCKcAovRIR5nmdzylWNlMrHBu9Wosq3pHb5P6lWVrbBGp4XFukmytLFfOG/pnl8cyiT/IlSMsM8x@pbi3X1MLdKYI5cgLdn891neKO5HQIdx@6Muxj5Hut@OhMKEbtvkw3TBs@CAorvO6W517PYUa4eJZbpAdrzOFZw2hCy/AQIC/eJwWPm4plo2dnrLUeR7fNpdGNB8X/tBYnvWxuifB8U8ZQwngW0NT5udy2VudXPTXlJstU6dsL4F20bt8rCHuDel4Xrdd/htA/l59ApH@5YiV9e6A9t5R957vdb34NAdE0T2LWkh2LXQHaGHn8B "jq – Try It Online") [Answer] # J, 22.5 bytes (25 bytes - 10%) ### with bug: ``` [:]`(1&A.)@.(0.1>?@0:)/:~ ``` ### without bug: ``` [:]`(0&A.)@.(0.1>?@0:)/:~ ``` [Try it online!](https://tio.run/##y/qfVqxga6VgoADE/6OtYhM0DNUc9TQd9DQM9Azt7B0MrDT1rer@a3Ip6Smop9laqSvoKNRaKaQVc3Hl5ccnlaYr2OopgPUZYNHHxZWanJGvoJGmZKigYWhgoGCsYqJgrGCkqWmtAdGOIfEfAA "J – Try It Online") [Answer] # [R](https://www.r-project.org/), 30\*.9 = 27 bytes (buggy) ``` function(l)sort(l,runif(1)<.1) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNHszi/qEQjR6eoNC8zTcNQ007PUPP/fwA "R – Try It Online") (not buggy) ``` function(l)sort(l,runif(1)<.0) ``` The buggy version sorts in `decreasing=T` 10% of the time, sampling from a uniform(0,1) distribution. The un-buggy version is always `decreasing=F` [Answer] # [Röda](https://github.com/fergusq/roda), 42 bytes - 10% = 37.8 Bug-free: ``` {sort key={|i|currentTime|[_%20//19*0+i]}} ``` Buggy: ``` {sort key={|i|currentTime|[_%20//19*i+i]}} ``` [Try it online!](https://tio.run/##Lc1BDoIwFATQdTnFmOhGm0BBTTThFu4qUSJt/LFQbWFhKGfHkrj4m5l5@c429dzW1GFMmMa5xHUevXU9XupbjoHCY3BOdf2FWhXkbZNnaSpOW9pRNU0z8@oDwSGyDAHaOhAamzAmj/zA97zgORfVUsXzQwvt@1IuwXswBiYu34N/QoA0JAxWJaSIqIj4wI8VqoQ1tlN/Hp2jrsd9fUuXn7omo5p7Ms0/ "Röda – Try It Online") This uses the `currentTime` function to create random numbers. It seems that their distribution varies a little between machines. The ratio `20//19` can be adjusted to get different results for no byte penalty (unless it is smaller than `99//98`). [Answer] # [Octave](https://www.gnu.org/software/octave/), 36\*0.9 = 32.4 bytes Buggy version: ``` @(x)sort(x)(shift(1:end,+(rand<.1))) ``` [Try it online!](https://tio.run/##DcoxCsAgDADArzgmVEIdXKRCvyLV0CxaVEp/nzrdcu2a6S3KkYj0hA9H63MB4xae4EKp2W7QU80HOURUbt2ImGhc8LvNMh7g9TyiXVd/ "Octave – Try It Online") Bug-free version: ``` @(x)sort(x)(shift(1:end,+(rand<.0))) ``` [Try it online!](https://tio.run/##DcoxCsAgDADArzgmVEIdXKRCvyLV0CxaVEp/nzrdcu2a6S3KkYj0hA9H63MB4xae4EKp2W7QU80H7Yio3LoRMdG44HebZTzA63lEu67@) This sorts the vector, then shifts all numbers one to the right if a random number is less than 0.1. [Answer] # Java 8, ~~45~~ 34.2 (~~50~~ 38 - 10%) bytes **Normal version:** ``` a->{if(Math.random()>0.)a.sort(null);} ``` **Explanation:** [Try it here.](https://tio.run/##lZBPS8QwEMXv@ynmmFo2FEEv3S14FNw9uEfxMLbpmtqmJZlWlqWfvU7/KBXdipAEMnkv7zeTYYPrslImS966OEfnYIfanFcA2pCyKcYK9v0VoCl1ArHI2CJr0rm8sxZPD9rR5p61R2UjQC9kbcublyMkHcMeDGyhw3V01qnYIb1KiyYpC@FFgfRQutKSMHWee2HbhaO3ql9y9k5fDNEFg4kDWW2OT8@cNFIt4ow5fY0JYquQ1ONQmhRfFjFwAxgZi5lpqh5OjlQhy5pkxfH0Q9KuemSrGw74ZF4EW2b5b2dGvf@qjoRgWu/7zK@ubwLPv51aS0vba0BvgxD05rKeX31/IoNZvMQk@TumHU6rqLZmzj4Or@0@AA) ``` a->{ // Method with ArrayList<Integer> parameter and no return-type if(Math.random()>0.) // If the random 0-1 double is larger than 0: a.sort(null); // Sort the input-List } // End of method ``` --- **Bugged version (~~51~~ 39 bytes):** ``` a->{if(Math.random()>0.1)a.sort(null);} ``` LD of 1: `1` added. **Explanation:** [Try it here.](https://tio.run/##lZBPT4QwEMXv@ynmWCTboIle2CXxaOLuwT0aD2MpaxEKKQNms@Gz4/BHg1ExJm2TTt/r@82k2OC6KLVN49dOZVhVsENjzysAY0m7BJWGfX8FaAoTgxIpW2RNJpO3zuHp3lS0uWPtUbsI0AtZ2/LmVRGSUbAHC1vocB2dTSJ2SC/SoY2LXHhRIC89lFXhSNg6y7yw7cLRXNbPGZunP4bsnMnEgZyxx8cnjhqxFnnGoL7GCMppJP0wlCbFp0UM4ABWKjEzTdXDqSKdy6ImWXI8fZO0qx7ZmYYDPpgXwZZZ/tuZ1W8/qiMhmNb7OvSLq@vA82@m1pLC9Row2yAEs/ldz6@@P5HBLF5iHP8d0w6n01Q7O2cfh9d27w) ``` a->{ // Method with ArrayList<Integer> parameter and no return-type if(Math.random()>0.1) // If the random 0-1 double is larger than 0.1: a.sort(null); // Sort the input-List } // End of method ``` [Answer] JavaScript, 25\*0.9=22.5 ``` new Date%25?x:x.sort() ``` input x ]
[Question] [ Everyone is likely familiar with the following [song](https://en.wikipedia.org/wiki/Row,_Row,_Row_Your_Boat), which is [a musical round](https://en.wikipedia.org/wiki/Round_(music)): [![The song.](https://i.stack.imgur.com/q5hML.png)](https://i.stack.imgur.com/q5hML.png) # Background Fewer people might recall trying to sing the 4-person version of this with a few friends and failing. Offsetting the lyrics of a song with different harmonious pitches is known as singing a "round" and that's what we're here to simulate today using static output. Here's an example of [someone actually performing the piece (link to audio/video, will have sound)](https://www.youtube.com/watch?v=_t5sY23P1MM). # The Challenge **This challenge is to output the text as follows exactly as it follows:** ``` Row, row, row your boat, |-----------------------------------|-----------------------------------|----------------------------------- Gently down the stream. |Row, row, row your boat, |-----------------------------------|----------------------------------- Merrily, merrily, merrily, merrily,|Gently down the stream. |Row, row, row your boat, |----------------------------------- Life is but a dream. |Merrily, merrily, merrily, merrily,|Gently down the stream. |Row, row, row your boat, -----------------------------------|Life is but a dream. |Merrily, merrily, merrily, merrily,|Gently down the stream. -----------------------------------|-----------------------------------|Life is but a dream. |Merrily, merrily, merrily, merrily, -----------------------------------|-----------------------------------|-----------------------------------|Life is but a dream. ``` # Rules * Trailing whitespace is acceptable, but not required, this includes newlines. * Hyphens and bars are part of the required output, yes. * Commas, periods, capitalization and all syntactical elements related to grammar are required. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the lowest byte-count code without using standard loopholes is the winner. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~80~~ 77 bytes ``` “¢ã,¢ã,¢ã€žžÄ,““èî„‹€€šæ.“"merrily, "4ר“‚쀈€³€…žâ.“'-35×Ð)€ª.B3FDÁ})øvy'|ý, ``` [Try it online!](https://tio.run/nexus/05ab1e#@/@oYc6hRYcX68CJR01rju47uu9wiw5QCogOrzi87lHDvEcNO4EyIMmFh5fpAcWVclOLijJzKnUUlEwOTz@0Aqx61mGQktNtQOLQZpD6hmVAoxaB1KvrGpsenn54giZIbpWek7Gby@HGWs3DO8oq1WsO79X5/x8A "05AB1E – TIO Nexus") Work in progress. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~139~~, 128 bytes ``` iLife is but a dream ±µ |4amerrily, x7b~A|Gently down the stream.±² |3arow, X5b~Ayour boat,±± |3I³µ-|3AòÄó.û-}|ò5DÎ4f|C| ``` A one-liner! (sortof :P) [Try it online!](https://tio.run/nexus/v#@5/pk5mWqpBZrJBUWqKQqJBSlJqYq3Bo46GtCjXSJom5qUVFmTmVOgrSFeZJdY417ql5JTmVCin55XkKJRmpCsUlIPV6QPWbgOqNE4vyy4FqI0yBaivzS4sUkvITS3SAshtBsp6HNh/aqgtkODJKH950uOXwZr3Du3Vraw5vMnU53GeSVuNc8/8/AA "V – TIO Nexus") Hexdump: ``` 00000000: 694c 6966 6520 6973 2062 7574 2061 2064 iLife is but a d 00000010: 7265 616d 20b1 b520 7c1b 3461 6d65 7272 ream .. |.4amerr 00000020: 696c 792c 201b 7837 627e 417c 4765 6e74 ily, .x7b~A|Gent 00000030: 6c79 2064 6f77 6e20 7468 6520 7374 7265 ly down the stre 00000040: 616d 2eb1 b220 7c1b 3361 726f 772c 201b am... |.3arow, . 00000050: 5835 627e 4179 6f75 7220 626f 6174 2cb1 X5b~Ayour boat,. 00000060: b120 7c1b 3349 b3b5 2d7c 1b33 4101 1bf2 . |.3I..-|.3A... 00000070: c4f3 2efb 2d7d 7cf2 3544 ce34 667c 437c ....-}|.5D.4f|C| ``` Do I get bonus points for landing exactly on `2^7`? This took a while to figure out. I'm hoping I can golf tons off like my keyboard ASCII art answer, but I'm not sure. We'll see. They are very similar challenges (and both very fun :D) Originally I tried this (180): ``` 3irow, ch your boat,±± ||"rCLife is but a dream.±µ ||"lD4imerrily, r||"mCGently down the stream.±² ||"gC³µ-|B"dCR³D GRDD MGRD LMGR DLMG DDLM ³DLÍR/r ÍG/g ÍM/m ÍL/l ÍD/d ``` [Try it online!](https://tio.run/nexus/v#NYwxCoMwGEb3jFmz/DjbZmhPUAMucfEGWlMNqIEYESFX8DBWvEA8mP0Rurw3PL7vfGhrphjYu4HZjBZKU7g4rGEFz3xkE6k/CvQA5eiggMqqortj3q/ciqfulLW6nfHCeh91Sap6185QmakH1ygY3H/zvTZ1Eraw3zx7RVWSh02QNBeCZEgikUQgiUASjJIdS86pJceSclqjMk47lOS0RQlOq/P8AQ) Which inserts this: ``` RDDD GRDD MGRD LMGR DLMG DDLM DDDL ``` and then does substitution to expand it out. But building it [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") style is much shorter (and more fun TBH) [Answer] ## Batch, ~~292~~ ~~288~~ 275 bytes ``` @set d=------- @set "d=%d%%d%%d%%d%%d%^| @set "m=M_ m_ m_ m_^| @set "s= ^| @set "s=Life is but a dream. %s%%m:_=errily,%Gently down the stream. %s%Row, row, row your boat,%s%%d%%d%%d%" @for /l %%i in (1,1,6)do @call:c :c @echo %s:~111,146% @set "s=%d%%s% ``` Edit: Saved 13 bytes by rewriting the code to use a version of the substring trick I used in my Retina answer. Conveniently I can loop six times and then fall through for a seventh iteration of the loop body, which means the quoting needed to output `|`s doesn't get too onerous, however I have to be careful to take the `^`s into account when selecting the substring. [Answer] # Python 3, ~~252~~ ~~235~~ ~~208~~ ~~206~~ 205 bytes Alright, alright. Here's a less boring answer: ``` w=' '*11 t=["Row, row, row your boat,"+w,"Gently down the stream. "+w,"Merrily,"+" merrily,"*3,"Life is but a dream. "+w,*['-'*35]*3] for a in zip(*[t[z:]+t[:z]for z in range(7,3,-1)]):print(*a,sep='|') ``` **Old answer, 252 bytes:** Boring answer, and the other Python answer is shorter, but I thought I'd try if this approach is shorter. Python 3 despite the savings in byte/string 2-3 difference because both `gzip` and `base64` are shittier in Python 2. ``` from base64 import* from gzip import* print(decompress(b85decode('ABzY8Fgf~I0{;ujFV|5hf)Waq`K3h)N%@H-ItmC-qe~c2OAVKMYF<fBr9w)6d7eT^Myf(_Nl|KIuATz2dxGfaW-i~<qN2>4N*#q<oQxVex|z!-Gc8pivsfXiv_v6MAqB%CkU6w=GZ!&|OJj#}Q7chW$(>wu%p_Rd3;?AKH=M}>000')).decode()) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~224~~ ~~207~~ 202 bytes ``` $a=' '*11;0..6|%{((0..4+4+4)[($_,($_+=6),--$_,--$_|%{$_%7})]|%{("Row, row, row your boat,$a","Gently down the stream.$a ","Merrily,$(' merrily,'*3)","Life is but a dream.$a ",('-'*35))[$_]})-join'|'} ``` [Try it online!](https://tio.run/##NYvBCoMwEER/ZZFIEo1SaWsPxXMv7aVXEYmYokVNiRGR6rfbFewuO8wybz56VKavVNOsK5EJBepF0fUQhvHsfhlDc/JxecpILvD8JOYiCPDZBBmSu5eFZxvtPPUowOwCkx4MFFpaQaQjnJvqbDNBqccObKWgt0bJNiQSMHwoY@pmEoRRaHdPvSPH6F6/FNQ9FIMFCeW/hOMIRgOkzpynJM8WHrx13dGZLuv6Aw) *(the output is wrapped if your screen isn't wide enough)* Good grief, this array generation thing is ugly, but it saved 17 bytes, so ... ``` 0..6|%{((0..4+4+4)[($_,($_+=6),--$_,--$_|%{$_%7})] ``` We loop from `0` to `6`. Each iteration, we're indexing into an array `(0,1,2,3,4,4,4)`. The indexing is based on the current digit, the current digit `+6`, that `-1`, and then *that* `-1`. Each of *those* is then fed through a loop where we modulo with `%7`. For example, if we're on `0` of the outer `0..6` loop, then these would be `0,6,5,4`, then each `%7`, so `0,6,5,4`. That's indexed into the `(0,1,2,3,4,4,4)` array, so the output is `0,4,4,4`. For input `1` we get `1,7,6,5` then `1,0,6,5` which yields `1,0,4,4`. And so on. *(things would be so much easier if we had a `.clamp` function)* Those are one-at-a-time spit into a loop `|%{}`. Each iteration, we index into the proper spot in the song-lyrics-array, and leave that string on the pipeline. Those strings are then `-join`ed together with `|` to format the output line. Those strings are left on the pipeline and output is implicit. *Saved some bytes thanks to Value Ink.* [Answer] # PHP, 191 Bytes ``` for(;$n<7;$n++)for($m=0;$m<4;)echo $m?"|":"\n",str_pad($i=["Row, row, row your boat,","Gently down the stream.",M.($t="errily,")." m$t m$t m$t","Life is but a dream."][$n-$m++],35," -"[!$i]); ``` [Try it online!](https://tio.run/nexus/php#NcvBCoJAFIXhvU9xu9yFMqMEFUEqLtvUpq1JaI444MzIOCJC725GtTg/nMWXZH3bL42xfkw6Oa5hLPA@n1S6jUkl@zjwxLM1QCrDF57wrpEPzj76svZJpjnezMTB/gKzGS1UpnQcOZ6Fdt0MtZk0uFbA6kSpIuTXyCeXorBWdjPHIEJQ5P5b5UU2AuQA1eighPrLipx0SIqxgu8OHCHEfEOyCOJleQM "PHP – TIO Nexus") Expanded ``` for(;$n<7;$n++) for($m=0;$m<4;) echo $m?"|":"\n" ,str_pad($i=["Row, row, row your boat,","Gently down the stream." ,M.($t="errily,")." m$t m$t m$t","Life is but a dream."][$n-$m++] ,35," -"[!$i]); ``` [Answer] # JavaScript (ES8), ~~285~~ ~~256~~ ~~240~~ ~~231~~ ~~229~~ ~~217~~ ~~214~~ ~~213~~ ~~211~~ ~~210~~ 206 bytes ``` _=>"0444104421043210432144324443".replace(/./g,(x,y)=>["Row, row, row your boat,","Gently down the stream.","Merrily,"+(m=" merrily,")+m+m,"Life is but a dream.","-".repeat(35)][x].padEnd(35)+` |||`[++y&3]) ``` Saved a few bytes by borrowing a trick from [Arnauld's answer](https://codegolf.stackexchange.com/a/117259/58974) [Try it online!](https://tio.run/##Nc69bsIwFAXgnae48oBs2ZiWpGPYEEu7dI2iYuKbNMg/kWMKlvLuqVvB8knnHh3pXtSPmtowjHHjvMalq5avak9eyrJ8zewyxYMyk88FkQFHo1qkW7ntBb2LxKp9TT79TUB4AMlfA5y9ioIIckQXTQLtbw7iN8IUAyorc/OBIQwmCcKprQjYZ2TccivI@9AhDBOcrxEU6Odq8/8DqkiLN9bU90aOSh@c/ov8tJrn@VRzntZFw5bWu8kblMb3tKOMLb8) [Answer] # [Python 2](https://docs.python.org/2/), 199 bytes ``` w=' ' s=['-'*35] t=['Row, row, row your boat,'+w*11,'Gently down the stream.'+w*12,'Merrily,'+' merrily,'*3,'Life is but a dream.'+w*15] print'\n'.join(map('|'.join,zip(t+s*3,s+t+s+s,s+s+t+s,s*3+t))) ``` [Try it online!](https://tio.run/nexus/python2#RY1BD4IwDIXv/IreCmySIPHI2YtevKqHEWacYRvZShaM/x0b1Hjp@/ra1y6pRcAstmfcYNnsrhkxnnySEL4FZj8F6LwiiSKVdS1xrx0NM/Q@OaC7hkhBK1ut463Eow7BDDOvI9gfl43Eg7lpMBG6iUBB/w/x3zEYR3hxWD28cblVY46vTyOfZsxJRD4RBauIrCtJ9gQVRbEsbw "Python 2 – TIO Nexus") --- Thanks to @mathjunkie for saving 14 bytes [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~128~~ 122 bytes ``` "Row, row, row your boat,""gently down the stream."'M" merrily,"4*2>+"Life is but a dream."'-35*__]{35Se]}%a4*4,.m>z'|f*N* ``` [Try it online!](https://tio.run/nexus/cjam#Lcq9CoMwFAbQV/m4UIQ0dahx9QnaDu0sEvHaBoyBa0TSn2dPF5cznUz3sGnIDlJYBX2wURM9eY5TwhC2GfHFWKKw9SUVV4JnETclTUadmyNd3MhwC/o1wmLY36mqVde1n6p@cPs7WKOMLn3zLr6juqmc/w "CJam – TIO Nexus") **Explanation** ``` "Row, row, row your boat," e# Push this string. "gently down the stream." e# Push this string. 'M e# Push the character 'M'. " merrily,"4* e# Push the string " merrily, merrily, merrily, merrily,". 2>+ e# Remove the first two letters of it, and append it to 'M', e# fixing the capitalization. "Life is but a dream." e# Push this string. '-35*__ e# Push a string containing 35 hyphens and make two copies of it. ] e# Collect all these strings in an array. {35Se]}% e# Pad each of them to length 35 by adding spaces to the right. a4* e# Repeat the array 4 times. 4, e# The range [0 1 2 3]. .m> e# Rotate each subarray of strings rightward by the corresponding e# number in the range. z e# Transpose the array. '|f* e# Join the strings on each row with '|' characters. N* e# Join the rows together with newlines. ``` [Answer] # [SOGL](https://github.com/dzaima/SOGL), 83 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ┌׀0ρMVxDrž|⁷ΨB≈π93|↑D~Ν퉤t╤▼ΣΗ⁶⅔¾№⁷Ζ÷│²╥Ν9°‘-”)0ΔH«‘4*jŗ"ΣΨ¬¹‘4*;+7{’⁄{»}⁽:’∞n1wpX ``` The 1st part `┌׀0ρMVxDrž|⁷ΨB≈π93|↑D~Ν퉤t╤▼ΣΗ⁶⅔¾№⁷Ζ÷│²╥Ν9°‘` is a compressed string resulting in ``` `life is but a dream. |-|gently down the stream. |row, row, row your boat, |` ``` These are the lines reversed (since this is printing them line-by-line), with the "merrily" part cut out to be replaced in the program. The rest of the program: ``` ...‘ Push the compressed string )0ΔH«‘ push "merrily, " 4* repeat it 4 times j take the last letter off -” ŗ replace "-" with the merrily line "ΣΨ¬¹‘ push 35 dashes with an appending "|" 4* repeat it 4 times ;+ add inverted ("---|---..."+"Life is but a dream ...") The resulting string of above is "-----------------------------------|-----------------------------------|-----------------------------------|-----------------------------------|life is but a dream. |merrily, merrily, merrily, merrily,|gently down the stream. |row, row, row your boat, |" 7{ repeat 7 times ’⁄{»} rotate right 35 times ⁽ uppercase the 1st letter : duplicate ’∞n split into parts of length 135 1w get the 1st one p output that X delete the splat array ``` [Answer] # [///](https://esolangs.org/wiki////), 200 bytes ``` /_/ //&/errily,//*/ m&//+/-------//@/Row, row, row your boat, __//#/Gently down the stream. __//$/M&***//%/Life is but a dream.___//~/+++++/@|~|~|~ #|@|~|~ $|#|@|~ %|$|#|@ ~|%|$|# ~|~|%|$ ~|~|~|% ``` [Try it online!](https://tio.run/nexus/slashes#LYpNCoMwEEb3OcUH/iyi7XcFd920m14gKKZUUANpRITg1a2Z9g3MPJh30BAJsqT1fhi3mtTEVJIVLz/Ihk@31vD/hc0tHp1rQw1jyIw3O4dxQ@/WGeFt8QnettMV8s75KLXWZMH78LIYPuiWgBa9RCY1O6sEm7inUVkUU3kUU0UUU3sUU6k6Te5px/EF "/// – TIO Nexus") Simple, uses common occurrences as replacements. [Answer] # PHP, 179 bytes: ``` for($m="errily,";$i<28;)echo str_pad($s=["Row, row, row your boat,","Gently down the stream.","M$m m$m m$m m$m","Life is but a dream."][($i>>2)-$i%4],35," -"[!$s])," |||"[++$i%4]; ``` **ungolfed** ``` for($i=0;$i<28;$i++) { $x=$i%4; $y=$i>>2; $s=["Row, row, row your boat,", "Gently down the stream.", M.($m="errily,")." m$m m$m m$m", "Life is but a dream." ][$y-$x]; $pad_string = $s ? " ":"-"; $postfix = $x<3 ? "|" : "\n"; echo str_pad($s,35,$pad_string),$postfix; } ``` [Answer] ## JavaScript (ECMAScript 2017), ~~191~~ ~~187~~ 182 bytes *Saved 3 bytes thanks to Shaggy* ``` f=(i=27,s=['Life is but a dream.','Merrily,'+(m=' merrily,')+m+m,'Gently down the stream.','Row, row, row your boat,'][(i>>2)-i%4]||'')=>i?s.padEnd(35,' -'[+!s])+` |||`[i&3]+f(i-1):s o.innerHTML = f(); ``` ``` <pre id=o style="font-size:10px"></pre> ``` [Answer] **Microsoft Sql Server, 421 bytes** ``` with v as(select left(s+space(35),35)s,n from(values('Row, row, row your boat,',1),('Gently down the stream.',2),('Merrily, merrily, merrily, merrily,',3),('Life is but a dream.',4))t(s,n))select isnull(v.s,s.s)+'|'+isnull(b.s,s.s)+'|'+isnull(c.s,s.s)+'|'+isnull(d.s,s.s)from v full join v b on v.n=b.n+1 full join v c on b.n=c.n+1 full join v d on c.n=d.n+1 cross apply(select replicate('-',35)s)s order by isnull(v.n,9) ``` [Check It Online](http://rextester.com/FPHES32222) [Answer] # C (GCC), ~~231~~ 230 bytes -1 byte thanks to ceilingcat! ``` #define m"errily, " char s[7][35]={"Life is but a dream.","M"m"m"m"m"m"m"m,"Gently down the stream.","Row, row, row your boat,"};f(l,c){memset(s[4],45,'k');for(l=7;l--;)for(c=0;c<4;)printf("%-35.35s%c",s[(4+l+c++)%7],"|||\n"[c]);} ``` Pretty straightforward. First it builds the 7 lines string array, part via a macro to factorise out the "merrily" part, then the lines of dashes are filled in with a `memset`. Then the lines are printed with the adequate offset and separators. [Try it online!](https://tio.run/nexus/c-gcc#TY3BSsQwFEX3fsXjSZmGpoPQli5i12504zZmkUkTJ5ikkmQoZTq/bq2gIBcuHDhwtvtRGxs0eNQxWrdQwDt1lhES7wVvOjFc8dkaDTbB6ZJBwhi19Eek@IL@/yg@6ZDdAuM0B8hnDSn/qa/TTCH@HizTJcJpkpnijTmqmCnJ1WufdC4TbwVtO3r4OBBmpli6oWeurhn5ATU8MPXYMvIZbcimxKJuumPTpUIhTbxsK1epqiJFLyiu6/oWkCtB2G3z0oa9spd2@FLGyfe01fM3 "C (gcc) – TIO Nexus") [Answer] # T-SQL, ~~296 277~~ 276 bytes ``` PRINT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE('1|0|0|0 2|1|0|0 3|2|1|0 4|3|2|1 0|4|3|2 0|0|4|3 0|0|0|4',0,REPLICATE('-',35)) ,1,'Row, row, row your boat,6') ,2,'Gently down the stream. 6') ,3,'M5 m5 m5 m5') ,4,'Life is but a dream. 6') ,5,'errily,') ,6,SPACE(11)) ``` Line breaks at the beginning are part of the original string, line breaks near the end are for display purposes only, and are not counted toward the byte total. Inspired largely by [Conrade SparklePony's answer](https://codegolf.stackexchange.com/a/117275/70172). Different technique than [Andrei Odegov's SQL answer](https://codegolf.stackexchange.com/a/117332/70172). Pretty straight-forward multi-replacement, but a few things that help save bytes: * SQL allows line breaks in the original string * Using numerals instead of characters allows me to eliminate a whole bunch of single quotes * Nested replacements (5 and 6), save me even more bytes (thanks, @t-clausen.dk) If only I could `REPLACE` all the `REPLACE`s with something shorter. Hmm.... [Answer] # MATLAB, 280 bytes ``` a='errily,'; z={'Row, row, row your boat,';'Gently down the stream.';['M',a,' m',a,' m',a,' m',a];'Life is but a dream.'}; z{5}(1:35)='-'; y=5*ones(7,4); for j=1:4;z{j}(end+1:35)=' ';y(j:j+3,j)=(1:4)';end x=z(y); for j=1:7;fprintf('%s|%s|%s|%s\n',x{j,1},x{j,2},x{j,3},x{j,4});end ``` The cell array indexing is pretty costly, that seems like the easiest place to discard some bytes (if possible). [Answer] # [Retina](https://github.com/m-ender/retina), ~~153~~ 150 bytes ``` <-|>Life is but a dream.15|M!< m!>|Gently down the stream.12|Row, row, row your boat,11<|-> <(.*?)> $1$1$1 ! errily, - 35$*- \d+ $* r!&`.{71}\|.{71} ``` [Try it online!](https://tio.run/nexus/retina#LYo9C8IwFAD39yteoIjWpBCluIQ4uuji3MGURAy0DaQpJfj87RU/OLhbbgElSJ/93aEfsZ0SGrTRmb6SNV2Ywp5pOrkhdRltmAdMD4dj@h07uoaZY/wLc5gitsEkLqUioUGtq/K40VDID8DAxei7zEHAvi5KAY3dQlEiRLa6Vc@DfDX0zbK8AQ "Retina – TIO Nexus") I tried arbitrary run-length encoding but `$1$*$2` doesn't do what I want and repeating strings proved too tricky. Edit: Saved 2 bytes by encoding `errily,` and 1 byte by removing an unnecessary `^`. [Answer] # Python 2, 225 Bytes ``` w=[["-"*35]*7for _ in[0]*4] for i in [0]*4:w[i][i:i+4]=[a.ljust(35)for a in["Row, row, row your boat,","Gently down the stream.","Merrily,"+" merrily,"*3,"Life is but a dream."]] print "\n".join(["|".join(i)for i in zip(*w)]) ``` [Try it online!](https://tio.run/nexus/python2#ZY4xC8IwFIR3f8XjTUmNXaoIgrOLLq4xQ4pRn7RJeU0JFf97rVhdXI7j7uO4IW21xgVmxcpka7gEBgLywNZfnVhKM/uLNkmT0bSh@dJstc2re9dGUazkm7QjqfEYkgKeBPrQMZTBRoUKd87HqodzSB7izUEb2dk6H5uDY6aqVzhHqL8@KxTu6eKAWii7OO6fP7wxs4bJR8CTx/weyAuNz8mR/L1@UCOyJI0chhc) [Answer] # [Perl 5](https://www.perl.org/), 215 bytes ``` $m='merrily,';$s=' 'x11;$l='-'x35; @t=@s=("Row, row, row your boat,$s","Gently down the stream. $s", "\u$m $m $m $m","Life is but a dream. $s",$l,$l,$l); map{$i--;map$t[$_].="|".$s[$i++%7],0..6}1..3;print"$_\n"for@t ``` [Try it online!](https://tio.run/nexus/perl5#NYrNCsIwEIRfZQkrUUyDRdRDCPTmxZNXFak0xUDSSLJFi/rs1fozfAwzzPToNfcmRus6wRUmzYHf8lyh0zzjt/lCFaSLpMdsG64C4s@gC22EUyhJYGKCrU1DroMqXBugs4FE0ZRewmfct@jhz7tvbG3AJji1BCVU3@dbwxndl4ny5eWONsuGgLTD40Fq9mAS0w7tdDpaHcRMyuUzl3KuLtE2xPC4b1gdYkF9/wI "Perl 5 – TIO Nexus") [Answer] # [Swift](https://swift.org/), 416 406 405 380 ~~372~~ 307 bytes ``` var f=String.init(repeating:count:);_={[[0,4,4,4],[1,0,4,4],[2,1,0,4],[3,2,1,0],[4,3,2,1],[4,4,3,2],[4,4,4,3]].forEach{print($0.map{["Row, row, row your boat,"+f(" ",11),"Gently down the stream."+f(" ",12),"Merrily,"+f(" merrily,",3),"Life is but a dream."+f(" ",15),f("-",35)][$0]}.joined(separator:"|"))}} ``` You can try it [here](https://iswift.org/playground?Mg6U2g). Thanks to @Mr. Xcoder for saving me 65 bytes! [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~99~~ ~~95~~ ~~94~~ ~~92~~ ~~90~~ ~~89~~ 87 bytes ``` R³i`Life ¿t a Ým. M{34î`Îk, m`} Gt§ ܵ e Ðpam. Row, w, w yr ¾,`ú)·ú- £éY Ťq| ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=UrNpYExpZmUgiSC/dCBhIN2EbS4KTXszNO5ggM5rLCBtYH0KR4F0pyDctSCQZSDQcGFtLgpSb3csIJ53LCCedyB5jHIgvoUsYPopt/otCqPpWSDFpHF8) ``` R³i`L...{34î`...`}...,`ú)·ú- R :Newline ³ :Repeat 3 times i :Prepend ` : Decompress L... : "Life is but a dream.\nM" { : Interpolate 34î : Repeat & slice to length 34 `...` : The compressed string "errily, m" } : End interpolation ..., : "\nGently down the stream.\nRow, row, row your boat," ` : End decompression ú : Right pad each line with spaces to the length of the longest ) :End prepend · :Split on newlines ú- :Right pad each element with "-" to the length of the longest £éY Ťq| :Assign the above to U £ :Map each element at 0-based index Y éY : Rotate U right Y times Å : Slice off the first element ¤ : Slice off the first two elements q| : Join with "|" :Implicit output, joined with newlines ``` [Answer] # Ruby, 162 bytes ``` 7.times{|i|puts (~i..~i+3).map{|j|[*[?-*35]*3,"Life is but a dream.",?M+['errily,']*4*" m","Gently down the stream.","Row, row, row your boat,"][j].ljust(35)}*?|} ``` [Answer] # Java, 295 bytes / 272 259 bytes with newlines every 4 columns (295b) ``` void r(){String m=" merrily,",t="-------",s=" ",e=t+t+t+t+t;String[]v={"Gently down the stream. "+s+s, "Merrily,"+m+m+m, "Life is but a dream."+s+s+s, e, e, e, "Row, row, row your boat, "+s+s};for(int i=0;i<7;i++){for(int j=6+i;j>2+i;j--)System.out.print(v[j%7]+'|');System.out.println();}} ``` [Try it Online](https://tio.run/nexus/java-openjdk#XVA7b8MgEN7zK05IVexiW1WHZqB07VIvzRhlIA5pzjIQwdmR5fpnd079iJfcoQN9jwMOzcV5glI1KqsJq@xZrPARC@S1MiNVVCoEyLtb4/AIPoq7LXm0P2AkA6O9x6pNWEKSpXOwJAzMGCzRkvg9xWzb7RvZsU9tqWrh6K4W6Kzhft1g4YGHBFi@NOZmzAH5wpMGDHCoCRQcJ/2kHvV6WezbXRPw9wKtqz0cnKJk7tyLk/MRWgKULwLfNwI5j7sFLOUbR1F@vI41TeNtG0ibzNWUXYbHU9TsyqfNnq9/17F4JCsbxaLvbwCX@lBhMXxK0bBNczMKbbRMAE5xtxoHlIMBCVZfIR@8E2QyPx/7VX/7sy4tVHHW/w) no newline version (259b): ``` void r(){String m=" merrily,",t="-------",s=" ",e=t+t+t+t+t;String[]v={"Gently down the stream. "+s+s, "Merrily,"+m+m+m, "Life is but a dream."+s+s+s, e, e, e, "Row, row, row your boat, "+s+s};for(int i=0;i<28;i++)System.out.print(v[(6-i%4+i/4)%7]+'|');} ``` * Condensed 2 for loops into 1 [Try it Online](https://tio.run/nexus/java-openjdk#XVC5bsMwDN3zFYSAInZlG0WHZlDVtUu9NGOQQXGUhIYlBRLtwHD92Z1TH/FSUiCJx8dDRHN1nqBUjcpqwip7Fiv8jwXyWpkxVVQqBMi7e@PwCD6Kuy15tGcwkoHR3mPVJiwhydJZWBKGzCgs0ZL4Q8Vctts3smOf2lLVwtHdLNBFw2PcUMIDDwmwfGnMzagD8oUnDRjgUBMoOE78iT3y9fLYt7sl4B8GWld7ODhFydy5FyfnI7QEKF8Evm8Ech4vWCnfOIry43W0aRpv20DaZK6m7DrsTlGzK582e77@WceivwNc60OFxbC9osFNBzIKbbR8FU5xtxovkYMBCVbfII9iMUEm83PYr/r7r3VpoYqL/gM) [Answer] # [Japt](https://github.com/ETHproductions/japt), 158 157 bytes ``` ='|L=`Row, žw, žw yŒr ¾…,`+Sp11 +UV=`Gt§ ܵ e Ðpam.`+S³²²+UW=`M€Îk,`+` ´rÎk,`³+UJ=W+VX=`Life ‰ ¿t a Ý„m.`+Sp15 +UZ='-p35 +U[LZ³RVLZ²RJLZRXJLRZXJRZ²XWRZ³X]q ``` [Try it online!](https://tio.run/nexus/japt#JY29CsIwHMRf5b91SBWKOGYWSlwibUNFSIcKImItBREcFHQQRPoA6ure6qpwebAa6/LjDu6j4c5WcC2Xa5dw/4M2OOeEN46uZqPM84gFIdcD7As8yFzxIpQpmTJLFl2bQI0KFQsirofYmcvc1jThmbcSNQt8HrFQcS1m05RwInwKSsjccGgHMq9vL2LudLLeT41FjFqGlpX0RSyVL2SsfGm9iixrNVk1zRc "Japt – TIO Nexus") [Answer] # [Stax](https://github.com/tomtheisen/stax), 63 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ∞╖]ÇàI╨‼Çö¼fi╩╨╛Aóß╟uƒ←37qÄô.Z╛Θ6►Mûj╚#Å[░]Oá0"y╧o╙)5;V╞♥╬F¼♫t~ ``` [Run and debug it](https://staxlang.xyz/#p=ecb75d808549d0138094ac6669cad0be41a2e1c7759f1b3337718e932e5abee936104d966ac8238f5bb05d4fa0302279cf6fd329353b56c603ce46ac0e747e&i=&a=1) [Answer] # [Perl 5](https://www.perl.org/), 163 bytes ``` say join'|',(('-'x26)x3,"Life is but a dream".$"x7,ucfirst(join$",("merrily,")x3),"Gently down the stream ",ucfirst "row, "x3 ."your boat ")[-$_..3-$_]for 1..7 ``` [Try it online!](https://tio.run/##NYthCsIwFIOvEh6DbdCV1qHDE/hHTyAiUzusbKu0HW7g2a0tYniEkJfvqWy/DsG1Cx5Gj/k7Z0WRV/m82pRzzWivOwXtcJk8WtysagfiGc0Nm66dts4XCcuIFTQoa3W/MIpgyWinRt8vuJnXCH9XcD7BiKI/C7LmxUBzDU6LmSwupvVxUB6r7Mx5Hf3UGQvJeROCFIi3hUSDGqvoqUmFSBm/vxQf8/TajC5UhzUXUnwB "Perl 5 – Try It Online") [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 292 bytes ``` B͍"-"'#*"|"3s "Row, row, row your boat,"b" "S*q"|"3sB͍>01B10B3*1-akr@>12B01B10B2*1-akr@>13B12B01B10B1-akr@>14B13B12B01B1-akr@>10B3*14B1-r0[10B2*14B13B1-akr0[10B14B13B12B1-akr]]@ B͍"Gently down the stream."c" "S*q"|"3s B͍"Merrily,"3" merrily,"S*q"|"3s B͍"Life is but a dream."f" "S*q"|"3s ``` [Try it online!](https://tio.run/##VY67DoJAEEV7vmIyFiYEDA9rQ7ax0UZLQ7HAEjfyiMMSQuIv@Gl@E8LyEJvJ5My5N0N1IeOuY5832rjdmPhCvzLwUjYW0DSgLWuCqOTKwggBr@ZTa33o4LjMdZhvujZ/UHBwPTYSbyE@W@CM9uxHJ6Q7em6TcxvjozScNVlCGoVhYAw/H0WhshaSsilA3QVUigTPdxiv3tTiWRDJrLXQR8jn/c84yVSArCCqFXBIxp501dN1Xw "Runic Enchantments – Try It Online") I don't generally do [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenges, but the layout was one I could work with without too much trouble. Runic does not have good ways to compress arbitrary strings, so all we have to work with are the repetitious parts. ### Explanation: Uncompressing slightly: ``` B͍"-"'#*"|"3s B͍"Row, row, row your boat,"b" "S*q"|"3s B͍"Gently down the stream."c" "S*q"|"3s B͍"Merrily,"3" merrily,"S*q"|"3s B͍"Life is but a dream."f" "S*q"|"3s >11B10B3*1-akr@ >12B11B10B2*1-akr@ >13B12B11B10B1-akr@ >14B13B12B11B1-akr@ >10B3*14B1-r0[10B2*14B13B1-akr0[10B14B13B12B1-akr]]@ ``` First 5 lines act as functions to build each portion of the song (where the first line generates the 35 `-` for the spacer using the decimal value of `#` to save 2 bytes over `3X5+`). The return instruction is at the beginning of the line to insure that all IPs that enter a function will also *leave* the function after the same number of cycles to avoid IPs merging (resulting in missing lines of output), as programs are rectangular and empty cells are implicit. The next four lines are responsible for printing the first four lines of the output The fifth line then prints the last 3 lines of output. Due to all three lines needing to start with at least one stanza-spacer it is not feasible to use 3 separate IPs (as they would need delays in order to avoid merging). `>`, `y`, `@`, and a newline cost more bytes (4) than `0[...]` (3 bytes) where `...` is arbitrary instructions (ie. another line of output). Conversely replacing `>` and `@` to use a single IP requires more bytes. Finally, merging all five entry-point lines onto the 2nd line saves 5 bytes worth of newlines. We just have to insure that the `B͍`ranch-return instruction moves to the end of its line first, preserving the function's functionality. ]
[Question] [ (First challenge, please let me know if there are any problems with it.) A ***heterogram*** is a word where no letter of the alphabet occurs more than once, and a ***palindrome*** is a phrase that is the same backwards and forwards. The challenge here is to write a piece of code that takes in a word (just letters) as input, and outputs whether or not it is a heterogram (truthy/falsy). The catch is that the program must be a palindrome -- reads the same backwards and forwards. Capitalization **doesn't** matter here, so for the heterogram to be valid it can't have both q and Q, for instance. No comments are allowed, and you cannot place strings that contain your code (or a significant part of your code) to try to make the palindrome part easy :P This is code-golf, so shortest code wins. Good luck! EDIT: Parens, brackets or other symbols that have left and right forms must be reversed approriately for the palindrome part. So (helloolleh) is a palindrome, but (helloolleh( is not. Apparently this is called a convenient palindrome. EDIT 2: You won't get any empty input, input with multiple words or input with characters other than letters. So don't worry about that :) [Answer] # Pyth, 17 bytes ``` Z.{rzZ.q.Zzr}.Z ``` [Try it online here.](http://pyth.herokuapp.com/?code=+Z.%7BrzZ.q.Zzr%7D.Z+) The leading space is necessary. I have counted it and the trailing space in the byte count. Here's the breakdown: ``` z z is initialized to the input r Z Z is initialized to 0, and r(string)0 converts the string to lowercase .{ .{ is pyth's builtin uniqueness test .q .q terminates the program .Zzr} This is just the program mirrored .Z . requires a number to immediately follow it If left blank the parser would throw an error Z This is just mirrored from the end The leading space suppresses the automatic printing of this 0 The trailing space mirrors the leading space ``` [Answer] # Python 3, 125 The main problem is to make the reverse of the code parsable. Then we can let it error out from undefined identifiers. ``` w=[str.lower][0]((input)()) (print)((max)((map)(w.count,w))<2) (2>((w,tnuoc.w)(pam))(xam))(tnirp) (()(tupni))[0][rewol.rts]=w ``` [Answer] # Perl, 43 bytes ``` print+m:^(?!.*(.).*\1|1/*.(.)*.!?)^:m+tnirp ``` Usage example: ``` echo "abcde" | perl -n entry.pl ``` [Answer] # Pyth - 11 bytes (Trailing and leading spaces necessary and counted). ``` z.{ z }.z ``` [Test Suite](http://pyth.herokuapp.com/?code=+z.%7B+z+%7D.z+&test_suite=1&test_suite_input=hello%0Ahelo&debug=0). ``` <space> Suppress print z Input (for palindromness) .{ Unique - actually does testing z Input <space> Suppress print } In operator .z Cached input list <space> At end of program makes empty tuple ``` [Answer] ## [><>](http://esolangs.org/wiki/Fish), ~~137~~ 131 Bytes When I saw this challenge, I thought ><> might finally be a good choice of language since using it you can mostly ignore palindromes; it is simple to make sure the pointer only stays where it should. While this is true, ><> unfortunately makes golfing conditionals excruciating (or just golfing in general). I hope to use some weird tricks I thought of to compensate for this, but here's a "quick" (not actually, both program-wise and creation-wise) answer. You can try it online [here](http://fishlanguage.com/playground). ``` i:0(?v>:"Z")?vl1-:1(?v&:{:@=?v$&e0.> ;n1<^ -*48< .00~< ;n-10<01-n; >~00. >84*- ^>1n; <.0e&$v?=@:}:&v?)1:-1lv?("Z":<v?)0:i ``` Returns 1 for true and -1 for false (I could change it to 0 but the length would stay the same, unfortunately) As always, let me know if this doesn't work and if you have any ideas on how to golf it down. I tested it against a few test cases, but there always could be an exception. Here's another version, one that I think is a bit more clever, but alas is ten bytes more. Truthy/falsey values this time are 1 and an error (`something smells fishy...`): ``` >i:0(?v>:"Z")?vl: 2(?v&{:@$:@=01-*2. < ;n1<^ -*48<f6+0.0< &1-:1)e*1.1*e(1:-1& >0.0+6f>84*- ^>1n; > .2*-10=@:$@:}&v?)2 :lv?("Z":<v?)0:i< ``` --- ## Explanation: Here's the code without the part added to make it a palindrome. This one doesn't use the "more clever" tricks I attempted to use for the alternate version, so it's a bit easier to explain (if anyone is interested in an explanation for the "tricks," I'd be happy to give one, though). ``` i:0(?v>:"Z")?vl1-:1(?v&:{:@=?v$&e0.> ;n1<^ -*48< .00~< ;n-10< ``` **Line 1:** ``` i:0(?v>:"Z")?vl1-:1(?v&:{:@=?v$&e0.> i:0(?v #Pushes input and directs down if negative >:"Z")?v #Directs down if input is greater than "Z" #(reduces lowercase input to uppercase) l #Pushes length #Main loop begins 1-:1(?v #Decrements top, and then directs down if less than 1 & #Pushes top of stack onto register (length minus 1) :{ #Duplicates top, shifts stack to the left :@ #Duplicates top, shifts top three values of the stack to the right =?v #If top two values are equal, directs down $ #Swaps top two values of the stack & #Pushes register onto stack e0. #Jumps back to the "1" after "?vl" #Main loop ends > #Makes sure when the pointer jumps back to i it goes the right way ``` Here's how the convoluted swapping (`:{:@=?v$`) works -- I'll use a test case of this stack: `[5,1,8,1]` where the last character is the top. `:{` The top of the stack is duplicated: `[5,1,8,1,1]`, and the stack shifted to the left: `[1,8,1,1,5]` `:@` The top is duplicated: `[1,8,1,1,5,5]`, then the top three values are shifted to the right: `[1,8,1,5,1,5]` `=?v` Unnecessary for this part of explanation `$` The top value is swapped once more yielding `[1,8,1,5]`, which, if you'll note, is the original stack shifted over once (as if `{` had been the only command). --- So what this does in English ("Thank God, he's actually explaining things") is check the entire stack against the top value and move to a point in the second line if any value equals the top. This checking is done proportionate to how many values there are in the stack (`l - 1`, where `l` is the length of the stack) so that all values are checked against each other. **Line 2:** ``` ;n1<^ -*48< .00~< ;n-10< n1< #If input is less than 0 (i.e. there is none), print 1 ; #and terminate < #If redirected because input is greater than "Z" -*48 #Push 32, subtract (reducing lowercase to uppercase, numerically) ^ #And move back to the portion that tests if input #is uppercase (which it will pass now) < #If counter is less than 1 (for main loop) .00~ #Pop the counter and jump to the beginning (i) < #If any two values in the stack are equal -10 #Push -1 (subtract 1 from 0) ;n #Print and terminate ``` [Answer] ## PHP, 126 Bytes You need to run this with the `short_tags` ini directive turned **off** in 5.4 or above. First golf ever. Two copies, the first prints a whole bunch of garbage with the falsy/truthy result: ``` <?=var_dump(max(array_count_values(str_split(end($argv))))<2)?><?(2>((((vgra$)dne)tilps_rts)seulav_tnuoc_yarra)xam)pmud_rav=?> ``` This version will not print any jargon (162 bytes): ``` <?=var_dump(max(array_count_values(str_split(end($argv))))<2);__halt_compiler()?><?()relipmoc_tlah__;(2>((((vgra$)dne)tilps_rts)seulav_tnuoc_yarra)xam)pmud_rav=?> ``` Run from the command line with ``` php -f golf.php heterogram ``` Probably can be golfed a bit further [Answer] # 05AB1E, 9 bytes ``` lDÙQqQÙDl ``` [Try it online.](http://05ab1e.tryitonline.net/#code=bETDmVFxUcOZRGw&input=VGVzdA) \*insert something about going all the way back to my very first challenge\* Non-competing since 05AB1E was made after this challenge. ## Explanation ``` lDÙQqQÙDl l Take input and lowercase it. DÙ Duplicate and uniquify. Q Compare the two strings. q Immediately exit. QÙDl The rest of the program is ignored. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog/releases), 3 bytes, language postdates challenge ``` DdD ``` [Try it online!](https://tio.run/nexus/brachylog#@@@S4vL/v1JiUnJiSqoSAA "Brachylog v1 – TIO Nexus") This is one of the very few programs that works in both Brachylog 1 and Brachylog 2. The TIO link is to Brachylog 1 for old times' sake. Also unsually for Brachylog, this is a full program, not a function. (Full programs in Brachylog implicitly output booleans, which is just what we want for this question.) The general principle here is that placing a predicate between a pair of identical uppercase letters is an assertion that the current value is invariant under that predicate. So you often see things like `AoA` for "is sorted" ("invariant under sorting"); `A↔A` would (in Brachylog 2) mean "is a palindrome" ("invariant under reversal"), and so on. This program is "invariant under removing duplicates", i.e. "doesn't contain duplicates". It's really convenient that this method of specifying invariance happens to be a palindrome. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes ``` ≠ụ≠ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompkcdy5VKikpTlfRqQMy0xJziVKXa04vK/z/qXPBw91Ig@f9/tFJlarGSjlJefl4qkMpILUktyk8vSswFchKTklNS04CM1NRUpVgA "Brachylog – Try It Online") The predicate succeeds if the input is a heterogram and fails if it is not. ``` ≠ The characters of the input are all distinct, ụ and when converted to upper case, ≠ are still all distinct. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` tuX=Xut ``` [Try it online!](https://tio.run/nexus/matl#@19SGmEbUVry/796aV5mYWlqXmpxsToA "MATL – TIO Nexus") Returns list [1, 1] if the input is a heterogram and [0, 0] if not. Explanation: ``` t % duplicate the input u % remove duplicates from the original X= % check the two lists are equal Xu % unique rows (does nothing as we now have a boolean) t % duplicate the result % (implicit) convert to string and display ``` ]
[Question] [ The shortest code that finds all *unique* "sub-palindromes" of a string, that is: any substring with length > 1 that is a palindrome. eg.1 ``` input: "12131331" output: "33", "121", "131", "313", "1331" ``` eg.2 ``` input: "3333" output: "33", "333", "3333" ``` [Answer] ## J, 24 ~~31~~ ~~40~~ ``` ~.(#~(1<#*]-:|.)&>),<\\. ``` Sample use: ``` ~.(#~(1<#*]-:|.)&>),<\\. '12131331' ┌───┬───┬───┬────┬──┐ │121│131│313│1331│33│ └───┴───┴───┴────┴──┘ ~.(#~(1<#*]-:|.)&>),<\\. '3333' ┌──┬───┬────┐ │33│333│3333│ └──┴───┴────┘ ``` Take that, GolfScript! [Answer] ## Python 124 ``` r=raw_input() l=range(len(r)) print', '.join(set('"'+r[i:j+1]+'"'for i in l for j in l if i<j and r[i:j+1]==r[i:j+1][::-1])) ``` [Answer] ## Haskell 98, 88 ~~91~~ ~~96~~ ``` import List main=interact$show.filter(\x->length x>1&&x==reverse x).nub.(tails=<<).inits ``` [Answer] ## Python - 138 136 This code does not duplicate sub-palindromes. ``` r=raw_input() i,l=0,len(r) j=l a=[] while i<l-1: t=r[i:j];j-=1 if t==t[::-1]:a+=['"'+t+'"'] if j<i+2:i+=1;j=l print", ".join(set(a)) ``` [Answer] ## Ruby - 126 102 97 characters ``` s=gets *m=*0..s.size puts m.product(m).map{|h,j|(c=s[h,j+1]).size>1&&c==c.reverse ? c:0}.uniq-[0] ``` [Answer] ## Golfscript, 48 characters subpalindrome.gs ``` {,}{(;}/{{,}{);}/}%{+}*{.,1>\.-1%=*},.&{`}%", "* ``` Usage: ``` echo "12131331" | ruby golfscript.rb subpalindrome.gs ``` The first operation `{,}{(;}/` turns a string into a list of trailing-substrings. A similar leading-substrings transform is then mapped over the result. Then flatten with `{+}*`, filter for palindromes using the predicate `.,1>\.-1%=*`, grab unique values with `.&`, then pretty print. It would be neater to extract the trailing-substrings transform as a block and reuse it as a replacement for leading-substrings after reversing each trailing substring, but I can't figure out a succinct way of doing that. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ǎU~Ḣ'Ḃ= ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLHjlV+4biiJ+G4gj0iLCIiLCJcIjEyMTMxMzMxXCIiXQ==) -1 thanks to lyxal ``` U # Unique ǎ # Substrings ~ # Where Ḣ # Length > 1 ' # And Ḃ= # Is palindromic ``` [Answer] ## Haskell - 170, 153 ``` import Data.List import Data.Set p a=fromList$[show x|x<-subsequences a,x==reverse x,length x>1] main=getLine>>=(\x->putStrLn$intercalate", "$toList$p x) ``` [Answer] ## J, 48 ``` f=:,@:". h=:\\. ~.(#~10&<)((]h-:"0&f|.h)#[:f]h) ``` eg ``` ~.(#~10&<)((]h-:"0&f|.h)#[:f]h) '12131331' 121 131 313 1331 33 ``` [Answer] ## Prolog, 92 ``` f(S,P):-append([_,X,_],S),X=[_,_|_],reverse(X,X),atom_codes(P,X). p(S,R):-setof(P,f(S,P),R). ``` Sample use: ``` ?- p("12131331",R). R = ['121', '131', '1331', '313', '33']. ?- p("3333",R). R = ['33', '333', '3333']. ``` [Answer] ### Windows PowerShell, 104 ~~109~~ ~~111~~ ``` 0..($l=($s="$input").length-1)|%{($a=$_)..$l|%{-join$s[$a..$_]}}|sort -u|?{$_[1]-and$_-eq-join$_[$l..0]} ``` This expects the input on stdin and will throw all found palindromes one per line on stdout: ``` PS Home:\SVN\Joey\Public\SO\CG183> '12131331'| .\subp.ps1 33 121 131 313 1331 ``` (When run from `cmd` it becomes `echo 12131331|powershell -file subp.ps1` – it's just that `$input` takes a slightly different meaning depending on how the script was called, but it can be stdin, just not interactively.) **2011-01-30 13:57** (111) – First attempt. **2011-01-30 13:59** (109) – Inlined variable declaration. **2011-06-02 13:18** (104) – Redone substring finding by joining a char array instead of calling `.Substring()` and inlined a bit more. [Answer] # Q, 78 ``` {a::x;(?)(,/)b@'(&:')({x~(|:)x}'')b:-1_1_'({(sublist[;a]')x,'1+c}')c::(!)(#)a} ``` usage ``` q){a::x;(?)(,/)b@'(&:')({x~(|:)x}'')b:-1_1_'({(sublist[;a]')x,'1+c}')c::(!)(#)a}"12131331" "121" "131" "313" "1331" "33" q){a::x;(?)(,/)b@'(&:')({x~(|:)x}'')b:-1_1_'({(sublist[;a]')x,'1+c}')c::(!)(#)a}"3333" "33" "333" "3333" ``` [Answer] ## [Retina](https://github.com/m-ender/retina), ~~34~~ 27 bytes ``` &@!`(.)+.?(?<-1>\1)+(?(1)^) ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7w31fNQTFBQ09TW89ew95G19AuxlBTW8New1AzTvN/cILKf0MjQ2NDY2NDLmMg4ALzjAxNTKEMAA "Retina – Try It Online") The test suite needs an `M` because it is followed by another stage to insert empty lines between test cases. ### Explanation ``` &@!`(.)+.?(?<-1>\1)+(?(1)^) ``` Print (`!`) all unique (`@`), overlapping (`&`) matches of the regex `(.)+.?(?<-1>\1)+(?(1)^)`. This matches a palindrome of length 2 or more using balancing groups. There's a caveat to the "all overlapping matches" part: we can get at most one match per starting position. However, if two palindromes of different length begin at the same position, the shorter palindrome will appear again at the end of the longer palindrome. And since the greediness of `+` prioritises longer matches, we're getting all palindromes anyway. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 10 bytes ``` ŒÙʒÂQ}žQSK ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6KTDM09NOtwUWHt0X2Cw9///iUnJSYkA "05AB1E – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 bytes ``` ã â fÅfêU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4yDiIGbFZupV&input=IjEyMTMxMzMxIg) ``` ã â fÅfêU :Implicit input of string ã :Substrings â :Deduplicate f :Filter elements that return truthy Å : Slice off first character f :Filter elements that return true êU : Test for palindrome ``` [Answer] # [Factor](https://factorcode.org/), 70 bytes ``` [ all-subseqs [ length 1 > ] filter [ dup reverse = ] filter members ] ``` [Try it online!](https://tio.run/##RcyxCsIwFIXhvU9xyG4hZlMUN3FxEafSIa23WkxivfdW9Oljtp7xO/APvtcX5@vldD5uIPSeKfUkNX2VvSyA6PWBJ3GiUFQFE5Pqb@IxKbZVZezaOuucNZVxZSY38CGsZO5KRNAgULqXhsUeLYYxKHHR2zyB6UMshN1yRIpdMbS5Gw@oBX0gz/kP "Factor – Try It Online") Having the two filters is actually shorter than having a single filter with some kind of `and` logic, or applying a single `filter` to two quotations with `bi@`. * `all-subseqs` Get all subsequences of the input. * `[ length 1 > ] filter` Take those with a length greater than one. * `[ dup reverse = ] filter` Take the palindromes. * `members` Remove duplicates. Using locals ties the byte count: ``` [ all-subseqs [| s | s length 1 > s s reverse = and ] filter members ] ``` [Answer] ## Perl, 112 ``` $_=<>;chop;s/./$&$' /g; map{/../&&$_ eq reverse&&$h{$_}++}split/ / for grep{s/./$`$& /g}split/ /; print for keys %h ``` [Answer] # JavaScript (ES6), 120 bytes ``` a=>{for(b=0,c=d=a.length,e=[];b<d;--c<b+2?(b++,c=d):1)(f=a.slice(b,c))==f.split``.reverse().join``&&e.push(f);return e} ``` This function takes a string as input and outputs an array. [Answer] ## Clojure, 81 bytes ``` #(set(for[i(range 2(+(count %)1))p(partition i 1 %):when(=(reverse p)(seq p))]p)) ``` `for` was a perfect match here :) Could use `:when(=(reverse p)p)` if input was a list of characters OR a full string didn't count as a palindrome, actually in that case the max range of `i` could be `(count %)` as well. Most compact case for reference: ``` #(set(for[i(range 2(count %))p(partition i 1 %):when(=(reverse p)p)]p)) ``` [Answer] ## Python, 83 102 chars ``` s=lambda t:(t[1:]or())and(t,)*(t==t[::-1])+s(t[1:])+s(t[:-1]) print set(s(input())) ``` The phrase `(t[1:]or())and...` is equivalent to `(...)if t[1:]else()` and saves one character! I'm overly proud of this, given the savings. Example: ``` python x "51112232211161" set(['11', '22', '11122322111', '161', '111', '112232211', '1223221', '22322', '232']) ``` [Answer] ## Scala 127 ``` object p extends App{val s=args(0);print(2.to(s.size).flatMap(s.sliding(_).toSeq.filter(c=>c==c.reverse)).toSet.mkString(" "))} ``` To keep this an apples to apples comparison with the other Scala answer, I also made mine an object that extends App. Rather than iterate the input string manually and use substring, I leveraged sliding() to create a sequence of all the substrings for me. [Answer] ## Scala 156 170 ``` object o extends App{val l=args(0).length-2;val r=for(i<-0 to l;j<-i to l;c=args(0).substring(i,j+2);if(c==c.reverse))yield c;print(r.toSet.mkString(" "))} ``` ``` object o{def main(s:Array[String]){val l=s(0).length-2;val r=for(i<-0 to l;j<-i to l;c=s(0).substring(i,j+2);if(c==c.reverse)) yield c;println(r.distinct.mkString(" "))}} ``` [Answer] # [Perl 6](https://perl6.org), ~~35~~ 32 bytes ``` {unique ~«m:ex/(.+).?<{$0.flip}>/} ``` [Test it](https://tio.run/##VVBBboMwELz7FSuEIqOAU2opByiUR/ReJbBUVghQbEdBiH6ov@jHqA00SX1Z7c7Mjnda7Kr9pCXCZc/ymJx72ORNgZBMg67Fp0b4@vk@R3jdUbb12OvL4D6xshLtmO7GydAzhVJBApQAOOFzyEPOQweSFKjDuePPw7nwuRh86Uzr@VbEzfsn4LfCLcWLCbE/fDNGMWmrQw3b2dXMpT6CbDoVHHugmahbrXzI8NpirrDwYDAGy5hZWgRBCu7czxDcuawUnTQEd10SnQw@kpGQsunWK634HWh0wp4uPM8QL4dKI72bLq42mg6V7moTjo30TxEbUMigQGyrG4dt1ise9jwc4sOqtjGtEo99CKnIOP0C "Perl 6 – Try It Online") ``` {set ~«m:ex/(.+).?<{$0.flip}>/} ``` [Test it](https://tio.run/##VVBdboMwDH7PKSyEqqBCOhapDzAYh9j71IKZUCkgEqoixC60W@xizAHWn7xY9vcXu8G23E@dQrjsRRqycw@btM4QomlQqOH79@cc4HXHxdYR72@D/SLysmjGeDdOxE00Kg0RcAZg@a@@9KX0LYhi4JaUljsP5yLnQvjSUeu4RiTpPQnkrUhDcULGzPc@KChkTXmoYDun0lx1R1B1q71jDzwpqqbTLiR4bTDVmDkwUMAyFoYWgBeDPfczBHeuyItWEcFeTYIT4SMbGcvrdt3SiD@BByfs@cJziHg5lB3ye@iSSqexW9RdW9FxzD3/FSGBhfIyxKa8cQRZKrFZV3kwe9jGhdXC3GrVOeKrUJqN0x8 "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 set # turn into a Set object (ignores duplicates) ~«\ # stringify 「~」 all of these 「«」 (possibly in parrallel) # otherwise it would be a sequence of Match objects m # match :exhaustive # in every way possible / ( .+ ) # at least one character 「$0」 .? # possibly another character (for odd sized sub-palindromes) <{ $0.flip }> # match the reverse of the first grouping / } ``` [Answer] # Perl, ~~43~~ 40 bytes Includes `+1` for `n` ``` perl -nE 's/(?=((.)((?1)|.?)\2)(?!.*\1))/say$1/eg' <<< 12131331 ``` [Answer] # [Coconut](http://coconut-lang.org/), 69 bytes ``` def f(s)=s and{s*(s[::-1]==s>""<s[1:])}-{""}|f(s[1:])|f(s[:-1])or s{} ``` [Try it online!](https://tio.run/##HY2xDoQgEER/ZbO5Ai6nyUpHDn@EUBiVxEIwrlbItyM61czLS2aMYwznUco0e/CCpWEYwpT4K9hq3ZAzhnvEP1vSTuYmIeariu98yyPJuAOnXCxSR4qUIvwBqhp0cPWwDttHbPsSjrb18iH1ls91Ltbd "Coconut – Try It Online") --- # [Python 2](https://docs.python.org/2/), 73 bytes ``` f=lambda s:s and{s*(s[::-1]==s>""<s[1:])}-{""}|f(s[1:])|f(s[:-1])or set() ``` [Try it online!](https://tio.run/##JYs7DoMwEAX7nGK1lR2FYnG3wrmI5cIIrCAFg1g3iHB2h89UM9J785o/U6pLifYbxrYLICwQUrfJU4ljrshbK2/ERhyx13u1Ie6/qO685BzpaQHps9IlngZDAodUkyFjCF@A5gA9PwDmZUgZjqMufw "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ẆQŒḂÐfḊÐf ``` [Try it online!](https://tio.run/##y0rNyan8///hrrbAo5Me7mg6PCHt4Y4uIPn/cDtQYOeM//@VDI0MjQ2NjQ2VAA "Jelly – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 27 bytes ``` {∪⍵/⍨≡∘⌽¨⍨⍵}∘⊃(,/1↓⍳∘≢,/¨⊂) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOpHHase9W7Vf9S74lHnwkcdMx717D20AsTr3VoL4nY1a@joGz5qm/yodzOI37lIRx@ooKtJE2iAgrqhkaGxobGxoToXkGMMBOoA "APL (Dyalog Classic) – Try It Online") ``` {∪⍵/⍨≡∘⌽¨⍨⍵}∘⊃(,/1↓⍳∘≢,/¨⊂) Monadic train: ⊂ Enclose the input, ⊂'12131331' ⍳∘≢ Range from 1 to length of input ⍳∘≢,/¨⊂ List of list of substrings of each length 1↓ Remove the first list (length-1 substrings) ⊃ ,/ Put the rest of the substrings into a single list. {∪⍵/⍨≡∘⌽¨⍨⍵} To the result, apply this function which keeps all palindromes from a list: ≡∘⌽¨⍨⍵ Boolean value of whether each (¨) string in argument ≡∘⌽ ⍨ is equal to its own reverse ⍵/⍨ Replicate (filter) argument by those values. This yields the length >1 palindromes. ∪ Remove duplicates from the list of palindromes. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` Êò2@ãX fêSÃc â ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=yvIyQONYIGbqU8NjIOI=&input=WyIxMjEzMTMzMSIKIjMzMzMiXQotUW0=) Explanation: ``` Êò2 #Get the range [2...length(input)] @ à #For each number in that range: ãX # Get the substrings of the input with that length fêS # Keep only the palindromes c #Flatten â #Keep unique results ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 99 bytes ``` $args|% t*y|%{$s+=$_ 0..$n|%{if($n-$_-and($t=-join$s[$_..$n])-eq-join$s[$n..$_]){$t}} $n++}|sort -u ``` [Try it online!](https://tio.run/##TZDRasMwDEXf/RXCKMNu4rLMb4NA/6OUUFq3ywhOZ7tsJfG3p4pxyvTgK5179SDfhl/j/Jfp@xkv0MA449Fd/VRA2DymYkRfNtiy9@0WLY3dRaBV2KqjPQsMjfoeOot@j@0SOEhlfl7IEmoPcsQQI0NblnHygwug7nNkbCcYUFWC1x@1rrWueQVLnyRPmZKdRHO5LmmqzNK7yr/IQmiSMEEBY6Log@vstQI0fzdzCuZMJ9N5yXPG3/tA4I1@IieTw1Hw7HI6kL@Wufxc1ziL8xM "PowerShell – Try It Online") Less golfed: ``` $args|% toCharArray|%{ $substring+=$_ 0..$n|%{ if( $n-$_ -and ($temp=-join$substring[$_..$n]) -eq -join$substring[$n..$_] ){ $temp } } $n++ }|sort -Unique ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes ``` {s.l>1∧.↔}ᵘ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6Ompoe7Omsfbp3wv7pYL8fO8FHHcr1HbVOAIjP@/49WMjQyNDY0NjZU0lEyNjZWigUA "Brachylog – Try It Online") (The header in the link is broken at the time of posting, so [here's](https://tio.run/##SypKTM6ozMlPN/r/v7pYL8fO8FHHcr1HbVNqH26dUf7/v5KhkaGxobGxoRIA) the predicate (function-equivalent in Brachylog) on only the first test case, with a `w` at the end to actually print the output.) ``` The output is { }ᵘ a list containing every possible unique s. substring of the input l the length of which > is greater than 1 one ∧ and . which ↔ reversed is itself. (implicit output within the inline sub-predicate) ``` I feel like there's a shorter way to check that the length is greater than 1. (If it didn't filter out trivial palindromes, it would just be `{s.↔}ᵘ`.) ]
[Question] [ Given an input of two integers *n* and *m*, output an ASCII ladder of length *n* and size *m*. This is an ASCII ladder of length 3 and size 3: ``` o---o | | | | | | +---+ | | | | | | +---+ | | | | | | o---o ``` This is an ASCII ladder of length 5 and size 1: ``` o-o | | +-+ | | +-+ | | +-+ | | +-+ | | o-o ``` This is an ASCII ladder of length 2 and size 5: ``` o-----o | | | | | | | | | | +-----+ | | | | | | | | | | o-----o ``` To be specific: * The length (*n*) represents how many squares the ladder is made up of. * The size (*m*) represents the width and height of the interior of—that is, not counting the "borders"—each square. * Each square is made up of the interior area filled with spaces, surrounded by `-`s on the top and bottom, `|`s on the left and right, and `+`s at all four corners. * Borders between squares merge together, so two lines in a row with `+--...--+` merge into one. * The corners of the entire ladder are replaced with the character `o`. * You may optionally output a trailing newline. The length of the ladder (*n*) will always be ≥ 2, and the size (*m*) will always be ≥ 1. Input can be taken as a whitespace-/comma-separated string, an array/list/etc., or two function/command line/etc. arguments. The arguments can be taken in whichever order is most convenient / golfiest. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. Tip: The examples above can also be used as test cases. [Answer] # Ruby, 71 ``` ->m,n{h=0;(?o+?+*(n-1)+?o).chars{|c|puts [?|+' '*m+?|]*h,c+?-*m+c;h=m}} ``` **ungolfed in test program** ``` f=->m,n{ h=0 #The number of | above the 1st rung is 0 (?o+?+*(n-1)+?o).chars{|c| #Make a string of all the rung ends o++...++o and iterate through it puts [?|+' '*m+?|]*h, #draw h vertical segments | ... | c+?-*m+c #and a rung with the correct ends h=m #The number of | above all rungs except the 1st is m } } f[gets.to_i,gets.to_i] ``` [Answer] # CJam, ~~43~~ 42 bytes I'm not sastified by the score. But I'm not Dennis, right? ``` q~:Z;'-'o{[\Z*1$N]}:X~['-_'+X\'|XZ*]@*1>1$ ``` Input is 2 space separated items. Length first ``` 2 3 o---o | | | | | | +---+ | | | | | | o---o ``` Explanation ``` q~:Z;'-'o{[\Z*1$N]}:X~['-_'+X\'|XZ*]@*1>1$ q~ e# read input :Z; e# Record the size in Z and discard '-'o{[\Z*1$N]}:X~ e# Create the initial line (and final). also creates a shorcut to do this later \ e# Capture two arguments Z* e# The separator is repeated size times 1$ e# Repeat the first argument N e# Add newline e# X is a function to create line in a ladder ['-_'+X\'|XZ*] e# Design the repeating part @* e# Repeat the pattern n times 1> e# Discard the initial 1$ e# Since the final line is same than the initial, we just write it. e# Implicit printing ``` [Answer] # JavaScript (ES6), 89 ... repeat, repeat, repeat ... ``` (n,m,R=x=>x.repeat(m),b=R(`|${R(' ')}| `),d=`o${c=R('-')}o `)=>d+R(b+`+${c}+ `,m=n-1)+b+d ``` **Test** ``` F=(n,m,R=x=>x.repeat(m),b=R(`|${R(' ')}| `),d=`o${c=R('-')}o `)=>d+R(b+`+${c}+ `,m=n-1)+b+d // Less golfed U=(n,m)=> { var R=x=>x.repeat(m), a=R(' '), b=R(`|${a}|\n`); c=R('-'), d=`o${c}o\n`; m=n-1; return d+R(b+`+${c}+\n`)+b+d } function test() { var i=I.value.match(/\d+/g) if (i) O.textContent=F(+i[0],+i[1]) console.log(i,I.value) } test() ``` ``` N,M: <input id=I value="3,5" oninput=test()> <pre id=O></pre> ``` [Answer] # C#, 1412 bytes ... My first CodeGolf attempt, Not likely to win but it works so here we go: ``` using System; namespace Ascii_Ladders { class Program { static void Main(string[] args) { int n = 0; int m = 0; Console.Write("Please enter Height: "); n = int.Parse(Console.ReadLine()); Console.Write("Please Enter Width: "); m = int.Parse(Console.ReadLine()); Console.Write("o"); for (int i = 0; i < m; i++) { Console.Write("-"); } Console.WriteLine("o"); for (int k = 0; k < n; k++) { for (int i = 0; i < m; i++) { Console.Write("|"); for (int j = 0; j < m; j++) { Console.Write(" "); } Console.WriteLine("|"); } if (k != n - 1) { Console.Write("+"); for (int i = 0; i < m; i++) { Console.Write("-"); } Console.WriteLine("+"); } } Console.Write("o"); for (int i = 0; i < m; i++) { Console.Write("-"); } Console.WriteLine("o"); Console.ReadKey(); } } } ``` [Answer] # Julia, 87 bytes ``` f(n,m)=(g(x)=(b=x[1:1])x[2:2]^m*b*"\n";(t=g("o-"))join([g("| ")^m for i=1:n],g("+-"))t) ``` This is a function that accepts two integers and returns a string. Ungolfed: ``` function f(n::Int, m::Int) # Create a function g that takes a string of two characters and # constructs a line consisting of the first character, m of the # second, and the first again, followed by a newline. g(x) = (b = x[1:1]) * x[2:2]^m * b * "\n" # Assign t to be the top and bottom lines. Construct an array # of length n where each element is a string containing the # length-m segment of the interior. Join the array with the # ladder rung line. Concatenate all of this and return. return (t = g("o-")) * join([g("| ")^m for i = 1:n], g("+-")) * t end ``` [Answer] # [pb](http://esolangs.org/wiki/pb) - 147 bytes ``` ^t[B]>>[B]vw[T!0]{b[43]<[X]b[43]>w[B=0]{b[45]>}v[X-1]w[B=0]{b[124]^}v[X]t[T-1]}t[111]b[T]<w[X!0]{b[45]<}b[T]w[Y!0]{w[B!0]{^}b[124]^}b[T]^>>[B]vb[T] ``` This is the kind of challenge that, by rights, pb should be really good at. Drawing simple pictures with characters is exactly what pb was designed for. Alas, it's just a wordy language I guess. Takes input length first, followed by size. Takes input in the form of byte values, for example: `python -c 'print(chr(5) + chr(7))' | ./pbi.py ladder.pb` Look, a fun animation! ![](https://i.stack.imgur.com/TdZfb.gif) With comments: ``` ^t[B] # Save length to T >>[B]v # Go to X=size+1, Y=0 w[T!0]{ # While T is not 0: b[43] # Write a '+' <[X]b[43] # Write a '+' on the left side as well >w[B=0]{b[45]>} # Travel back to the right '+', writing '-' on the way v[X-1] # Go down by X-1 (== size) w[B=0]{b[124]^} # Travel back up to the '+', writing '|' on the way v[X] # Go down by X (== size + 1, location of next '+') t[T-1] # Decerement T } t[111] # Save 'o' to T (it's used 4 times so putting it # in a variable saves bytes) b[T] # Write an 'o' (bottom right) <w[X!0]{ # While not on X=0: b[45]< # Travel left, writing '-' on the way } b[T] # Write an 'o' (bottom left) w[Y!0]{ # While not on Y=0: w[B!0]{^} # Skip nonempty spaces b[124] # Write a '|' ^ # Travel up } b[T] # Write an 'o' (top left, replaces existing '+') ^>>[B]v # Go back to where the size is saved and go to X=size+1, Y=0 b[T] # Write an 'o' (top right, replaces existing '+') ``` [Answer] ### Pure bash, ~~132 130 128~~ 127 bytes Yes I could drop 1 more byte replacing last `${p% *}`, but I prefer this: ``` p=printf\ -v;$p a %$1s;$p b %$2s;o="|$a|\n";h=+${a// /-}+\\n v=${a// /$o} a=${b// /$h$v}${h//+/o};a=${a/+/o};${p% *} "${a/+/o}" ``` Sample: ``` ladders() { p=printf\ -v;$p a %$1s;$p b %$2s;o="|$a|\n";h=+${a// /-}+\\n v=${a// /$o} a=${b// /$h$v}${h//+/o};a=${a/+/o};${p% *} "${a/+/o}" } ladders 3 4 o---o | | | | | | +---+ | | | | | | +---+ | | | | | | +---+ | | | | | | o---o ladders 2 1 o--o | | | | o--o ``` [Answer] # Pyth, 34 bytes ``` .NjjNm*QTvz*2YjC:M++J"+|o"m"- -"QJ ``` [Test suite](https://pyth.herokuapp.com/?code=.NjjNm%2aQTvz%2a2YjC%3AM%2B%2BJ%22%2B%7Co%22m%22-+-%22QJ&test_suite=1&test_suite_input=3%0A3%0A5%0A1%0A2%0A5&debug=0&input_size=2) Takes arguments newline separated on STDIN. Uses a helper function, `:`, which builds each type of vertical string from three characters, then replicates as necessary, transposes and joins on newlines. [Answer] ## Haskell, ~~100~~ 97 bytes ``` l#s=unlines$t:m++[t]where _:m=[1..l]>>["+"!"-"]++("|"!" "<$u);t="o"!"-";o!i=o++(u>>i)++o;u=[1..s] ``` Usage example: ``` *Main> putStr $ 4 # 3 o---o | | | | | | +---+ | | | | | | +---+ | | | | | | +---+ | | | | | | o---o ``` How it works: ``` l#s=unlines$t:m++[t] -- concat top line, middle part and end line -- with newlines between every line where -- where _:m= -- the middle part is all but the first line of [1..l]>> -- l times ["+"!"-"] -- a plus-dashes-plus line ++("|"!" "<$u) -- followed by s times a bar-spaces-bar line t="o"!"-" -- very first and last line o!i=o++(u>>i)++o -- helper to build a line u=[1..s] ``` Edit: @Christian Irwan found 3 bytes. Thanks! [Answer] # brainfuck - 334 bytes ``` ,[<+<<<<+>>>>>-]<[[>>]+[<<]>>-]<----[>---<----]--[>[+>>]<<[<<]>++++++]>[+.>>]-[<+>---]<+++++++>>--[<+>++++++]->---[<------->+]++++++++++[<++<]+++++[>[++++++>>]<<[<<]>-]>[-]>.-<<----[>>+++<<----]--[>+<--]>---<<<<++++++++++.,[>[>+>+<<-]>[<+>-]>[<<<<[>>>>>>[.>>]<<[<<]>>-]>>>>>[.>>]<<[<<]>-]<<<<+>-]>>>>[-]----[>---<----]>+.[>]<<<<<[.<<] ``` I expected this to be a lot shorter. This sets up a "string" that looks like `| (...) |` and one that looks like `+----(...)----+`, printing each one as necessary, with some special casing for the `o`s on the top and bottom. Requires an interpreter that uses 8-bit cells and allows you to go left from cell 0 (be it into negative cells or looping). In my experience, these are the most common default settings. With comments: ``` ,[<+<<<<+>>>>>-]<[[>>]+[<<]>>-] Get m from input; make a copy Turn it into m cells containing 1 with empty cells between <----[>---<----] Put 67 at the beginning (again with an empty cell between) --[>[+>>]<<[<<]>++++++] Add 43 to every nonempty cell >[+.>>] Add 1 to each cell and print it -[<+>---]<+++++++ Put 92 after the last 45 (no empty cell!) >>--[<+>++++++] Put 43 immediately after the 92 ->---[<------->+] Put 234 after 43 ++++++++++ And 10 after that [<++<] Add two to the 234; 92; the empty spaces; and left of the 111 +++++[>[++++++>>]<<[<<]>-] Add 30 to each 2; the 94; and the 236 >[-]>.-<<----[>>+++<<----] Erase leftmost 32; Print 111; subtract 68 from it --[>+<--]>--- Put 124 where the 32 was <<<<++++++++++., Print a newline; override the cell with n from input [ n times: >[>+>+<<-]>[<+>-] Make a copy of m >[ m times: <<<< Look for a flag at a specific cell [ If it's there: >>>>>>[.>>] Go to the 43; print it and every second cell after <<[<<]>>- Clear the flag ] >>>>>[.>>] Go to the 124; print it and every second cell after <<[<<]> Go back to the copy of m -] <<<<+> Plant the flag -] >>>> [-]----[>---<----]>+ Erase the 124; add 68 to 43 .[>] Print it; then head to the end <<<<<[.<<] Go to the last 45; print it; then print every second cell to the left ``` [Answer] # PowerShell, 77 ~~80~~ ``` param($l,$s)$a='-'*$s ($c="o$a`o") (($b=,"|$(' '*$s)|"*$s)+"+$a+")*--$l $b $c ``` [Answer] # Jolf, 36 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=z4FwaSxhKzJKKzJKIm8tfCAiaiJvKC4rKW8Kby4rbycrJDEr&input=NQoKMw) ``` ρpi,a+2J+2J"o-| "j"o(.+)o o.+o'+$1+ ``` ## Explanation ``` ρpi,a+2J+2J"o-| "j"o(.+)o\no.+o'+$1+ pi j repeat vertically j times ,a+2J+2J"o-| " a box with dimensions 2+J ρ "o(.+)p\np.+o' replace with regex +$1+ with the -...- ``` [Answer] # Perl, 98 bytes ``` ($n,$m)=@ARGV;print$h="o"."-"x$m."o\n",((("|".(" "x$m)."|\n")x$m.$h)x$n)=~s{o(-+)o(?=\n.)}{+$1+}gr ``` [Answer] ## C, 122 bytes ``` f(int m,int n,char*s){int i=0,w=3+m++;for(;i<w*m*n+w;++i)*s++=i%w>m?10:" |-+-o"[!(i/w%m)*2+!(i%w%m)+!(i/w%(m*n))*2];*s=0;} ``` [Try it online](https://ideone.com/jAItbm). [Answer] # Tcl, 187 bytes ``` lassign $argv n w set c 0 while { $c < [expr {($w * $n) + ($n + 2)}]} {if {[expr {$c % ($n + 1)}] == 0} {puts "o[string repeat "-" $w ]o"} else {puts "|[string repeat " " $w ]|"} incr c} ``` This code is made to put into a file with arguments input on the command line. provide number of boxes and width in that order. [Answer] # PHP, 81bytes Expects 2 arguments, passed when calling the PHP command directly. The first one is the size and the 2nd one is the number of steps. ``` $R=str_repeat;echo$P="o{$R('-',$W=$argv[1])}o ",$R("|{$R(' ',$W)}| $P",$argv[2]); ``` May require some improvements. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 30 bytes ``` (‛+on¬i:⁰-p,⁰(\|:⁰꘍p,))\o:⁰-p, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%28%E2%80%9B%2Bon%C2%ACi%3A%E2%81%B0-p%2C%E2%81%B0%28%5C%7C%3A%E2%81%B0%EA%98%8Dp%2C%29%29%5Co%3A%E2%81%B0-p%2C&inputs=3%0A3&header=&footer=) ``` ( ) # Length times... ‛+on¬i # If first iteration, o, else + : # Duplicate ⁰- # add (size) minuses p, # Add the o/+ and print ⁰( ) # Size times \| # A pipe character : # Duplicate ⁰꘍ # Add (size) spaces p, # Add the pipe and print \o: # Push two os ⁰- # Add (size) minuses p, # Add the o and print ``` [Answer] ## Python 2, 94 bytes ``` def F(n,m):a,b,c,d='o|+-';r=[a+d*m+a]+([b+' '*m+b]*m+[c+d*m+c])*n;r[-1]=r[0];print'\n'.join(r) ``` 'Ungolfed': ``` def F(n,m): # 'o---o' r = ['o'+'-'*m+'o'] # ('| |'*m+'+---+') n times r += (['|'+' '*m+'|']*m+['+'+'-'*m+'+'])*n # replace last +---+ with o---o r[-1] = r[0] print '\n'.join(r) ``` [Answer] # [Perl 5](https://www.perl.org/), 91 + 1 (-a) = 92 bytes ``` $_='|'.$"x$F[1].'|';push@a,y/| /+-/r,($_)x$F[1]while$F[0]--;$a[0]=y/| /o-/r;say for@a,$a[0] ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3la9Rl1PRalCxS3aMFYPyLEuKC3OcEjUqdSvUdDX1tUv0tFQideEyJdnZOakAlkGsbq61iqJQNoWrCwfqMy6OLFSIS2/CKgVLPP/v6mC8b/8gpLM/Lzi/7q@pnoGhgb/dRMB "Perl 5 – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-l`, 35 bytes ``` (^YsXbRLaJW'-)XbWR^('|XbRLaJ'+)WR'o ``` [Try it online!](https://tio.run/##K8gs@P9fIy6yOCIpyCfRK1xdVzMiKTwoTkO9BiKirq0ZHqSe////f92c/8b/jQE "Pip – Try It Online") ### Explanation ``` (^YsXbRLaJW'-)XbWR^('|XbRLaJ'+)WR'o a is length, b is size, s is space (implicit) sXb String containing b spaces RLa List containing a copies of that string JW'- Join on "-" and wrap the result in "-" as well Y Necessary for operator precedence reasons ^ Split into a list of characters ( )Xb String-repeat each character in the list b times This list represents the central columns of the ladder '|Xb String containing b pipe characters RLa List containing a copies of that string J'+ Join on "+" ( )WR'o Wrap in "o" ^ Split into a list of characters This list represents the outer columns of the ladder WR Wrap the left list in the right list, vectorizing ``` ### Some other versions I tried a lot of different approaches trying to catch Pyth... ``` [Y'-XbWR'o;@>(sXbWR'|RLbPE'-XbWR'+RL:a)y] 41 Y^(t**b.1*:t**bX--a.1)" --"@yXbWR"|o+"@y 40 Y'|XbRLaJ'+YyWR'o;Z:sXbRLaJW'-RLbPEyAEy 39 t**:b(" |-o-+"<>2)@_@^t.1M$*Y[ttXa-1].1 39 J*Z:sXbRLaJW'-RLbWR:^('|XbRLaJ'+)WR'o 37 Y^$*Y[t**:btXa-1].1" --"@yXbWR"|o+"@y 37 ``` I'm particularly fond of the `t**b` ones, which use math to generate the ladder's vertical pattern: ``` b Size; e.g. 3 t Preset variable for 10 **: Set t to t**b (e.g. 1000) a Length; e.g. 3 -1 2 tX String-repeat (the new value of) t 2 times: 10001000 [ ] Put t and the above into a list: [1000; 10001000] .1 Append 1 to both of them: [10001; 100010001] $*( ) Fold on multiplication: 1000200020001 ``` The `1000200020001` can then be used to generate the patterns `o|||+|||+|||o` and `- - - -`, which make up the ladder. Unfortunately, I couldn't get this approach to be shorter than the join/wrap approach. ]
[Question] [ # Introduction Let's start by arranging all fractions from 0 to 1 in order of lowest denominator, then lowest numerator: 1/2, 1/3, 2/3, 1/4, 3/4, 1/5, 2/5, 3/5, 4/5, 1/6, 5/6, 1/7... Note that duplicates aren't counted, so I haven't listed 2/4, 2/6, 3/6, or 4/6, since they already appeared in their simplified forms (1/2, 1/3, and 2/3). Your task is now simple: given a positive integer `n`as a command line argument, print to standard output the `n`th fraction in the list. Thus, an input of `5` should yield an output of `3/4` (**not** 0.75). # Bowlers Your goal is to solve this in the longest program possible. Your score is the number of characters. # Golfers Your goal is to take existing answers, and golf them. When golfing those answers, remove one or more characters from the code, and optionally rearrange the remaining characters, in such a way that the resulting code is still a valid solution in the same language. Your score is the product of all the reductions. (So if you remove 10 characters from one answer, and 15 from another, your score is 150.) # Rules 1. A valid program must have at least three unique characters. 2. Only ASCII characters may be used. 3. If your program's size is reduced, your score is reduced accordingly. 4. When golfing a program... 1. Edit the code in the text of the answer 2. Change the character count listed 3. Leave the following comment: `**Removed X characters (from Y to Z)**` (in bold) 5. You may not golf a valid program into an invalid one. 6. The golfed program must work in some version of the language listed. So if the original answer is marked as Python, and the code only works in Python 2, you may golf it to a program that only works in Python 3. 1. Therefore, it is recommended (but not required) that you be specific in titling your answer, mentioning the version and/or compiler used. 7. If you already golfed an answer, you may golf it again. 8. If you golf the same answer multiple times, your score for that answer is the *sum* of your reductions. 1. For example, if you reduce 10 characters from a program, and later remove another 15, and also golf 7 characters from another answer, your total score is (10+15)\*7=175. 2. This applies regardless of whether someone else golfed the program in between your golfings. 9. You may golf your own answer, but you do not receive any points for doing so. # Winners I will try to keep this leaderboard periodically updated. If I make a mistake, please let me know, or else you can edit this post yourself. ## Top bowlers 1. Dennis (CJam): 1.17 × 10678 2. Pppery (CPython 3.6.2): 25984 3. OldCurmudgeon (Java): 278 ## Top golfers 1. jimmy23013: 105.2 \* 10152 2. Martin Ender: 2.8 \* 1014484 3. Pppery: 2 \* 104111 [Answer] # CJam, 1.17 × 10678 bytes ``` ",,,",KK#b:c~ ``` Well, the string should actually contain 1,167,015,602,222,203,651,546,923,533,233,456,645,527,427,020,625,754,322,603,554,937,551,735,592,092,356,520,085,507,613,447,896,812,875,213,856,544,974,386,642,866,232,121,069,637,599,975,236,272,634,227,913,998,493,360,693,139,149,236,571,503,883,331,020,249,908,672,008,574,221,022,612,893,546,658,640,986,973,481,700,267,591,531,514,666,040,606,217,610,439,998,612,592,897,511,421,801,308,639,396,208,196,301,077,376,577,788,009,239,468,384,204,073,426,482,794,344,190,683,235,393,373,061,689,668,389,239,477,158,591,879,792,606,717,529,814,802,500,558,822,508,662,266,027,694,882,649,391,373,447,012,817,270,871,840,254,480,631,579,732,459,294,193,158,457,158,597,836,239,348,386,288,579,699,763,150,579,966,400,972,286,547,196,034,472,447,664,813,466,769,145,983,290,696,497,053,781,354,086,441,505,174,165,846,491,136,000,001,121,501,860,331,520,000,000,000,004,508,876,800,000,000,000,000,000,126 commas, but the editor didn't let me post the entire code... :( [Answer] # Python, 176 bytes Not a bowler, but... ``` import sys,fractions def f(t): c=0 for i in range(t+10): for j in range(1,i): if fractions.gcd(j,i)==1:c+=1 if c==t:return str(j)+'/'+str(i) print f(int(sys.argv[1])) ``` [Answer] # CJam, 9.44 × 10284 ``` "ddd",'iib:c~ ``` The string actually contains 943,611,762,745,112,544,157,801,937,289,871,933,621,396,073,807,297,328,579,826,246,436,861,144,651,900,144,172,793,266,430,374,467,343,433,363,000,182,294,622,535,895,774,344,720,689,882,873,880,571,351,234,260,849,874,055,687,224,065,790,608,381,303,357,434,711,286,607,328,858,338,155,948,406,237,564,203,055,794,077,541,968,210,416,550,049,644,382,519,576,532,604,460,863,849 d's. Note that the decoded program is slow in the online interpreter. [Answer] # CJam, 3.8 × 1087 bytes ``` "ddd",'#i,(;(bb:c~ ``` The string contains 3,795,999,425,660,798,101,493,706,445,244,921,058,557,321,207,441,420,808,131,205,973,714,113,789,081,612,593,756,565 d's. The generator script for the previous version of this answer, which might be useful later: ``` "'/ea(i(_)),:)_m*{_~{_@\%}h!=\~>&},=~o" "'bi,(;(;{#}*b":B~'d*`',B":c~" ``` [Answer] # CJam, 9.44 × 10284 ``` ",,,",'iib:c~ ``` The string actually contains 943,611,762,745,112,544,157,801,937,289,871,933,621,396,073,807,297,328,579,826,246,436,861,144,651,900,144,172,793,266,430,374,467,343,433,363,000,182,294,622,535,895,774,344,720,689,882,873,880,571,351,234,260,849,874,055,687,224,065,790,608,381,303,357,434,711,286,607,328,858,338,155,948,406,237,564,203,055,794,077,541,968,210,416,550,049,644,382,519,576,532,604,460,863,849 commas. [Answer] # Java - 278 ``` import java.math.*;void m(String a){BigInteger i=null;BigInteger n=i.ONE;BigInteger d=n.add(n);BigInteger e=n;for(i=e;i.compareTo(i.valueOf(Integer.parseInt(a[0])))<0;i=i.add(e))do if((n=n.add(e)).compareTo(d)>=0)d=d.add(n=e);while(!n.gcd(d).equals(e));System.out.print(n+"/"+d);}} ``` Ungolfed: ``` import java.math.*; void m(String args[]){ BigInteger i=null; BigInteger n=i.ONE; BigInteger d=n.add(n); BigInteger e=n; for(i=e; i.compareTo(i.valueOf(Integer.parseInt(args[0])))<0; i=i.add(e)) do if((n=n.add(e)).compareTo(d)>=0) d=d.add(n=e); while(!n.gcd(d).equals(e)); System.out.println(n +"/"+d); } } ``` ### Original version I have made no attempt to arbitrarily extend this solution. Not sure if that will gain me or lose me points. It is, however, a correct solution that will work for very large numbers. ``` public class Test { static class Fractions implements Iterator<String> { // Start at 1. BigInteger numerator = BigInteger.ONE; // Start at 2. BigInteger denominator = BigInteger.ONE.add(BigInteger.ONE); @Override public boolean hasNext() { // Never ending! return true; } @Override public String next() { String next = numerator + "/" + denominator; do { // Keep selecting the next one. step1(); // Until they are relatively prime. } while (!numerator.gcd(denominator).equals(BigInteger.ONE)); return next; } private void step1() { // Take a single step. numerator = numerator.add(BigInteger.ONE); if (numerator.compareTo(denominator) >= 0) { // num >= den - step denom up and num rewinds to 1. numerator = BigInteger.ONE; denominator = denominator.add(BigInteger.ONE); } } } // Returns the nth fraction. public String nthFraction(BigInteger n) { Iterator<String> f = new Fractions(); for (BigInteger i = BigInteger.ONE; i.compareTo(n) < 0; i = i.add(BigInteger.ONE)) { f.next(); } return f.next(); } // Returns the nth fraction. public String nthFraction(long n) { return nthFraction(BigInteger.valueOf(n)); } public void test() { Iterator<String> f = new Fractions(); for (int i = 1; i < 100; i++) { System.out.println(i + "=" + f.next()); } } public static void main(String args[]) { try { //new Test().test(); if (args.length >= 1) { System.out.println(new Test().nthFraction(Integer.parseInt(args[0]))); } else { System.out.println(new Test().nthFraction(5)); } } catch (Throwable t) { t.printStackTrace(System.err); } } } ``` [Answer] # CPython 3.6.2, 25984 bytes ``` t=int().__sub__(int()==int()) t=t.__sub__(int().__sub__(t));t=t.__sub__(int().__sub__(t));t=t.__sub__(int().__sub__(t));t=t.__sub__(int().__sub__(t));t=t.__sub__(int().__sub__(t));t=int().__sub__(t).__sub__(int()==int()) d=__builtins__.__dict__;l=list(d); c=d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d)) _=d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))\ndd=d[ l[_]].__dict__ ll=list(dd) d[l[d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))]](dd[ll[d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))]](d[l[_]](),(d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d)))))) ``` This answer was created by porting the code of Soham Chowdhury's Python answer through the cracker I wrote for wizzwizz4's cop answers to [restricted mini challengs](https://codegolf.stackexchange.com/questions/136150/restricted-mini-challenges-cops-thread). I hope I'm not violating some rule against posts to old [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenges. [Answer] # Ruby, ~~488 412 377 347 341~~ 214 bytes Starting with a more "regular-looking" program; Curious to see what awful things you can do to it. ``` require 'set' g=Enumerator.new do|y| v=Set.new d=2 loop do (1...d).each do|n| x=n.to_f/d if v.include?(x)==false v.add(x) y.yield(n.to_s+'/'+d.to_s) end end d+=1 end end i=0 $*[0].to_i.times do i=g.next end puts i ``` ]
[Question] [ A *radioactive quine* is a [quine](http://en.wikipedia.org/wiki/Quine_(computing))-like program that has an even number of characters and, when run, outputs itself with exactly half of its characters removed. The output itself may be a radioactive quine, so the program can "[decay](http://en.wikipedia.org/wiki/Radioactive_decay)" multiple times. It could be said that the [half-life](http://en.wikipedia.org/wiki/Half-life) of a radioactive quine is one run, up to a certain number of runs (decays). # Example The [Python 2](https://www.python.org/download/releases/2.7.2/) program (28 characters) ``` 1234;print'print\'abcdefg\'' ``` is a radioactive quine with 2 decay steps because when it is run it outputs ``` print'abcdefg' ``` which is the original program with these 14 characters removed: `1234;print'\\'`. When `print'abcdefg'` is run in turn it outputs `abcdefg` which is `print'abcdefg'` with the 7 characters `print''` removed. The program `abcdefg` is not a radioactive quine so the cycle has come to an end. # Challenge Write a radioactive quine **in 1024 characters or less** that has the most decay cycles. The 1024 character limit means that the maximum number of decay cycles possible is 10 since the `1024 → 512 → 256 → 128 → 64 → 32 → 16 → 8 → 4 → 2 → 1` decay pattern would be optimal. The example above has 2 decay cycles. ### Details * Just like [normal quines](http://en.wikipedia.org/wiki/Quine_(computing)), radioactive quines may not take input or read their own source. * All output must go to stdout or your language's closest alternative. * You may use any characters. It is not limited to ASCII. * The characters in a radioactive quine that are removed may be removed from any indices (but the remaining characters may not be rearranged). So `radquine` could decay into `radq` or `uine` or `rdui` or `rain`, etc. * Note that only a program with an **even number of characters** can possibly be a radioactive quine. * It's fine if the final output of the decay cycle (`abcdefg` in the example) has an even number of characters. It doesn't matter what happens when this output is run as a program. # Winning The winner will be the submission with the most decay cycles. **Update:** Since trivial answers are possible I'm following yasen's advice and saying that in case of ties, the starting radioactive quine with the most unique characters wins. (Naturally 1024 is the limit here.) In the rare chance there is still a tie, the highest voted answer wins. [Answer] # CJam, 10 cycles ``` '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ``` --- # CJam, 10 cycles, 876 unique characters ``` "\"''''''''\""'""'BCD'µϨ¶'·ϩ¸'¹Ϫº'»ϫ¼'½Ϭ¾'¿ϭÀ'ÁϮÂ'ÃϯÄ'ÅϰÆ'ÇϱÈ'ÉϲÊ'ËϳÌ'ÍϴÎ'ÏϵÐ'Ñ϶Ò'ÓϷÔ'ÕϸÖ'×ϹØ'ÙϺÚ'ÛϻÜ'ÝϼÞ'ßϽà'áϾâ'ãϿä'åЀæ'çЁè'éЂê'ëЃì'íЄî'ïЅð'ñІò'óЇô'õЈö'÷Љø'ùЊú'ûЋü'ýЌþ'ÿЍĀ'āЎĂ'ăЏĄ'ąАĆ'ćБĈ'ĉВĊ'ċГČ'čДĎ'ďЕĐ'đЖĒ'ēЗĔ'ĕИĖ'ėЙĘ'ęКĚ'ěЛĜ'ĝМĞ'ğНĠ'ġОĢ'ģПĤ'ŃЯń'ţпŤ'ťрŦ'ŧсŨ'ũтŪ'ūуŬ'ŭфŮ'ůхŰ'űцŲ'ųчŴ'ŵшŶ'ŷщŸ'Źъź'Żыż'Žьž'ſэƀ'ƁюƂ'ƃяƄ'ƅѐƆ'Ƈёƈ'ƉђƊ'Ƌѓƌ'ƍєƎ'ƏѕƐ'Ƒіƒ'ƓїƔ'ƕјƖ'ƗљƘ'ƙњƚ'ƛћƜ'Ɲќƞ'ƟѝƠ'ơўƢ'ƣџƤ'ƥѠƦ'Ƨѡƨ'ƩѢƪ'ƫѣƬ'ƭѤƮ'Ưѥư'ƱѦƲ'Ƴѧƴ'ƵѨƶ'ƷѩƸ'ƹѪƺ'ƻѫƼ'ƽѬƾ'ƿѭǀ'ǁѮǂ'ǃѯDŽ'DžѰdž'LJѱLj'ljѲNJ'Njѳnj'ǍѴǎ'Ǐѵǐ'ǑѶǒ'Ǔѷǔ'ǕѸǖ'Ǘѹǘ'ǙѺǚ'ĥРĦ'ħСĨ]Ǜѻǜ_ǝѼǞ\\Ǥ\"ǥҀǦ썐īУĬ썑ĭФĮ썒ĩТĪ썓Ņаņ썔Ňбň썕ʼnвŊ썖ŋгŌ썗ōдŎ썘ŏеŐ썙őжŒ썚œзŔ썛ŕиŖ썜ŗйŘ썝řкŚ썞śлŜ썟ŝмŞ썠şнŠ썡šоŢ썢įХİ썣ıЦIJ썤ijЧĴ썥ĵШĶ썦ķЩĸ썧ĹЪĺ써ĻЫļ썩ĽЬľ썪ĿЭŀ썫ŁЮł썬ǟѽǠ썭ǡѾǢ썮ǧҁǨ썯ǩ҂Ǫ썰ǫ҃Ǭ썱ǭ҄Ǯ썲ǯ҅ǰ썳DZ҆Dz썴dz҇Ǵ썵ǵ҈Ƕ썶Ƿ҉Ǹ썷ǹҊǺ썸ǻҋǼ썹ǽҌǾ썺ǿҍȀ썻ȁҎȂ썼ȃҏȄ썽ȅҐȆ썾ȇґȈ썿ȉҒȊ쎀ȋғȌ쎁ȍҔȎ쎂ȏҕȐ쎃ȑҖȒ쎄ȓҗȔ쎅ȕҘȖ쎆ȗҙȘ쎇șҚȚ쎈țқȜ쎉ȝҜȞ쎊ȟҝȠ쎋ȡҞȢ쎌ȣҟȤ쎍ȥҠȦ쎎ȧҡȨ쎏ȩҢȪ쎐ȫңȬ쎑ȭҤȮ쎒ȯҥȰ쎓ȱҦȲ쎔ȳҧȴ쎕ȵҨȶ쎖ȷҩȸ쎗ȹҪȺ쎘Ȼҫȼ쎙ȽҬȾ쎚ȿҭɀ쎛ɁҮɂ쎜ɃүɄ쎝ɅҰɆ쎞ɇұɈ쎟ɉҲɊ쎠ɋҳɌ쎡ɍҴɎ쎢ɏҵɐ쎣ɑҶɒ쎤ɓҷɔ쎥ɕҸɖ쎦ɗҹɘ쎧əҺɚ쎨ɛһɜ쎩ɝҼɞ쎪ɟҽɠ쎫ɡҾɢ쎬ɣҿɤ쎭ɥӀɦ쎮ɧӁɨ쎯ɩӂɪ쎰ɫӃɬ쎱ɭӄɮ쎲ɯӅɰ쎳ɱӆɲ쎴ɳӇɴ쎵ɵӈɶ쎶ɷӉɸ쎷ɹӊɺ쎸ɻӋɼ쎹ɽӌɾ쎺ɿӍʀ쎻ʁӎʂ쎼ʃӏʄ쎽ʅӐʆ쎾ʇӑʈ쎿ʉӒʊ쏀ʋӓʌ쏁ʍӔʎ쏂ʏӕʐ쏃ʑӖʒ쏄ʓӗʔ쏅ʕӘʖ쏆ʗәʘ쏇ʙӚʚ쏈ʛӛʜ쏉ʝӜʞ쏊ʟʠʡ\\Ӟ\"ʢʣӟ;"2%'""Y%a" ``` [Try it online.](http://cjam.aditsu.net/) ### How it works * `"xyzw"` pushes the string `xyzw`. * `"xyzw"2%` pushes the string `xz`. * `"xyzw";` pushes nothing. * `]_` duplicates the entire stack. * `'x` pushes the character `x`. ### Example run ``` $ C=$(cat decay); while ((${#C} > 1)); do echo $C; C=$(cjam <(echo $C)); done; echo $C "\"''''''''\""'""'BCD'µϨ¶'·ϩ¸'¹Ϫº'»ϫ¼'½Ϭ¾'¿ϭÀ'ÁϮÂ'ÃϯÄ'ÅϰÆ'ÇϱÈ'ÉϲÊ'ËϳÌ'ÍϴÎ'ÏϵÐ'Ñ϶Ò'ÓϷÔ'ÕϸÖ'×ϹØ'ÙϺÚ'ÛϻÜ'ÝϼÞ'ßϽà'áϾâ'ãϿä'åЀæ'çЁè'éЂê'ëЃì'íЄî'ïЅð'ñІò'óЇô'õЈö'÷Љø'ùЊú'ûЋü'ýЌþ'ÿЍĀ'āЎĂ'ăЏĄ'ąАĆ'ćБĈ'ĉВĊ'ċГČ'čДĎ'ďЕĐ'đЖĒ'ēЗĔ'ĕИĖ'ėЙĘ'ęКĚ'ěЛĜ'ĝМĞ'ğНĠ'ġОĢ'ģПĤ'ŃЯń'ţпŤ'ťрŦ'ŧсŨ'ũтŪ'ūуŬ'ŭфŮ'ůхŰ'űцŲ'ųчŴ'ŵшŶ'ŷщŸ'Źъź'Żыż'Žьž'ſэƀ'ƁюƂ'ƃяƄ'ƅѐƆ'Ƈёƈ'ƉђƊ'Ƌѓƌ'ƍєƎ'ƏѕƐ'Ƒіƒ'ƓїƔ'ƕјƖ'ƗљƘ'ƙњƚ'ƛћƜ'Ɲќƞ'ƟѝƠ'ơўƢ'ƣџƤ'ƥѠƦ'Ƨѡƨ'ƩѢƪ'ƫѣƬ'ƭѤƮ'Ưѥư'ƱѦƲ'Ƴѧƴ'ƵѨƶ'ƷѩƸ'ƹѪƺ'ƻѫƼ'ƽѬƾ'ƿѭǀ'ǁѮǂ'ǃѯDŽ'DžѰdž'LJѱLj'ljѲNJ'Njѳnj'ǍѴǎ'Ǐѵǐ'ǑѶǒ'Ǔѷǔ'ǕѸǖ'Ǘѹǘ'ǙѺǚ'ĥРĦ'ħСĨ]Ǜѻǜ_ǝѼǞ\\Ǥ\"ǥҀǦ썐īУĬ썑ĭФĮ썒ĩТĪ썓Ņаņ썔Ňбň썕ʼnвŊ썖ŋгŌ썗ōдŎ썘ŏеŐ썙őжŒ썚œзŔ썛ŕиŖ썜ŗйŘ썝řкŚ썞śлŜ썟ŝмŞ썠şнŠ썡šоŢ썢įХİ썣ıЦIJ썤ijЧĴ썥ĵШĶ썦ķЩĸ썧ĹЪĺ써ĻЫļ썩ĽЬľ썪ĿЭŀ썫ŁЮł썬ǟѽǠ썭ǡѾǢ썮ǧҁǨ썯ǩ҂Ǫ썰ǫ҃Ǭ썱ǭ҄Ǯ썲ǯ҅ǰ썳DZ҆Dz썴dz҇Ǵ썵ǵǶ썶ǷǸ썷ǹҊǺ썸ǻҋǼ썹ǽҌǾ썺ǿҍȀ썻ȁҎȂ썼ȃҏȄ썽ȅҐȆ썾ȇґȈ썿ȉҒȊ쎀ȋғȌ쎁ȍҔȎ쎂ȏҕȐ쎃ȑҖȒ쎄ȓҗȔ쎅ȕҘȖ쎆ȗҙȘ쎇șҚȚ쎈țқȜ쎉ȝҜȞ쎊ȟҝȠ쎋ȡҞȢ쎌ȣҟȤ쎍ȥҠȦ쎎ȧҡȨ쎏ȩҢȪ쎐ȫңȬ쎑ȭҤȮ쎒ȯҥȰ쎓ȱҦȲ쎔ȳҧȴ쎕ȵҨȶ쎖ȷҩȸ쎗ȹҪȺ쎘Ȼҫȼ쎙ȽҬȾ쎚ȿҭɀ쎛ɁҮɂ쎜ɃүɄ쎝ɅҰɆ쎞ɇұɈ쎟ɉҲɊ쎠ɋҳɌ쎡ɍҴɎ쎢ɏҵɐ쎣ɑҶɒ쎤ɓҷɔ쎥ɕҸɖ쎦ɗҹɘ쎧əҺɚ쎨ɛһɜ쎩ɝҼɞ쎪ɟҽɠ쎫ɡҾɢ쎬ɣҿɤ쎭ɥӀɦ쎮ɧӁɨ쎯ɩӂɪ쎰ɫӃɬ쎱ɭӄɮ쎲ɯӅɰ쎳ɱӆɲ쎴ɳӇɴ쎵ɵӈɶ쎶ɷӉɸ쎷ɹӊɺ쎸ɻӋɼ쎹ɽӌɾ쎺ɿӍʀ쎻ʁӎʂ쎼ʃӏʄ쎽ʅӐʆ쎾ʇӑʈ쎿ʉӒʊ쏀ʋӓʌ쏁ʍӔʎ쏂ʏӕʐ쏃ʑӖʒ쏄ʓӗʔ쏅ʕӘʖ쏆ʗәʘ쏇ʙӚʚ쏈ʛӛʜ쏉ʝӜʞ쏊ʟʠʡ\\Ӟ\"ʢʣӟ;"2%'""Y%a" "''''''''""'C'Ϩ'ϩ'Ϫ'ϫ'Ϭ'ϭ'Ϯ'ϯ'ϰ'ϱ'ϲ'ϳ'ϴ'ϵ'϶'Ϸ'ϸ'Ϲ'Ϻ'ϻ'ϼ'Ͻ'Ͼ'Ͽ'Ѐ'Ё'Ђ'Ѓ'Є'Ѕ'І'Ї'Ј'Љ'Њ'Ћ'Ќ'Ѝ'Ў'Џ'А'Б'В'Г'Д'Е'Ж'З'И'Й'К'Л'М'Н'О'П'Я'п'р'с'т'у'ф'х'ц'ч'ш'щ'ъ'ы'ь'э'ю'я'ѐ'ё'ђ'ѓ'є'ѕ'і'ї'ј'љ'њ'ћ'ќ'ѝ'ў'џ'Ѡ'ѡ'Ѣ'ѣ'Ѥ'ѥ'Ѧ'ѧ'Ѩ'ѩ'Ѫ'ѫ'Ѭ'ѭ'Ѯ'ѯ'Ѱ'ѱ'Ѳ'ѳ'Ѵ'ѵ'Ѷ'ѷ'Ѹ'ѹ'Ѻ'Р'С]ѻ_Ѽ\"Ҁ썐У썑Ф썒Т썓а썔б썕в썖г썗д썘е썙ж썚з썛и썜й썝к썞л썟м썠н썡о썢Х썣Ц썤Ч썥Ш썦Щ썧Ъ써Ы썩Ь썪Э썫Ю썬ѽ썭Ѿ썮ҁ썯҂썰썱썲썳썴҇썵썶썷Ҋ썸ҋ썹Ҍ썺ҍ썻Ҏ썼ҏ썽Ґ썾ґ썿Ғ쎀ғ쎁Ҕ쎂ҕ쎃Җ쎄җ쎅Ҙ쎆ҙ쎇Қ쎈қ쎉Ҝ쎊ҝ쎋Ҟ쎌ҟ쎍Ҡ쎎ҡ쎏Ң쎐ң쎑Ҥ쎒ҥ쎓Ҧ쎔ҧ쎕Ҩ쎖ҩ쎗Ҫ쎘ҫ쎙Ҭ쎚ҭ쎛Ү쎜ү쎝Ұ쎞ұ쎟Ҳ쎠ҳ쎡Ҵ쎢ҵ쎣Ҷ쎤ҷ쎥Ҹ쎦ҹ쎧Һ쎨һ쎩Ҽ쎪ҽ쎫Ҿ쎬ҿ쎭Ӏ쎮Ӂ쎯ӂ쎰Ӄ쎱ӄ쎲Ӆ쎳ӆ쎴Ӈ쎵ӈ쎶Ӊ쎷ӊ쎸Ӌ쎹ӌ쎺Ӎ쎻ӎ쎼ӏ쎽Ӑ쎾ӑ쎿Ӓ쏀ӓ쏁Ӕ쏂ӕ쏃Ӗ쏄ӗ쏅Ә쏆ә쏇Ӛ쏈ӛ쏉Ӝ쏊ʠ\"ʣ;"Y%a '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''']_"썐썑썒썓썔썕썖썗썘썙썚썛썜썝썞썟썠썡썢썣썤썥썦썧써썩썪썫썬썭썮썯썰썱썲썳썴썵썶썷썸썹썺썻썼썽썾썿쎀쎁쎂쎃쎄쎅쎆쎇쎈쎉쎊쎋쎌쎍쎎쎏쎐쎑쎒쎓쎔쎕쎖쎗쎘쎙쎚쎛쎜쎝쎞쎟쎠쎡쎢쎣쎤쎥쎦쎧쎨쎩쎪쎫쎬쎭쎮쎯쎰쎱쎲쎳쎴쎵쎶쎷쎸쎹쎺쎻쎼쎽쎾쎿쏀쏁쏂쏃쏄쏅쏆쏇쏈쏉쏊"; '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''' '''''''''''''''' '''''''' '''' '' ' ``` [Answer] # CJam, 10 cycles, 1023 unique characters ``` "39c'LS 0¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈ̴̵̶̷̸̯̰̱̲̳̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮͯ͘͜͟͢͝͞͠͡ͰͱͲͳʹ͵Ͷͷ͸͹ͺͻͼͽ;Ϳ΀΁΂΃΄΅Ά·ΈΉΊ΋Ό΍ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ΢ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώϏϐϑϒϓϔϕϖϗϘϙϚϛϜϝϞϟϠϡϢϣϤϥϦϧϨϩϪϫϬϭϮϯϰϱϲϳϴϵ϶ϷϸϹϺϻϼϽϾϿЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖֽ־ֿ׀ׁׂ׃ׅׄ׆ׇ׈׉׊׋׌׍׎׏אבגדהוזחטיךכלםמןנסעףפץצקרשת׫׬׭׮ׯװױײ׳״׵׶׷׸׹׺׻׼׽׾׿؀؁؂؃؄؅؆؇؈؉؊؋،؍؎؏ؘؙؚؐؑؒؓؔؕؖؗ؛؜؝؞؟ؠءآأؤࡋࡌࡍࡎࡏࡐࡑࡒࡓࡔࡕࡖࡗࡘ࡙࡚࡛࡜࡝࡞࡟ࡠࡡࡢࡣࡤࡥࡦࡧࡨࡩࡪ࡫࡬࡭࡮࡯ࡰࡱࡲ૙૚૛૜૝૞૟ૠ൧൨ྲྀླྌྊྉྈྒ೨ഥദ೾೯ംഢ೼೻೺ബೳഇഄਗ਼ગઘੰ੡ੴઔ੮੭੬ઞ੥ઌੜ੤੯੣ઑ੧એ੢੹ੳ੶ߌࠉࠊߢߓߦࠆߠߟߞࠐߗ߾ߎߖߡߕࠃߙࠁߔ߫ߥߨԾջռՔՅ՘ոՒՑՐւՉհՀՈՓՇյՋճՆ՝՗՚ʰ˭ˮˆʷˊ˪˄˃˂˴ʻˢʲʺ˅ʹ˧ʽ˥ʸˏˉˌ"_`8)<\654f-T$,7+Y/W*A;> ``` ### Output ``` "39c'LS 0¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈ̴̵̶̷̸̯̰̱̲̳̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮͯ͘͜͟͢͝͞͠͡ͰͱͲͳʹ͵Ͷͷ͸͹ͺͻͼͽ;Ϳ΀΁΂΃΄΅Ά·ΈΉΊ΋Ό΍ΎΏΐΑΒΓΔΕΖֽ־ֿ׀ׁׂ׃ׅׄ׆ׇ׈׉׊׋׌׍׎׏אבגדהוזחטיךכלםמןנסעףפࡋࡌࡍࡎࡏࡐࡑࡒ૙૚೨ഥ೾೼೻೺ഄਗ਼ગઘੰ੡ੴઔ੮੭੬ઞ੥੹੶ߌࠉࠊߢߓߦࠆߠߟߞࠐߗ߾ߎߖߡߕࠃߙࠁߔ߫ߥߨԾջռՔՅ՘ոՒՑՐւՉհՀՈՓՇյՋճՆ՝՗՚ʰ˭ˮˆʷˊ˪˄˃˂˴ʻˢʲʺ˅ʹ˧ʽ˥ʸˏˉˌ"_`8)<\654f-T$,7+Y/W*A;> "39c'LS 0¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈ̴̵̶̷̸̯̰̱̲̳̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌ͅ͏ֽ͓͔͕͖͐͑͒־ֿ׀ׁׂ׃ׄࡋࡌਗ਼ગੰ੮੭੬੶ߌࠉࠊߢߓߦࠆߠߟߞࠐߗ߫ߨԾջռՔՅ՘ոՒՑՐւՉհՀՈՓՇյՋճՆ՝՗՚ʰ˭ˮˆʷˊ˪˄˃˂˴ʻˢʲʺ˅ʹ˧ʽ˥ʸˏˉˌ"_`8)<\654f-T$,7+Y/W*A;> "39c'LS 0¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ̴̵̶ֽ̯̰̱̲̳־ߌࠉߢߠߟߞߨԾջռՔՅ՘ոՒՑՐւՉ՝՚ʰ˭ˮˆʷˊ˪˄˃˂˴ʻˢʲʺ˅ʹ˧ʽ˥ʸˏˉˌ"_`8)<\654f-T$,7+Y/W*A;> "39c'LS 0¡¢£¤¥¦§¨̯̰ԾջՔՒՑՐ՚ʰ˭ˮˆʷˊ˪˄˃˂˴ʻˏˌ"_`8)<\654f-T$,7+Y/W*A;> "39c'LS 0¡¢ʰ˭ˆ˄˃˂ˌ"_`8)<\654f-A> "39c'LS 0"_8654> 39c'LS 0 'L 0 L0 0 ``` ### How it works * ``8)<` returns the first 9 characters of the string with double quote. * `654f-` decreases each character by 654. * `T$,` returns the string length on the top of the stack. * `7+Y/W*>` returns appropriate number of characters from the end of the decoded string. * `_`8)<\654f-A>` is a simplified version without calculating the number of characters. * `_8654>` does nothing useful. * `39c` is the character `'`. The string in each program ends with the output without `"39c'LS 0`, with each character value increased by 654. And each string is a substring of the one in the previous program, because it is the substring if both of them are decoded. The only character used twice is the double quote (`"`). Non-ascii characters cannot appear in blocks directly without a string in CJam. And there are no comment characters. So I think 1024 in CJam is impossible. It might be possible in GolfScript. And it should be easier in languages like Sclipting. But I'm too lazy to do that. It can be generated with the following program: ``` {9>654f+}:U; {"\"39c'LS 0"\+}:V; { _,24-,'¡f+ \U+ V "\"_`8)<\654f-T$,7+Y/W*A;>"+ }:T; "\"39c'LS 0\"_8654>" U"¡¢"\+V"\"_`8)<\654f-A>"+ TTTTT ``` # CJam, 10 cycles, all printable ascii ``` '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''']_" !#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJK"; ``` ### How it works In the first time it prints 512 `'`s. Then it works just like Dennis's answer. [Answer] # [Marbelous](https://github.com/marbelous-lang), 10 cycles ``` 3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333334 ``` There are 1023 3's and then one 4. This will print 511 3's (since 33 is the hexadecimal ascii value of 3) and one 4 (since 3 is the hexadecimal ascii value of 4). This keeps going until we are left with: ``` 34 ``` which prints `4` and is not a valid Marbelous program. **Another solution, using 22 distinct characters:** ``` 01333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333334 23 45 67 89 AB CD EF AA AA AA AA AA AA AA AA ab :ab }0 \/3333 ``` In this one I've defined a function that takes one input and prints two 3's. I then feed 16 inputs to it, which prints the number 3 32 times. This all consists of 64 characters. , then there are 959 3's and one 4. This all reduces to 511 3's and one 4. This then continues like the solution above. Since I can print two 3's by adding just 3 characters (any literal plus a newline), I can add a bunch more useless devices to the `ab` function to use more distinct characters. As long as 511 of the characters I use stay 3's and one a 4. [Answer] ## CJam, 10 Cycles, 947 Unique characters I think I am getting a hang of it now. A sweet tricky approach to the problem brings be 937 unique characters and still space for more. ``` "\"['''''''''''''''']_\""`'`'''`"\"\\\"0123456789\\\";\"\"@ABCDEFGHIJKLMNOPQRSTUV\";"`'`'''`"\"WXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~®¯°±²³´\";"`'`"\"µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪ\";"`"īĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞ"`';"ȟȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿˀˁ˂˃˄˅ˆˇˈˉˊˋˌˍˎˏːˑ˒˓˔˕˖˗˘˙˚˛˜˝˞˟ˠˡˢˣˤ˥˦˧˨˩˪˫ˬ˭ˮ˯˰˱˲˳˴˵˶˷˸˹˺˻˼˽˾˿̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇͈͉͍͎̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌̕̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮͯ͘͜͟͢͝͞͠͡ͰͱͲͳʹ͵Ͷͷ͸͹ͺͻͼͽ;Ϳ΀΁΂΃΄΅Ά·ΈΉΊ΋Ό΍ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ΢ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώϏϐϑϒϓϔϕϖϗϘϙϚϛϜϝϞϟϠϡϢϣϤϥϦϧϨϩϪϫϬϭϮϯϰϱϲϳϴϵ϶ϷϸϹϺϻϼϽϾϿЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏ"; ``` --- Here is the output of all the cycles starting from initial state ``` "\"['''''''''''''''']_\""`'`'''`"\"\\\"0123456789\\\";\"\"@ABCDEFGHIJKLMNOPQRSTUV\";"`'`'''`"\"WXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~®¯°±²³´\";"`'`"\"µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪ\";"`"īĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞ"`';"ȟȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿˀˁ˂˃˄˅ˆˇˈˉˊˋˌˍˎˏːˑ˒˓˔˕˖˗˘˙˚˛˜˝˞˟ˠˡˢˣˤ˥˦˧˨˩˪˫ˬ˭ˮ˯˰˱˲˳˴˵˶˷˸˹˺˻˼˽˾˿̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇͈͉͍͎̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌̕̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮͯ͘͜͟͢͝͞͠͡ͰͱͲͳʹ͵Ͷͷ͸͹ͺͻͼͽ;Ϳ΀΁΂΃΄΅Ά·ΈΉΊ΋Ό΍ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ΢ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώϏϐϑϒϓϔϕϖϗϘϙϚϛϜϝϞϟϠϡϢϣϤϥϦϧϨϩϪϫϬϭϮϯϰϱϲϳϴϵ϶ϷϸϹϺϻϼϽϾϿЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏ"; "\"['''''''''''''''']_\""`'`"\"\\\"0123456789\\\";\"\"@ABCDEFGHIJKLMNOPQRSTUV\";"`'`"\"WXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~®¯°±²³´\";"`"\"µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪ\";""īĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞ"; "\"['''''''''''''''']_\""`"\"\\\"0123456789\\\";\"\"@ABCDEFGHIJKLMNOPQRSTUV\";"`"\"WXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~®¯°±²³´\";""µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪ"; "\"['''''''''''''''']_\"""\"\\\"0123456789\\\";\"\"@ABCDEFGHIJKLMNOPQRSTUV\";""WXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~®¯°±²³´"; "['''''''''''''''']_""\"0123456789\";""@ABCDEFGHIJKLMNOPQRSTUV"; ['''''''''''''''']_"0123456789"; '''''''''''''''' '''''''' '''' '' ' ``` As you can see, in each iteration, the right half of the line is a single string appended with `;`, thus it gets removed while evaluating. [Try it online](http://cjam.aditsu.net/) [Answer] ## APL, 10 cycles ``` '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''01''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ``` That is 511 `'`s, characters `01`, and then 511`'`s **Explaintion** In APL, `'` are NOT escaped as `\'` but `''`. Yes, double quote marks!! **Proof of correctness** Suppose there are `x` quote marks on the left side of `01`, and `x` is odd. Then, number of quote marks on the left side of `01` in the output = `(x-1)/2` Similarly, for `x` quote marks on the right, there is `(x-1)/2` quote marks on the right in the output So, for a program of length `L`, which has `L/2-1` quote marks on each side, the output contains: * `((L/2-1)-1)/2 = L/4-1` quote marks on the left * 2 characters `01` * and `L/4-1` quote marks on the right which gives a total of `L/2` characters in the output. Note that because `x` is a power of 2 minus 1, `(x-1)/2 = ((2^n-1)-1)/2 = 2^(n-1)-1` is still a power of 2 minus 1 and odd if n>1 When n = 1, there are 0 quote marks on each side, so the output is `01`, which evaluates to `1`. ]
[Question] [ # The Collatz sequence Given a positive integer \$a\_1\$, the [Collatz sequence](https://en.wikipedia.org/wiki/Collatz_conjecture) with starting value \$a\_1\$ is defined as \begin{equation} a\_{n+1} = \begin{cases} a\_n/2 & \mathrm{if}\ a\_n\ \mathrm{is}\ \mathrm{even} \\ 3a\_n+1 & \mathrm{if}\ a\_n\ \mathrm{is}\ \mathrm{odd}. \end{cases} \end{equation} It is [conjectured](https://en.wikipedia.org/wiki/Collatz_conjecture#Statement_of_the_problem) that, for any starting value, this sequence always reaches the number \$1\$. This challenge assumes that the conjecture is true. # The challenge Given an integer \$a\_1 > 2\$, compute the Collatz sequence until \$1\$ is reached for the first time. Let \$N\$ be the number of sequence terms (including \$a\_1\$ and \$a\_N = 1\$). From the sequence of numbers \begin{equation} a\_1, a\_2, a\_3, \ldots, a\_N \end{equation} form a sequence of points in the plane by taking all pairs of consecutive terms \begin{equation} (a\_1, a\_2), (a\_2, a\_3), \ldots, (a\_{N-1}, a\_N) \end{equation} and plot these points on a 2D graph, joining consecutive points by a line segment. # Example For input \$12\$ the Collatz sequence is (\$10\$ terms); \begin{equation} 12, 6, 3, 10, 5, 16, 8, 4, 2, 1. \end{equation} The sequence of points is (\$9\$ points): \begin{equation} (12, 6), (6, 3), (3, 10), (10, 5), (5, 16), (16, 8), (8, 4), (4, 2), (2, 1). \end{equation} The plot contains \$8\$ line segments, as shown in the following graph. Note that some of the segments partially overlap. For clarity, the plot includes markers at the \$9\$ points. [![enter image description here](https://i.stack.imgur.com/SXS7n.png)](https://i.stack.imgur.com/SXS7n.png) # Additional rules * Graphical output is required, with output being [flexible](https://codegolf.meta.stackexchange.com/questions/9093/default-acceptable-image-i-o-methods-for-image-related-challenges) as usual. * Only the straight lines are required in the graph. Line width is flexible, as long as the plot can be seen reasonably well. Line color is also flexible, and may be different for each segment, as long as lines are distinguishable from the background. * Other elements in the graph are not required, but are allowed (point markers, grid lines, axis labels, ...). * Horizontal and vertical axis scales need not be the same. Axis limits are arbitrary, as long as the graph can be seen fully and clearly. The axes may be swapped, and each axis may be reversed. * The code should work for any input given unlimited resources. It is acceptable if in practice it fails for large inputs due to time, memory or data-type limitations. * If the input happens to be a counterexample for the Collatz conjecture the code can do anything, such as get stuck in an infinite loop or order a pizza. * [Programs or functions](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet) are accepted. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Shortest code in bytes wins. # Test cases | Input | Output | | --- | --- | | `3` | [enter image description here](https://i.stack.imgur.com/u8p5i.png) | | `4` | [enter image description here](https://i.stack.imgur.com/4DtDx.png) | | `27` | [enter image description here](https://i.stack.imgur.com/xOUsN.png) | | `649` | [enter image description here](https://i.stack.imgur.com/Mt3Fs.png) | | `650` | [enter image description here](https://i.stack.imgur.com/5eSka.png) | | `46720` | [enter image description here](https://i.stack.imgur.com/rL0ly.png) | | `345435` | [enter image description here](https://i.stack.imgur.com/LUtDC.png) | | `63728127` | [enter image description here](https://i.stack.imgur.com/xTgng.png) | [Answer] # [Python 3.8](https://docs.python.org/3.8/) with turtle, ~~156~~ 127 bytes Thanks to [Noodle9](https://codegolf.stackexchange.com/users/9481/noodle9) for catching a mistake! ``` from turtle import* def f(n,x=0): while~-n:goto(w:=n,n:=[n//2,3*n+1][n%2]);x<1!=clear();setworldcoordinates(0,0,x:=max(x,n),x) ``` Animation for \$a\_1=27\$: [![animation of turtle for testcase 27](https://i.stack.imgur.com/1dSRs.gif)](https://i.stack.imgur.com/1dSRs.gif) [Answer] # [J](http://jsoftware.com/), 52 bytes ``` load 'plot' f=:[:plot[:(}:;}.)(2&|{-:,1+*&3)^:(>&1)^:a: ``` [Try it online!](https://tio.run/##y/r/Pyc/MUVBvSAnv0SdK83WKtoKxIy20qi1sq7V09QwUqup1rXSMdTWUjPWjLPSsFMzBFKJVv//AwA "J – Try It Online") Wasn't sure if loading the graphics lib counted towards byte count, so I included it. Here's an image of calling `f 27` in the J console: [![27](https://i.stack.imgur.com/UG8UB.png)](https://i.stack.imgur.com/UG8UB.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes ``` r0×€:⁸ ×3‘ƊHḂ?Ƭ;Ɲ_/AÞṪçƊ+ṪƲƝẎŒṬx€€3 ``` [Try it online!](https://tio.run/##y0rNyan8/7/I4PD0R01rrB417uA6PN34UcOMY10eD3c02R9bY31sbry@4@F5D3euOrz8WJc2kD626djch7v6jk56uHNNBVAbEBn////fyAgA "Jelly – Try It Online") A pair of links that takes an integer argument and returns an RGB matrix on the (0 to 1) scale. Approach is the same as PBM output below but loses some bytes from the simpler output format. --- # Previous PBM answer [Jelly](https://github.com/DennisMitchell/jelly), ~~49~~ 44 bytes ``` r0×€:⁸ ×3‘ƊHḂ?Ƭ;Ɲ_/AÞṪçƊ+ṪƲƝẎŒṬµZL;L;FKṭ“P1 ``` [Try it online!](https://tio.run/##AVgAp/9qZWxsef//cjDDl@KCrDrigbgKw5cz4oCYxopI4biCP8asO8adXy9Bw57huarDp8aKK@G5qsayxp3huo7FkuG5rMK1Wkw7TDtGS@G5reKAnFAxIP///zIy "Jelly – Try It Online") A full program that takes an integer argument and prints the contents of a PBM file. Thanks to @cairdcoinheringaahing for some nice golfs totally 5 bytes! ## Example for 22: [![Example image for 22](https://i.stack.imgur.com/x8PkR.jpg)](https://i.stack.imgur.com/x8PkR.jpg) --- # Original SVG-based answer: [Jelly](https://github.com/DennisMitchell/jelly), 83 bytes ``` ×3‘ƊHḂ?Ị¬$пµj”,$ƝKṭṀ,`$“¡×ȯFṗẓ"az⁺Ṭ*,ġẎlḣḂ⁷Ọ]Ẏɦ?÷hṖF.IØṣƘŻÇÄ<,Ḥ:ẆṡṂȮXȷḷ[eʂmJ]»Ỵ¤;" ``` [Try it online!](https://tio.run/##AagAV/9qZWxsef//w5cz4oCYxopI4biCP@G7isKsJMOQwr/CtWrigJ0sJMadS@G5reG5gCxgJOKAnMKhw5fIr0bhuZfhupMiYXrigbrhuawqLMSh4bqObOG4o@G4guKBt@G7jF3huo7Jpj/Dt2jhuZZGLknDmOG5o8aYxbvDh8OEPCzhuKQ64bqG4bmh4bmCyK5YyLfhuLdbZcqCbUpdwrvhu7TCpDsi////NDU "Jelly – Try It Online") A full program taking an integer argument and printing an SVG. For example, with 45: ``` <svg width="136" height="136"><path stroke="red" fill="none" d="M45,136 136,68 68,34 34,17 17,52 52,26 26,13 13,40 40,20 20,10 10,5 5,16 16,8 8,4 4,2 2,1"/></svg> ``` [![Example SVG](https://i.stack.imgur.com/Hm3ff.jpg)](https://i.stack.imgur.com/Hm3ff.jpg) [Answer] # [R](https://www.r-project.org/) >= 4.1, ~~81~~ 74 bytes ``` \(x,y=x){while(x>1)y=c(y,x<-c(x/2,3*x+1)[x%%2+1]);plot(y,c(y[-1],NA),"l")} ``` [Try it at RDRR.io!](https://rdrr.io/snippets/embed/?code=f%20%3C-%20function(x%2Cy%3Dx)%7Bwhile(x%3E1)y%3Dc(y%2Cx%3C-c(x%2F2%2C3*x%2B1)%5Bx%25%252%2B1%5D)%3Bplot(y%2Cc(y%5B-1%5D%2CNA)%2C%22l%22)%7D%0Af(45)) Note this uses RDRR because TIO doesn’t support graphical output. It also uses `function` in place of `\` since RDRR doesn’t support R 4.1.0 yet. Thanks to @DominicVanEssen for saving 7 bytes! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 70 bytes ``` Graphics@Line@Last@Reap[#//.a_/;a>1:>Last@Sow@{a,If[2∣a,a/2,3a+1]}]& ``` -17 bytes from @att `63728127` [![enter image description here](https://i.stack.imgur.com/C8eZR.png)](https://i.stack.imgur.com/C8eZR.png) [Answer] # Julia using GR, 121 99 77 bytes Even better version by @MarcMush: ``` using GR !x=while(X=x[end])>1 plot([x;],(x=[x;X%2>0 ? 3X+1 : X/2])[2:end])end ``` Improved version thanks to the tips found [here](https://codegolf.stackexchange.com/questions/24407/tips-for-golfing-in-julia): ``` using GR c(a)=(i=1;while a[i]>1 a=[a;%(a[i],2)>0 ? 3a[i]+1 : a[i]/2];i+=1end;plot(a[1:i-1],a[2:i])) ``` What has been done: * single-line notation for functions -10 bytes * replace `push!` by array concatenation -3 bytes * use input `a` as array - 6 bytes * replace `end` by variable `i` that stores the length -3 bytes Original version: ``` using GR function c(x) a=[x] while a[end]>1 push!(a,%(a[end],2)>0 ? 3a[end]+1 : a[end]/2)end plot(a[1:end-1],a[2:end])end ``` Calling `c(27)` gives: [![enter image description here](https://i.stack.imgur.com/1Qcqb.png)](https://i.stack.imgur.com/1Qcqb.png) [Answer] # [SageMath](https://doc.sagemath.org/), ~~81~~ \$\cdots\$ ~~74~~ 71 bytes Saved 3 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!! ``` f=lambda n,*r:n-1and f(c:=[n/2,3*n+1][n%2],*r,(n,c))or list_plot(r,1<2) ``` [Try it online!](https://sagecell.sagemath.org/?z=eJwFwUEKgCAQAMC7r_ASaG2EK1RIvkQkTBECW8P8P81kW8JzpcAJmnXe0KwCJZ5FNNbRgqBHmpR3NKCHNjlBEKWXtfFyf_18S-2igTpQMpbFqjfcFW7yB5BhGQ4=&lang=sage&interacts=eJyLjgUAARUAuQ==) ### f(63728127) [![f(63728127)](https://i.stack.imgur.com/RojlB.png)](https://i.stack.imgur.com/RojlB.png) [Answer] # [Red](http://www.red-lang.org), ~~230~~ 212 bytes ``` func[n][a: to[]n while[n > 1][append a n: either odd? n[3 * n + 1][n / 2]]to-pair m: last sort copy a view[base 500x500 draw append[line]collect[while[a/2][keep as-pair a/1 / m * 500(first a: next a)/ m * 500]]]] ``` [Try it online!](https://tio.run/##PY7BasQwDETv/Yo5dreUbFJ6yaH7D70KH9RYIaZe2TjuJv16VyWwAiEYaeapiG@f4sk9zW3@0YnUEY@oiZxiW0IUUnygNzVnUQ@GjpBQFylI3l@h9IYzFC//R4oOg3M1vWYOBbcRkdeKNZWKKeVfs9@DbPTFq@D9ctmt4QtvOOIpBhU3pRhlqnTwuRscfYtk8HrEctcb52ZYsz/PoRjCnlbZbZ4eG2fV2h8 "Red – Try It Online") I don't know if red has a scalable plotting mechanism, but this was what I managed to get using the draw dialect. All outputs are scaled to 500x500 and there may be some inaccuracies for larger inputs due to downscaling and pairs being integers. In the red interpreter, you will have to redefine the function before each run because the words get messed up. -4 after using default axes. -18 bytes from Galen Ivanov. ## Output(n=12) (old) [![enter image description here](https://i.stack.imgur.com/fn7di.png)](https://i.stack.imgur.com/fn7di.png) [Answer] # [Factor](https://factorcode.org/) + `ui.gadgets.charts ui.gadgets.charts.lines math.unicode`, ~~208~~ ~~204~~ 199 bytes ``` [ [ [ 3 dupn , odd? [ 3 * 1 + ] [ 2/ ] if dup 1 ≠ ] loop , ] f make chart new over supremum 1 + '[ 0 _ ] dup 2array >>axes line new COLOR: red >>color rot 2 clump >>data add-gadget "" open-window ] ``` It's quotation (anonymous function) that accepts an integer from the data stack and opens a window with the chart in it. This only works in recent-ish builds of Factor, as the `chart` gadget is fairly new; I used build `2074`. Here's what it looks like for an input of `27`: [![enter image description here](https://i.stack.imgur.com/W6QuO.png)](https://i.stack.imgur.com/W6QuO.png) Unfortunately, the `chart` gadget doesn't come with any constructors. It requires us to manually calculate axes, and build its subcomponents which themselves don't come with any constructors. This leads to a bit of verbosity. [Answer] # HTML + JS, 166 bytes JS: 156 bytes HTML: 14 bytes This is a pretty basic implementation that renders to the DOM using an HTML canvas. A good chunk of the code is spent scaling the output to fit within the canvas. Anyone got any better ideas to handle this? The input is specified inline in the code, set the number inside `x=[...]`. ``` x=[9];c=C.getContext`2d`;c.beginPath();while((z=x[0])-1)x.unshift(z%2?3*z+1:z/2);r=Math.max(...x)/99;x.map((a,i)=>c.lineTo(a/r,99-x[i-1]/r));c.stroke() ``` ``` <canvas id=C> ``` [Answer] # [Python 3](https://docs.python.org/3/) + matplotlib, 127 bytes ``` def f(n,r=[]): k=n while ~-n:n=[n//2,3*n+1][n%2];r+=[n] p.plot(*zip(*[[k]+r,r]),'-o');p.show() import matplotlib.pyplot as p ``` -5 bytes thanks to @ovs!!! [Answer] # MATLAB 1999, ~~95~~ 84 bytes -1 from Luis Mendo ``` n=input('');i=n;while i>1;i=(i+mod(i,2)*(5*i+2))/2;n=[n;i];end;plot([0/0;n],[n;0/0]) ``` [![enter image description here](https://i.stack.imgur.com/KwaRQ.png)](https://i.stack.imgur.com/KwaRQ.png) Even `A(2:)` and A(2:-1)` was unavailable at that time... [Answer] # Python + Pygame, 228 bytes ``` from pygame import* d=display n=int(input()) k=[] while n>1:k+=[[n,n:=[n//2,3*n+1][n%2]]] M=max(k)[0] S=500 g=lambda s:[S*s[0]/M,S*s[1]/M] s=d.set_mode([S,S]) for i,j in enumerate(k):draw.line(s,[99]*3,g(k[i-1]),g(j)) d.update() ``` No TIO link because Pygame is not supported there. Reversed y-axis. I could save one byte by setting `S` to 99 or something, but I chose not to for easier viewing. I could also change `[99]*3` to `[9]*3` but I chose not to for easier viewing. Here is an example for input 63728127: [![Example](https://i.stack.imgur.com/IEp3b.png)](https://i.stack.imgur.com/IEp3b.png) ]
[Question] [ # Reverse and Invert a String ## Challenge In this challenge. You'll be writing a program which will output or return the input, reversed and inverted. First, each character should be converted to its character code. Then, that should be converted to base-2. Following, that string should be reversed. After, the string should be inverted (1 -> 0 and 0 -> 1). Finally, that should be converted back to base 2 and then converted back to a character. If an character results to be an unprintable, you may optionally output it but they do not have to be removed. ``` H -> 72 -> 1001000 -> 0001001 -> 1110110 -> 118 -> v e -> 101 -> 1100101 -> 1010011 -> 0101100 -> 44 -> , l -> 108 -> 1101100 -> 0011011 -> 1100100 -> 100 -> d l -> 108 -> 1101100 -> 0011011 -> 1100100 -> 100 -> d o -> 111 -> 1101111 -> 1111011 -> 0000100 -> 4 -> (unprintable) , -> 44 -> 101100 -> 001101 -> 110010 -> 50 -> 2 -> 32 -> 100000 -> 000001 -> 111110 -> 62 -> > W -> 87 -> 1010111 -> 1110101 -> 0001010 -> 10 -> (newline) o -> 111 -> 1101111 -> 1111011 -> 0000100 -> 4 -> (unprintable) r -> 114 -> 1110010 -> 0100111 -> 1011000 -> 88 -> X l -> 108 -> 1101100 -> 0011011 -> 1100100 -> 100 -> d d -> 100 -> 1100100 -> 0010011 -> 1101100 -> 108 -> l ! -> 33 -> 100001 -> 100001 -> 011110 -> 30 -> (unprintable) ``` ## Scoring Shortest code in bytes wins. **-15% Bonus:** if your program removes un-printables from the output. This must be *at least* all characters below 32 except newlines (char 10) [Answer] # Pyth, 14 bytes ``` smCi!M_jCd2 2z ``` [Try it online.](https://pyth.herokuapp.com/?code=smCi%21M_jCd2+2z&input=Hello%2C+World%21&debug=0) ### How it works ``` m z Map over the input with lambda d: Cd Cast d to character. j 2 Convert to base 2. _ Reverse the resulting array. !M Mapped logical NOT. i 2 Convert back to integer. C Cast to character. s Concatenate the resulting characters. ``` [Answer] # Perl, ~~57~~ 51 characters (50 characters code + 1 character command-line option.) ``` s/./$_=unpack b8,$&;s|0+$||;"chr 0b".y|10|01|r/gee ``` Sample run: ``` bash-4.3$ perl -pe 's/./$_=unpack b8,$&;s|0+$||;"chr 0b".y|10|01|r/gee' <<< 'Hello, World!' v,dd2> Xdl bash-4.3$ perl -pe 's/./$_=unpack b8,$&;s|0+$||;"chr 0b".y|10|01|r/gee' <<< 'Hello, World!' | od -tad1 0000000 v , d d eot 2 > nl eot X d l rs nl 118 44 100 100 4 50 62 10 4 88 100 108 30 10 0000016 ``` [Answer] # JavaScript (~~ES6~~ ES7), ~~119~~ ~~114~~ 108 bytes This turned out way longer than expected :( Thanks to @vihan for 5 bytes saved! Thanks to @ETHProductions for another 6 bytes saved! **To test:**  Run the snippet below, enter input like `"Hello, World!"`, and click *Test!* ``` x=>String.fromCharCode(...[for(y of x)+('0b'+[...y.charCodeAt().toString(2)].reverse().map(z=>z^1).join``)]) ``` ``` <!-- Try the test suite below! --><strong id="bytecount" style="display:inline; font-size:32px; font-family:Helvetica"></strong><strong id="bytediff" style="display:inline; margin-left:10px; font-size:32px; font-family:Helvetica; color:lightgray"></strong><br><br><pre style="margin:0">Code:</pre><textarea id="textbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><pre style="margin:0">Input:</pre><textarea id="inputbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><button id="testbtn">Test!</button><button id="resetbtn">Reset</button><br><p><strong id="origheader" style="font-family:Helvetica; display:none">Original Code Output:</strong><p><div id="origoutput" style="margin-left:15px"></div><p><strong id="newheader" style="font-family:Helvetica; display:none">New Code Output:</strong><p><div id="newoutput" style="margin-left:15px"></div><script type="text/javascript" id="golfsnippet">var bytecount=document.getElementById("bytecount");var bytediff=document.getElementById("bytediff");var textbox=document.getElementById("textbox");var inputbox=document.getElementById("inputbox");var testbtn=document.getElementById("testbtn");var resetbtn=document.getElementById("resetbtn");var origheader=document.getElementById("origheader");var newheader=document.getElementById("newheader");var origoutput=document.getElementById("origoutput");var newoutput=document.getElementById("newoutput");textbox.style.width=inputbox.style.width=window.innerWidth-50+"px";var _originalCode=null;function getOriginalCode(){if(_originalCode!=null)return _originalCode;var allScripts=document.getElementsByTagName("script");for(var i=0;i<allScripts.length;i++){var script=allScripts[i];if(script.id!="golfsnippet"){originalCode=script.textContent.trim();return originalCode}}}function getNewCode(){return textbox.value.trim()}function getInput(){try{var inputText=inputbox.value.trim();var input=eval("["+inputText+"]");return input}catch(e){return null}}function setTextbox(s){textbox.value=s;onTextboxChange()}function setOutput(output,s){output.innerHTML=s}function addOutput(output,data){output.innerHTML+='<pre style="background-color:'+(data.type=="err"?"lightcoral":"lightgray")+'">'+escape(data.content)+"</pre>"}function getByteCount(s){return(new Blob([s],{encoding:"UTF-8",type:"text/plain;charset=UTF-8"})).size}function onTextboxChange(){var newLength=getByteCount(getNewCode());var oldLength=getByteCount(getOriginalCode());bytecount.innerHTML=newLength+" bytes";var diff=newLength-oldLength;if(diff>0){bytediff.innerHTML="(+"+diff+")";bytediff.style.color="lightcoral"}else if(diff<0){bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgreen"}else{bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgray"}}function onTestBtn(evt){origheader.style.display="inline";newheader.style.display="inline";setOutput(newoutput,"");setOutput(origoutput,"");var input=getInput();if(input===null){addOutput(origoutput,{type:"err",content:"Input is malformed. Using no input."});addOutput(newoutput,{type:"err",content:"Input is malformed. Using no input."});input=[]}doInterpret(getNewCode(),input,function(data){addOutput(newoutput,data)});doInterpret(getOriginalCode(),input,function(data){addOutput(origoutput,data)});evt.stopPropagation();return false}function onResetBtn(evt){setTextbox(getOriginalCode());origheader.style.display="none";newheader.style.display="none";setOutput(origoutput,"");setOutput(newoutput,"")}function escape(s){return s.toString().replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}window.alert=function(){};window.prompt=function(){};function doInterpret(code,input,cb){var workerCode=interpret.toString()+";function stdout(s){ self.postMessage( {'type': 'out', 'content': s} ); }"+" function stderr(s){ self.postMessage( {'type': 'err', 'content': s} ); }"+" function kill(){ self.close(); }"+" self.addEventListener('message', function(msg){ interpret(msg.data.code, msg.data.input); });";var interpreter=new Worker(URL.createObjectURL(new Blob([workerCode])));interpreter.addEventListener("message",function(msg){cb(msg.data)});interpreter.postMessage({"code":code,"input":input});setTimeout(function(){interpreter.terminate()},1E4)}setTimeout(function(){getOriginalCode();textbox.addEventListener("input",onTextboxChange);testbtn.addEventListener("click",onTestBtn);resetbtn.addEventListener("click",onResetBtn);setTextbox(getOriginalCode())},100);function interpret(code,input){window={};alert=function(s){stdout(s)};window.alert=alert;console.log=alert;prompt=function(s){if(input.length<1)stderr("not enough input");else{var nextInput=input[0];input=input.slice(1);return nextInput.toString()}};window.prompt=prompt;(function(){try{var evalResult=eval(code);if(typeof evalResult=="function"){var callResult=evalResult.apply(this,input);if(typeof callResult!="undefined")stdout(callResult)}}catch(e){stderr(e.message)}})()};</script> ``` [Answer] # JavaScript (ES7), 126 bytes - 15% = 107.1 I was playing around with [this answer](https://codegolf.stackexchange.com/a/63070/42545) to see if the bonus was worth it. Apparently, it is. The test suite was stolen from the same answer, but I added my own twist: full support of the 15% bonus! :) ``` x=>String.fromCharCode(...[for(y of x)if((c=+('0b'+[...y.charCodeAt().toString(2)].reverse().map(z=>z^1).join``))>31|c==10)c]) ``` ``` <!-- Try the test suite below! --><strong id="bytecount" style="display:inline; font-size:32px; font-family:Helvetica"></strong><strong id="bytediff" style="display:inline; margin-left:10px; font-size:32px; font-family:Helvetica; color:lightgray"></strong><br><strong id="score" style="display:inline; font-size:32px; font-family:Helvetica">Score:</strong><strong id="scorediff" style="display:inline; margin-left:10px; font-size:32px; font-family:Helvetica; color:lightgray"></strong><br><br><pre style="margin:0">Code:</pre><textarea id="textbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><pre style="margin:0">Input:</pre><textarea id="inputbox" style="margin-top:5px; margin-bottom:5px">"Hello, World!"</textarea><br><button id="testbtn">Test!</button><button id="resetbtn">Reset</button><br><p><strong id="origheader" style="font-family:Helvetica; display:none">Original Code Output:</strong><p><div id="origoutput" style="margin-left:15px"></div><p><strong id="newheader" style="font-family:Helvetica; display:none">New Code Output:</strong><p><div id="newoutput" style="margin-left:15px"></div><script type="text/javascript" id="golfsnippet">var bytecount=document.getElementById("bytecount");var bytediff=document.getElementById("bytediff");var score=document.getElementById("score");var scorediff=document.getElementById("scorediff");var textbox=document.getElementById("textbox");var inputbox=document.getElementById("inputbox");var testbtn=document.getElementById("testbtn");var resetbtn=document.getElementById("resetbtn");var origheader=document.getElementById("origheader");var newheader=document.getElementById("newheader");var origoutput=document.getElementById("origoutput");var newoutput=document.getElementById("newoutput");textbox.style.width=inputbox.style.width=window.innerWidth-50+"px";var _originalCode=null;function getOriginalCode(){if(_originalCode!=null)return _originalCode;var allScripts=document.getElementsByTagName("script");for(var i=0;i<allScripts.length;i++){var script=allScripts[i];if(script.id!="golfsnippet"){originalCode=script.textContent.trim();return originalCode}}}function getNewCode(){return textbox.value.trim()}function getInput(){try{var inputText=inputbox.value.trim();var input=eval("["+inputText+"]");return input}catch(e){return null}}function setTextbox(s){textbox.value=s;onTextboxChange()}function setOutput(output,s){output.innerHTML=s}function addOutput(output,data){output.innerHTML+='<pre style="background-color:'+(data.type=="err"?"lightcoral":"lightgray")+'">'+escape(data.content)+"</pre>"}function getByteCount(s){return(new Blob([s],{encoding:"UTF-8",type:"text/plain;charset=UTF-8"})).size}function getScore(s){var a=1;try{b=eval('('+s+')("Hello, World!")');if(b=="v,dd2>\nXdl")a=.85}catch(e){};return getByteCount(s)*a}function onTextboxChange(){var newLength=getByteCount(getNewCode());var oldLength=getByteCount(getOriginalCode());bytecount.innerHTML=newLength+" bytes";var diff=newLength-oldLength;if(diff>0){bytediff.innerHTML="(+"+diff+")";bytediff.style.color="lightcoral"}else if(diff<0){bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgreen"}else{bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgray"}newLength=getScore(getNewCode());var oldLength=getScore(getOriginalCode());score.innerHTML="Score: "+newLength;var diff=Math.round((newLength-oldLength)*100)/100;if(diff>0){scorediff.innerHTML="(+"+diff+")";scorediff.style.color="lightcoral"}else if(diff<0){scorediff.innerHTML="("+diff+")";scorediff.style.color="lightgreen"}else{scorediff.innerHTML="("+diff+")";scorediff.style.color="lightgray"}}function onTestBtn(evt){origheader.style.display="inline";newheader.style.display="inline";setOutput(newoutput,"");setOutput(origoutput,"");var input=getInput();if(input===null){addOutput(origoutput,{type:"err",content:"Input is malformed. Using no input."});addOutput(newoutput,{type:"err",content:"Input is malformed. Using no input."});input=[]}doInterpret(getNewCode(),input,function(data){addOutput(newoutput,data)});doInterpret(getOriginalCode(),input,function(data){addOutput(origoutput,data)});evt.stopPropagation();return false}function onResetBtn(evt){setTextbox(getOriginalCode());origheader.style.display="none";newheader.style.display="none";setOutput(origoutput,"");setOutput(newoutput,"")}function escape(s){return s.toString().replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}window.alert=function(){};window.prompt=function(){};function doInterpret(code,input,cb){var workerCode=interpret.toString()+";function stdout(s){ self.postMessage( {'type': 'out', 'content': s} ); }"+" function stderr(s){ self.postMessage( {'type': 'err', 'content': s} ); }"+" function kill(){ self.close(); }"+" self.addEventListener('message', function(msg){ interpret(msg.data.code, msg.data.input); });";var interpreter=new Worker(URL.createObjectURL(new Blob([workerCode])));interpreter.addEventListener("message",function(msg){cb(msg.data)});interpreter.postMessage({"code":code,"input":input});setTimeout(function(){interpreter.terminate()},1E4)}setTimeout(function(){getOriginalCode();textbox.addEventListener("input",onTextboxChange);testbtn.addEventListener("click",onTestBtn);resetbtn.addEventListener("click",onResetBtn);setTextbox(getOriginalCode())},100);function interpret(code,input){window={};alert=function(s){stdout(s)};window.alert=alert;console.log=alert;prompt=function(s){if(input.length<1)stderr("not enough input");else{var nextInput=input[0];input=input.slice(1);return nextInput.toString()}};window.prompt=prompt;(function(){try{var evalResult=eval(code);if(typeof evalResult=="function"){var callResult=evalResult.apply(this,input);if(typeof callResult!="undefined")stdout(callResult)}}catch(e){stderr(e.message)}})()};</script> ``` [Answer] # CJam, 14 ``` q{i2bW%:!2bc}% ``` [Try it online](http://cjam.aditsu.net/#code=q%7Bi2bW%25%3A!2bc%7D%25&input=Hello%2C%20World!) **Explanation:** Pretty straightforward: ``` q read input {‚Ķ}% convert each character i convert to number 2b convert to base 2 (digit array) W% reverse :! invert each digit 2b convert from base 2 c convert to character ``` ### "Printable" version, 20 - 15% = 17 ``` q{i2bW%:!2bc' ,N--}% ``` [Answer] ## PHP - 187 182 163 bytes ``` <?php $s=$_GET["s"];$m="array_map";echo join($m("chr",$m("bindec",$m(function($v){return strtr($v,[1,0]);},$m("strrev",$m("decbin",$m("ord",str_split($s))))))));?> ``` Pass the value as `GET["s"]`. array\_map returns an array with all the elements of the second parameter (an array) after applying the callback function (first parameter) to all of them. Not sure if I should take the 15% off, since `echo` doesn't output unprintable characters, but I didn't remove them. Just glad I finished, since this is the first challenge I take part. [Answer] # C function, 63 ``` o;f(o,char *s){for(;*s;*s=o,s++)for(o=0;*s;*s/=2)o+=o+!(*s%2);} ``` [Answer] # K5, 28 bytes ``` `c${b/~|{x@&|\x}@(b:8#2)\x}' ``` This is a bit inconvenient because K5's `decode` operator performs a fixed-width base conversion, so to comply with the problem statement I have to trim leading zeroes. The lambda `{x@&|\x}` accomplishes this step. Smear: ``` |\0 0 1 0 1 1 0 1 0 0 1 1 1 1 1 1 ``` Gather: ``` &|\0 0 1 0 1 1 0 1 2 3 4 5 6 7 ``` Select: ``` {x@&|\x}0 0 1 0 1 1 0 1 1 0 1 1 0 1 ``` The whole program in action: ``` `c${b/~|{x@&|\x}@(b:8#2)\x}'"Hello, World" "v,dd2>\nXdl" ``` I believe [oK](http://johnearnest.github.io/ok/index.html)'s natural behavior with unprintables makes this eligible for -15%, giving this a score of 28\*0.85 = **23.8**. [Answer] # Julia, 77 bytes - 15% = 65.45 ``` s->join(filter(isprint,[Char(parse(Int,join(1-digits(Int(c),2)),2))for c=s])) ``` This creates an unnamed functon that accepts a string and returns a string. Unprintable characters are removed, which qualifies this for the bonus. Ungolfed: ``` function f(s::AbstractString) # digits() returns the digits in reverse order, so no explicit # reverse() is needed x = [Char(parse(Int, join(1 - digits(Int(c), 2)), 2)) for c = s] # Remove unprintables, join into a string return join(filter(isprint, x)) end ``` [Answer] ## PowerShell, ~~199 175~~ (171 - 15%)=145.35 ``` param([char[]]$a)($a|%{$b=[convert]::ToString(+$_,2);$c=[convert]::ToInt32("$((-join$b[$b.Length..0])-split0-replace1,0-join1)",2);if($c-gt31-or$c-eq10){[char]$c}})-join'' ``` Uses ~~an unfortunate amount of~~ some .NET calls/built-ins, which ~~significantly~~ bloats the code. ### Explained: Takes the input `param(..)` and casts it as a `char[]` so we can work through it appropriately. The next bit `(..)-join''` collects and joins our output together. Inside those parens, we iterate with `$a|%{..}` as a foreach loop. Inside the loop: * We create a new string `$b`, which is our input letter cast as an int `+$_` and `[convert]`ed to base `2` * This next bit, setting `$c`, is tricky, so let's start inside and work our way out * We reverse the string `$b` with `(-join$b[$b.length..0])` * We leverage my previous code for [inverting a binary string](https://codegolf.stackexchange.com/a/58475/42963) and recast the result as a string with `"$(..)"` * We feed that string into a different .NET call that `[convert]`s `ToInt32` from base `2`, which is finally stored that into `$c` * If `$c` is greater than `31`, or equal to `10`, we cast it as a char and that value is left on the pipeline for output (which is what gets collected and `-join''`ed together, above), else nothing gets left on this particular iteration Phew. Qualifies for the -15% bonus, as well. ### Example ``` PS C:\Tools\Scripts\golfing> .\reverse-and-invert-a-string.ps1 "Hello, World!" v,dd2> Xdl ``` [Answer] # ùîºùïäùïÑùïöùïü, 39 chars / 73 bytes ``` √¥‚ü¶√Ø]ƒá‚áùœöƒé(+‚Äú0b`+‚ü¶a.√º‚¨Æ√ü¬ß2]√π‚¨Æƒá‚áÄ$^1)√∏`‚Äù‚∏©√∏‚¨Ø‚¶Ü ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=Hello%2C%20world!&code=%C3%B4%E2%9F%A6%C3%AF%5D%C4%87%E2%87%9D%CF%9A%C4%8E%28%2B%E2%80%9C0b%60%2B%E2%9F%A6a.%C3%BC%E2%AC%AE%C3%9F%C2%A72%5D%C3%B9%E2%AC%AE%C4%87%E2%87%80%24%5E1%29%C3%B8%60%E2%80%9D%E2%B8%A9%C3%B8%E2%AC%AF%E2%A6%86)` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `K`, 5 bytes ``` bR‚ĆvB ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=K&code=bR%E2%80%A0vB&inputs=Hello&header=&footer=) epic. -2 bytes from Lyxal. -1 byte from Lyxal. [Answer] ## [Minkolang 0.11](https://github.com/elendiastarman/Minkolang), 26 bytes ``` od?.(d2%,$r2:d)xrI1-[2*+]O ``` [Try it here.](http://play.starmaninnovations.com/minkolang/old?code=od%3F%2E%28d2%25%2C%24r2%3Ad%29xrI1-%5B2%2A%2B%5DO&input=Hello%2C+World%21) ### Explanation ``` od?. Takes input as character, halting if empty (d2%,$r2:d)x Converts to binary, inverting digits on the way r Reverses stack I1-[2*+] Converts to decimal O Outputs as character (if printable) ``` [Answer] # MATLAB, 60 bytes ``` @(y)[arrayfun(@(x)bin2dec([97-fliplr(dec2bin(x)) '']),y) ''] ``` Basically each character in turn is converted into a binary string (with no leading zeros). The array is flipped and is subtracted from 97 ('0'+'1') which inverts the character. This is converted back to decimal. After all characters have been processed, the whole array is then converted back to characters before being returned. [Answer] # Python 3, 95 91 Straightforward implementation. ``` print(''.join(chr(int(''.join('10'[j>'0']for j in bin(ord(i))[:1:-1]),2))for i in input())) ``` Ungolfed: ``` inp = input() ints = (ord(i) for i in inp) bins = (bin(i) for i in ints) revs = (i[2:][::-1] for i in bins) #without leading '0b' invs = (''.join('0' if j == '1' else '1' for j in i) for i in revs) newInts = (int(i, 2) for i in invs) newChars = (chr(i) for i in newInts) newStr = ''.join(newChars) print(newStr) ``` [Answer] # Ruby, 62 characters ``` gets.bytes{|b|$><<b.to_s(2).reverse.tr("01","10").to_i(2).chr} ``` Samply run: ``` bash-4.3$ ruby -e 'gets.bytes{|b|$><<b.to_s(2).reverse.tr("01","10").to_i(2).chr}' <<< 'Hello, World!' v,dd2> Xdl bash-4.3$ ruby -e 'gets.bytes{|b|$><<b.to_s(2).reverse.tr("01","10").to_i(2).chr}' <<< 'Hello, World!' | od -tad1 0000000 v , d d eot 2 > nl eot X d l rs nl 118 44 100 100 4 50 62 10 4 88 100 108 30 10 0000016 ``` [Answer] # C#, 156 bytes - 15% = 132.6 ``` class P{static void Main(string[]a){try{for(int i=0,b,c;;){for(b=a[0][i++],c=0;b>0;b/=2)c=c<<1|1-b%2;if(c==10|c>31)System.Console.Write((char)c);}}catch{}}} ``` Indentation and new lines for clarity: ``` class P{ static void Main(string[]a){ try{ for(int i=0,b,c;;){ for(b=a[0][i++],c=0;b>0;b/=2) c=c<<1|1-b%2; if(c==10|c>31) System.Console.Write((char)c); } } catch{} } } ``` [Answer] # Javascript 123 bytes ``` s=>[].map.call(s,s=>String.fromCharCode("0b"+s.charCodeAt().toString(2).split('').reverse().map(s=>s^1).join(''))).join('') ``` [Answer] # [Retina](http://github.com/mbuettner/retina), ~~1107~~ 629 bytes - 15% = 534.65 (non-competing) *Uses features added after challenge date. (Implicit behavior of `$*`, `¬∂`, Sorting)* Retina doesn't have a built-in to convert a character to its ASCII ordinal or back... so behold its lustrous length. This handles printable ASCII, and removes unprintables as well as newlines. Byte count assumes ISO 8859-1 encoding. The code contains unprintable characters. ``` ¬∂ ¬± S_` %(S`¬± {2` $` }T01`-`_o )Ms`. \d+ $* +`(1+)\1 ${1}0 01 1 %O$^`. T`01`10 1 01 +`10 011 0 m`^1{1,31}$ M%`1 m`^0¬∂? 126 ~ 125 } 124 | 123 { 122 z 121 y 120 x 119 w 118 v 117 u 116 t 115 s 114 r 113 q 112 p 111 o 110 n 109 m 108 l 107 k 106 j 105 i 104 h 103 g 102 f 101 e 100 d 99 c 98 b 97 a 96 ` 95 _ 94 ^ 93 ] 92 \ 91 [ 90 Z 89 Y 88 X 87 W 86 V 85 U 84 T 83 S 82 R 81 Q 80 P 79 O 78 N 77 M 76 L 75 K 74 J 73 I 72 H 71 G 70 F 69 E 68 D 67 C 66 B 65 A 64 @ 63 ? 62 > 61 = 60 < 59 ; 58 : 57 9 56 8 55 7 54 6 32 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / 48 0 49 1 50 2 51 3 52 4 53 5 ¬∂ ``` [**Try it online**](http://retina.tryitonline.net/#code=wrYKwrEKU19gCiUoU2DCsQp7MmAKJGAKfVQwMWABLX9gX28KKU1zYC4KXGQrCiQqCitgKDErKVwxCiR7MX0wCjAxCjEKJU8kXmAuCgpUYDAxYDEwCjEKMDEKK2AxMAowMTEKMAoKbWBeMXsxLDMxfSQKCk0lYDEKbWBeMMK2PwoKMTI2Cn4KMTI1Cn0KMTI0CnwKMTIzCnsKMTIyCnoKMTIxCnkKMTIwCngKMTE5CncKMTE4CnYKMTE3CnUKMTE2CnQKMTE1CnMKMTE0CnIKMTEzCnEKMTEyCnAKMTExCm8KMTEwCm4KMTA5Cm0KMTA4CmwKMTA3CmsKMTA2CmoKMTA1CmkKMTA0CmgKMTAzCmcKMTAyCmYKMTAxCmUKMTAwCmQKOTkKYwo5OApiCjk3CmEKOTYKYAo5NQpfCjk0Cl4KOTMKXQo5MgpcCjkxClsKOTAKWgo4OQpZCjg4ClgKODcKVwo4NgpWCjg1ClUKODQKVAo4MwpTCjgyClIKODEKUQo4MApQCjc5Ck8KNzgKTgo3NwpNCjc2CkwKNzUKSwo3NApKCjczCkkKNzIKSAo3MQpHCjcwCkYKNjkKRQo2OApECjY3CkMKNjYKQgo2NQpBCjY0CkAKNjMKPwo2Mgo-CjYxCj0KNjAKPAo1OQo7CjU4CjoKNTcKOQo1Ngo4CjU1CjcKNTQKNgozMgogCjMzCiEKMzQKIgozNQojCjM2CiQKMzcKJQozOAomCjM5CicKNDAKKAo0MQopCjQyCioKNDMKKwo0NAosCjQ1Ci0KNDYKLgo0NwovCjQ4CjAKNDkKMQo1MAoyCjUxCjMKNTIKNAo1Mwo1CsK2Cg&input=SGVsbG8sIFdvcmxkIQ) If you check out the [Retina tutorial for unary arithmetic](https://github.com/m-ender/retina/wiki/Tutorial:-Unary-arithmetic), you'll recognize several different pieces of my code as coming from there. *Thanks to Martin for golfing off hundred of bytes* [Answer] # Java, 205 - 15% = 174.2 ``` interface F{static void main(String[]a){for(int i=0,c,s;i<a[0].length();++i){c=a[0].charAt(i);s=Integer.numberOfLeadingZeros(c);c=~(Integer.reverse(c)>>s)&-1>>>s;if(c==10|c>31)System.out.print((char)c);}}} ``` Ungolfed: ``` interface F { static void main(String[] a) { for (int i = 0, c, s; i < a[0].length(); ++i) { c = a[0].charAt(i); s = Integer.numberOfLeadingZeros(c); c = ~(Integer.reverse(c) >> s) & -1 >>> s; if (c == 10 | c > 31) System.out.print((char)c); } } } ``` I think this solution is a bit interesting in its use of the `Integer` methods `Integer.reverse` and `Integer.numberOfLeadingZeros` which do what they sound like, and the shift of `-1 >>> s` where `s` is the number of leading zeroes, to get the mask to mask off high bits that we don't want. I just regret that the name of the latter method is so damn verbose, but that's what I get for golfing in Java. Output: ``` v,dd2> Xdl ``` [Answer] # Japt, 25 bytes Want to create a golfy JavaScript program, but the shortest method involves lots of long function names? That's what Japt was made for. :) ``` UmX=>Xc s2 w mY=>Y^1 n2 d ``` Try it in the [online interpreter](https://codegolf.stackexchange.com/a/62685/42545)! ### How it works ``` // Implicit: U = first item in input UmX=> // for each character X in U: Xc s2 w // take the char-code of X, convert to binary, and reverse mY=> // for each character Y in this: Y^1 // take Y XOR 1 (converts 1 to 0 and 0 to 1) n2 d // convert the result back to decimal, then to a character // Implicit: output last expression ``` --- Using the current version of Japt (as of v1.4.4), the byte count can be cut to 14: ``` ¬Æc ¬§w m^1 n2 d ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=rmMgpHcgbV4xIG4yIGQ=&input=IkhlbGxvLCBXb3JsZCEi) [Answer] # PHP, 80 bytes ``` while(a&$c=$argn[$i++])echo chr(bindec(strtr(strrev(decbin(ord($c))),10,"01"))); ``` takes input from STDIN; run with `-R`. **bonus version, ~~97~~ 110 bytes -> 93.5 score** ``` while(a&$c=$argn[$i++])ctype_print($c=chr(bindec(strtr(strrev(decbin(ord($c))),10,"01"))))||" "==$c?print$c:0; ``` prints ASCII 10 and 32 to 126 (newline and printables) --- breakdown, TiO and if possible some golfing will follow; I¬¥m tired right now. [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` c_¬§√î¬Æ^1√É√ç ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Y1%2bk1K5eMcPN&input=IkhlbGxvLCBXb3JsZCEi) [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` m(c·∏ãm¬¨‚Üî·∏ãc ``` [Try it online!](https://tio.run/##yygtzv7/P1cj@eGO7txDax61TQEykv///@@RmpOTr6MQnl@Uk6IIAA "Husk ‚Äì Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` OBU¬¨·∏Ñ·ªå ``` [Try it online!](https://tio.run/##y0rNyan8/9/fKfTQmoc7Wh7u7vn//78HUDBfRyE8vygnRREA "Jelly ‚Äì Try It Online") Explanation: ``` OBU¬¨·∏Ñ·ªå Main link: z O Convert z to a list of character codes. B Convert the codes to bit lists. U Reverse the bits (not the lists). ¬¨ Invert the bits. ·∏Ñ Convert back to decimal. ·ªå Convert back to string. ``` [Answer] # [Factor](https://factorcode.org/), ~~50~~ ~~46~~ 41 bytes ``` [ [ >bin reverse 97 v-n vneg bin> ] map ] ``` [Try it online!](https://tio.run/##JcyxCsIwFIXhvU9x7KxdRYWu6uIi4lA6xHrUYnoTb2LAp48R14@f/2aG6DSfjvvDdo3JxEfjjQYqAl9vysDw18RfGPCkCi28MsaP11EiNlVV72itm@Ps1F5nde7Qob2MAmVi2WG1RFoIkvCO4i36svXo82CsRZO/ "Factor ‚Äì Try It Online") *-4 bytes thanks to @Bubbler!* *-5 bytes thanks to @Bubbler!* Even though removing control characters is just `[ control? ] reject` it's not worth the 15% discount. * `[ ... ] map` Map over the code points in the input string. * `>bin` Convert a code point to a binary string. * `reverse` Reverse it. * `97 v-n vneg` Invert the string (1s become 0s and vice-versa). * `bin>` Convert from a binary string to decimal. [Answer] # Haskell, 167 bytes ``` import Data.Char import Numeric r '0'='1' r '1'='0' s=map (chr.fst.head.(readInt 2 (`elem` "01") digitToInt).(map r).reverse.flip (showIntAtBase 2 intToDigit . ord)"") ``` Unfortunately Haskell gets quite verbose when needing to read/print in another base‚Ķ [Answer] # Perl 6,  66 bytes Going all-out by removing the non-printing control characters gets me to (83+1)-15% = **71.4** ``` perl6 -ne 'print grep /<-:C+[\n]>/,.ords¬ª.base(2)¬ª.flip.map({chr :2([~] $_.comb.map(+!+*))})' ``` If I remove the code that strips out the control characters I save quite a bit 65+1 = **66** ``` perl6 -ne 'print .ords¬ª.base(2)¬ª.flip.map({chr :2([~] $_.comb.map(+!+*))})' ``` ( I used `¬ª` instead of `>>` for clarity ) [Answer] ## Racket 250 15% bonus = 212 bytes ``` (Œª(s)(list->string(map integer->char(filter(Œª(x)(or(> x 31)(= x 10)))(for/list((i(string->list s)))(string->number(string-append "#b"(list->string(map(Œª(i)(if(equal? #\0 i)#\1 #\0))(reverse(string->list(number->string(char->integer i)2)))))))))))) ``` Ungolfed: ``` (define (f s) (list->string (map integer->char (filter (Œª(x)(or(> x 31)(= x 10))) (for/list ((i (string->list s))) (string->number (string-append "#b" (list->string (map (Œª(i)(if(equal? #\0 i) #\1 #\0)) (reverse (string->list (number->string (char->integer i) 2) ))))))))))) ``` Testing: ``` (f "Hello, World!") ``` Output: ``` "v,dd2>\nXdl" ``` [Answer] # [Zsh](https://www.zsh.org/), 114 bytes \$\times\$ 0.85 \$=\$ 96.9 ``` for c (${(s::)1})b=(${(s::)$(([##2]#c))})&&b=${(j::)${(Oa)b}}&&s+=${(#)$((2#$b^(2**$#b-1)))} <<<${s//[^[:print:]]} ``` [Try it online!](https://tio.run/##NYvBCgIhFEX3foWhOO9NxDAuZWbfrg8QB3JKKiRDgyDx221ctDz33PNNt@oAoboQ6UqBZ0hK4VjQzn/gAJoxadiKWFAIO2/i0USG0xltKUKkfRtZ@0rG7QKy7zmzhxG3hkzTxHMaBr1o9Yr351sZUyoS4mh3vHof6CdEf9l19Qc "Zsh ‚Äì Try It Online") Without filtering for printables, this would scores **98 bytes**. ``` for char (${(s::)1}){ bits=(${(s::)$(([##2]#char))}) # convert to binary, split into characters bits=${(j::)${(Oa)b}} # reverse order of bits, join on empty string string+=${(#)$((2#$b^(2**$#b-1)))} # XOR with the 2**(len(bits) - 1), convert from codepoint } <<<${string//[^[:print:]]} # ${string//find/replace} ``` ]
[Question] [ # Background In the online graphing calculator [Desmos](https://www.desmos.com/calculator), there is a certain shape that appears in the lower left portion of the graph in many high detail graphs, which the Desmos community has dubbed "Bernard". You can see an example of it in this [graph](https://www.desmos.com/calculator/zwanvat5bj) and an isolated version of it in this [graph](https://www.desmos.com/calculator/redbernard). This shape is a consequence of the quadtree algorithm which Desmos utilizes to actually graph equations. I barely comprehend how it all works, but by descending into "deeper", or more detailed, quadrants, a more detailed Bernard can be created. (Don't take my word for how Bernard is formed, I barely understand how it works myself.) A screenshot of what Bernard looks like for posterity: [![](https://i.stack.imgur.com/bgYpp.png)](https://i.stack.imgur.com/bgYpp.png) In this challenge, you will write code that will print out a 2d array version of a depth-`n` Bernard. # How to create Bernard? Given a positive integer `n`, create a \$2^n\times2^n\$ grid of `1`'s and `0`'s. If \$n=1\$, then fill in the \$2\times2\$ grid like so: ``` 0 1 1 1 ``` That is your output. If \$n>1\$, then recursively fill in the grid in the following way: 1. Split the grid into 16 blocks of size \$2^{n-2}\times2^{n-2}\$. 2. Fill in the square regions according to the below diagram, and recurse on the region labelled `R`: ``` 0 0 1 1 0 0 0 R 1 1 1 1 1 1 1 1 ``` 3. If the region `R` is a \$1\times1\$ or a \$2\times2\$ region, then finish this step and output the resulting array. If the region `R` is a \$1\times1\$ region, then fill its only entry with `1`. If `R` is a \$2\times2\$ region, then fill it in the following way: ``` 0 1 1 1 ``` 4. If step 3 does not apply, then repeat steps 1-4 but on region `R`. # Worked example: `n=4` `n` is 4, so we will have a \$16\times16\$ grid. Following step 1, we fill the grid in the following way (with `R` denoting the region we will recurse on): ``` 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 R R R R 0 0 0 0 0 0 0 0 0 0 0 0 R R R R 0 0 0 0 0 0 0 0 0 0 0 0 R R R R 0 0 0 0 0 0 0 0 0 0 0 0 R R R R 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 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 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 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 1 1 1 1 ``` The region `R` is \$4\times4\$, so we recurse. The region `R` should now look like this, with the new `R` inside the grid denoting where to recurse: ``` 0 0 1 1 0 0 0 R 1 1 1 1 1 1 1 1 ``` Because `R` is now \$1\times1\$, we fill it in, so it becomes: ``` 0 0 1 1 0 0 0 1 1 1 1 1 1 1 1 1 ``` Placing this back into the original \$16\times16\$ grid, we obtain the desired output: ``` 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 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 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 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 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 1 1 1 1 1 1 1 1 ``` # Task Given a positive integer `n` as input, return a \$2^n\times2^n\$ 2d array which represents the depth-`n` Bernard. # Test Cases ``` n=1 0 1 1 1 n=2 0 0 1 1 0 0 0 1 1 1 1 1 1 1 1 1 n=3 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 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 1 1 1 n=4 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 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 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 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 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 1 1 1 1 1 1 1 1 ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 21 bytes ``` (|,/2\,'/4\10+)/[;+1] ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs9Ko0dE3itFR1zeJMTTQ1tSPttY2jOXiSlMwBGIjIDYGYhMAuhsIhw==) Same algorithm, but uses a bit of base trick to generate the zero- and one-matrices at appropriate places. ``` 10+ Map 0 to 10 and 1 to 11 4\ Base 4; 10 becomes (2 2) and 11 becomes (2 3) 2\ Base 2; 2 becomes (1 0) and 3 becomes (1 1) ``` --- # [K (ngn/k)](https://codeberg.org/ngn/k), 23 bytes ``` (,/(1|)\|,'/|^:\)/[;+1] ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs9LQ0dcwrNGMqdFR16+Js4rR1I+21jaM5eJKUzAEYiMgNgZiEwDeZgmn) A straightforward implementation. Uses the recurrence pattern: ``` f(n+1) = [ zeros, f(n) reversed ] [ ones, ones ] ``` ### How it works ``` (,/(1|)\|,'/|^:\)/[;+1] a function that takes n and ( )/ applies the recurrence n times on +1 the 1x1 matrix containing a single 1: ^:\ converge-scan using "test if each atom is null"; gives (mat; zeros) ,'/| reverse the order and horizontally join the two matrices | reverse vertically (1|)\ converge-scan using "max with 1"; gives (mat; ones) ,/ join vertically ``` [Answer] # [Desmos](https://desmos.com/calculator), ~~94~~ 92 bytes ``` f(n)=[0^{0^{4^{round(u+.5log_4dd)-u}-x}}forx=L,y=L] d=3y-2^n2 u=(0^{0^d}+n)/2 L=[2^n...1]-.5 ``` [Try it on Desmos!](https://www.desmos.com/calculator/jfwyqforaq) The matrix is returned in row-major order. *-2 bytes thanks to [@Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow) (`log_4(dd)/2` → `.5log_4dd`)* Golfing note: `0^{0^{E-x}` can be converted to `\{E>x,0\}`, but this requires moving `E=round(u+.5log_4d)-u` to its own line and doing `\for` instead of just `for`, so that is equal or +1 byte. ## How it Works The top third of matrix Bernard consists of right-aligned blocks of height \$2^{n-2},2^{n-4},\ldots,2^{\operatorname{mod}(n,2)}\$, and the bottom two-thirds consists of right-aligned blocks of height \$2^{n-1},2^{n-3},\ldots,2^{\operatorname{mod}(n+1,2)}\$. Each block has width equal to twice its height, and the top and bottom converge near `y=m=2^n/3`. The main difficulty is for each `y`, find the height of the current block. First we find the distance of `y` from the convergence y-value `m`. This is \$D=y-\frac{2^n}{3}\$ To figure out how many steps this is away, consider a situation where `n` is even, so the top third has step sizes \$1,4,16,\ldots\$. The partial sums of this geometric sequence are \$p(k)=\frac{4^k-1}{3}\$, e.g. \$p(2)=\frac{4^2-1}{3}= 5 = 1+4\$. Then \$(x,y)\$ on the top third is in step size \$4^k\$ iff \$p(k)\leq D<p(k+1)\$. This can be re-arranged to \$4^k\leq 3D+1\leq 4^{k+1}\$, so \$k=\operatorname{floor}(\log\_4(3D+1))\$ Ignoring golfing and the bottom side, this would give `{x < floor(log_4(3D+1)): 1, 0}` for the condition for filling in 1. The final golfed code uses \$d=3y-2^{n+1}\approx 3D+1\$ (the `y` values are flipped, so this is really proportional to the distance of `y` from `2^n*2/3`, explaining `2^{n+1}` instead of `2^n`). Hence we have `{x < floor(log_4(d)): 1, 0}` as the current condition. See what it looks like [on Desmos](https://www.desmos.com/calculator/dcf52qjsyc). There's a few problems left: nothing is filled in for the bottom two-thirds, and the heights of the top third is twice as big as it should be for odd `n`. Let's deal with the first problem first by just replacing `log_4(d)` with `log_4(abs(d))` to handle negative `d`, or equivalently `log_4(d^2)/2`, which golfs to `.5log_4dd`. Then our condition becomes `{x < floor(log_4(d)): 1, 0}`. See [on Desmos](https://www.desmos.com/calculator/anznvhmvyj). The issue now is that the heights of the top third are twice too big for odd `n`, and the heights of the bottom two-thirds are twice too big for even `n`. The solution comes down to handling off-by-half in the exponent of `4^{...}` by adding and subtracting `u=(0^{0^d}+n)/2` withing/outside the `round`. If `d` is positive (top third) and `n` is even, then `u` is an integer, so it doesn't affect the `round`. If `d` is negative (bottom two-thirds) and `n` is odd, then `u` is an integer, so it doesn't affect the `round`. Otherwise, `n` is a half-integer, so it causes `round` to behave like `1+floor`, fixing the sizing issues. [Answer] # [Python](https://www.python.org), 76 bytes ``` f=lambda n:(x:=1<<n>>1)and[x*[0]+j for j in f(n-1)[::-1]]+x*[x*[1,1]]or[[1]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3fdJscxJzk1ISFfKsNCqsbA1tbPLs7Aw1E_NSoiu0og1itbMU0vKLFLIUMvMU0jTydA01o62sdA1jY7WB0kBkqANk5xdFRwMpqJkWaUX5uQoFBUWZeSUKmbkF-UUlUB4XyKhMkFFFiXnpqRqmmlYQCY00jUxNTYh-mNsA) Straight-forward recursion. Take the previous upside down, add a block of zeros on the left and a block of ones below. Just seeing that @Bubbler used [the same recursion](https://codegolf.stackexchange.com/a/248821/107561) a few hours before me. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 2Ṛ;»Ṁ²ƊƊ¡’Bz0ZU ``` A full program that accepts a positive integer from STDIN and prints a list representation of the Bernard. **[Try it online!](https://tio.run/##AScA2P9qZWxsef//MuG5mjvCu@G5gMKyxorGisKh4oCZQnowWlX/w4dH/zQ "Jelly – Try It Online")** (The footer prints the result as a grid instead of in the raw list format.) ### How? Builds the Bernard in chunks consisting of the equal rows, starting with the row with the single `1`. At each step we reverse what we have so far and append the next chunk. Each new chunk has as many rows as we've built so far but with double the number of `1`s. Under the hood, each row is first calculated as one more than its binary value. This starts at `2` and squares for each new chunk. ``` 2Ṛ;»Ṁ²ƊƊ¡’Bz0ZU - Main Link: no arguments 2 - literal two ¡ - repeat STDIN times starting with X=2: Ɗ - last three links as a monad - f(X): Ṛ - reverse the current list (2 gives its decimal digits reversed = [2]) Ɗ - last three links as a monad - f(Z=that): Ṁ - maximum of Z » - vectorised maximum with Z -> an array of the same shape as Z, all populated with the maximum value in Z ² - square them ; - (reversed X) concatenate with (that) ’ - decrement all the values B - convert them to binary lists z0 - transpose with filler zero } Z - transpose } prepends zeros U - reverse each ``` [Answer] # [Factor](https://factorcode.org/), ~~90~~ ~~89~~ 83 bytes ``` [ 2^ 3 dupn iota -rot '[ _ 3 /i bitxor bit-length 2^ 1 <array> _ 0 pad-head ] map ] ``` [Try it online!](https://tio.run/##HY4xT8NADIX3/oq3dUppWlgAsSKWLlWnqkVO4iYnLndXn6OSIn57MJks@316/i5Ua5TpsP/YvT@jJ@2Q@TpwqDmj5cBC3t1JXQwZFxlnZFU5vbnMIBEaM5Kw6pjEBYWL@GIJ7PGyWPygxAZbPOIJv9MRm7MtzZCCYUooJCqWR3za9cHBWr@j/I/Cc2hNxfgSr/OXN6PWSNQUHVODk4kknKwzuz55LpQqzysEb1Ed@xRNj6nupj8 "Factor – Try It Online") Port of @alephalpha's [PARI/GP answer](https://codegolf.stackexchange.com/a/248823/97916). [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 52 bytes ``` n->matrix(l=2^n,,i,j,j+2^#binary(bitxor(i-1,l\3))>l) ``` For input \$n\$, the number of \$1\$s in the \$i\$-th row (\$1\$-index) is \$2^{\#\operatorname{binary}(\operatorname{bitxor}(i-1,\lfloor2^n/3\rfloor))}\$, where \$\#\operatorname{binary}\$ means the number of the binary digits. This is because the binary representation of \$\lfloor2^n/3\rfloor\$ is \$(1010\dots)\$. [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN03ydO1yE0uKMis0cmyN4vJ0dDJ1snSytI3ilJMy8xKLKjWSMksq8os0MnUNdXJijDU17XI0oXq10kDiCrYKhjoKJjoKBUWZeSUamToKSlZKmtYQboFGmkampiZUx4IFEBoA) [Answer] # [Python](https://www.python.org), ~~121~~ 104 bytes ``` lambda n:[[*map(int,f"{m:0{2**n}b}")]for m in g(n)] g=lambda n:[1][n:]or g(n-1)[::-1]+2**~-n*[2**2**n-1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RY3RCoIwGIWv8ymGN27LQQsCGfgkcxeTnA7a71C7CLEX6UaIeqfepplFV4dzDt85t6e_DE0L893kxeM8GJa9mpN25VEjEFJSpz22MKQmHp3YjXtKYSqnmCjTdsghC6jGQFRU53-KKwlChT5UjBMpBONqG9ArAyqDLish-v5ly5RdpjoNdYV5eiAi2vgu_GJqsCVpX_k8KSAhv_hjVn6eV30D) This is a much more interesting method, but is not well golfed because Python isn't great at converting binary numbers into a matrix (at least as far as I am aware). Works by taking a start list of `[1]`. For each integer `i` up to `n`, reverse the list and add to it `2**~-n*[2**2**n-1]`. This outputs the following pattern ``` [1, 3] [3, 1, 15, 15] [15, 15, 1, 3, 255, 255, 255, 255] [255, 255, 255, 255, 3, 1, 15, 15, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535] ``` Which is then converted into binary, with each item in the list forming a row in the matrix. -17 bytes thanks to @pxeger --- # [Python](https://www.python.org), ~~119~~ 117 bytes ``` f=lambda n:[[1]][n:]or-(-(p:=2**n)//4)*[(q:=p//2)*[0]+q*[1]]+[l+r for l,r in zip(p//4*[p//4*3*[0]],f(n-2))]+q*[[1]*p] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY9BDoIwEEXXeorumJY2FcSENOlJahcYqTbBoVRY6FXcsNE7eRsBdTOZP3kvP_N4hVt_bnEcn0PvRPkenG6qy-FYEVTGZNYaVLaNAgQEpXPGkEpZUGagUzpImU_rxqYdm9nUNGkkro2k4ZF4JHcfYIIKZpa5nVnLHaDIKV2sSWPB_srLWfWzGCs81ZDxHVXrVYgee2AOPOXXOuhkjwn9n5fw9f9PfAA) Follows the algorithm as outlined in the question -2 bytes thanks to pxeger [Answer] # JavaScript (ES6), 95 bytes A rather straightforward recursive construction. ``` n=>[...Array(1<<n)].map((_,y,a)=>a.map(g=(k=n,x,_,Y=y)=>k--?Y>>k|x>>k&g(k,x%=m=1<<k,_,~Y%m):1)) ``` [Try it online!](https://tio.run/##XU7LbsIwELzzFXsoZFexLeXQS5M14jMiisCiJAKTNTIIJQL668GKeuplZueh1Zzc3V338Xi5aQk/h7HhUdiujTGrGN2ARVUJbUznLohbNShHbN0kW0bPonq1VTUPyfZaL2tr/bNPsGjRq37OHacPPnV@63lHXwXR2ISIAgxFCQIVw2fiPCd4zAD2Qa7hfDDn0OJOaxD@eMgLtN5R@S9uUGgaEoEtRHMKR8EMMqK/81syghwmLmev8Q0 "JavaScript (Node.js) – Try It Online") ### Commented ``` n => // n = input [...Array(1 << n)] // build an array of 2 ** n entries .map((_, y, a) => // for each item at position y in this array a[]: a.map( // iterate over a[] again using ... g = ( // ... the recursive callback function g taking: k = n, // k = dimension, initialized to n x, // x = horizontal position _, // (ignored reference to the array) Y = y // Y = vertical position ) => // k-- ? // decrement k; if it was not 0: Y >> k | // insert a '1' if we are in the lower part (*) x >> k & // or we are in the right part and the result g( // of this recursive call is also 1: k, // pass the new value of k x %= // update x to x modulo m, m = 1 << k, // where m = 2 ** k _, // (useless reference to the array) ~Y % m // update Y to (-Y - 1) modulo m ) // end of recursive call : // else: 1 // insert a '1' and stop the recursion ) // end of inner map() ) // end of outer map() ``` *(\*) The sign of Y is inverted at each iteration, so the 'lower' part is actually the upper part when Y is negative.* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÎF¼RNoF¾ª]oÅ10ζRø ``` [Try it online](https://tio.run/##ASUA2v9vc2FiaWX//8OORsK8Uk5vRsK@wqpdb8OFMTDOtlLDuP/Cu/80) or [verify all test cases](https://tio.run/##ATkAxv9vc2FiaWX/NUVOIm49w78iLCL/ME5GwrxSTm9Gwr7Cql1vw4UxMM62UsO4/yIuVsK7LMK2Py7Ctf8). (The footer is to pretty-print the matrix.) **Explanation:** Step 1: Create alternating lists of \$2^x\$ amount of 0-based values depending on the input: ``` Î # Push 0 and the input F # Loop `N` in the range [0, input): ¼ # Increase `¾` by 1 (it's 0 by default) R # Reverse the current list (or 0 in the first iteration) No # Push 2 to the power `N` F # Inner loop that many times: ¾ª # Append `¾` to the list # (`ª` will convert the 0 to [0] in the very first iteration) ] # Close both loops ``` [See just this step online for all test cases.](https://tio.run/##yy9OTMpM/W/q6mevpPCobZKCkr3SfwM/t0N7gvzy3Q7tO7Qq9r@SXpiO3qGt/wE) Step 2: Calculating \$2^v\$ for each of these values determines the amount of trailing `1`s per row: ``` o # Map each value to 2 to the power that value Å1 # Then convert each inner value to a list of that many 1s ``` [See the first two steps online for all test cases.](https://tio.run/##ATMAzP9vc2FiaWX/NUVOIm49w78iLCL/ME5GwrxSTm9Gwr7Cql1vw4Ux/yIuVsK7LMK2Py7Ctf8) Step 3: Add leading `0`s to each row, and output the resulting matrix: ``` ζ # Zip/transpose this list of rows; swapping rows/columns, 0 # using a 0 as filler-character for unequal length rows R # Reverse the list of lists ø # Zip/transpose the matrix back # (after which it is output implicitly as result) ``` [Answer] # [Uiua](https://www.uiua.org/), 19 bytes ``` ⍥(⊂⊃∘=.⍉⊂⊃-⍉.⇌):¤¤1 ``` [Try it online!](https://uiua.org/pad?src=0_3_1__QiDihpAg4o2lKOKKguKKg-KImD0u4o2J4oqC4oqDLeKNiS7ih4wpOsKkwqQxCkIzCkI4Cg==) ## How it works ``` ⍥(⊂⊃∘=.⍉⊂⊃-⍉.⇌):¤¤1   ¤¤1 1x1 matrix containing a single 1   : flip the values on the stack, bringing n to the top of the stack ⍥ repeat the following n times:   ⇌ reverse the matrix's rows, flipping it vertically   . duplicate ⊃-⍉ apply subtraction from the duplicate and transpose in parallel   subtraction from the same matrix results in a 0 matrix ⊂ join the resulted matrices vertically   ⍉ transpose back, reverting the previous transpose and making the join horizontal . duplicate   ⊃∘= apply identity (keep, do nothing) and equality against the duplicate in parallel equality against the same matrix results in a 1 matrix   ⊂ join ``` [Answer] # [Python 3](https://docs.python.org/3/), 138 bytes ``` import re def f(n):r=[int(bin(i)[2:])for i in range(2**n)];return[[1-bool(re.match('1(13)*(12|0)',str(x+y+y+10**n)))for x in r]for y in r] ``` [Try it online!](https://tio.run/##XU7LDoIwELzzFb2xi0goxEuNX9JwAG2liWybtSaQ@O/IQy9mDjPJZB5hir2nep7dEDxHwSa5GSssECq@aEcROkfgUFeqQetZOOFIcEt3A1WWETZnNvHFpLU8dt4/gE0xtPHaQypB1piBrN4lpvkzMoyHaYEs1yBudeNW16xy2uXvSgi8zCd/mzIXJ1SJ@NrFTmCXizh/AA "Python 3 – Try It Online") [Answer] # [Haskell](https://www.haskell.org), 111 bytes ``` data T a=C a|Q(T a)(T a)(T a)(T a) f 0=C 1 f 1=Q(C 0)(C 1)(C 1)$C 1 f n=Q(C 0)(Q(C 1)(C 1)(C 0)$f$n-2)(C 1)$C 1 ``` The matrix is represented as a [quadtree](https://en.wikipedia.org/wiki/Quadtree). (I don't know if this output format is accepted). [Answer] # [Python 3](https://docs.python.org/3/) with [numpy](https://numpy.org/), ~~77~~ 76 bytes ``` from numpy import* f=lambda n:n<eye(1)or kron(c_[:4:2,1:3],f(n-1)[::-1]+1)>1 ``` [Try it online!](https://tio.run/##DcoxDsIwDADAnVd4jKEdTGGxKB@pKhQggQhiR1YY8vrQm6@0@laZeo@mGeSXS4OUi1rd7@L89fn@9CAsl9CCI1SDj6m4x23hEx8H4mkdopORcGEeaT0QXqnH7QkkAfPyCu6MDMWSVLdVxP4H "Python 3 – Try It Online") * `n<eye(1)` produces `[[True]]` for n=0, the base case, and `[[False]]` for positive n, causing the expression after it to be used. * `c_[:4:2,1:3]` produces \$ \begin{pmatrix}0&1\\2&2\end{pmatrix}\$, and is 1 byte shorter than the direct way of writing that matrix. * The grid for n-1 is recursively obtained and flipped vertically, and then 1 is added, making it consist of 1s and 2s. `kron` then produces a copy of it in the top-right quadrant (>1 where the pre–+1 version had a 1), a doubled copy of it in each bottom quadrant (always >1), and zero in the top-left quadrant (never >1). [Answer] # BQN, 19 bytes ``` {(∾⟜×⟜⋆0¨∾˘⌽)⍟𝕩≍≍1} ``` [Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyjiiL7in5zDl+KfnOKLhjDCqOKIvsuY4oy9KeKNn/CdlaniiY3iiY0xfQoK4oCiU2hvd+KImEbCqDEr4oaVNApA) *-1 thanks to @att* ## Explanation Input is *x*. * `(...)⍟𝕩≍≍1` execute *x* times on matrix `[[1]]`... * `0¨⊸∾˘` row-wise prepend matrix of 0s * `1¨⊸∾` column-wise prepend matrix of 1s * `⌽` column-wise reverse Example of how one iteration works: ``` 0 1 # start 1 1 0 0 0 1 # 0¨⊸∾˘ 0 0 1 1 1 1 1 1 # 1¨⊸∾ 1 1 1 1 0 0 0 1 0 0 1 1 0 0 1 1 # ⌽ 0 0 0 1 1 1 1 1 1 1 1 1 ``` ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` ↑1FENX²ι«‖↓UO⊗ιι1M⊕ι↑»‖UB0 ``` [Try it online!](https://tio.run/##NY2xDoIwFEVn@IqG6TXBRI2TbobFASUaP6CUBzaWPtK0MBi/vb5Btntzc87VL@U1KZtS440LcHxOpSh2hTzlPXkBtZrg4qYYrnFs0YMsRUMLh30pjJRSfPLsjr1FzWxFi2Mwu7WW3AAVxdZiB4Yhs1qzmmZkpfY4ogv/mW95@@arissDw1np9@Apug6KLcMpHdJmtj8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Works by drawing the horizontal mirror image of Bernard, using the property that each Bernard is the vertical mirror image of the previous Bernard extended to the left with `0`s and then extended down with `1`s. ``` ↑1 ``` Output the lone `1` on its own row, leaving the cursor above the row. ``` FENX²ι« ``` Loop `n` times, adding `2ⁱ` rows each time, thus resulting in a total of `2ⁿ` rows. ``` ‖↓ ``` Reflect vertically, leaving the cursor below Bernard. ``` UO⊗ιι1 ``` Draw the next size rectangle of `1`s. ``` M⊕ι↑ ``` Move back to the top of the Bernard. ``` »‖ ``` Reflect horizontally to complete the Bernard. ``` UB0 ``` Fill the background with `0`s. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `Ṁ`, 20 bytes ``` 0?(ṘnEn›ẋJ)E1vẋ0ÞṪṘ∩ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuYAiLCIiLCIwPyjhuZhuRW7igLrhuotKKUUxduG6izDDnuG5quG5mOKIqSIsIuKBiyIsIjQiXQ==) [Answer] # [brev](https://idiomdrottning.org/brev), 190 bytes ``` (define(b n)(define(e d v)(make-list(expt 2(- n d))v)) `(,@(e 2 `(,@(e 1 0),@(e 1 1))),@((over(append(e 1 0)(e 2 0)x))(b(- n 2))),@(e 1(e 0 1))))(define(b 1)'((0 1)(1 1)))(define(b 0)'((1))) ``` 236 with whitespace added back in: ``` (define (b n) (define (e d v) (make-list (expt 2 (- n d)) v)) `(,@(e 2 `(,@(e 1 0) ,@(e 1 1))) ,@((over (append (e 1 0) (e 2 0) x)) (b (- n 2))) ,@(e 1 (e 0 1)))) (define (b 1) '((0 1) (1 1))) (define (b 0) '((1))) ``` Bonus! I like coming up with my own solution but here's my implementation of Bubbler's idea, at 135 bytes (displayed here with 15 unnecessary bytes of whitespace for readability) ``` (define (u n) ((fn `(,@((over `(,@((over 0) x) ,@x)) (reverse x)) ,@((over `(,@((over 1) x) ,@((over 1) x))) x))) (u (- n 1)))) (define (u 0) '((1))) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 80 bytes ``` f=n=>n?f(n-1).reduce((v,e)=>[p=[...e.map(_=>0),...e],...v,p.map(_=>1)],[]):[[1]] ``` [Try it online!](https://tio.run/##XU5LDoIwEN1zilmY0Am0kYUbcfAgtRECxUBwSoqyIZwdgejG5OX9ZjGvLcZiKH3TvyS7yi41rWDK@FoLlgkqb6t3aYUYY4uU6Z60UsqqZ9GLO2VHjLdoNh7j/lcnaGJt8Kx1YsxSOy8YCJIUGC4Ep1WjCGEKAErHg@us6txD5FIC02HiGaTMMf07r4Nwf@CBMvCqdQ2LEELEr71xiBDBrmkwLx8 "JavaScript (Node.js) – Try It Online") # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 75 bytes ``` f=lambda n,g=[]:n and f(n-1,[0]*(p:=2**~-n)+g)[::-1]+p*[g+[1,1]*p]or[g+[1]] ``` [Try it online!](https://tio.run/##LcnBCgIhEIDh@z7FHNXVyCIIwSeRORibJrTjMHjp0qsbVKefj59f49HpfGWZs8Rn3m9bBrI1JgwEmTYoipy36YhGcYgnY96O9Fp1CsF5XNmkuiZvPRrGLl8gzrZzlwHM0mgspQs0aASSqd6Vt3DRYYH/Pvyiimpazw8 "Python 3.8 (pre-release) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 72 bytes ``` f=lambda n,z=0:[l:='0'*z+2**n*'1'][n:]or f(m:=n-1,z+2**m)[::-1]+2**m*[l] ``` [Try it online!](https://tio.run/##HYpBCsMgEAC/4m11ayC2FMoGX2I9WBJbQTciuTSft8XbMDP1e3x2vj1q6z3aHMprDYL1aWdymSzMgOflisgIBrxj8nsTURayPBk9UlGOaDJ@MLrse/w/SSQWLfB7k3dForbEh0x649UCPRnUgiVUObyOMiml@w8 "Python 3.8 (pre-release) – Try It Online") ]
[Question] [ **This challenge was posted as part of the [April 2018 LotM challenge](https://codegolf.meta.stackexchange.com/q/16116/31716), as well as for Brain-flak's 2nd birthday** --- I was thinking about what the most efficient way to encode brain-flak programs would be. The obvious thing to do, since there are only 8 valid characters, is to map each character to a 3-bit sequence. This is certainly very effective, but it's still very redundant. There are some features of brain-flak code that we could take advantage of to shorten the encoding. * The nilads, which are all represented by 2 matched brackets, really act as a single unit of information rather than 2. If we replaced each bracket with a single byte character, this would make the encodings much smaller without losing any data. * This one is less obvious, but the *closing bytes* of the monads are redundant too. Think you could guess what the `'?'` characters represent in the following snippet? ``` {(({}?<>?<>? ``` If we assume the input is valid brain-flak code, then there is only one option for each of those question marks. This means that we can unambiguously use a *close monad* character to represent every closing bracket. This has the added benefit of keeping the character set small, which would greatly help if we wanted to use a huffman encoding. Since the *close monad* character will most likely be the most common character by a wide margin, it could be represent by a single bit, which is hugely efficient. These two tricks will let us compress brain-flak code via the following algorithm: 1. Replace every closing bracket of a monad with `|`. Or in other words, replace every closing bracket that **is not** preceded by it's opening match with a bar. So... ``` (({})<(()()())>{}) ``` would become ``` (({}|<(()()()||{}| ``` 2. Replace every nilad with it's closing bracket. Therefore, matched brackets with nothing in them use the following mapping: ``` () --> ) {} --> } [] --> ] <> --> > ``` Now our last example becomes: ``` ((}|<()))||}| ``` 3. Remove trailing `|` characters. Because we know that the total number of bars should equal the total number of `({[<` characters, if there are bars at the end missing, we can infer them. So an example like: ``` ({({})({}[()])}) ``` would become ``` ({(}|(}[) ``` Your challenge for today is to reverse this process. Given a string of compressed brain-flak containing only the characters `(){}[]<>|`, expand it into the original brain-flak code. You can assume that the input will always expand to valid brain-flak. This means that no prefix of the input will ever contain more `|` than `({[<` characters. The input will not contain trailing `|` characters. These must be inferred from context. As usual, you can submit either a full program or a function, and input/output formats are permissive. And since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), your code will be scored by the length of the source code in bytes, the smaller the score the better. ### Test cases Here are some test cases. If you would like more, you can generate your own test cases with [this python script](https://tio.run/##bYzBCsIwEETv@YqQS3dRCupNbH@k6aFgioE0DUlEpJtvr0nVkw4sO7ydHfeMt9me1lVPbvaRe8XYEOcp8Cb7etT2OhgDQoJEWhLJTvZ0aUkCFUCFUEHUij3X1t0jIDKrHrlACDbOnpe@fNp2ODOepUdulIVCkDcNP75xUXndNVu4O/QbVibnvy0CU9@Kn7wg8ckG9beMMee1jZBR7UP02kFFFeK6wgJLwjwdYI8p@xc) and [the Brain-Flak Wiki](https://github.com/DJMcMayhem/Brain-Flak/wiki), which is where the majority of these test cases come from. ``` #Compressed code #Original code ()))) (()()()()) ([([}()||||(>||{(})|>|}{((<}|||>}|}>} ([([{}(())])](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{} ({(}|(}[)|||} ({({})({}[()])}{}) (((()))||(](((}}||(}([(((}))||||(]((}}|}|}}|||]||]|[))||(}))|}(}|(}]]|} ((((()()()))([]((({}{}))({}([((({}()())))]([](({}{}){}){}{})))[]))[])[()()])({}()()){}({})({}[][]){} ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~952 916~~ 818 bytes ``` {(({})[(((()()()()()){}){}){}])((){[()](<{}>)}{}){{}(({})()<>)(<>)}{}(<>)<>(({})[(((()()()){}){}()){({}[()])}{}])((){[()](<{}>)}{})({}<>{})<>(({})[((((()()()()()){}){})){}{}])((){[()](<{}>)}{})({}<>{})<>(({})[(((((()()()()()){}){}){}())){}{}])((){[()](<{}>)}{})({}<>{}){{}(<(<>({})()()<>)>)}{}<>(({})[(((()()()()()){}){}){}()])((){[()](<{}>)}{}){{}(({})[()])(<>)<>(<({}<{({}<>)<>}{}>)>)<>{({}<>)<>}{}(<>)}{}(<>)<>(({})[(((((()()()()()){})){}{}())){}{}])((){[()](<{}>)}{})({}<>{})<>(({})[((((()()()()()){}){})()){}{}])((){[()](<{}>)}{})({}<>{})<>(({})[(((((()()()()()){}){}){}())()){}{}])((){[()](<{}>)}{})({}<>{}){{}<>(<(({})[()()])(<>)<>(<({}<{({}<>)<>}{}>)>)<>{({}<>)<>}{}>)}{}<>(({})[(((((()()()()()){}){})()){}{}){}])((){[()](<{}>)}{}){{}{}(<(<>{}<>)>)}{}(<>)<>(<({}<{({}<>)<>}{}>)>)<>{({}<>)<>}{}<>}{}{({}<>)<>}<> ``` Saved 360 bytes by calculating opposing brackets relatively rather than from scratch (e.g. `')'` = `'(' + 1` instead of `(((5 * 2) * 2) * 2) + 1`) Saved 34 bytes with some direct replacements from DJMcMayhem Saved 10 bytes by overlapping the `>]}` handling code Saved 118 bytes by deduplicating rolls Saved 40 bytes by taking advantage of the empty stack to simplify the first roll Saved 48 bytes by marking EOF with -1, enabling more concise roll code Saved 36 bytes by using the [stock equals logic](https://github.com/DJMcMayhem/Brain-Flak/wiki/Comparisons) instead of my own Saved 98 bytes thanks to Jo King finding a more efficient way to build the output [Try it online!](https://tio.run/##rZLdDoMgDIVfp73wDRpexHjhlixZtuzC29JnZ21lGQFxmsw/4Ainfgcvy3x/Dbfn/EiJAVhwBD3wc6Iqfk2oKo@AExBLQDGVxZcAUkAgF62hUDmtFtaqbh42c8tRX1PQtnRoPkbvE6s3WLT708PYSGFWPif0CQ1b5byXk5PngMgKsVfTodhU65RKJ9GqrpMcIdrNFP6SKhzK1elzHucSaXagC9L/Y/O@ummZ74Hy/vgKFFICBokgI8YYJQ3XNw "Brain-Flak – Try It Online") First time golfing in Brain-Flak, so there are probably some really big improvements, but it works. Lots of copy/paste to handle each bracket type, and big thanks to the [automatic integer generator](https://brain-flak.github.io/integer/) and the Roll snippet from [here](https://github.com/DJMcMayhem/Brain-Flak/wiki/Stack-Operations). Explanation [here](https://tio.run/##rVXBbpwwED3DV4zgUFtppH6Ai9RDpUZqo6o9Ig4O6zRWWEBeS21l/O10xrBZJ@xmQxMDwozNzPN7z3BjpG4vbxt5P44umVv@DYPwtev6NE0egl9ku2kUdL1qdfsLboys75XdpQljzvOSYeP7g2MknBXHqCsZr5hwvuAeo3O@q1to1R8L9Z00oHeQsQyrOedDPsZFwZkIbxwwwE/bGQUZzxAZjYoiiVoOVm17@Agf0gWsCQ/dMU6AKPNJeEt0JaHDV0WBc@KyU9GLi7jiggm81pEhVpU7wjx2ny@6rOnimscqJrNAIuYc0wTWC2Qdn1GVSb@g4FK6KnufFRl0BjJP9QIiURxx2rVu5OaMv0jHl5PKY4cFD0weYoJW7cLS8dFTHurEkciLOXw3CrfBJnj2jBFPyxTk@Q@Zqlc5ka33YvEGXmSrl@nPujFqk66k5HPWnGVfJ/wTxUv0r5j86yL/Eoalheum2536WJ6Uhp@hSdt3SM8we5mcyYgjQdAffy1/qL6RtYLf2t6BhB3twM0ezINxX0LCQfX8eq@SrK0yaRqVzD8jQ9HP45Dhyfb41PfNXzBqi3OJnyVPj6ZfbftG19pCb3RrxzGQx/kwsAp73mPHMyLVU3AKYxQPHBoqOsswncY989ipqsGPl/U/), TIO formats it more easily Bonus answer: # [Compressed Brain-Flak](https://codegolf.stackexchange.com/q/161056/71434) 583 bytes ``` {((}|[((()))))|}|}|}||(){[)|(<}|||}|{}((}|)>|(>||}(>|>((}|[((()))|}|})|{(}[)|||}||(){[)|(<}|||}|(}>}|>((}|[(((()))))|}|}||}}||(){[)|(<}|||}|(}>}|>((}|[((((()))))|}|}|})||}}||(){[)|(<}|||}|(}>}|{}(<(>(}|))>||||}>((}|[((()))))|}|}|})||(){[)|(<}|||}|{}((}|[)||(>|>(<(}<{(}>|>|}||||>{(}>|>|}(>||}(>|>((}|[((((()))))|}||}})||}}||(){[)|(<}|||}|(}>}|>((}|[(((()))))|}|}|)|}}||(){[)|(<}|||}|(}>}|>((}|[((((()))))|}|}|})|)|}}||(){[)|(<}|||}|(}>}|{}>(<((}|[))||(>|>(<(}<{(}>|>|}||||>{(}>|>|}|||}>((}|[((((()))))|}|}|)|}}|}||(){[)|(<}|||}|{}}(<(>}>||||}(>|>(<(}<{(}>|>|}||||>{(}>|>|}>|}{(}>|>|> ``` [Try it online!](https://tio.run/##lZFNDoJADIWv87rgBpNehMwCTUyMxoXbac8@9g0YMIAoTEjb6c/3yuk5XB/d5T7cai2AWw9A@Ji31yClF0MKM9ziTBI1aLjx0UURC8QKPApsXQtXn/MXU8yPcpdIspsfcAlKvgBkWDcUybYkIjc5CZ5CQpgkM9O3s1I8tw0g@UHFTCH/SpZ9zURuAg4VfKxkhbPxr9s@fdzl99ZxJlNrnZpHvxxWA3dwpjM4httAXlnmGel576CynM1rd34B "Brain-Flak – Try It Online") (Note that the above link does not run because TIO doesn't have a Compressed Brain-Flak interpreter. You can find a transpiler to Brain-Flak [here](https://codegolf.stackexchange.com/q/161056/71434)) I have checked that this is valid by transpiling to Brain-Flak using [this](https://tio.run/##rVNJbsMwDPwOecgPCH4kyCENUKBo0UOuIt/ucGgHVi15A@pNEk0OZ0b2x/P@9Xv5/Ll/D0MhKs5XioPfJ0ckrxtHtFyJbyTFlR3R4llCLMokGcQgukAaITBGHBjI7CHGa9EYa4SGTNwnqjtaYrqLAW0SYkZ9qTATGm0L5C2fUvlkkKBRyW6xdKRiUkdWHF30TSVHFG16Sv/iKh3yNdVPfpxzpNmBVSHrX@y0rwla@3ugfT7mgGj@M26gwjjM8zT0ZSOJaSyx@26sRhrLeGhVhAK2Qh4F1taSq8/5VRfzvdyaEq/mpx0KfkEQYe0o4r4kUE45QrDOYwpmZvpeNIpn2CDEB1TMLPisZF7XnF8gBOwq@GNJQ6ez1@mnj15uQ8c1TXW4PF4) tool, now efficient enough that timing out is unlikely. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~103~~ 98 bytes ``` [])}>] $&; T`])}>|`[({<; r`(.*)((;)|(?<-3>.))* $&$.1$*; (?<=(.)((;)|(?<-3>.))*); ;$1 T`;-{`_>-}`;. ``` [Try it online!](https://tio.run/##XYyxDsIwDET3fEeEzpUaqWJ0CT/BFkWEgYGFoWKL/e3lUjYuGc7n89uen9f7se@liuca4knDrQ1vraCvGraGNAmgYriu8zknkYm9mJY4aWB2QfrfiwaNC0k693bPszdN@w6hAgqKQ4xCNutwsWzegdWZZTfPHsDc4GX0OFG85UWlc/bg5NDKD1SPlG8g6vjlqI@9H6Razb8 "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 5 bytes with inspiration from @MartinEnder. Explanation: ``` [])}>] $&; T`])}>|`[({<; ``` Put a `;` after every close bracket and change them all to open brackets, and change the `|`s to `;`s too. ``` r`(.*)((;)|(?<-3>.))* $&$.1$*; ``` Count the number of unmatched open brackets and add that many `;`s. ``` (?<=(.)((;)|(?<-3>.))*); ;$1 ``` Copy each opening bracket to its matching `;`. ``` T`;-{`_>-}`;. ``` Flip the copied brackets and delete the `;`s. [Answer] # [TIS](https://github.com/Phlarx/tis.git), ~~670~~ 666 bytes -4 bytes for jumping forward to jump back Code: ``` @0 MOV UP RIGHT @1 MOV ANY ACC SUB 41 NOP NOP NOP NOP NOP NOP NOP NOP MOV ACC DOWN @2 NOP MOV 124 LEFT @3 MOV ANY DOWN @4 MOV UP ACC JGZ O MOV 40 LEFT JLZ ( MOV 41 LEFT JRO 3 O:SUB 21 MOV ACC DOWN JRO -8 (:MOV 41 RIGHT @5 MOV ANY DOWN @6 MOV ANY DOWN @7 MOV UP ACC JGZ O MOV 60 LEFT JLZ < MOV 62 LEFT JRO 3 O:SUB 31 MOV ACC DOWN JRO -8 <:MOV 62 RIGHT @8 MOV ANY DOWN @9 MOV ANY DOWN @10 S:MOV UP ACC JGZ O MOV 91 LEFT JLZ [ MOV 93 LEFT JRO 3 O:SUB 31 MOV ACC DOWN JRO -8 [:MOV 93 RIGHT @11 MOV ANY DOWN @12 MOV ANY DOWN @13 MOV UP ACC JEZ | MOV 123 LEFT JLZ { MOV 125 LEFT JRO 2 |:MOV DOWN LEFT JRO -7 {:MOV 125 RIGHT @14 MOV ANY DOWN @15 MOV UP DOWN @16 MOV UP LEFT ``` Layout: ``` 6 3 CCCCCCCCCCCCCCCCSC I0 ASCII - O0 ASCII - ``` [Try it online!](https://tio.run/##jZHfToMwFMbvz1OcS7wgoX9gW0MMWOdkmXQZTiPEBzDxTu/AZ6@Dtmx0xHjRpN/Xc873a/v98aV1FsGTesHjHg/F5vEZMjLovHzDXEqojnfICZRq/@caWqTEe/VaQkZHj1COu/XDaSwbx5oa7mL7lO2mRjUYPDL1212NgXGIdQ4KwxiU6JEomUYOh0sIhO2wd4m90MTTi3mI5AIiNQ6dgWDzEKmwHRZi6YWuPE0iqMQsx4qcORrjsP9zNMJ2uI8lfjD1DTZ5j3WNnf1FdgZprRVPSLohrB9zYS@gFa7YQXA/M3aZVidO93O0TtsmuHn/6W51@KkTZCBP17xalYQiwrySRYEhqHH7Cw "TIS – Try It Online") I doubt this is smallest, but I don't see a way to make it smaller. Unfortunately, all the `NOP`s seem necessary for timing, and I can't put the stack where `@14` currently is because of the read from `ANY` in `@11`. The structure of this solution is as follows: ``` Input | V 0 1:synchro 2:EOF 3 4:parens 5 6 7:angles 8 9 10:squares 11 12 13:curlies 14 15 stack 16 | V Output ``` Upon seeing an open brace, the open is sent along the left column to be output, and the close is sent along the right column to the stack. Upon seeing a close brace, the open and close are both sent along the left column to be output. Upon seeing a pipe, the stack is popped and sent to output. Upon EOF, `@1` will begin reading from `@2`, instead of the input stream from `@0`. `@2` produces an endless stream of pipes, so the stack will be drained. Once both the input and the stack are exhausted, the program halts. Warning: due to the limitations of TIS, the stack size is limited to 15. If anything is nested deeper than that, this implementation will produce an incorrect result. [Answer] # JavaScript (ES6), 107 bytes Takes input as an array of characters. Returns a string. ``` a=>a.map(c=>(n=(S='|()[]{}<>').indexOf(c))?n&1?(s=[S[n+1],...s],c):S[n-1]+c:s.shift(),s=[]).join``+s.join`` ``` [Try it online!](https://tio.run/##dU5BbsIwELz3GRzKrBIs5YqweUIPHK2ViEzSBlEb1ahCivftYRN6LOM9jHdnZ/bc/rY5/AzX2yamUzf1dmqta813e0WwDtHiYNcF5HmUnVuTGeKpu3/0CET7@N7ska0/@Fg1XBtjMteBtvrfNFyFbTb5a@hvoFpVTOachng8VvmPTCHFnC6duaRP9PBqsAIpVkz09t/QwwuoKOBKGSFUXJER2In2nBRx8nJZ5QXi5/XXIoUeoP6sTNQVoqlK6RnLS1ffHMhz@UU@z2UJYH7aTw8 "JavaScript (Node.js) – Try It Online") [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), ~~606 548 496 418 394~~ 390 bytes ``` {((({})))(<>)(((((((([(())()()()]){}){}){}())(()))(((())()())()){}{})){}[()])({<(({}<>{}[()]))>(){[()](<{}>)}{}<>}{}<><{}>){({}({})<>)(<>)}{}({}<>)(<>)(((((((([(())()()()]){}){}){}())(()))(((())()){}()){})){})({<(({}<>{}[()]))>[()]{()(<{}>)}{}<>}{}<>){(<({}(<()>)<>({})<{({}<>)<>}>)>)<>{({}<>)<>}}{}({}()<>){{}({}<>)((<>))}{}{}<>(<({}(<()>)<><{({}<>)<>}>)>)<>{({}<>)<>}{}<>}{}{({}{}<>)<>}<> ``` [Try it online!](https://tio.run/##lVFBbsNACPxLTnDIDxBS32H1kOaSqlIOuQJv386wdt1EUaraqzUM7Myw/ridPq@X0/lrjBCRKFUVc5X1WUQA9PuuqPYiJGyUrcoVxdNRC1sljGzma64uGozEolyLpd46DbRSm8LW1T77fycTmj6eeOAnwPDgAfpGBybq8NBOYjpAhze459Od0Gz8GKVTMjK7I3tBtOoT2CDzMcYBf6IyxXOfXRNTZhZfTaSsEUzNQnMthDhweceZuG90GopZjsUopEDt5M6iihh6Pf1vJWYUelDBHvpLJXmXNWnBj/GBOTvTtxgeFI3FVGgFI/h@7NkZciPs2A/j@PYN "Brain-Flak (BrainHack) – Try It Online") I started this by golfing [Kamil Drakari's answer](https://codegolf.stackexchange.com/a/161083/76162), but it got away from me to the point where I decided to post it as a separate answer. ### Explanation: ``` { #While input on stack ((({})))(<>) #Preserve copy of the character ((((( #Push the differences between start bracket characters ((([(())()()()]){}){}){}()) #Push -31, 1 (())) #Push -30, 1 (((())()())()){}{}) #Push -19, 1 ){}[()]) #Push -39 ({<(({}<>{}[()]))>(){[()](<{}>)}{}<>}{}<><{}>) #If the character is any of the start brackets {({}({})<>)(<>)}{} #Push the current character + TOS to the other stack ({}<>)(<>) ((((( #Push the differences between end bracket characters ((([(())()()()]){}){}){}()) #Push -31, 1 (())) #Push -30, 1 (((())()){}()){}) #Push -19, 1 ){}) #Push -40 ({<(({}<>{}[()]))>[()]{()(<{}>)}{}<>}{}<>) #If the character is any of the end brackets {(<({}(<()>)<>({})<{({}<>)<>}>)>)<>{({}<>)<>}}{} #Push the character + TOS to the output ({}()<>) #If the character is not a | {{}({}<>)((<>))}{} #Move current character to the other stack and push a zero {} #Pop the top value of the stack, either the | or a 0 <>(<({}(<()>)<><{({}<>)<>}>)>)<>{({}<>)<>}{}<> #And push top of other stack to the output }{} {({}{}<>)<>}<> #Reverse output and append the excess end brackets ``` And of course... # Compressed Brain-Flak, 285 bytes: ``` {(((}|||(>|(((((((([()|)))||}|}|})|()||((()|))|)|}}||}[)||({<((}>}[)||||){[)|(<}|||}>|}><}||{(}(}|>|(>||}(}>|(>|(((((((([()|)))||}|}|})|()||((()|)|})|}||}|({<((}>}[)||||[)|{)(<}|||}>|}>|{(<(}(<)||>(}|<{(}>|>|||||>{(}>|>||}(})>|{}(}>|((>|||}}>(<(}(<)||><{(}>|>|||||>{(}>|>|}>|}{(}}>|>|> ``` [Answer] ## Haskell, ~~127~~ 121 bytes ``` (""#) (u:t)#('|':b)=u:t#b s#(c:b)|elem c")>]}"=m c:c:s#b|q<-m c:s=c:q#b s#b=b++s m c="> < ] [)(} {"!!mod(fromEnum c-6)27 ``` [Try it online!](https://tio.run/##NYwxU4QwEIV7fsVeUtxmTiwsdIYh6ey0sowZh0Q4HYHjLlCR/evignebFO@9fft9VfGnbtul0fC@oBBSZTgVo5K4T/vCK81GesiixMA21W3dQRDKOBKaVRGKKH06l/lqog7FWXpue@0Ph5hxqIWBEhxYhQSz2O260yc2l1P33E@8zh/Vw9PSVd89aOiq4fUDcJjGt/Hy0sM9NApsBiBwRkpIVom7zSqeq7RoCVXiQZMS91QyiWbEkjgzlMjQtXqDcH6LeBjFt44V8QUSE1mqf6TbUn4rzK3fbvV1TxvOOYa5bPkNTVsd45KHYfgD "Haskell – Try It Online") Edit: -6 bytes by using @Laikoni's [function to find the matching bracket](https://codegolf.stackexchange.com/a/161087/34531). [Answer] # [Ruby](https://www.ruby-lang.org/), 104 bytes ``` a=[];$<.chars{|c|r="|[{(<>)}]";i=r.index(c);i<1||(i<5?a:$>)<<r[-i];$>.<<i<1?a.pop: c};$><<a.reverse.join ``` This is a full program that outputs to the console. `(i<5?a:$>)<<r[-i]` has got to be one of the coolest golfs I have ever done. [Try it online!](https://tio.run/##DcuxCsMgEIDhVykhgw496JAlnuZBxMFYodchCRcaWjyf3br@Hz9/1l9r0fpgRoT0inwWScJ2EF8UOl3DYMgy0PbMX5W0IXyIKMJpifPoNCL7O/XbAWK3JcKxH/Mt1Z4QI3C@Mp8Z3jttramivJYqon0Q9wc "Ruby – Try It Online") # [Ruby](https://www.ruby-lang.org/), 106 bytes ``` ->s{a=[];(s.chars.map{|c|r="|>)}][{(<";d=r[-i=r.index(c)];i<5||a<<d;i<1?a.pop: i<5?d+c:c}+a.reverse).join} ``` This is my first solution. An anonymous lambda function that takes and returns strings. [Try it online!](https://tio.run/##JYpBDoIwEEWvQli1ITRx4QZaPEgzi1pKrIlAWjEaZs5eB/0zi5f3f9qunzKZ0g55d8ZCL7LyN5eyerh1R4/J1DhIArsLXfejSbaNJqk4j@EtvIQ@6jOi03pkOl2cWpe1q1hexsZ3nhqnUniFlINU9yXOVNbtmavJ1oIjpUQUwETEQMIeeMi/ZsvHFcLx9jc/ehLEAIBUQ/kC "Ruby – Try It Online") [Answer] # Java 10, 424 bytes ``` s->{int i=0;for(var c:s.toCharArray()){if("(<[{".indexOf(c)>-1)i++;if(c=='|')i--;}for(;i-->0;)s+='|';s=s.replace(")","()").replace(">","<>").replace("]","[]").replace("}","{}");char[]c=s.toCharArray(),r=new char[124];r[40]=41;r[60]=62;r[91]=93;r['{']='}';var o="";for(;++i<c.length ;){if(c[i]=='|'){c[i]=o.charAt(0);o=o.substring(1);}if("(<[{".indexOf(c[i])>-1&")>]}".indexOf(i+1<c.length?c[i+1]:0)<0)o=r[c[i]]+o;}return c;} ``` It's kind of lengthy, but I couldn't figure out how to shorten it further. This is a nice challenge though. Try it online [here](https://tio.run/##dVRbT9swFH4Ov8Lyw@qjtFG7ISRwkglNe5z2wKPlh5C6YBaSzk47kOPf3h07aWEDcpGPv3P9TnL8UO2rxcP612G7u210Teqmspb8qHRL3Fmi216ZTVUr8v1pW7VrZQKa1PeVEZKoiLGb3uj2jtTd49Yoa9Ua@Fniz5Ipou2rHpd9p9fkEeNO9uhfmTsLMeApujoKBTnYRemwAKKLJd90hu0rQ@orm/XdN8x/bUz1zACc3jDKcuFoptHz6eeG1VAuVqDTlKOuLorZMAO9WHAfonCUyiUHmwac28JmRm0b5Mgo0DllQOEFKRHJy9eIRETI14hHxHkKfGxLXfxX4twUrfpDonb1@VxyI86XsjhfoXCBwsVnFC5Xsrj8gsLMzWQx8zMe6HYFpZE7T1Od11mj2rv@nvDIuhZajuRcFLsspLju2RJ4hzu7u7Wx1WwF3L/TJnQKnfpEoZT@Bdfp6pTqKxqlK3m1hHwJXWFEcJJpx71R/c60pOb@kCT4wZMtpurZ8QPOCWWO@YF5gV2NG@cBX8FAgscmv@8DeEV7BuP9oaVgwjMY8GLlMGAuGMrBO8Zyj1jpB196Ohk6j/Ewr2R5ib8MloHbvPQu2jtfhp3zuA/LRxmPfDC8f4eT@5gVC@nRj0mUPNbHPJaFIowEZETxDqXL8IhoHvQ@ZpVyyhljxcYAEyGcC4lDFTFiYBabKKM2KuMTjEDI@IpgI@FojMvEQ6Jy4h8G2Oh91at/Jnjk9mZe5@TNKXCCbNfset2146hP4OS4xkEPwzGip55l09Hy6kyJnb15tr16zLpdn8VCmvboss7U713VWHbKllJC06N2ZOQPfwE). Ungolfed version: ``` s -> { // lambda taking a String argument and returning a char[] int i = 0; // used for counting the number of '|'s that have been removed at the end of the input for(var c : s.toCharArray()) { // look at every character if("(<[{".indexOf(c) > -1) // if it's an open monad character i++; // we will need one more '|' if(c == '|') // if it's a close monad character i--; // we will need one '|' less } for(; i-- > 0; ) // add as many '|' s += '|'; // as necessary s = s.replace(")", "()").replace(">", "<>").replace("]", "[]").replace("}", "{}"); // replace compressed nilads with their uncompressed versions char[] c = s.toCharArray(), // from now on working on a char[] is more efficient since we will only be comparing and replacing r = new char[124]; // map open monad characters to their counterparts: r[40] = 41; // '(' to ')' r[60] = 62; // '<' to '>' r[91] = 93; // '[' to ']' r['{'] = '}'; // '{' to '}' var o = ""; // we use this String as a kind of stack to keep track of the last open monad character we saw for(; ++i < c.length ;) { // iterate over the length of the expanded code if(c[i] == '|') { // if the current character is a close monad character c[i] = o.charAt(0); // replace it with the top of the stack o = o.substring(1); // and pop the stack } if("(<[{".indexOf(c[i]) > -1 // if the current character is an open monad/nilad character & ")>]}".indexOf(i+1 < c.length ? c[i+1] : 0) < 0) // and it's not part of a nilad (we need to test for length here to avoid overshooting) o = r[c[i]]+o; // using the mapping we established, push the corresponding character onto the stack } return c; // return the uncompressed code } ``` [Answer] # Python 2, ~~188~~ ~~184~~ ~~180~~ ~~177~~ ~~174~~ 173 bytes ``` p,q='([{<',')]}>' d,s,a=dict(zip(p,q)),[],'' for c in input(): if c in d:a+=c;s+=[c] elif'|'==c:a+=d[s.pop()] else:a+=dict(zip(q,p))[c]+c for c in s[::-1]:a+=d[c] print a ``` Saved 4 bytes thanks to DJMcMayhem. [Try it online!](https://tio.run/##RY7BDoMgEETvfgW33Y20SXukwo8QDwY1JWkUhR5a4dsp1TTdzOntzsy6V7jP0zVnxxcJqLcGOFCbFFQ997yTvTUB39ZhOSDiuuUA1TivzDA7FblnQBIVs@NBetHV0tx8LbVpKzY87AgRpDRf3mt/drND2jd@2NmvYOGOqJhq88/3WojTpT28Jc@tdgqsy7m8ijohxTKoYtwwUVQxbYhNKkylmFSCDw "Python 2 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 122 bytes ``` D='()<>[]{} ' def f(x): a=s='' for c in x:i=D.find(c);a+=i<0and s[0]or D[i-(i&1):i+1];s=D[i+1][i&1:]+s[i<0:] return a+s ``` [Try it online!](https://tio.run/##XVHLbuMwDLzrK4QcViSSBi325kY@Bb32A1QejMbGCg3UwHKxKWR@e0rK7SJZPSBxOORQ4ulz@vOefl8ue@8Ad22gwtaZQz/YAc7YGNv57J0zdngf7auNyZ6b6PfbIaYDvOJjt/Zxd9@lg83hnoSzD/EO4q8HbOL6gR6zF0AuQaCG1jkIuyFjx376GJPt1vky9XnK1ttw3uZpjCfAbT4d4wRYRc8qulqtjP03AGVc24DLRHONBggMOMuAdp4LMM7tzAVgx4K1PHPL//ELSy4kJNi1iAXERvkWLjWscKtWYbH1uFGT/DNwUD2@xQuj7ACSVwJvawTVkxggubHUBSx1yBWXwqmiMrVk0hUqXf1cFYlu9WrK@hkIQbMWFdUKamJ9Uf0/qt7qrEtJGKjuoBzCH7Ic328gcZZrOWnMd7fcS3pJ7rotZIw2UPu7sV3Kf/tRe1n73VTe2OeP4yS9H0DRJfg0xjTBErUQNja4py4e3cY9vzkKC@r9kpPQXL4A "Python 3 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 152 bytes ``` fst.p m c="> < ] [)(} {"!!mod(fromEnum c-6)27 p(c:r)|elem c")]}>",(s,t)<-p r=(m c:c:s,t)|c/='|',(s,'|':t)<-p$r++"|",(u,v)<-p t=(c:s++m c:u,v) p e=("",e) ``` [Try it online!](https://tio.run/##JYxBa8MwDIXv@RWqKVQiyQY7bBDqXsbuPRYyH4Jnd2VJGmx3l9p/vZ6cSQI9vqen78H/mHHMVn5m68PTUk2gpTjAHhT0hAnuYrOZrl9o3XX6mG9st6/08lYtqDtH0YyGkSCVDqJB3wTatws4iUw73RUQ9bPcxV1xeXXrxdbVtYicuDW/ayJI/ufrusQKqxYwEoVoDOVpuMwg4TIH4wYdwGbkIqIYUbFKiUXCvsgC/zFTbraiKtOv58VPmFgoFdND23E4@9ye3o/HPw "Haskell – Try It Online") or [verify all test cases](https://tio.run/##NVFNa9wwEL37V0xEIDPY20IPDRjbl9KeUljopaDq4HXkZKm9ayxtKFj6693OzDb6sKQ3b94bya99@O2n6Tq2v65jiB@WYoahNR004MASZtjM3d18fsZxPc9fTxcO7z7Tp8diwaFeKfnJM2TI5c5UGKpIzW6BtUVG66EWIA0f24f0IFFeamXcr2VpEmdcqjfNiC3rhbKUNMGKBXyLxlSertGHGKAFWwAaJG6mMoh062SoAo1YtBkpccMupQ0zpS7lDbHJjHU55S5LJvO2zPnkyGHTEW3IZ6Kmy5vSt9zJact8loUd1IAlE2YrFiokecTTIksxl96JKOpMQ8e7zO6Y2ZW3dCvPKcpdCnMyrNIlntXEuZuFSuk1Ca2obeIjpioodeuLOI1qUIeQyDqdVjiO3sm8/C/bcVBu54pC3hiwrw7ED71c4o@4Pp3gHo4jjNBD28IB4qs/gdn3IRjwU/BgvvXHqQb/Z/FD9M9goCyZxx8Dh0uEl3O8YSxRFHN/PLH43C/fQe30v17/DuPUv4Tr7ueX/f4f "Haskell – Try It Online"). `p` implements a recursive parser, which might be over kill for the simple grammar. [Answer] # [Python 2](https://docs.python.org/2/), 244 bytes ``` s=input() B='([{<' C=')]}>' Z=zip(B,C) P=sum(map(s.count,B))-s.count('|') for i,j in Z:s=s.replace(j,i+j) s+=P*'|' b=[0] for i in s:[b.pop()for j,k in Z if j==b[-1]<k==i];b+=[i][:i in B];s=i=='|'and s.replace(i,C[B.find(b.pop())],1)or s print s ``` [Try it online!](https://tio.run/##RY6xcsMgEER7voKOuwhr4pSyL4X0A67NUEi2NUG2ESOkIrb4dgVkzwQo3uzu7eF@x5/efi2LJ2PdNAKykgSo516wigTq8C3YkR7GQSkrZAfy0x3utQOfn/rJjrJE3LwZxCyQtf3Ajey4sfxYePL5cHG3@nSBTpqsQ@YzOnzEJGtIfepXPIV9oZrc9Q4wSZ28rg3ctLwjatRmq/dXIqN3TUbKaFWsU6Xexa8TxcLanvn/NiMrVeatsWd416KWW4zVnrnB2JH7ZREQDyLOM@hIIUQIoBIm8SVHNd5ozTo9tcaTHyBE0HoO4g8 "Python 2 – Try It Online") It took way more than an hour or two to get this working... ]
[Question] [ ### Introduction A [**queue**](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) is an abstract data type where elements are **added to the front** (enqueue) and **removed from the back** (dequeue). This is also known as the [FIFO (First In First Out)](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics)) principle. It is best shown with an example: [![enter image description here](https://i.stack.imgur.com/ZX7ja.png)](https://i.stack.imgur.com/ZX7ja.png) --- ### Challenge Given a **non-empty** array that contains **positive integers** and **elements that indicate a *dequeue*** (removing an element), output the final list of the queue. Let's say that `X` denotes a dequeue in this example. Let's take a look at the following list: ``` [45, X, X, 37, 20, X, 97, X, 85] ``` This can be translated to the following queue-pseudo code: ``` Queue Enqueue 45 -> 45 Dequeue -> Dequeue -> (dequeue on an empty queue is a no-op) Enqueue 37 -> 37 Enqueue 20 -> 20 37 Dequeue -> 20 Enqueue 97 -> 97 20 Dequeue -> 97 Enqueue 85 -> 85 97 ``` You can see that in the end, the result is `[85, 97]`, which is the output for this sequence. --- ### Test cases **Note** that you may choose any other symbol or character for `X`, as long as it's not a positive integer. ``` [1, X, 2, X, 3, X] -> [] [1, 2, X] -> [2] [1, 2, 3] -> [3, 2, 1] [1, 2, X, X, X, 3] -> [3] [1, 2, X, 3, X, 4] -> [4, 3] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! [Answer] # Python 2, ~~56~~ ~~53~~ 50 bytes ``` q=[] for i in input():q=[[i]+q,q[:i]][i<0] print q ``` [Try it Online!](https://tio.run/nexus/python2#@19oGx3LlZZfpJCpkJkHRAWlJRqaVkDR6MxY7UKdwmirzNjY6Ewbg1iugqLMvBKFwv//ow11FIx0FHSBlDGEMolVAAA) Dequeue is `-1`. This trick allows easy pythonic slicing of the queue. [Answer] # Mathematica, 102 bytes Definitely not the shortest solution, but I couldn't resist because it's kind of perverse. ``` r=Reverse@{##}& a_~f~b___:=b f[a_,b___,]:=b ToExpression[{"r[","f["~Table~StringCount[#,"]"],#}<>"]"]& ``` After some helper functions, this defines a pure function that takes a string as input: in the string, numbers are separated by commas (whitespace is optional); the dequeue character is `"]"`; and the list does not have delimiters in the front or back. For instance, the first example in the OP would be input as the string `"45,],],37,20,],97,],85"`. The output of the function is a list of numbers. The function counts how many dequeues `"]"` are in the input string, appends that many copies of `"f["` to the front of the string, and then surrounds the whole thing by `"r[...]"`. In the example above, this produces `"r[f[f[f[f[45,],],37,20,],97,],85]"`; notice the brackets are balanced. Then, `ToExpression` interprets the resulting string as a piece of Mathematica code and executes it. The function `f` is conveniently defined to retain all its arguments except the first (and also ignores trailing commas; this is necessary to handle dequeueing empty queues anyway), and `r` converts the resulting sequence of numbers into a list of numbers in the right order. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` F;@Ṗṛ?¥/ ``` Uses any falsy value (**0** or empty iterable) to dequeue. [Try it online!](https://tio.run/nexus/jelly#@@9m7fBw57SHO2fbH1qq//9w@6OmNe7//0dHm5jqKCgYQLCxuY6CEZRtaQ6hLUxjdbgUohUMocqMoLQxiFZAAghlRuhSuJUZE6fMAAkb41dmDKVNUJTFAgA "Jelly – TIO Nexus") ### How it works ``` F;@Ṗṛ?¥/ Main link. Argument: A (array) / Reduce A by the link to the left. ¥ Combine the two links to the left into a dyadic chain. F Flatten the left argument. ṛ? If the right argument is truthy: ;@ Concatenate the right argument and the flattened left argument. Else: Ṗ Pop; remove the last element of the flattened left argument. This is why flattening is required, as Ṗ doesn't handle integers as intended for this challenge. ``` [Answer] # [Retina](https://github.com/m-ender/retina), 30 bytes ``` 1+`\d+,(.*?)X,?|^X, $1 O^$`\d+ ``` [Try it online!](https://tio.run/nexus/retina#U9VwT/hvqJ0Qk6Kto6GnZa8ZoWNfExehw6ViyOUfpwIS///fUCdCxwiIjXUiuAxBLDBpDGGDIYwNVKFjAgA "Retina – TIO Nexus") Repeatedly removes the first number that's (not necessarily immediately) followed by an `X` together with that `X`, or an `X` at the beginning of the string. Then reverses the remaining numbers. [Answer] # JavaScript, ~~70~~ ~~63~~ ~~53~~ ~~50~~ 43 bytes Thanks @Neil for golfing off 10 bytes with x.map instead of for loop and ternary expression Thanks @Arnauld for golfing off 3 bytes Thanks @ETHproductions for golfing off 7 bytes ``` x=>(t=[],x.map(a=>+a?t=[a,...t]:t.pop()),t) ``` [Try it online!](https://tio.run/nexus/javascript-node#S7P9X2Frp1FiGx2rU6GXm1igkWhrl2hnYA8USdTR09MribUq0SvIL9DQ1NQp0fyfnJ9XnJ@TqpeTn66RphFtYqqjFKEExgrG5joKRgYQtqU5hLYwjdXU/A8A) Dequeue can be any non-numeric value other than true. [Answer] ## Mathematica, ~~46~~ 45 bytes *Thanks to ngenisis for saving 1 byte.* ``` Reverse[#//.{_Integer:0,a___,X,b___}:>{a,b}]& ``` Basically the same as my Retina answer, using pattern matching. We repeatedly match the first `X` and remove it along with the first number (if one exists). After we're done, we reverse the list. [Answer] # Pure Bash, 72 Input given as command-line parameters. ``` for a;{ [ ${a/X} ]&&q=(${a:n++,0} ${q[@]})||((n-=n>0)) } echo ${q[@]::n} ``` [Try it online](https://tio.run/nexus/bash#@5@WX6SQaF3NFa2gUp2oH1GrEKumVmirAeRY5Wlr6xjUAsULox1iazVrajQ08nRt8@wMNDW5arlSkzPyoXJWVnm1////NzH9HwGExub/jQyAtKU5kLAwBQA). [Answer] # Haskell, 41 bytes ``` x&y:z|y<1=init x&z|w<-y:x=w&z x&y=x ([]&) ``` [Answer] # Haskell, ~~41~~ 40 Bytes ``` l#a|a>0=a:l|l>[]=init l|1>0=l ``` Function is `foldl(#)[]` (Also included in bytecount with a byte of separation in between) [Try it online!](https://tio.run/nexus/haskell#jY7NCsJADITvfYpAPShsYftHVWhfpOwhtqsGYrbURRH67nWL4EmwCWQgfDPMzDFO2Ogajzxx05qahDzwlIYfzzckgRp6B8NI4mEDZ8c9b@Nda9qiVDpsXqls0UMVzr40EXznhykNULa4lP5LZquYfE3Op@kqMjRThYmSREOHAicLox0YO9vDk/wVUF4gTpLB3cnTw0LIsRc7zm8 "Haskell – TIO Nexus") X is any non-positive integer EDIT: -1 byte thanks to nimi [Answer] # Julia, ~~78~~ ~~76~~ ~~73~~ 57 bytes ``` f(a)=(q=[];[x<1?q=q[2:end]:push!(q,x)for x=a];reverse(q)) ``` Thanks to Harrison Grodin for some excellent Julia golfing suggestions. Replaced if/else with ternary and for/end with list comprehension for a savings of 16 bytes. ``` f(a)=(q=[];for x in a if x<1 q=q[2:end]else q=[q...,x]end end;reverse(q)) ``` Removed some unnecessary spaces for a savings of 3 bytes. Before negative numbers or zero were allowed: ``` f(a)=(q=[];for x in a if x==:X q=q[2:end] else q=[q...,x] end end;r everse(q)) ``` Ungolfed: ``` function dequeue(list) queue = [] for x in list if x < 1 queue = queue[2:end] else queue = [queue..., x] end end reverse(queue) end ``` I'm fairly new to Julia; there may be a better way. Uses `:X` for X, which is a Symbol in Julia. Updated: Now that 0 is allowed, uses 0 (or any negative number) for X, saving two characters. Updated again to remove some whitespace that I didn't realize wasn't needed. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes ``` vi"@?@wh}IL) ``` Input is an array of numbers, with `0` for "dequeue". Output is numbers separated by spaces. An empty result is shown as nothing. [Try it online!](https://tio.run/nexus/matl#@1@WqeRg71CeUevpo/n/f7SJqY6CARgZm@soGEGYluZgysI0FgA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/##y00syfmfoO6cWJyqoO4QlqFupZ7h8r8sU8nB3qE8o9bTR/N/bGyES8j/aEMdBQMdBSMwaQwkY7lAQkbILGOEGAyhCBmDSZNYAA). ### Explanation ``` v % Concatenate stack contents: gives []. This will grow to represent the queue i % Input numeric array " % For each entry in the input array @? % If current entry is non-zero @wh % Prepend current entry to the queue } % Else IL) % Remove last element from the queue % End (implicit) % End (implicit) % Display (implicit) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes Saved a byte thanks to *Riley* ``` )Evyai¨ëy¸ì ``` [Try it online!](https://tio.run/nexus/05ab1e#@6/pWlaZmHloxeHVlYd2HF7z/3@0oY6CkY6CeoS6joIxlDaJBQA "05AB1E – TIO Nexus") **Explanation** Dequeues are denoted by *any letter*. ``` ) # wrap stack in a list (pushes empty list) Ev # for each y in evaluated input yai # if y is a letter ¨ # remove the first element of the list ëy¸ì # else, prepend y to the list ``` [Answer] # GNU Sed, 43 Score includes +2 for use of the `-r` and `-n` flags. ``` G s/X\n( *|(.*)\b\S+ *)$/\2/ s/\n/ / h $p ``` [Try it online](https://tio.run/nexus/sed#@@/OVawfEZOnoaBVo6GnpRmTFBOsraClqaIfY6QPlIrJ01fQ58rgUin4/9/ElCsCCI3NuYwMgLSlOZCwMP2XX1CSmZ9X/F@3KA8A). ### Explanation ``` # Implicitly read the next line G # append a newline, then the contents of the hold space s/X\n( *|(.*)\b\S+ *)$/\2/ # If the input was an X, remove it, the newline, and any element at the end s/\n/ / # Otherwise if the input was not an X, it is simply enqueued by removing the newline between it and the rest of the line h # save a copy of the queue to the hold space $p # since we're using -n to suppress output at the end of processing each input line, then this explicit print is required in the last line ``` [Answer] # PHP, 85 Bytes ``` <?$r=[];foreach($_GET as$v)is_int($v)?array_unshift($r,$v):array_pop($r);print_r($r); ``` -8 Bytes `$v` instead of `is_int($v)`if every dequeue value belongs to false [Answer] # [Python 3](https://docs.python.org/3/), ~~95~~ 94 bytes ``` def f(x):q=[];[*map(lambda s:exec(("q.pop(0)"if q else"","q+=[s]")[s!="X"]),x)];print(q[::-1]) ``` [Try it online!](https://tio.run/nexus/python3#VY3NCsIwEITvPkXc066N0l@qKXkPIeRQbQKFVhPjIW9fS3qQHpbdmR2@WQZjmcVIwkulO3Wae4dTPz@GngVhonkigr@4t8OcYLTMMzMFA8DBZ1IFDaTCUcIdNPFIunOf8fVFr4Q4F5oWi6pu@PpOU7W8zNN1a9O6NpoOa6ZIqtxCPNE2u9yLauf/uXs7EXi91v8A "Python 3 – TIO Nexus") Also 94 bytes: ``` def f(x):q=[];[*map(lambda s:exec((("","q.pop(0)")[q>[]],"q+=[s]")[s!="X"]),x)];print(q[::-1]) ``` [Answer] # [Perl 5](https://www.perl.org/), 28 + 1 = 29 bytes 28 bytes of code + `-p` flag. ``` /\d/?$\=$_.$\:$\=~s/.* $//}{ ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@K8fk6JvrxJjqxKvpxJjBWTUFevraXGp6OvXVv//b8hlxBXBZQzEJlwA "Perl 5 – TIO Nexus") It uses a string (`$\`) as the queue: when the input contains an integer (`/\d/?`, we append it at the beginning of `$\` (`$\=$_.$\`), and otherwise, we remove the last one with `s/.*\n$//`. At the end, `$\` is implicitly printed thanks to `-p` flag (and those unmatched `}{`). --- Other approaches: * **33 bytes**, using an array as the queue (it's the most natural way to do it in Perl I think, but not the shortest): ``` /X/?pop@F:unshift@F,$_}{$_="@F" ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAtyPmvH6FvX5Bf4OBmVZpXnJGZVuLgpqMSX1utEm@r5OCm9P@/IZcRVwSXMRCbAAA "Perl 5 – TIO Nexus") * **52 bytes**, using regex and `reverse` (it happens to be quite exactly the same thing as Martin Ender's Retina answer - thanks to whom I saved 2 bytes on it). Reversing the list takes a lot of characters though, because to preserve the integers, I have to convert the string to an array to reverse it, then back to a string to print it. (`say for` instead of `$_=join$",` can save 2 bytes, but it requires `-E` or `-M5.010` and it's not that interesting). ``` s/\d+ (.*?)X ?|^X/$1/&&redo;$_=join$",reverse split ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@F@sH5OiraChp2WvGaFgXxMXoa9iqK@mVpSakm@tEm@blZ@Zp6KkU5RallpUnKpQXJCTWfL/v4mpQgQQGpsrGBkAaUtzIGFhCgA "Perl 5 – TIO Nexus") [Answer] ## Swift 3, 70 bytes Assuming we have an array of Ints like `let x = [1, 2,-1,3,-1,4]` ``` print(x.reduce([].prefix(0)){(a,i)in return i>0 ?[i]+a:a.dropLast(1)}) ``` Note that `[].prefix(0)` is a sneaky way to get an empty ArraySlice [Answer] ## Batch, 160 bytes ``` @set s=. @for %%n in (%*)do @if %%n==X (call set s=%%s:* =%%)else call set s=%%s:~,-1%%%%n . @set t= @for %%n in (%s:~,-1%)do @call set t= %%n%%t%% @echo%t% ``` This was harder than it needed to be. * Although Batch can enumerate the result of splitting a string, it can't easily remove an element from the enumeration. * It can remove the first item, but only if there is at least one item. Otherwise you get garbage. This means that I a) need to have an end-of-queue marker, which doesn't get removed, and b) have to manipulate the queue back-to-front, so new items get inserted in just before the end marker, so that old items can be removed from the front, which then means I c) have to reverse the queue before printing it. [Answer] # PHP, 70 bytes ``` foreach($argv as$v)+$v?$r[]=$v:array_shift($r);krsort($r);print_r($r); ``` [Answer] # C#, 115 bytes +33 bytes for using ``` l=>{var r=new List<int>();foreach(var n in l)if(n<0)try{r.RemoveAt(0);}catch{}else r.Add(n);r.Reverse();return r;}; ``` Anonymous method which returns a list of integers after performing the en-queuing and dequeuing operations. Negative integers are used for removing elements from the queue. Full program with ungolfed method and test cases: ``` using System; using System.Collections.Generic; public class Program { static void PrintList(List<int> list) { var s = "{"; foreach (int element in list) s += element + ", "; if (s.Length > 1) s += "\b\b"; s += "}"; Console.WriteLine(s); } public static void Main() { Func<List<int>, List<int>> f = l => { var r = new List<int>(); foreach (var n in l) if (n < 0) try { r.RemoveAt(0); } catch { } else r.Add(n); r.Reverse(); return r; }; // test cases: var list = new List<int>(new[]{1, -1, 2, -1, 3, -1}); // {} PrintList(f(list)); list = new List<int>(new[]{1, 2, -1}); // {2} PrintList(f(list)); list = new List<int>(new[]{1, 2, 3}); // {3, 2, 1} PrintList(f(list)); list = new List<int>(new[]{1, 2, -1, -1, -1, 3}); // {3} PrintList(f(list)); list = new List<int>(new[]{1, 2, -1, 3, -1, 4}); // {4, 3} PrintList(f(list)); } } ``` [Answer] # Scala, 97 bytes ``` type S=Seq[_];def f(a:S,b:S):S=a match{case h::t=>f(t,if(h==0)b dropRight 1 else h+:b);case _=>b} ``` As input, `f` takes a list with `0` as the "dequeue" element. It uses tail-recursion with a second parameter (`b`), acting as an accumulator. Initially, `b` is the empty `Seq` (`Nil`). **Explanations :** ``` type S=Seq[_] // defines a type alias (save 1 byte since Seq[_] is used 3 times) def f(a: S, b: S): S = { // a is the initial list, b is an accumulator a match { case h::t => // if a is non-empty f(t, // recursive call to f with 1st parameter as the tail if (h==0) b dropRight 1 // if h == 0 (dequeue) then remove last element of b, else h+:b // otherwise, just add h at the beginning of b in recursive call ) case _ => b // when the list is empty, return b (final result) } } ``` *Note :* `b dropRight 1` is used instead of `b.tail` to avoid exception : `tail of empty list`. **Test cases :** ``` f(Seq(45, 0, 0, 37, 20, 0, 97, 0, 85), Nil) // List(85, 97) f(Seq(1, 0, 2, 0, 3, 0), Nil) // List() f(Seq(1, 2, 0), Nil) // List(2) f(Seq(1, 2, 3), Nil) // List(3, 2, 1) f(Seq(1, 2, 0, 0, 0, 3), Nil) // List(3) f(Seq(1, 2, 0, 3, 0, 4), Nil) // List(4, 3) ``` `f` can also work with other types (`String`, `char`, ..., even heterogeneous list of those types!) : ``` f(Seq(false, '!', "world", 0, "Hello"), Nil) // List(Hello, world, !) ``` [Answer] ## REXX, 115 bytes ``` arg n do while n>'' parse var n m n if m=X then pull else queue m end o= do while queued()>0 pull a o=a o end say o ``` Takes a space-separated string, prints a space separated string [Answer] # C++, ~~122~~ 119 bytes ``` #import<list> void f(std::list<int>o,std::list<int>&q){for(int i:o)if(i)q.push_front(i);else if(q.size())q.pop_back();} ``` 0 indicates a dequeue. [Try it online!](https://tio.run/nexus/cpp-gcc#dU5da4QwEHz3VywelATkaM8@abhfcnBYjXSpZjWJfaj42@0mpy09eiEMOzP7MesB@4GsVx06f04@CRtohfNNUQRFofFnyv7yp1HOLVnBNWBBEluBcjwOk3u/tpaMZ1rqzmlgZzw6/NJChgYarm9V/SFkuawHNHU3NRoUkvNWV/123Wvn7wIAGpnMCfC7M2jyZdQ5gskClRsnC7eAUET5NllzCUqxypBCWv4u3a30YlhekjDcV2jEfjoGm18yeM7gFDFnXLaDP@7pgZj/27n/R24e8TW4ybJ@Aw) [Answer] # Ruby, ~~65~~ 54 bytes ``` q=[];(eval$*[0]).each{|i|q=[i]+q;q=q[1..-2]if i<0};p q ``` The separator can be any negative number. [Answer] # [Python 2](https://docs.python.org/2/), 58 bytes ``` def f(x,r=[]): for i in x:r=i and[i]+r or r[:-1] print r ``` [Try it online!](https://tio.run/##XYzBCoMwEETv@Yo5GppCTRTbgF8S9lCwoXuJsnjQr09DBKHCMrvzdphlX79zsjlPn4jYbEbGQNorxFnA4ITNy8h4pykw3QQFS/D3lhQW4bRCcmxC1xs86rjBwB7na6jr2ZNWJdNWZ49U0ZPai3F/n7P4Ql3VjnT@AQ "Python 2 – Try It Online") Uses `0` as a dequeue value -10 bytes [thanks to](https://codegolf.stackexchange.com/questions/114749/when-integers-join-the-queue/114761?noredirect=1#comment513447_114761) [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger) [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~18~~ 17 bytes -1 byte from @ngn ``` (){$[y;y,;-1_]x}/ ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NSkOzWiW60rpSx1rXMD62olb/f5qCg7qChompggEQGpsrGIFoS3MgYWFqbQikjEDiCgZAthGUNIawITqgbKAKBRPN/wA "K (ngn/k) – Try It Online") Uses `0` as the dequeue element. * `(){...}/` set up a reduction seeded with `()` (an empty list), over the (implicit) input * `$[...]x` apply `x` (the queue) to the result of `$[]` (cond) * `$[y;y,;-1_]` depending on the new value (i.e. if it is `0` or isn't), return a function projection either prepending the new value (`y,`), or dequeuing the last element (`-1_`) [Answer] # [J](http://jsoftware.com/), 18 bytes ``` (*@[;@{}:@];,)/@|. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NbQcoq0dqmutHGKtdTT1HWr0/mtypSZn5CtYmCpYmivoWimkKZiYAnUYKBibKxiBaKCwAVAaokxdHaLGEChmBFKkYACRMFKwBQuDBFEBRN4YKGMI02sE5GLII/SDbUeSMwHy4DrBdgKFFP4DAA "J – Try It Online") * `(...)/@|.` Reverse and reduce by verb in parens... * `}:@];,` Create the two options (regular vs deque, represented by `0`) as a boxed pair: left elm is the deque case (ie, accumlator with tail removed `}:@]`) and right elm is the normal case (new elm appended as head `,`). * `(*@[...{` Pick the correct case, which is the signum of the left argument in the reduction `*@[`, from our boxed pair `{`... * `;@` And unbox it. [Answer] # [Zsh](https://www.zsh.org/), 46 bytes ``` for a (`<&0`)$a&&{shift -p;:}||set $a $@ <<<$@ ``` [Try it online!](https://tio.run/##qyrO@P8/Lb9IIVFBI8FGzSBBUyVRTa26OCMzrURBt8Daqrampji1REElUUHFgcvGxkbF4f9/E1MFKyA0NlcwMgDSluZAwsIUAA "Zsh – Try It Online") [Answer] # [Julia 0.7](http://julialang.org/), 41 bytes ``` !a=(q=[];a.|>i->q=i>0?[i;q]:q[1:end-1];q) ``` [Try it online!](https://tio.run/##yyrNyUw0//9fMdFWo9A2OtY6Ua/GLlPXrtA2087APjrTujDWqjDa0Co1L0XXMNa6UPN/hIKtggGXYrShjkKEjoIRmDQGkrEKNXYKBUWZeSU5eRBpI1yixrEKWBXDkHEsDmljMGmCLP0fAA "Julia 0.7 – Try It Online") ]
[Question] [ Your task: given an input string, determine whether the binary representation of that string does not have 4 `1`s or `0`s in a row, anywhere. Furthermore, your code itself should not contain any such runs of four in a row. ## Test Cases ``` String Binary Result U3 01010101 00110011 Truthy 48 00110100 00111000 Falsy Foobar 01000110 01101111 Falsy 01101111 01100010 01100001 01110010 Feeber 01000110 01100101 Truthy 01100101 01100010 01100101 01110010 $H 00100100 01001000 Truthy <Empty> - Truthy ``` ## Rules * Input will always be within the range of printable ASCII, including whitespace characters. + Your code may use any encoding, since it only matters at the bit level. * Because this condition prevents the use of white space and many other chars, your code actually *can* contain such runs of four in a row, at a 10 byte penalty for each run. + A run of 5 `1`s or `0`s counts as two runs, 6 in a row counts as three runs, etc. * Input will be a string or char array, not any other form. * You may write a complete program or function. * You must provide the binary representation of your code in your answer. Good luck, lowest score wins! [This script](https://tio.run/nexus/python3#TZAxT8MwEIXn3K@wutgmbUgLQxXhAWYGJNhKBzd125MSx7pchSLx34OdFuhNlr/37j3diG3oiEU/9HNBDno28Vn0vEdfkLN7pQF9OPMzmdYGtUM/3w3sLJEdVM9zeebDYi21hovOSAlw6EigQC@u1goyNLhZVVvIvk7YONE4r1A/rSOJSJYyx6hJ6twgQCD0rOQLektD9ekjTiyGBEOuqLs2xC1qVsb5XsaZaeCObWPKm3Sy/ujUFDW5Fw86NTmIULSW69Ple4MV5o/bhLJpR26WAI0zqcK/@X6tITgzKe6W5bWjUPLV@SOfppI9U3TEW/yyN@dtw8MfDLfwI60S73VH7sadJ804/gA) might help you with your challenge, put your code in the input and it will give you your code's binary representation, it's length, your penalty, and the total score, if you're using UTF-8. ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. ``` /* Configuration */ var QUESTION_ID = 111758; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 60042; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang > b.lang) return 1; if (a.lang < b.lang) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } 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] # [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly) + 0 penalties = 18 ``` 79Ọv2;$ḅ⁹b2+4\b4FẠ ``` Returns `1` if there are no equal bit strings of length **4** or more in the 8-bit word representation of the ASCII string input, and `0` otherwise. **[Try it online!](https://tio.run/nexus/jelly#@29u@XB3T5mRtcrDHa2PGncmGWmbxCSZuD3cteD/o8Z96upZXIfbHzWtObrn8EQg5Q3Ekf//R6uHGqvrcKmbWIBIt/z8pMQiMCs1NSkVzFLxAJHq6iAMZHCi8BSgPKAhEFmIaUgiCkBGLAA)** (test suite with some extra cases added) Using Jelly's [codepage](https://github.com/DennisMitchell/jelly) there are no length 4 or longer substrings of equal bits: ``` 7 0x37 00110111 9 0x39 00111001 Ọ 0xB5 10110101 v 0x76 01110110 2 0x32 00110010 ; 0x3B 00111011 $ 0x24 00100100 ḅ 0xD4 11010100 ⁹ 0x89 10001001 b 0x62 01100010 2 0x32 00110010 + 0x2B 00101011 4 0x34 00110100 \ 0x5C 01011100 b 0x62 01100010 4 0x34 00110100 F 0x46 01000110 Ạ 0xAB 10101011 ``` With equal-bit run lengths of: ``` 221323221211111312322133122121221111213121123132213111122211311332313211313211111112 ``` ### How? Tricks to avoid demerits are: * to avoid the "convert from character to ordinal" monad `O` by converting the number `79` to a character using `Ọ` followed by an "evaluation of Jelly code with input", `v`. * to avoid direct conversion to binary using `B` (`0x42`, `1000010`) by the simple two-byte alternative `b2` using the generic dyadic base conversion. * to avoid a few normal choices for counting the runs of equal bits - first choice would be "all overlapping slices of given length", `ṡ` (`0xF5` or `11110101`). A second choice might be to utilise "all sublists", `Ẇ` (`0xCF` or `11001111`). A workaround I used before the current one was to take the increments (between consecutive elements) with `I` (putting zeros and ones on an equal footing), and to look for any occurrence of three zeros in a row. To do that I converted all the zeros to ones by use of the binomial function with `2c` i.e. **2Cx** - making the `-1`s become `0`s the `1`s become `2`s, and the `0`s become `1`s; that way the code can look for the first occurrence of the sublist `[1,1,1]` with `w111`. However a shorter way became apparent - to mimic the action of "all overlapping slices of given length", `ṡ`, one can use a **4**-wise overlapping reduce with some dyad, `<dyad>4\`. If this is performed with addition, `+4\`, it counts the `1`s, so then any `0` or `4` being present is the indicator to return a truthy value. The issue here is that the next obvious step would be to take the modulo **4** of that to put the `0` and `4` entries on an equal footing while leaving the other possible values (`1`, `2`, and `3`) unchanged, but `+\%4` has `\%` inside, which has bit-value 010111**0000**100100. In order to avoid that penalty the numbers are all converted to base **4** with `b4` (mapping `0` to `[0]`, `1` to `[1]`, `2` to `[2]`, `3` to `[3]`, and `4` to `[1,0]`) and the whole list is flattened with `F`. Now the last test is simply to check if there are any `0`s in the list, achievable directly with the monad `Ạ`. ``` 79Ọv2;$ḅ⁹b2+4\b4FẠ - Main link: printable ASCII character list 79 - 79 Ọ - character from ordinal : 'O' v - evaluate as Jelly code : input -> 'O' converts the input to ordinals $ - last two links as a monad 2 - 2 ; - concatenate (why? see the note beneath the code block) ḅ⁹ - convert from base 256 : gets an integer representing the byte string b2 - convert to base 2 AKA binary 4\ - 4-wise reduce with + - addition (sums all overlapping slices of length 4) b4 - convert to base 4 (vectorises) F - flatten into a single list Ạ - any falsy? ``` Note: The reason a **2** is concatenated with the ordinal list is to deal with the edge cases where the only run of **4** in the input string is in the leading zeros of the very first character - these characters are: tab; line-feed; and carriage-return. Without this the base 256 conversion effectively strips leading zeros from the (fully concatenated) binary string; with the leading **2** the leading zeros will be there and an extra one and zero before them. Since no printable ASCII has exactly three leading zeros there is no need to discard these extra bits before the rest of the check. [Answer] # Java 7, ~~812~~ ~~726~~ ~~673~~ ~~644~~ ~~634~~ ~~616~~ ~~599~~ ~~588~~ 145 bytes + 10\*44 = 585 ``` boolean b(char[]b){String g="";for(char c:b)g+=g.format("%"+(1-1)+"8d",new Integer(Integer.toString(c,2)));return!g.matches(".*(.)\\1\\1\\1.*");} ``` I am using newlines instead of spaces to try to minimize penalty... [Try it online!](https://tio.run/nexus/java-openjdk#lY/BSsQwEIbveYoYFCbbNVD1sFh6EEH04GnxtLuHJBuzhTYpyVRZSp@9xtajeygEhmS@f/JN26m60lTXMkb6LivXj8r72khHFOiTDLuD4v0WQ@UssSVjxacPU4PoR8VtVlqRXhqJwG5YBvltzjO2ObK1M9/kzaGxJsBfFejnSaDXd5zzIhjsgruyIuX1yURgYgWC7/f5fMSK8WIY21kyosRUvnx1pE1ShXnY7iB5TyZ5qmhJ08fTBXhB6PYc0TTCdyjaBGPtQAkF7OOeJZvntMdTCPIMvzbkEvywWQC/eK9kWBIwRpklgevXBfA/6ECG8Qc "Java (OpenJDK 8) – TIO Nexus") ### Binary ``` 01100010011011110110111101101100011001010110000101101110000010100110001000101000011000110110100001100001011100100101101101011101011000100010100101111011010100110111010001110010011010010110111001100111000010100110011100111101001000100010001000111011011001100110111101110010001010000110001101101000011000010111001000001010011000110011101001100010001010010110011100101011001111010110011100101110011001100110111101110010011011010110000101110100001010000010001000100101001000100010101100101000001100010010110100110001001010010010101100100010001110000110010000100010001011000110111001100101011101110000101001001001011011100111010001100101011001110110010101110010001010000100100101101110011101000110010101100111011001010111001000101110011101000110111101010011011101000111001001101001011011100110011100101000011000110010110000110010001010010010100100101001001110110111001001100101011101000111010101110010011011100010000101100111001011100110110101100001011101000110001101101000011001010111001100101000001000100010111000101010001010000010111000101001010111000101110000110001010111000101110000110001010111000101110000110001001011100010101000100010001010010011101101111101 ``` ## Old bitshifting solution 141 bytes + 10\*101 = 1,151 ``` boolean b(char[]b){ int o=0,p=0,i; for(char c:b){for(i=0;i<8;){if((c&(1<<i++))<1){o=0;p++;}else{p=0;o++;}if(3<o|3<p)return 6<5;}}return 5<6;} ``` [Try it online!](https://tio.run/nexus/java-openjdk#lY6xasMwEIZ3PYXIECRcTIKbECp5KIVunUKnkEFSlUbg6IQstwRVz@5e3I7t4OE4fu77jy8MunOGmk71PX1RzudRA3RWeaKZOat4OGqeifOJQLu6CzhOkBPE6UjMA15vybUr4eRO8OxOjJklW0vpqopzueYZmyJUlSi2623GHwJuCclGwlcjA482DdGTrdyIUn7DRm5FGcOPYJ9UwvUB7o1eUJPtU3T@/XBUaDeJU01b6u3nFBgXhO6vfbKXGoZUB4RT55muNVu8Nos6wRP6P8aoroxzpP@D73cz4GcAreKcgrXazin8gRZSxm8 "Java (OpenJDK 8) – TIO Nexus") ### Binary ``` 011000100110111101101111011011000110010101100001011011100000101001100010001010000110001101101000011000010111001001011011010111010110001000101001011110110000101001101001011011100111010000001010011011110011110100110000001011000111000000111101001100000010110001101001001110110000101001100110011011110111001000101000011000110110100001100001011100100000101001100011001110100110001000101001011110110110011001101111011100100010100001101001001111010011000000111011011010010011110000111000001110110010100101111011011010010110011000101000001010000110001100100110001010000011000100111100001111000110100100101011001010110010100100101001001111000011000100101001011110110110111100111101001100000011101101110000001010110010101100111011011111010110010101101100011100110110010101111011011100000011110100110000001110110110111100101011001010110011101101111101011010010110011000101000001100110011110001101111011111000011001100111100011100000010100101110010011001010111010001110101011100100110111000001010001101100011110000110101001110110111110101111101011100100110010101110100011101010111001001101110000010100011010100111100001101100011101101111101 ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 26 + 1 × 10 = 36 bytes ### Notes Contains one 4-run of 1s. Requires `⎕IO←0` which is default on many systems. Note that this *must* be run on a Classic interpreter so that strings are one byte per character. ### Submission `1≠⊃⌽⌈\∊(×4\¨⍳≢⍬⍬)⍷¨⊂11⎕DR⍞` [Try it online!](https://tio.run/nexus/apl-dyalog-classic#U9Z71DfV0/9R2wQDrkcd7Wn/DR91LnjU1fyoZ@@jno6YRx1dGoenm8QcWvGod/OjzkWPetcAkeaj3u1Aka4mQ0OgbpegR73z/gM1/0/jCjXmSuMysQASbvn5SYlFIEZqalIqiKHiASS4DA0VwHoU1Mm0SV3hUe9cBafMvMSiSgWXxJJEhaDUgqLU4tS8ksSSzPw8hfw0hZKMVIWCovz0osRcheL80qLkVAA "APL (Dyalog Classic) – TIO Nexus") ### Binary source 0011000110101100100111001011001010010111010111001011100100101000110101110011010001011100101010001011110010111011101010111010101100101001101110101010100010011011001100010011000110001100010001000101001010001101 ### Explanation `⍞` Prompt for string input `11 ⎕DR` convert to **1**-bit Boolean (**1**) **D**ata **R**epresentation `⊂` enclose so we can apply multiple things to it `(`…`) ⍷¨` binary indicators where each of the following sequences begin…  `×` sign (no-op on binary data, but included as spacer to split runs)  `4 \¨` expand (copy) each to length four  `⍳` the integers up to  `≢` the tally of  `⍬⍬`  the list consisting of two empty numeric lists `∊` enlist (flatten) `⌈\` cumulative maximum `⌽` reverse `⊃` pick the first `1 ≠` is one different from? (i.e. NOT) ### Walk-through We will input "48" to the ungolfed un-de-runned version `~ ∨/ ∊ (0 0 0 0)(1 1 1 1) ⍷¨ ⊂ 11 ⎕DR ⍞`: `11 ⎕DR ⍞` converts "48" to 0 0 1 1 0 1 0 0 0 0 1 1 1 0 0 0 (i.e. Dec 52 56, Hex 34 38) `(0 0 0 0)(1 1 1 1) ⍷¨ ⊂` finds beginnings of 0-runs and 1-runs; (0 0 0 0 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) `∨/ ∊` looks if there is any Truth (i.e. any runs); 1 `~` negates that; 0 [Answer] # Jelly 28 + 140 demerits = 168 ``` L8_0xṭ OBUÇ€UFŒr<4FẠ ``` # Explanation ``` OB ``` Converts the argument to a list of their binary encodings, e.g. ``` “U3”OB -> [[1, 0, 1, 0, 1, 0, 1], [1, 1, 0, 0, 1, 1]] ``` The next piece ``` UÇ€U ``` fixes the fact that the above list can be missing characters as `B` does not include leading zeros. `Ç€` calls the previously defined link over each element which restores that ``` L8_0xṭ ``` This link is equivalent to ``` lambda x: x + repeat(0, 8 - len(x)) ``` For example ``` [1, 1, 0, 0, 1, 1] L8_0xṭ -> [1, 1, 0, 0, 1, 1, [0, 0]] ``` We upend the list before and after this operation (the two `U` calls in that list) to get that to be a prepend rather than an append. The next piece ``` FŒr ``` Flattens the list (`F`), giving the total binary string of the ASCII encoding, and run-length encodes the output (`Œr`). So for example ``` L8_0xṭ “U3”OBUÇ€UF -> [1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0] ``` and ``` L8_0xṭ “U3”OBUÇ€UFŒr -> [[1, 1], [0, 1], [1, 1], [0, 1], [1, 1], [0, 1], [1, 1], [0, 1], [1, 2], [0, 2], [1, 2], [0, 2]] ``` Finally we check whether each element is < 4 (thankfully this is always true for 0,1) with ``` <4F ``` For example ``` L8_0xṭ “U3”OBUÇ€UFŒr<4F -> [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ``` Finally ``` Ạ ``` Returns 0 if any of those are falsy (in this case, 0). # Code Pages In Jelly's code page this code is 20 bytes but has 27 runs worth of rule violations. In UTF-8 it is 28 bytes but with only 14 runs worth of violations. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 22 + 3 \* 10 = 52 Saved 2 penalty runs borrowing the *delta* trick from *Jonathan Allan's* [Jelly answer](https://codegolf.stackexchange.com/a/111785/47066) ``` $Ç256+bvy¦}J¥J6Ìb¦å2ÍQ ``` [Try it online!](https://tio.run/nexus/05ab1e#@69yuN3I1Ew7qazy0LJar0NLvcwO9yQdWnZ4qdHh3sD//91SU5NSiwA "05AB1E – TIO Nexus") **Explanation** ``` $ # push 1 and input (1 to handle the empty string) Ç # convert to list of ascii values 256+ # add 256 to each b # convert each to binary vy¦} # chop off the leading digit of each J # join to string ¥ # take delta's J # join to string 6Ìb¦ # push bin(6+2)[1:] = 000 å # check if this exists in the delta's string 2ÍQ # compare to 2-2 = 0 ``` **Binary representation of the code** ``` 00100100 11000111 00110010 00110101 00110110 00101011 01100010 01110110 01111001 10100110 01111101 01001010 10100101 01001010 00110110 11001100 01100010 10100110 11100101 00110010 11001101 01010001 ``` The 3 penalty runs come from `vy¦}` which is used to chop off the first byte in each binary string, but it's still cheaper than the 4 runs we'd get from the shorter `€¦`. [Answer] # [Perl](https://www.perl.org/), 33 + 160 = 193 32 bytes of code + 1 byte for `-n` flag. ``` $_=unpack"B*";print!m+(.)\1\1\1+ ``` (the input needs to be supplied without final newline. The *Try it online* link has `-l` flag on to remove newlines, but for a single input, it's not needed). [Try it online!](https://tio.run/nexus/perl#U1YsSC3KUdDNyfuvEm9bmleQmJyt5KSlZF1QlJlXopirraGnGWMIgtr//4cac5lYcLnl5yclFnG5paYmpRZxcQEA "Perl – TIO Nexus") xxd dump : ``` 00000000: 00100100 01011111 00111101 01110101 01101110 01110000 $_=unp 00000006: 01100001 01100011 01101011 00100010 01000010 00101010 ack"B* 0000000c: 00100010 00111011 01110000 01110010 01101001 01101110 ";prin 00000012: 01110100 00100001 01101101 00101011 00101000 00101110 t!m+(. 00000018: 00101001 01011100 00110001 01011100 00110001 01011100 )\1\1\ 0000001e: 00110001 00101011 1+ ``` A few notes: * `(.)\1\1\1` saves a few penalties over `(.)\1{3}`, `1111|0{4}` or any other regex I could think of (using `0` or `{}` comes at a heavy cost). * `print` saves ~8 points over using `-p` and `$_=` because `p` contains a run of 4 `0` while `n` doesn't. * `+` as a delimiter for the regex saves a run of `1` that is in `/`. * doing two steps instead of one with `!~` saves two runs (`~` is `01111110` in binary). * `unpack"B*"` is quite expensive (4 runs), but I couldn't find cheaper (solutions bases on `ord` will be even more expensive). [Answer] # PHP, 98 + 270 = 368 bytes I wanted to take a different approach from what [Titus proposed](https://codegolf.stackexchange.com/questions/111758/disconnect-4-bits/111798#111798), and ended with a slightly longer, yet less penalized program. ``` $v=unpack('H*',$argv[1]);$e=base_convert($v[1],16,2);echo!stristr($e,'0000')&&!stristr($e,'1111'); ``` Outputs `1` for truthy, nothing for falsey. [Try it here !](https://eval.in/746423) **Binary-encoded :** ``` 0010010001110110001111010111010101101110011100000110000101100011011010110010100 0001001110100100000101010001001110010110000100100011000010111001001100111011101 1001011011001100010101110100101001001110110010010001100101001111010110001001100 0010111001101100101010111110110001101101111011011100111011001100101011100100111 0100001010000010010001110110010110110011000101011101001011000011000100110110001 0110000110010001010010011101101100101011000110110100001101111001000010111001101 1101000111001001101001011100110111010001110010001010000010010001100101001011000 0100111001100000011000000110000001100000010011100101001001001100010011000100001 0111001101110100011100100110100101110011011101000111001000101000001001000110010 1001011000010011100110001001100010011000100110001001001110010100100111011 ``` (22 occurences of `0000` and 5 occurrences of `1111`, hence 270 bytes of penalty) [Answer] # PHP, 86 bytes+370=456 ``` for(;$c=ord($argn[$i++]);)$s.=sprintf("%08b",$c);echo!preg_match("#(.)\\1\\1\\1#",$s); ``` creates the binary string and uses a regex to detect streaks. Output is `1` for truthy; empty for falsy. Run with `echo '<string>' | php -nR '<code>'`. **tweaks** * backreferences save 100 penalty for 3 bytes. (-97 score) **abandoned ideas** * `join(array_map(str_split()))` would cost 31 bytes and 90 penalty * and `<?=`/`$argv[1]` instead of `echo`/`$argn` cost another 2+40. * `str_pad(decbin())` is costlier than `sprintf`: 7 bytes and 110 penalty. * `strtr` saves 80 penalty for 13 extra bytes, but backreferences are better. * Grouping the backreferences `#(.)\\1{3}` saves 3 bytes, but adds 10 penalty. * `foreach` costs 3+50. * No saving possible on the variable names. * output buffering costs 42+120. [Answer] # JavaScript (ES8), 91 bytes + 430 penalty = 521 total This will output `1` for `true` and `0` for `false`. ``` s=>1-/(.)\1\1\1/.test([...s].map(c=>c.charCodeAt().toString(2).padStart(3+5,1-1)).join("")) ``` ``` 01110011001111010011111000110001001011010010111100101000001011100010100101011100001100010101110000110001010111000011000100101111001011100111010001100101011100110111010000101000010110110010111000101110001011100111001101011101001011100110110101100001011100000010100001100011001111010011111001100011001011100110001101101000011000010111001001000011011011110110010001100101010000010111010000101000001010010010111001110100011011110101001101110100011100100110100101101110011001110010100000110010001010010010111001110000011000010110010001010011011101000110000101110010011101000010100000110011001010110011010100101100001100010010110100110001001010010010100100101110011010100110111101101001011011100010100000100010001000100010100100101001 ``` --- ## Try it ``` f= s=>1-/(.)\1\1\1/.test([...s].map(c=>c.charCodeAt().toString(2).padStart(3+5,1-1)).join("")) console.log(f("U3")) console.log(f("48")) console.log(f("Foobar")) console.log(f("Feeber")) console.log(f("$H")) console.log(f("")) ``` [Answer] # MATL, 16 bytes + 60 = 76 bytes ``` 8&B!1e&Y'tgw4<Z& ``` Try it at [**MATL Online**](https://matl.io/?code=8%26B%211e%26Y%27tgw4%3CZ%26&inputs=%27Feeber%27&version=19.8.0) [Answer] ## [CJam](https://sourceforge.net/p/cjam), 23 bytes *Uses [Jonathan Allan's idea](https://codegolf.stackexchange.com/a/111785/8478) to work with deltas.* ``` 1q256b2b2ew::-[TTT]#)g- ``` [Try it online!](https://tio.run/nexus/cjam#@29YaGRqlmSUZJRabmWlGx0SEhKrrJmu@/8/DgkA "CJam – TIO Nexus") Binary representation: ``` 00110001011100010011001000110101 00110110011000100011001001100010 00110010011001010111011100111010 00111010001011010101101101010100 01010100010101000101110100100011 001010010110011100101101 ``` Explanation: ``` 1 e# Push a 1 for (much) later, because we can't use ! for logical NOT. q e# Read input. 256b e# Treat characters as base 256 digits. 2b e# Convert to binary. The last two steps together give us a flat binary e# representation of the input, avoiding both :~ and e_ for flattening. 2ew e# Get all pairs of consecutive bits. ::- e# Compute their differences. [TTT] e# Push [0 0 0]. # e# Find its index in the list of differences, or -1 if not found. )g e# Increment and take signum. We've now got the result we want but e# with the wrong truth value. - e# Subtract it from the 1 we pushed earlier to negate the truth value. ``` [Answer] # Pyth, 19 + 12 \* 10 = 139 ``` !|}*"0"4.BQ}*"1"4.B ``` ### Binary ``` 00100001 01111100 01111101 00101010 00100010 00110000 00100010 00110100 00101110 01000010 01010001 01111101 00101010 00100010 00110001 00100010 00110100 00101110 01000010 ``` ### Explanation ``` !|}*"0"4.BQ}*"1"4.B *"1"4 # Repeat ; '1111' .B # Convert ; input as a binary string } # In ; '1111' in the binary repr *"0"4 # Repeat ; '0000' .BQ # Convert ; input as a binary string } # In ; '0000' in the binary repr | # Or ; 4 consequent idenical digits found ! # Negate ; True if not found, False if found ``` [Answer] # JavaScript, 173 + 89 \* 10 = 1063 JavaScript is not good at converting strings to binary, but I figured I'd give this challenge a shot just for fun. ### Code: ``` function(n){b="";for(var t=0;t<n.length;t++)c=[n.charCodeAt(t).toString(2)],c.unshift(Array(8-c[0].length+1).join(0)),b+=c.join("");return b.match(/[1]{4,}|[0]{4,}/g)?!1:!0} ``` ### Binary: ``` 0110011001110101011011100110001101110100011010010110111101101110001010000110111000101001011110110110001000111101001000100010001000111011011001100110111101110010001010000111011001100001011100100010000001110100001111010011000000111011011101000011110001101110001011100110110001100101011011100110011101110100011010000011101101110100001010110010101100101001011000110011110101011011011011100010111001100011011010000110000101110010010000110110111101100100011001010100000101110100001010000111010000101001001011100111010001101111010100110111010001110010011010010110111001100111001010000011001000101001010111010010110001100011001011100111010101101110011100110110100001101001011001100111010000101000010000010111001001110010011000010111100100101000001110000010110101100011010110110011000001011101001011100110110001100101011011100110011101110100011010000010101100110001001010010010111001101010011011110110100101101110001010000011000000101001001010010010110001100010001010110011110101100011001011100110101001101111011010010110111000101000001000100010001000101001001110110111001001100101011101000111010101110010011011100010000001100010001011100110110101100001011101000110001101101000001010000010111101011011001100010101110101111011001101000010110001111101011111000101101100110000010111010111101100110100001011000111110100101111011001110010100100111111001000010011000100111010001000010011000001111101 ``` ### Explanation: Create a string to work with: ``` b=""; ``` Loop over each character in the string: ``` for(var t=0;t<n.length;t++) ``` Create an array and convert the string to binary using character code: ``` c=[n.charCodeAt(t).toString(2)] ``` Add the leading zeros to the array: ``` c.unshift(Array(8-c[0].length+1).join(0)) ``` Join the array back into a string: ``` b+=c.join("") ``` Return whether or not a string of four or more 1's or 0's was found in the binary result using a regular expression: ``` return b.match(/[1]{4,}|[0]{4,}/g)?!1:!0 ``` ### Fiddle: <https://jsfiddle.net/vrtLh97c/> ### Stats: Length: 173 bytes Penalty: 890 Total: 1063 Code Golf is hard :) [Answer] # Pyth, 21 + 2 \* 10 = 41 ``` J-T2-4eS%2.nr.[dJ.BwJ ``` [Try it online!](http://pyth.herokuapp.com/?code=J-T2-4eS%252.nr.%5BdJ.BwJ&input=Feeber&test_suite=1&test_suite_input=U3%0A48%0AFoobar%0AFeeber&debug=0) Binary representation: ``` 01001010 00101101 010101[00 00]110010 00101101 00110100 01100101 01010011 00100101 00110010 00101110 01101110 01110010 00101110 01011011 01100100 01001010 00101110 01[0000]10 01110111 01001010 ``` [Answer] # Retina, 101 + 1390 = 1491 The code contains unprintable characters, but they show up in Chrome if you edit the post. `-` is `\x01-\x7f`. ``` ¶ ± S_` %(S`± {2` $` }T01`-`_o )Ms`. .+ $* +`(1+)\1 ${1}0 01 1 m+`^(?!.{8}) 0 0{8}|¶ M&`(.)\1{3} 0 ``` [**Try it online**](https://tio.run/nexus/retina#@39oG9ehjVzB8QlcqhrBCUBmtVECl0oCV22IgWECo259Qnw@l6ZvcYIel542l4oWl3aChqG2Zowhl0q1Ya0Bl4EhlyFXrnZCnIa9ol61Ra0mF1AMSNcAzeXyVUvQ0AOqrTau5TL4/98tNTUptQgA) This code uses [this `ord`](http://chat.stackexchange.com/transcript/message/32786271#32786271), followed by conversion to binary and a simple check for overlapping sequences of four. In binary: ``` 11000010101101100000101011000010101100010000101001010011010111110110000000001010001001010010100001010011011000001100001010110001000010100111101100110010011000000000101000100100011000000000101001111101010101000011000000110001011000000000000100101101011111110110000001011111011011110000101000101001010011010111001101100000001011100000101000101110001010110000101000100100001010100000101000101011011000000010100000110001001010110010100100000001000010100010010001111011001100010111110100110000000010100011000000110001000010100011000100001010011011010010101101100000010111100010100000111111001000010010111001111011001110000111110100101001000010100011000000001010001100000111101100111000011111010111110011000010101101100000101000001010010011010010011001100000001010000010111000101001000000010111101100110011011111010000101000110000 ``` Penalties counted with [this Python program](https://tio.run/nexus/python3#ZY/fSsMwFMbx0vMUMU57YrfQKEItjD3BQJiXYtOtqUTaZKTxqhafyRsfYC9W07E5wavz/3e@75JsbKnNa0Z0a2dpev8wE1Cqaixz60rcsMwp/@4M2VdcmXCgMDqtR4wNutla54lTAON4TindfcPuC1a5hCtcyZB2txImEvqnRMiz2afMLbBlKznwGCY3EEsUMXsWMOlEn0AiQEATyxdcXPAu7RmEXogfgQvLa4k87HZ3PSThF@wle5uvtclb77BlGZwfdFPK36w22BRbrItmXRZkk9EuS9J1T3llXVN4PNllU9IyBrB12nj8wxyN7QfKFLXXqiVzUiuDTvFKm7Koa3QRLuZHZSyakn/n7MClj0dKRuiU/DLZMPwA). [Answer] # [Python 2](https://docs.python.org/2/), 74 (length) + 130 (penalty) = 204 ``` k,n=2*[1] for[c]in(input(n)*2*2*2)[:1:-1]:n,k=k*ord(c[:n%16%15])+n/2,k*128 ``` Output is via exit code; **0** is truthy, **1** is falsy. Produces garbage output to STDOUT and STDERR. [Try it online!](https://tio.run/nexus/bash#RY5Nq4JAGIXXzq94F7dGvabM1I2wj13RrlUrkfDjFQflHdHxgkS/3XQRceDwcBYPJ0sMnGCTKtP5zQCHA/Dz7cLHyqOjdCMRs0K3URYrshU1vbHJceUcJwpFuBJxSF51rFzd5nYWhbQQ24X4i51fCqRXuULuxsnHZgs8QBE8he9vX3vINbNUAc1gSk3y@2B5giDH/4D6ut6DKZGYZWFWajBtb8qBWVh3@NmKpO6mqVAs14Qjv68545vdVBet06SdATHFGX6uU/E3 "Bash – TIO Nexus") ### Binary dump ``` 00000000: 01101011 00101100 01101110 00111101 00110010 00101010 k,n=2* 00000006: 01011011 00110001 01011101 00001010 01100110 01101111 [1].fo 0000000c: 01110010 01011011 01100011 01011101 01101001 01101110 r[c]in 00000012: 00101000 01101001 01101110 01110000 01110101 01110100 (input 00000018: 00101000 01101110 00101001 00101010 00110010 00101010 (n)*2* 0000001e: 00110010 00101010 00110010 00101001 01011011 00111010 2*2)[: 00000024: 00110001 00111010 00101101 00110001 01011101 00111010 1:-1]: 0000002a: 01101110 00101100 01101011 00111101 01101011 00101010 n,k=k* 00000030: 01101111 01110010 01100100 00101000 01100011 01011011 ord(c[ 00000036: 00111010 01101110 00100101 00110001 00110110 00100101 :n%16% 0000003c: 00110001 00110101 01011101 00101001 00101011 01101110 15])+n 00000042: 00101111 00110010 00101100 01101011 00101010 00110001 /2,k*1 00000048: 00110010 00111000 28 ``` [Answer] ## JavaScript (ES6), ~~87~~ 88 + ~~390~~ 380 = ~~477~~ 468 bytes ``` s=>1-/(.)\1\1\1/.test(s.replace(/[\S\s]/g,c=>(256+c.charCodeAt()).toString(2).slice(1))) ``` In binary: ``` 01110011001111010011111000110001001011010010111100101000001011100010100101011100001100010101110000110001010111000011000100101111001011100111010001100101011100110111010000101000011100110010111001110010011001010111000001101100011000010110001101100101001010000010111101011011010111000101001101011100011100110101110100101111011001110010110001100011001111010011111000101000001100100011010100110110001010110110001100101110011000110110100001100001011100100100001101101111011001000110010101000001011101000010100000101001001010010010111001110100011011110101001101110100011100100110100101101110011001110010100000110010001010010010111001110011011011000110100101100011011001010010100000110001001010010010100100101001 ``` Over half of the penalty is down to zeros in the overlap between bytes, rather than the runs in the following characters: `=>//pa//=>aCoAo`. Since the `/`s (`00101111`) pay a penalty I tried a) switching from `test` to `match` b) switching from `replace` to `map` but the score always ended up higher. However I did find that `[\S\s]` was an improvement over `[^]`. Edit: Saved 9 bytes overall thanks to @Shaggy. [Answer] # [Pyth](https://github.com/isaacg1/pyth), [16 + 1 x 10 = 26 bytes](https://tio.run/nexus/python3#TZA/b8IwEMVn/CksFtsE0kAZUFQPZe7Qqp34MxgwcG3iuOdDVaR@d2oH2nKT5d97957uDLVvkHhow5CjZYF0fOaBduBytGYnFQPnT/SIujZebsANNy1Zg2haGWgoTrQfzYRS7KLTQjC2b5ADB8ev1pL1QMNyUq5Z7@sIleWVdRLUwyySiEQhMoiapM40MOYRHEkxB2ewLVcu4sRiiNdo821T@7hF9os43@M4fcWoIVPp4iYdjTtY2UV17tG9Sk323Oe1oe3x8r2EErLpOqFetyPTY8Yqq1OFf/PdTDFvdacYjItrRy7Fk3UHOnYlA2F0xFv8smfrTEXtH/S38C2t4q/bBu2NO0ua8/lzEeoyn7@8fwym691i8gM) ``` qZsm:.BQjk*4]dZ2 m 2 for d being the natural numbers below 2 ]d [d] *4 [d,d,d,d] jk "dddd" : Z search for the above in .BQ the binary representation of the input (true/false) s sum the 2-element array generated above, 1 for True, 0 for False qZ is equal to 0 ``` [Try it online!](http://pyth.herokuapp.com/?code=qZsm%3A.BQjk%2a4%5DdZ2&test_suite=1&test_suite_input=%22U3%22%0A%2248%22%0A%22Foobar%22%0A%22Feeber%22%0A%22%24H%22%0A%22%22&debug=0) ## Binary ``` 01110001 01011010 01110011 01101101 00111010 00101110 01[0000]10 01010001 01101010 01101011 00101010 00110100 01011101 01100100 01011010 00110010 ``` ## Tricks The following alternations are done to avoid the demerits: * Using `qZ` (is equal to zero) instead of `!` (negate) * Using `:xy0` (search for) instead of `}xy` (is sublist) * Using `Z` (variable, default to zero) instead of `0` (zero itself) ## Improvements I do not find any way to circumvent the penalty. We have these commands related to binary: * `.B` binary (`00101110 01[0000]10`) * `C` charcode (`01[0000]11`) * `.O` octary (`00101110 0100[1111]`) * `.H` hexadecimal (`00101110 01001[000`) Note that `.H` will also give us a penalty, because every printable character has its binary representation starting with `0`. Therefore, I used the most direct one, which is `.B`, directly converting it to binary. I can end with `.H` to avoid the penalty, but it costs me 27 bytes... ## Generation I found all allowed characters, which are those that do not contain `0000` or `1111`, and that do not end with `000` (because the next character must start with `0`): * `"#$%&')*+,-.12345679:;DEFGIJKLMNQRSTUVWYZ[\]bcdefgijklmnqrstuvw` Here are the characters that end with `1000`. They can only be used at the end: * `(8HXhx` ]
[Question] [ Output one random character for each character of source code (as illustrated below). The probability of each character is its frequency in the original source code. Thus the output will be fake source code resembling a quine. # Specification * **Restrictions** + Standard [quine](/questions/tagged/quine "show questions tagged 'quine'") constrains apply. No empty programs or functions. Also no reading your own source. * **Output** + The number of characters output should be exactly the number of characters in the source code + *Each* output character should be randomly choosen + The probability of choosing any character is equal to `(occurrences in source) / (length of source)` + This means that even a unary solution needs to 'randomly' choose `1` with probability `1`. Which is to say that the output can't be hard coded. * **Winning** + This is code golf, so fewest bytes wins # Example ``` Program Frequency Probability Possible Output ------- --------- ----------- --------------- a@!@ a - 1 a - 25% @@a@ ! - 1 ! - 25% @ - 2 @ - 50% ``` ``` Program Frequency Probability Possible Output ------- --------- ----------- --------------- caBaDBcDaBDB a - 3 a - 25% aaaBBBBccDDD B - 4 B - 33% c - 2 c - 17% D - 3 D - 25% ``` [Answer] # [Perl 5](https://www.perl.org/), 54 bytes ``` $_=q{print$_[rand@_]for@_="\$_=q{$_};eval"=~/./g};eval ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3rawuqAoM69EJT66KDEvxSE@Ni2/yCHeVikGLKcSX2udWpaYo2Rbp6@nnw7h/P8PAA "Perl 5 – Try It Online") Produces output like: ``` _anr_;q.=fn_}v"_eo_f=n\di{nqde}[;}}o}t==@$@$=nvr$}/r=. "q}=g{;}=[av$a}a__l[q@@;$;_}./@__a.ne=@@i_}_aet.=$=_o" /arr_r]po{{l_=;__e"_et=="@vr__a_}@nl"ll~$=~_q~d"=v$~$/ q/@=_$__{f{vl;.]@=__=@lpapr}da@eeg_[$@lr\_{{pq$$$vrq=/ =v{[_l=p{{={/n$nv$n[_/aev_v=@on}la;}q{_otr$oaglve$.a_} _aa;@r='{{=@{ntf;;.if}f}a$;$g/n;g;_}rroaqra=;}l.gre[t' ``` In a brief test, ~3-4% of the results of the program `eval` successfully. I'm not sure what that says about Perl... [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), 14 bytes ``` {{E*`mR}`mR}E* ``` [Try it online!](http://cjam.tryitonline.net/#code=e3tFKmBtUn1gbVJ9RSo&input=) ### Explanation Each character appears exactly twice, so the probabilities of the characters should all be the same. ``` { e# Repeat this block 14 times. {E*`mR} e# Push this (nonsensical) block. ` e# Stringify it, giving the string "{E*`mR}", which contains each of the e# seven characters once. mR e# Select one of the characters at random. }E* ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “;⁾vṾWṁ$X€”vṾ ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCcO-KBvnbhub5X4bmBJFjigqzigJ124bm-&input=) ### How it works ``` “;⁾vṾWṁ$X€”vṾ Main link. No arguments. “;⁾vṾWṁ$X€” Set the argument and return value to the string s := ';⁾vṾWṁ$X€'. Ṿ Uneval; construct a string representation of s. This yields r := '“;⁾vṾWṁ$X€”'. v Dyadic eval; evaluate s with argument r. ;⁾vṾWṁ$X€ Evaluated link (s). Argument: r ⁾vṾ Yield 'vṾ'. ; Concatenate r with 'vṾ'. This yields t := '“;⁾vṾWṁ$X€”vṾ', i.e., the original source code. $ Combine the previous two links into a monadic chain. W Wrap; yield ['“;⁾vṾWṁ$X€”vṾ']. ṁ Mold; repeat ['“;⁾vṾWṁ$X€”vṾ'] once for each charcter in t. X€ Random each; select a character, uniformly at random, of each of the 13 repetitions of t. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 22 bytes ``` "+Q ²£ZgMqB"+Q ²£ZgMqB ``` [Test it online!](http://ethproductions.github.io/japt/?v=master&code=IitRILKjWmdNcUIiK1EgsqNaZ01xQg==&input=) ### How it works ``` "+Q ²£ZgMqB"+Q ²£ZgMqB // Implicit: B = 11 "+Q ²£ZgMqB" // Take this string. +Q // Append a quotation mark. ² // Double the result. £ // Replace each char in the result Z with Zg // the char in Z at index MqB // random integer in the range [0, 11). // Implicit: output last expression ``` [Answer] # Pyth, 16 Bytes ``` smO+N"m1NOs+6"16 ``` [**try it online!**](https://pyth.herokuapp.com/?code=smO%2BN%22m1NOs%2B6%2216&debug=0) Contains each char twice therefore the probability is the same as if each was only in there once. ``` smO+N"m1NOs+6"16 # +N"m1NOs+6" # Add a quotation mark to the string: "m1NOs+6 O # random choice from the string m 16 # do this 16 times. s # join the list into a string ``` [Answer] # PHP, ~~71~~ ~~140~~ ~~110~~ ~~124~~ ~~140~~ 120 bytes ``` for($i=2*$n=strlen($s='for($i=2*$n=strlen($s=.chr(39));$i--;)echo$s[rand(0,$n-1)];'.chr(39));$i--;)echo$s[rand(0,$n-1)]; ``` run with `php -d` 1. creates a string containing the code without the quotation marks 2. and concatenates the quotation mark *once* using `ord` (same probability as if I would double the string and add two quotes); 3. then loops over twice the length of the string to get random characters from it. Can possibly be golfed further, but my attempts on eval where futile so far. I will probably not go deeper here. [Answer] **Python 2, 88 bytes** ``` s='''from random import*; print "".join(choice(s) for c in "s='"+s+"';exec s")''';exec s ``` All *actual* merit in getting this far goes to mbomb007 - thanks for your help (and the pointer about backslashes) [Answer] ## Ruby, 47 bytes ``` eval r="47.times{$><<('eval r=%p'%r)[rand 47]}" ``` This is based on the standard `eval` quine: ``` eval r="$><<'eval r=%p'%r" ``` It's a byte longer than the shortest quine, but it's usually the better choice for generalised quines, because any computation done on the source code string does not need to be duplicated. Whereas in the usual quine, every additional computation needs to go both inside and outside the main string, it is only needed inside the main string for this kind of quine. As for what the code actually does: after obtaining a string representing the entire source code, we simply select a random character (by selecting a random index) 47 times and print each character separately. [Answer] # Wolfram Language/Mathematica, 109 Bytes ``` Function[Print[StringJoin[RandomChoice[StringSplit[StringJoin[ToString[FullForm[Slot[0]]],"[]"],""],109]]]][] ``` sample output: ``` niPi[no,ili[Siu[,Sdoio9nthg"t ginuu[1[o]"i,icgi[0TncrS"[ln"o0]r,i][Jon[[et]0"]m [ri"a[]motrin,iFoFnultnnno,Jl ``` Oh those square brackets. [Answer] # JavaScript, 128 bytes ``` a=";a+=uneval(a);alert(a.replace(/./g,_=>a[Math.random()*64|0]))a=";a+=uneval(a);alert(a.replace(/./g,_=>a[Math.random()*64|0])) ``` Note: only works in Firefox due to the use of `uneval`. Sample runs: ``` )a(rgc=d6m_a4uar=hp(lll(,d=m=dee(M(gtraoan0)(M(aaaa(M]c)e)/M()/u//M6_n/a"*unea(/>atugrn(a=nav"|;)|=)/,ataa,aaangtue;am)t0;|ctoa/ =lvct;eee,,a.e=6r0;);Mtaaoa.aeea4)a[r.6]e/ll+l.)=)|a[(c"rao4ea/=_acaMh=veerva"a(_(d(l)lgn.;rM">=ea40a*).e(h(laa6r)4a)rhlar=t(ta[ [rt]ll]n))aota.e)g;>ae*;..4tt];l[;].*lnr4(mnM|alg(a.ag(.=e(a>>aa>.hga;a/pat+elc];apc=(ag)tao.).ll4u)dah]r(ul)>lr;,)ret(e/g(=_c*r M.r)_;.a(lraalg("mac>dmrlr"0/ah(a()ead|/0a(m.|u0)(a(0_[dn)a]/raal;eata)a.ataeaa*l)=ra()la=(a)*aaea>n;.a.)ca)orM(tm*a,a=)p;(>r)aa ``` [Answer] # Jelly, 44 bytes I hope I have interpreted all the rules correctly (I'm not *quite* sure what the "carry payload" thing is in meta or if it's even relevant to this challenge). ``` “ẋ2;8220Ọ;8221ỌXµ44СḊ”ẋ2;8220Ọ;8221ỌXµ44СḊ ``` Test it out at [**TryItOnline**](http://jelly.tryitonline.net/#code=4oCc4bqLMjs4MjIw4buMOzgyMjHhu4xYwrU0NMOQwqHhuIrigJ3huosyOzgyMjDhu4w7ODIyMeG7jFjCtTQ0w5DCoeG4ig&input=) This constructs a string from which to choose characters. The initial string has all the character used *except* the open and close quotes. It then doubles that string and concatenates *one of each* of the open and close quotes from ordinals (hence the need to double the other characters). Lastly it repeatedly picks random characters from the composed string to the length of the program. [Answer] ## Pyke, 35 bytes ``` 35F\";"\\+3322 5**F;H)s"\"2*+2* H)s ``` [Try it here!](http://pyke.catbus.co.uk/?code=35F%5C%22%3B%22%5C%5C%2B3322+5%2a%2aF%3BH%29s%22%5C%222%2a%2B2%2a+H%29s) To check: remove the final `H` and the resulting string contains the right number of each character (with the extra `H`) This does NOT use a generalised quine or in fact a quine at all. It relies on being able to create a string containing all the characters in the source. It *should* be able to do it for any code but each character logarithmically increases code size. The only number of times a character is allowed in the source is 2 or 7 [Answer] ## Ruby, ~~81~~ 67 bytes *Saved a bunch of bytes by stealing some tricks from Martin's solution* ``` s="s=%p;67.times{$><<(s%%s)[rand 67]}";67.times{$><<(s%s)[rand 67]} ``` I didn't realize that you had to randomly select every time; I thought a shuffle would do the trick. This can probably be golfed, but it's the shortest I could get it. [Standard Ruby quine](https://codegolf.stackexchange.com/a/80/31541) with a few modifications so it prints out the shuffled string. I'm sad because it took like fifteen minutes to figure out the formatting quirks before I realized that I was subconsciously stealing it anyway. I think the string shuffling can be shortened but I don't know how; I might also be able to finagle the formatting into being shorter once I put some thought into it. Help would be appreciated. [Try it online!](https://ideone.com/ClUmW2) [Answer] **C, 125 bytes** ``` char*s="char*s;l,i;f(){l=i=strlen(s);while(i--)putchar(s[rand()%l]);}";l,i;f(){l=i=strlen(s);while(i--)putchar(s[rand()%l]);} ``` **C, 60 bytes for golfed but not quine code taking any string** ``` l,i;f(char*s){l=i=strlen(s);while(i--)putchar(s[rand()%l]);} ``` While for counting characters my solution needed 86: ``` c[256];i;f(char*s){i=256;while(*s)c[*s++]++;while(--i)while(c[i]?c[i]--:0)putchar(i);} ``` [Answer] # C, 136 bytes ``` main(a){for(a=136;a--;)rand()%68?putchar("main(a){for(a=136;a--;)rand()%68?putchar([rand()%67]):putchar(34);}"[rand()%67]):putchar(34);} ``` Example output: ``` ;%7c(u)"r4-hd)nnr-%n6;6(4or(n4(6(a:=a3r-:()hp(:aa%;4rru}h;(a()3mh3rdi7));a-u36:r3on[4?p((]6n6?()-6t736unhr%:[%[[d(p:[ru)-n(6r=:](p-})8"] ``` This program outputs 136 characters randomly. The entire source code (less " quotation marks) is contained in a string. The program determines the probability of outputting a quotation mark as 2/136, otherwise outputting one of the other 67 characters randomly. There are two occurrences of each character in the string in the program. The probability of outputting a character from the string is 134/136. The probability of choosing a specific character in the string is 1/67. So the chance of outputting a character in the string is 134/136 \* 1/67 = 2/136. There are two occurrences of each string character in the program, so there is a 1/136 probability of outputting a character for each occurrence in the program. The order of symbols inside the string doesn't matter. [Answer] # [R](https://www.r-project.org/), 174 bytes ``` cat(sample(el(dimnames(a<-table(c("\n",el(strsplit(scan(,""),"")))))),174,T,a),sep="") cat(sample(el(dimnames(a<-table(c("\n",el(strsplit(scan(,""),"")))))),174,T,a),sep="") ``` [Try it online!](https://tio.run/##K/r/PzmxRKM4MbcgJ1UjNUcjJTM3LzE3tVgj0Ua3JDEJKJisoRSTp6QDlCsuKSouyMkEKk9OzNPQUVLSBGEw0DE0N9EJ0UnU1ClOLbAFinLRyNj//wE "R – Try It Online") The function `sample` performs discrete random sampling. Itcan take as 4th argument a vector `prob` of probabilities. The vector `prob` does not need to be normalized (i.e. it does not need to sum to 1): here, we use a vector of counts, and `sample` does the renormalizing. The 2 lines are identical. The 1st line does the hard work, and reads the contents of the 2nd line to get the counts of each character. So here, the vector of probabilities `a` actually sums to 87=174/2. Note the special treatment of the newline, which `scan` does not read. I can't think of a way of avoiding this without having to add more bytes to handle quotation marks. [Answer] # Python 3, ~~134~~ 132 bytes I use every character in my source code within the string the correct number of times, then multiply the string by two to include itself. The program prints a random character from that string for each character in the code (the length is hard-coded.) ``` from random import* for i in[0]*134:print(choice("""from random import* for i in[0]*134:print(choice(""*""2""),end='')"""*2),end='') ``` [**Try it online**](http://ideone.com/hzVgV2) I avoided backslashes like the plague. As soon as the code contains `\n` or `\"`, you have a problem, because the string doesn't contain backslashes yet, so you have to add those also, but in a separate string multiplied by a higher number, because it takes two backslashes to represent one (`\\`). ### Example output: ``` i(tc*"3]i o''r=,,,h34t"r ri"](fco t)niap)t "it2nc0o npoi3'"nto(*4 i(ido' r*4f"oi]d rm ,i"eif)m"d m emi dfr n*p 3*(i""r1d"dr menc hio' ``` I gotta say, it reminds me of FlogScript. [Answer] ## PowerShell v2+, 175 bytes ``` $d='$d={0}{1}{0}{2}-join(0..174|%{3}[char[]]($d-f [char]39,$d,"`n",[char]123,[char]125)|Random{4})' -join(0..174|%{[char[]]($d-f [char]39,$d,"`n",[char]123,[char]125)|Random}) ``` Quines in PowerShell suck, because the string replacement delimiters `{}` also denote loops and whatnot, so you need to use a *bunch* of `char`s in the `-f` operator, which bloats the code. Similar-ish to my [Quine on Every Line](https://codegolf.stackexchange.com/a/57648/42963) answer. Basically we loop from `0` to `174` and each iteration re-calculate the quine `$d`, cast it as a `char`-array, and pull out a `Random` element chosen uniformly from the input. By definition, this gives probability `(occurrences in source) / (length of source)` as required. Those characters are encapsulated in parens and `-join`ed together back into a string. ### Example ``` PS C:\Tools\Scripts\golfing> .\faux-souce-code.ps1 }}[${hr[`ini}}] [5i,=[]0,j2($=n4(dm]jh]jc]]7 }..j"rnj9|fn,4r]{9]('["jdh0}$rd,-f,a.c"}{h1 ]5d,),0n5|nh(]73a9da4aRi[5}a}430}}rd$,$r)-hhr%or79-R.R-`'r'aa|=1f0][|[{7}do1]$ja0 rd{h ``` (Yes, that's a newline in the output -- when a string containing a newline is `char`-array'd, the ``n` is treated as a character, since a `char`-array is just an array of byte codes, so it also has a 1/175th chance of being selected.) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 20 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` f←{(,⎕CR'f')[?⍴⍨20]} ``` `f←{`...`}` define **f** as `(,⎕CR'f')` listified (`,`) **C**haracter (table) **R**epresentation (`⎕CR`) of **f** (`'f'`) `[?⍴⍨20]` indexed with (`[`...`]`) random-up-to (`?`) repeat-itself-times (`⍴⍨`) of twenty Let us run it (with a dummy argument) a few times: ``` f⍬ )0'0](⍨(([],}⎕))⎕'f2 f⍬ {'['}f[←R[)2←?}⍨]}C2 f⍬ ,,⍨←?2}⍴?'⍨}C,'{⎕(C0 ``` Fine, but is the distribution correct? Let us run it on 10,000 dummy arguments and see how many times each character occurs: ``` {⍺ , 1E¯4× ⍴⍵}⌸ ∊ f¨ ⍳1E4 C 0.9952 ⎕ 0.9996 ' 1.9777 f 2.004 ← 1.0018 ⍨ 1.0173 0 1.0213 ] 1.0049 [ 0.9988 2 0.9943 { 0.9895 ) 1.0093 R 1.0054 , 1.0029 ? 0.9943 } 0.9861 ⍴ 1.0032 ( 0.9944 ``` Clearly, `f` and `'` occur twice as often as the other characters, just like in the original source code. How did we do it? ``` {⍺ , 1E¯4× ⍴⍵}⌸ ∊ f¨ ⍳1E4` ``` `⍳1E4` generates the first 10,000 integers `f¨` runs **f** on each of those numbers `∊` flattens all the pseudo-quines into a single 200,000-character string `⌸` is a higher-order function which for each unique character in the right side data, feeds the left-side function the unique element as left-argument and the indices where that character occurs as right-argument. The left-side function is ``` {⍺ , 1E¯4× ⍴⍵} ``` `⍺` left-argument, i.e. the unique character `,` followed by `1E¯4×` 1×10⁻⁴ times `⍴⍵` the shape of the right-argument (the occurrence indices), i.e.how many times it occurs Finally, `⌸` puts it all together in a table. [Answer] # C#, ~~277~~ ~~280~~ 268 bytes. ``` using System;class a{static void Main(){var s="using System;class a{static void Main(){var s=\"x5Cx5C\x5C\x5C\";Random d=new Random();for(int i=0;i++<268;)Console.Write(s[d.Next(0,134)]);}}";Random d=new Random();for(int i=0;i++<268;)Console.Write(s[d.Next(0,134)]);}} ``` Ungolfed: ``` using System; class a { static void Main() { var s="using System;class a{static void Main(){var s=\"x5Cx5C\x5C\x5C\";Random d=new Random();for(int i=0;i++<268;)Console.Write(s[d.Next(0,134)]);}}"; Random d=new Random(); for(int i=0;i++<268;) Console.Write(s[d.Next(0,134)]); } } ``` Pretty sure this works correctly. Sample output: ``` fn;i)(]ns;<ftt08et]i+ii8]m[W}dr{rmte,)t edayid 2s cmsee\;ta["e n;o}]iolys;t sftoR{.=g vs8;(sd isWrecn++iia]iuf"avs\i<{ee vfs[ensin\s i]0a(We.0ns R(2roo=ldxil\{t(o"aistt.;. r w"m1];idi}Ctitiindnn;M[,[+0(,o"]mca[rmnm)<;n"8ReaystinRsanr([(d,n\.ateiR sd.=[=;ttn.;wna)cCt[=+t{Wxs(\}rg ``` [Answer] # [Julia 1.0](http://julialang.org/), 50 bytes ``` (a=:(print.(rand("(a=:($(a)))|>eval", 50))))|>eval ``` [Try it online!](https://tio.run/##fVBLTsMwEN37FCPDwpZCSRbdRHJvwCpLQMiKp8GVcaKx03bBATgLx@IiwU6VqCCEF6P5@H1mDqOzujpPQZE@cc4noVUtBrI@bgRpbwSfO7dCSynfd3jUjhewLeVaTgn2WNXozV31DDdA@NYfESJp66zvIAVkbKZ0XgTJGvWAUW8GTQFzvYwky3Si@b/DDO716OJLiKYfIyi4JEyQKeBEMnUIjSVslz8Zte8JLFgPVV2VZckgvYU8WWfsN@anjGSt65PdxM8uqoTazJJNTN46ya49rmrh6@Mzm8tyy9wWwEHtIN2R@jGduE0xCqWElUXWunfou/gqcl6AsZ2NQW1Typ8i4Hmo/4aGFRiuYfN@0zc "Julia 1.0 – Try It Online") based on this quine: ``` (a=:(print("(a=:($(a)))|>eval")))|>eval ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/XyPR1kqjoCgzr0RDCcxW0UjU1NSssUstS8xRgrP@/wcA "Julia 1.0 – Try It Online") [Answer] # [R](https://www.r-project.org/), 136 bytes ``` a=scan(,"");cat(intToUtf8(sample(rep(c(10,utf8ToInt(a)),2),136,T))) a=scan(,"");cat(intToUtf8(sample(rep(c(10,utf8ToInt(a)),2),136,T))) ``` [Try it online!](https://tio.run/##K/r/P9G2ODkxT0NHSUnTOjmxRCMzryQkP7QkzUKjODG3ICdVoyi1QCNZw9BApxQoGJLvmVeikaipqWOkqWNobKYToqmpyUUNM/7/BwA "R – Try It Online") The "read-a-second-copy-and-sample-from-it" approach is shamefully copied from [Robin Ryder's answer](https://codegolf.stackexchange.com/a/231716/95126): please upvote that one. Here, however, rather than counting the instances of each character and using this to weight the sampling, we just sample uniformly from the full set of characters (including repetitions). [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 75 bytes ``` exec(a:='from random import*;print(*choices("exec(a:=%r)"%a,k=75),sep="")') ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P7UiNVkj0cpWPa0oP1ehKDEvBUhl5hbkF5VoWRcUZeaVaGglZ@RnJqcWayjBFKsWaSqpJupk25qbauoUpxbYKilpqmv@/w8A "Python 3.8 (pre-release) – Try It Online") ]
[Question] [ The age-old question - is it better to walk or run? There are two trains of thought. If you run, you cause the rain to effectively hit you from the front, which increases your surface area and basically causes you to run into the raindrops, getting hit with more water. However, if you walk, you spend longer in the rain. Actually, there is no good answer, because if the rain is about to get worse, you'd better run to get out of it even if you get hit more immediately, because you don't want to get hit by the rain later on. In fact, if you can't predict the future, you don't actually have a good way to know what the optimal strategy is. However, we are not subject to such constraints, and can take the future as input. ## Specification You are trying to get somewhere \$N\in\mathbb{Z}\_{\geq1}\$ metres away (\$N\$ will be supplied as input). However, it has started raining. For the next \$N\$ seconds, a certain amount of rain will be falling per second, and will be constant within the span of a 1-second period of time. Specifically, during the \$i\$th second (\$1\leq i\leq N\$), there will be \$a\_i\in\mathbb{Z}\_{\geq0}\$ units of rain. You will also be given \$\{a\_1,a\_2,\dots,a\_N\}\$ as input. It rains the same amount at all locations across that distance, but once you reach your destination, you will no longer get hit by rain. Now, you want to know how to get rained on the least. During each second, you must either walk or run. On the \$i\$th second, if you walk, you will move 1 metre and get hit by \$a\_i\$ units of rain. If you run, however, you will move 2 metres but get hit by \$2a\_i\$ units of rain. Note that if you are 1 metre from the finish, if you run, it only makes sense to be hit by half of that because you're in the shelter after the first half-second, but since \$\frac{2a\_i}2=a\_i\$, you can just walk instead, so you don't really need to consider this case. What is the least amount of rain you can get hit by in order to cross those \$N\$ metres? ## I/O Format You may take \$N\$ as an input if you wish. Since it's the same as the length of the list, you're allowed to exclude it. You may take \$\{a\_1,a\_2,\dots,a\_N\}\$ as an input if you wish. I'm not sure how you'd solve the problem without it. You must output a single non-negative integer, the least amount of rain (in units) that you can be hit by in order to cross those \$N\$ metres. ## Example ``` 10 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` The rain is progressively getting worse. Clearly, every second you spend outside makes the rain worse, so it's better to get hit by double the amount now than wait and get hit by the larger amount later. If you run for 5 seconds, you will move 10 metres and get hit by \$15\times2=30\$ units of rain. In comparison, if you walk for 10 seconds, you get hit by 55 units. ``` 6 [1, 0, 1, 0, 1, 0] ``` The rain is acting weird. In this case, if you run for 3 seconds, you get hit by 4 units of rain. However, if you only run during the second and fourth seconds, and walk during the first and third, you still cover 6 metres, but here you only get hit by 2 units since you run during the time when the rain is stopped, and no rain doubled is still no rain. ## Test Cases ``` 7 [1, 0, 2, 5, 3, 0, 0] -> 11 1 [1] -> 1 6 [2, 5, 5, 2, 3, 1] -> 18 1 [5] -> 5 3 [3, 3, 5] -> 9 9 [1, 0, 3, 1, 1, 1, 3, 2, 3] -> 9 5 [3, 2, 0, 0, 0] -> 5 7 [3, 1, 4, 4, 3, 5, 3] -> 19 ``` You can generate more test cases [here](https://tio.run/##dU/NasMwDD7HTyF6ste0OB27FLJHyGm3rIxAnFUQy8ZxWvb0mdTSLQyGweL700/8yudAz8vSuwF8uDjd45RLSB2SOaoCBxAC6hoswyK5PCcCqwo3rrRqpUm0tSdxTG7FeyR9gKeHDtvfebCDw31mWx1PpvzHU608Rin0MaTMFPXBK@WpBN9BzV/USHwEUpyzNvspjsiVI9czjg7e0iyLNey9h/dSOKJ5giejCmnT/tGstDcwhAQf3Fqin043hi@NSQxTTgx55w2/LQjsbvCdBG92rz/87aqmhM48DGZZKgsv3w); the input accepts the max \$N\$ and the max \$a\_i\$. It's also an ungolfed reference implementation (the `move` function) (I could have probably figured out a DP relation to solve this more efficiently, but I was too lazy, and since it's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), I don't suppose anyone else will use a more efficient solution either...) ## Scoring * this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); since you are writing on your umbrella and have limited space, your code must be as short as possib- wait, you had an umbrella? [...] * [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden as usual * have fun and happy golfing! [Answer] # [J](http://jsoftware.com/), 44 39 27 bytes ``` #{0,[:<./]+/\@#~1+2#:@i.@^# ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/lasNdKKtbPT0Y7X1YxyU6wy1jZStHDL1HOKU/2typSZn5CsYGirYKqQpGAK16igY6SiY6igYg9kGUHmINJRjAeZBlJmC1QMVQyVNwXKmEI4lmGMMhCgCEGtAemDIGGIKshEQIQMUV1jCZIBaTMDIGOLW/wA "J – Try It Online") -12 after reading [rak1507's clever idea](https://codegolf.stackexchange.com/a/223785/15469)! Using 3 3 5 as an example: * `1+2#:@i.@^#` One plus all binary numbers from `0` to `2^<length>-1` ``` 1 1 1 1 1 2 1 2 1 1 2 2 2 1 1 2 1 2 2 2 1 2 2 2 ``` * `]...#~` Use each of those as a mask to replicate the input (trailing zeros are just fill): ``` 3 3 5 0 0 0 3 3 5 5 0 0 3 3 3 5 0 0 3 3 3 5 5 0 3 3 3 5 0 0 3 3 3 5 5 0 3 3 3 3 5 0 3 3 3 3 5 5 ``` * `+/\@` And scan sum each row: ``` 3 6 11 0 0 0 3 6 11 16 0 0 3 6 9 14 0 0 3 6 9 14 19 0 3 6 9 14 0 0 3 6 9 14 19 0 3 6 9 12 17 0 3 6 9 12 17 22 ``` At this point the problem is essentially solved, because the 3rd column is "how wet we are after moving 3 meters". All we need to do now is... * `[:<./` Take the min of all rows and... * `#{0,` Pluck the 3rd column. ## original approach, 39 bytes ``` [:<./1#.[(*2-~/\0,#<.+/\)"#.1+2#:@i.@^# ``` [Try it online!](https://tio.run/##VY7BCsIwEETvfsXQHGptuk0aAza0UBA8efLa4kUs6sU/8NdjzKZgyQYy@2Yn@/IZ5TN6hxwSCi7cinC8nE9@dB3VWtC43TXVp56UFB2V9VRkgnTZCDc8abgKX2zut8cbWqPHDB1iJBoJK2HiWyXOOIlDVGyz0R/MCdrILIs2ChPOqsHf/GaWMpzyH8EttdqiXUgY2ccyvKv/Ag "J – Try It Online") Tries all possible combinations. Using 3 3 5 as an example: * `1+2#:@i.@^#` One plus all binary numbers from `0` to `2^<length>-1` ``` 1 1 1 1 1 2 1 2 1 1 2 2 2 1 1 2 1 2 2 2 1 2 2 2 ``` * `+/\` Scan sum each row ``` 1 2 3 1 2 4 1 3 4 1 3 5 2 3 4 2 3 5 2 4 5 2 4 6 ``` * `#<.` Minimum of each element and input length, 3 in this case: ``` 1 2 3 1 2 3 1 3 3 1 3 3 2 3 3 2 3 3 2 3 3 2 3 3 ``` * `0,` Append 0: ``` 0 1 2 3 0 1 2 3 0 1 3 3 0 1 3 3 0 2 3 3 0 2 3 3 0 2 3 3 0 2 3 3 ``` * `2-~/\0` Successive deltas: ``` 1 1 1 1 1 1 1 2 0 1 2 0 2 1 0 2 1 0 2 1 0 2 1 0 ``` * `*` Multiply each by the input (J dyadic hook): ``` 3 3 5 3 3 5 3 6 0 3 6 0 6 3 0 6 3 0 6 3 0 6 3 0 ``` * `1#.` Sum rows: ``` 11 11 9 9 9 9 9 9 ``` * `[:<./` Minimum: ``` 9 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` ▼moΣ↑L¹MṘπL¹2 ``` A (sorta) port of my APL solution, just for fun. Husk is certainly an ... interesting ... language. -2 each from Razetime and Leo ``` ▼moΣ↑L¹MṘπL¹2 πL¹2 cartesian power of [1,2] of length of the list MṘ replicate moΣ↑L¹ sum of len(input) take each list ▼ minimum ``` [Try it online!](https://tio.run/##yygtzv7//9G0Pbn55xY/apvoc2in78OdM843ABlG////jzbWMdQxAUJjHVMd41gA "Husk – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes ``` f[a_,b___,c_]=a+Min[b~f~c,a+f@b] f@a_:0=a ``` [Try it online!](https://tio.run/##RU3LCoMwELz7FQGhF7eQGu0LLPmBQqFHkbCGBj3ooXgT8@tp3LUIy7A7Mzsz4NR9Bpx6iyG4Gg20xhiwpqkwe/Zj3XrnLWDmdNskTqO5ywrD69uPU50eH07rtDn4t8XRz8l8AiFB5CBKEIp2uUCkV2C2JDlqxJUrKLpp5f9V/Y9i/@bLOXOLZV9Bo7gz0pTCHQWRZxAXEFcQt@iXe82OS7KEHw "Wolfram Language (Mathematica) – Try It Online") Input `f[a1, a2, ..., aN]`. [Answer] # [Python 2](https://docs.python.org/2/), 51 bytes ``` f=lambda h=0,*t:t and h+min(f(*t),h+f(*t[:-1]))or h ``` [Try it online!](https://tio.run/##PY7dCoMwDIXv@xS5tJqBtetkgk8ivXA4aaHWIh1jT9/Vhg0Cycn58hM@0ey@S2kd3bw9lhnM2GIdhwizX8A0m/XVWtWRo2nOPA0XoTnfDzDpbax7ghgYeHSj9eEVK84gHNZHyLDjqUeYBEKL0CEoBFnqVjNxGprdciJHFST7gkylWRaTLL0s7v9NJ/MLSVOaKWI72l9O9NTK1LWEpA/0Fw "Python 2 – Try It Online") Essentially a port of my [Mathematica answer](https://codegolf.stackexchange.com/a/223787/81203). [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 23 bytes ``` {⍺⊃0,⌊⌿+\⍵/⍤1⍨⍉1+⊤⍳2*⍺} ``` Takes the length as ⍺ and the array as ⍵. ``` {⍺⊃0,⌊⌿+\⍵/⍤1⍨⍉1+⊤⍳2*⍺} ⍉1+⊤⍳2*⍺ all possible combinations of 1 and 2 of length ⍺ ⍵/⍤1⍨ replicate ⍵ +\ cumulative sum ⌊⌿ minimum reduce ⍺⊃0, take the ⍺-th item (prepend a dummy item so it works with 0 based indexing) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6sf9e561NVsoPOop@tRz37tmEe9W/Uf9S4xfNS74lFvp6H2o64lj3o3G2kB1dX@TwPqedTbB9TwqHfNo94th9YbP2qbCDQtOMgZSIZ4eAb/N1dIUzDUUTDQUTDSUTDVUTAGsw24DIHiOoZcZkAKImEKVgGUNgTLmXIZA0ljsIgplyXcFJACGDKGaOEyhag0ghgNMt0cIgJUYwJGxhC7AQ "APL (Dyalog Extended) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 53 bytes ``` f=lambda n,h=0,*t:n>0and h+min(f(n-1,*t),h+f(n-2,*t)) ``` [Try it online!](https://tio.run/##PY7dCsIwDIXv@xS5XLcI7WodDuaLjF5M5mihxiEV8elrf1AI9OScL0n3T7AP6mPcJr/cr@sChHYS2IaRLmKhFWx3d9RsDR1kcjnaLus@ax7f1vkbyJGlMT852l@h4Qz2p6MAicPW8zggzBJBIPQIGkEVLQyTOTDslJ6a6IKkXNZQG5aaWRUvNef/psz8StUpw3Rl@7q/nBiqlahjKVV/YL4 "Python 2 – Try It Online") Uses a kind-of sketchy splatted input format of `f(N, l_1, l_2, ..., l_N)`. **68 bytes** ``` lambda n,l:min(sum(l[:n-k]+sorted(l[:-k])[:k])for k in range(n/2+1)) ``` [Try it online!](https://tio.run/##PU7bCoMwDH3vV@SxxY7ZOicT/JKuDw51ltUoXhj7@q4XNghJz6UnWT77OKN0Q3N3tp0eXQvIbT0ZpNsxUatqPL10ts3r3ncBesRU7dswr/ACg7C2@OwpnmUmGHPv0dgeRE1CTmNwOXbKCCyrwR0G6knmKg5KcMg5SA4lhyK@c01EEDS5@pGUMlq8LpJYauKBKiLnwe2fFDy/KtIvTcrklSk/rqgS5V2XWEW6QH8B "Python 2 – Try It Online") An efficient solution, unlike the exponential-time solution above. Picks how many seconds `k` to walk, minimizing the sum of first `k` numbers plus the sum of the smallest `n-k` among them which are chosen to be doubled. Here's a nifty recursive version: **66 bytes** ``` f=lambda n,l:l and min(sum((l+sorted(l)+[1e999])[:n]),f(n,l[:-1])) ``` [Try it online!](https://tio.run/##PY7dCsMgDIXvfYpcKnVQ27mh0CeRXHS0pYK1pbWMPb2zygaB/JwvJ9k@YV59E@PUuX55DT147rSD3g@wWE@Pc6HUVce6h3GgjlVGjEopZEZ7ZHyiCTf6JpCx@J6tG0Focnl01m9noIzAtlsfIJMsPjkYwaHm0HCQHNpc10jEJSB5pFQUmZGkiyJKJKkxbZ6lRv2dLuYXbdlCIgvbFP984llGibrnaMsH@AU "Python 2 – Try It Online") [Answer] # JavaScript (ES6), ~~53~~ 52 bytes *Saved 1 byte thanks to @l4m2* Expects `(n)(list)`. ``` f=(n,[k,...a])=>n>0&&Math.min(f(n-1,a),f(n-2,a)+k)+k ``` [Try it online!](https://tio.run/##hZBNDoIwEIX3nqIrQuNQKFiRBdzAExAWDYIi2BohXh9Liz8g0cksZjHfey/vzO@8zW/VtXOEPBR9X8a2gLQGQgjPcJyIxLOsPe9O5FIJu7SFQ4FjGA5fHetabZ9L0cqmII08qpcQUEoBeYB8QAxQoG8vQ3owRq6LKF1NITpA48v3jNCM2SrGWDDtpYw@JEZmt2DE/hixGaOE00DrL5GGiWZM9GphiPXcwATNlhlmfHxT2LuzX9lCwyjtjd7AdD5tO@of "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 57 bytes A direct recursive implementation of the task. ``` f=lambda N,a:N>0and min(f(N-x,a[1:])+x*a[0]for x in[1,2]) ``` [Try it online!](https://tio.run/##hZBNboMwEEb3PsW3w26dCkOdFCRyBC6AUOUqQUHix6KkoaenY9M0EVVVywvP6M2bGdvP8dR30TxXWWPat4NBLk2a70PTHdDWHa94vpmkKVRaisfpwRRhWfUDJtRdoWRUivlyqpsjVMooZSX682iRYTCXV4rPIxdP77apRx5gs0cgGHWAIaI1lh8/TCNd3Q8TSChB0Lem7kbunpSxAwWgeahcIMs8Mu9AYyCUiCS0ROzfYYnboa5KMUXcffb3cRzbolhE2htJt65y2IvT6X91msUoYm/5EyYsYcl1CdfveuNlgvKGaW@LlhVXW9413XmMDM/@xsvHrL8k@QI "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 2ṗx@"Fṁɗ€§Ṃ ``` A dyadic Link accepting \$N\$ on the left and \$A\$ on the right that yields the smallest amount of rain. **[Try it online!](https://tio.run/##y0rNyan8/9/o4c7pFQ5Kbg93Np6c/qhpzaHlD3c2/f//3@x/tKGOgQ4UxwIA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/o4c7pFQ5Kbg93Np6c/qhpzaHlD3c2/T@8XB/I/v8/OtpcRyHaUEfBQEfBSEfBVEfBGMw2iI3l0gGJRxuCWWZAFkTeFKwQqMoQrsQUzAIKgTAQQfiWcINBimHIGKIdrMIUosMIYiPMUnOIKFCtCRgZQ5wFlIsFAA "Jelly – Try It Online"). ### How? ``` 2ṗx@"Fṁɗ€§Ṃ - Link: integer, N; list (of length N), A 2 - two ṗ - (implicit range of 2 = [1,2]) Cartesian power (N) € - for each (walk/run list, x): ɗ - last three links as a dyad - f(x, A): " - zip with: @ - with swapped arguments: x - repeat elements F - flatten ṁ - mould like (A) (i.e. cut to length N) § - sums Ṃ - minimum ``` [Answer] # Vim, 90 bytes ``` "aDqmdd{"cyGO0<esc>Gp:.,$sor n Go0<esc>ggVGJ0@awwhD:s/ /+/g 0C<c-r>=<c-r>" ,<c-r>b<esc>0"bD"cpG@mq@m0C<c-r>=min([<c-r>b]) ``` [Try it online!](https://tio.run/##K/v/XynRpTA3JaVaKbnS3d/AJrU42c69wEpPR6U4v0ghj8s9HyKWnh7m7mXgkFhenuFiVayvoK@tn85l4GyTrFtkZwsmlbh0wHQSWL2BUpKLUnKBu0NuoUMuTF1uZp5GNERRrCbX///mXMZchlwmQGjMZcpl/F@3DAA "V (vim) – Try It Online") This is vanilla vim (TIO supports V, which is backwards compatible with vim). Vim doesn't really do branching recursion (at least, I don't know a good way without just writing pure vimscript, and it's possible that would be shorter, but certainly less fun!), so this answer uses a method that's different from most of the existing answers. **tl;dr**: Takes N followed by the list, one int per line. Finds the minimum over prefices length `n-k` of the sum of that prefix plus its `k` smallest elements. Long version: ## How? We observe that, given a list `l` of length `n`, if we choose to run `k` times, we will always choose to run on the `k` smallest elements of the length `n-k` prefix of `l`, and we will avoid the length `k` suffix of `l` entirely. Thus, the solution can be arrived at by concatenating the length `n-k` prefix with the sorted version of itself, and taking the length `n` head of this new list which has length `2*(n-k)`. Once `2*(n-k)` becomes smaller than `n`, we must stop because we can't run more than `n/2` times. ``` "aDqmdd{"cyGO0<esc>Gp:.,$sor n " input like 3, [2, 1, 5] newline separated "aD " cut N into register a qm " def m: dd{ " delete current line, go to top "cyG " copy file contents into register c O0<esc> " prepend 0 Gp " go to end, paste register c below :.,$sor n " sort the new copy of l numerically " -> [0,2,1,5,1,2,5] Go0<esc>ggVGJ0@awwhD:s/ /+/g Go0<esc>gg " append a 0 at the end, go back to top " -> [0,2,1,5,1,2,5,0] VGJ " join all the lines by spaces 0@aw " go to the (n+1)th number w " go one more and **exit function if we can't** " note that the prepended and appended 0 were necessary for this magic stopping condition to work hD " go left to the preceding space and delete the rest of the line " -> '0 2 1 5' :s/ /+/g " replace all spaces with '+' " ->'0+2+1+5' 0C<c-r>=<c-r>" " eval the current line and replace it with the result " -> '8' ,<c-r>b<esc>0"bD"cpG@mq@m0C<c-r>=min([<c-r>b]) ,<c-r>b<esc> " append a comma followed by the contents of register b " -> '8,' 0"bD " cut the result of that into b (accumulates) "cp " write back the original list G@m " go to the end and recurse, causing the last element of l to get deleted at the start of m q@m " stop defining m, then call it " now register b contains a comma separated list of the sub-results 0C<c-r>=min([<c-r>b]) " take the min of those and replace the current (only) line with the result ``` The next iteration will look like ``` [2,1] -> [0,2,1,1,2,0] -> '0 2 1 1 2 0' -> '0 2 1 1' -> '0+2+1+1' -> '4' -> '4,8,' ``` and finally: ``` [2] -> [0,2,2,0] -> '0 2 2 0' -> **try to go past end of line and exit instead** ``` So after `m` terminates, the final state is ``` buffer: 0 2 2 0 b: 4,8, ``` And so the (only) line in the buffer gets replaced with the evaluation of `min([4,8,])` and we have the desired output: `4`. A note on the stopping condition `@aww`: In the common case, what we want to do is delete everything from the `n+1`st number onwards, which is achieved by just `@aw` (and no prepending/appending 0s). However, just `@aw` won't cause `m` to exist by error if it moves at all, i.e. even if there are just two numbers ('words') on the line, so we need the second `w` to actually cause `m` to exit, hence the need to prepend 0. (We also can't decrement `N` before reading it because that would fail when N=1--`0w` doesn't move 0 words because `0` isn't a count; it moves to the beginning of the line and then moves 1 word!). The appended `0` is so that we always have something to delete even when there are exactly `n` numbers left, otherwise we would stop without checking the prefix of size `n/2` for even `n`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` Åœʒà3‹}εœ€*}Oß ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cOvRyacmHV5g/KhhZ@25rUcnP2pao1Xrf3j@///mXNHGOgqGOgomYARkmwLJWAA "05AB1E – Try It Online") Tries all combinations by looking at every permutation of every integer partition of \$N\$ which only consists of 1's and 2's. Porting rak's APL answer will probably be shorter. [Answer] # [R](https://www.r-project.org/), ~~68~~ 67 bytes *Edit: -1 byte thanks to detective work by Giuseppe* ``` f=function(t,r,s=r[1])`if`(t>0,s+min(f(t-1,u<-r[-1]),s+f(t-2,u)),0) ``` [Try it online!](https://tio.run/##jZHNCoMwDIDvPkVhl5al0Np1Tpi@iIwJw4KHdaCVPb7rj0M7FRZ6KGm@fCHtxmer7@/G6Kbvi1EVatAP0740NtBBX3QVv5G6VTU2JYP@aKuxwoZyGK60q6h9tVmXSWEgBBhZNsQZoAfmgBigFJAEJPydEYLmOCBaIs6TJcg9GJWtI4ARd3ZcUEnvtMJVm8Bd1kL5j1BGnHCc8J592nN5xOXzZtyI3yPC0FOnDU5OvjQs8neXu3NmE2cdJ39E@I@Nn8iT8QM "R – Try It Online") A recursive function that pretty much follows the logic of the explanation. Note to [R](https://www.r-project.org/) golfers: I thought it should be possible to still save a byte by assigning the twice-used `r[-1]` to a variable at the first use (since `u<-r[-1]` and `u` together are shorter than two `r[-1]`s), but I just [couldn't seem to make it work](https://tio.run/##TYzBCsIwEETvfsWCl106gWxFvJj@SBELpYEcjJBN8PNj9aJzmsc8pvRHyvfXVvNmFnoMseW1pmfmigILZdabLCkuXCcPG3abbYhc3Yh2dWV2@44PK5oIvPwf8gW0soI8aASdQadv9yL0y5HcRKqH/gY). Giuseppe has now managed to to make it run by just swapping the order of the arguments to `min` or by using a different variable name, which is rather wierd and doesn't fill me with unbounded confidence about [R](https://www.r-project.org/) for my real-world work... [Answer] # [Julia 0.6](http://julialang.org/), ~~50~~ 44 bytes ``` n<r=n>0&&(!i=r[]i+(n-i<r[2:end]);min(!1,!2)) ``` [Try it online!](https://tio.run/##hZDdDoIgGIbPuwpcm8OFGz@hqeiNMA/a6oBmrLG6fkKYZKaLccDB87zfx3t7DepcWKuFaXWH0xQmqjWyVweocyWMpPVVX/qsuSsNE4ISmmX2YZR@DhoSLCSpCW76DKyffd4BhneTUDoeAYwARYAjwPwbz@1RICQKxAmb4R8h8oWQIZr7GW7AUvf8aT6A/x/AI8@EZD530xr5KvLV9ONxlemysFxI@Oa5z6ehmEU3a/uUnneZR39Z6PWn0cq@AQ "Julia 0.6 – Try It Online") Thanks to MarcMush for -6 bytes. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~39~~ 30 bytes ``` I⌊EΦEX²⊕LθΦ⍘ι12μ⁼ΣιLθΣEι×Iλ§θμ ``` [Try it online!](https://tio.run/##VU7NCoMwDH6V4ilCd9Btp5224UCYILibeCgatNDW2dZtb99l6mUhhC98P0k7CNuOQoVQWmk8XIXzUEgj9ayhEE@4SeXRLrAc34RSznLTWtRoPHZwR9P7AaY4jjnbxBfhsPKU14PkLErSiDj9E2TTLJSDisIlrX/martIlofU6NZfFDFnn5sOPzAtKWudQqjrPWcJZ4elCR9pNk3YvdQX "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ² Literal 2 X Raised to power θ Input array L Length ⊕ Incremented E Map over implicit range ι Current index ⍘ Convert to string 12 Using digits `12` Φ μ Remove leading digit Φ Filter strings where ι Current string Σ Digital sum ⁼ Equal to θ Input array L Length E Map over strings ι Current string E Map over characters λ Current character I Cast to integer × Multiplied by θ Input array § Indexed by μ Current index Σ Take the sum ⌊ Take the minimum I Cast to string Implicitly print ``` Previous less brute-forcey 39-byte version: ``` ≔⟦υ⟦ω⟧⟧ηFθ⊞η⁺⁺§η±²2⁺§η±¹1I⌊E⊟ηΣEι×Iλ§θμ ``` [Try it online!](https://tio.run/##ZYy9DsIwDIR3nsLqZEthaIGpU8XEUFQJtihDVEITqUl/0gJvH0IpE9bpZJ8/Xa3lWHeyDaHw3jQO@cyAP4VgoCnf3LsRcCCoZq9RM6ja2eNixXRyN/X6hGfVyElhRsQgyRJasX8iXYg0IYrV1WjchEfpJyyNM3a2WMoeq65HHbHLehsGV2OV/5Jt/Px6BwaW1slD4HzHIGWwXxT3Q3QhwvbRvgE "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⟦υ⟦ω⟧⟧η ``` Start with an (empty) list of ways of walking and running to get to a distance of `-1` and a list of one (empty) way of walking and running to get to a distance of `0`. ``` Fθ⊞η⁺⁺§η±²2⁺§η±¹1 ``` Build up the ways of walking and running to get to distances of `1`..`N`. ``` I⌊E⊟ηΣEι×Iλ§θμ ``` For each way of walking and running to get to a distance of `N`, calculate the amount of rain, and output the minimum. ]
[Question] [ When you edit a post on SE, any further edits within a 5-minute grace period are merged into it. Given a list of times you edit a post, count the edits not in a grace period. Say you edit at minutes `[0,3,4,7,9,10,11,12]`. This results in 3 edits at times `[0,7,12]`, with the rest happening in their grace periods. ``` 0: [3,4] 7: [9,10,11] 12: [] ``` * The first edit is at minute 0. The edits at minutes 3 and 4 are within its 5-minute grace period, and so don't count. * The second edit is at minute 7. The edits at minutes 9, 10, 11 are within its grace period. * The third edit at minute 12 is just past the edge of the 5-minute grace period starting at minute 7. So, the output is 3. The list of times in minutes will be an list of increasing integers. The first number will always be 0 for the initial posting, which we count as an edit. **Test cases:** ``` [0] [0,3,5,7] [0,3,4,7,9,10,11,12] [0,30,120] [0,4,8,12,16] [0,4,8,12,16,20] [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] [0,5,10,15,20] [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] [0,1,4,5,9,11,12,14,16,18,23,24,26,28,29,30] ``` Outputs: ``` 1 2 3 3 3 3 4 5 5 6 ``` For ease of copying, here are the inputs, outputs, and input/output pairs: ``` [[0], [0, 3, 5, 7], [0, 3, 4, 7, 9, 10, 11, 12], [0, 30, 120], [0, 4, 8, 12, 16], [0, 4, 8, 12, 16, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [0, 5, 10, 15, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 4, 5, 9, 11, 12, 14, 16, 18, 23, 24, 26, 28, 29, 30]] [1, 2, 3, 3, 3, 3, 4, 5, 5, 6] [([0], 1), ([0, 3, 5, 7], 2), ([0, 3, 4, 7, 9, 10, 11, 12], 3), ([0, 30, 120], 3), ([0, 4, 8, 12, 16], 3), ([0, 4, 8, 12, 16, 20], 3), ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], 4), ([0, 5, 10, 15, 20], 5), ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 5), ([0, 1, 4, 5, 9, 11, 12, 14, 16, 18, 23, 24, 26, 28, 29, 30], 6)] ``` **Leaderboard:** ``` var QUESTION_ID=141949,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/141949/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] # JavaScript, 36 bytes ``` f=$=>$>f&&1+f($.filter(b=>b-$[0]>4)) ``` [Try it online!](https://tio.run/##nY/NCsIwEITvPkUPRRKcFjdN@oM0L1IKRm2kpTai4uvXtOAf3jztzjDfsNuZu7nuL@35Fg3u0IyjLcNSh9oul7SyLIxt29@aC9uVeheF1brWkvNx74ar65u4d0dWLYLA@5gHEihkbyGRoQCtQQQSL99r8UIkci9B6Y@Bd4gg5jqF1FfmH6WgBCRBagIoA3m4eGJqjqn/i77IiSqeYTnHcogEQkL4Y/1e@N/qRR2fzJmZUltmOI871w7bYMs34wM) ### How it works In each recursive call we delete all elements from the array which are more than 4 minutes distant from the first element. There is a little trick with variable name `$`. The check `$>f` firstly converts the array to a string and then compare it to the string representation of the function `f` and then compares them lexicographically. The first character of stringified array is a digit and therefore only one-char variable name whose ascii index is smaller than indices of all digits is `$`. Replacing `$` with any other variable name will always return `false`. [Answer] # Mathematica, ~~46~~ ~~40~~ ~~37~~ 33 bytes ``` (i=1;j=0;#-j<5||(i++;j=#)&/@#;i)& ``` ### Explanation ``` i=1;j=0 ``` Set `i` to `1` and `j` to `0`. ``` ... /@# ``` Map onto all elements of the input... ``` #-j<5||(i++;j=#)& ``` If `(element) - j < 5` is false, then increment `i` and set `j` to the element (short-circuit evaluation). ``` ;i ``` Output `i`. [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` Γ(→₀f>+4 ``` [Try it online!](https://tio.run/##nY@xDcIwEEV7pqAM4he@8zm2GxaJ0iIkRENEDykYgOzCAAzAEF7EXJwgoKX7/@79r7vdqdvn5aHqUn85rh73/ByqdL2l/rzdrCXn3Jh20RhYOPhZCTwiyIAIxNNQDU@kIKgG1b8O85rApcKh1prwVQSyIAG5kSYP0mQsGVcY92fFJzZG4puUwgSwBQtYD1Qd9ZP2BQ "Husk – Try It Online") ## Explanation ``` Γ(→₀f>+4 Implicit input, a list of numbers. Γ( Deconstruct into head n and tail x (if empty, return 0). f>+4 Keep those elements of x that are greater than n+4. ₀ Call main function recursively on the result. → Increment. ``` [Answer] # [Python 2](https://docs.python.org/2/), 58 bytes ``` a=input() x=[0] for k in a:x+=[k]*(k-x[-1]>4) print len(x) ``` [Try it online!](https://tio.run/##BcFBCoAgEADAu6/wqLWBW0EU2EcWDx2KxFhFDOz1NpO@ckceWzus5/QWpUW1ZJy4YpZBepbHVntLwXUqDJUGdPusRcqei3xOVlW3RgYmmGGBFdAAIuDofg) * Saved 2 bytes thanks to @Mr. Xcoder. ## 49 bytes ``` f=lambda a:a>[]and-~f([x for x in a if x-a[0]>4]) ``` Using the recursive method shown in @ThePirateBay's [solution](https://codegolf.stackexchange.com/a/141959/6710). * Saved a byte thanks to @Mr. Xcoder. * Saved 2 bytes thanks to @Halvard Hummel. [Try it online!](https://tio.run/##DcqxCoAgFEbhV/nHghtoBVGQLyION0ISSkUcbOnVzeEMB7745iv4sVa73/wcJ4M3VtqwP4fPdrrAhoQC58FwFmVgLYyaTV9jcj6jGUGYCDNhIawE2V7K1tjQDw) [Answer] ## Husk, 6 bytes ``` Lüo<+5 ``` [Try it online!](https://tio.run/##nY@xDQIxEARzqiAEsYH37HvbEiXQwetzJISQeFEAFEVEBJ3QiLn3PwJSst272dXd9tTvyny/6J@X83F5v5bN43ZYr7SU0rpu1jp4KOKkAiIy6ECCMg7NyEgGJNNg8@swrQmpFYrGatJXEejBAOpAM4KWzDWjldE/Kz6xIZLfZKhMgnhIgNiBprN90r0A "Husk – Try It Online") ``` o<+5 a function that takes two arguments and checks if the second is less than the the first plus 5 ü remove equal elements from the input list using the above function as the equality test L return the length of the remaining list ``` [Answer] # MATLAB, 34 bytes ``` @(x)nnz(uniquetol(x+1,4/max(x+1))) ``` Anonymous function that inputs an array and outputs a number. This uses the [`uniquetol`](https://es.mathworks.com/help/matlab/ref/uniquetol.html) function, specifically its form `y = uniquetol(x, t)`, which gives `y` containing unique elements of `x` with tolerance `t`. In doing so, the function [seems](https://stackoverflow.com/questions/46101271/what-does-uniquetol-do-exactly) to follow a "lazy" approach: sort `x`, pick its first entry, and keep skipping entries for as long as they are within tolerance of the latest picked entry. That is exactly what is needed here. The `uniquetol` function automatically scales the specified tolerance by the maximum absolute value in `a`. This is why we need the division here. `x+1` is used instead of `x` to avoid division by 0. Verification of test cases: ``` >> f = @(x)nnz(uniquetol(x+1,4/max(x+1))); >> inputs = {... [0] ... [0,3,5,7] ... [0,3,4,7,9,10,11,12] ... [0,30,120] ... [0,4,8,12,16] ... [0,4,8,12,16,20] ... [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] ... [0,5,10,15,20] ... [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] ... [0,1,4,5,9,11,12,14,16,18,23,24,26,28,29,30] ... }; >> outputs = cellfun(f, inputs) outputs = 1 2 3 3 3 3 4 5 5 6 ``` [Answer] # [J](http://jsoftware.com/), 20 bytes ``` [:#(,}.~5>(-{.))/@|. ``` [Try it online!](https://tio.run/##nY9BCsJADEX3PcUHQVqwY5OZtDMVi/dwKRZx4wHUXn3MTKuISxeBn@T9T3KNccS@x7FflZunmWQo67upqu3hYYrifLrcMK4HNNhpWQi6RTlVAdSACMTzUBueSQefptT@dMuawDlC0GqM/w4iC3IgSTR1IHWG7JHMyL8RH1uyhDfpMuPBFuzAeqDqoJ/E@AI "J – Try It Online") ## Explanation ``` [:#(,}.~5>(-{.))/@|. Input: array A |. Reverse /@ Reduce from right-to-left {. Head of RHS - Subtract with LHS 5> Less than 5 }.~ Drop that many from , Join [:# Length ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ ~~19~~ ~~18~~ ~~15~~ ~~14~~ 11 bytes ``` v®y‹iy4+©\¼ ``` **Explanation:** ``` v # loop on input ® # push register_c, start at -1 y‹i # if current item greater than last item y4+ # push new max on stack ©\ # push new max on register_c, and pop it from stack ¼ # increment counter_variable # implicit print of counter_variable ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/7NC6ykcNOzMrTbQPrYw5tOf//2gDHUMdEx1THUsdQ0MdQyMdQxMdQzMdQwsdI2MdIxMdIzMdIyDbUsfYIBYA "05AB1E – Try It Online") **Edit** * -3 bytes thanks to [Riley](https://codegolf.stackexchange.com/users/57100/riley) and the usage of counter\_variable * no need for counter\_variable after all * -3 bytes again thanks to [Riley](https://codegolf.stackexchange.com/users/57100/riley) and the usage of register\_c [Answer] # [Haskell](https://www.haskell.org/), ~~31~~ 30 bytes ``` f(x:y)=f[z|z<-y,z-4>x]+1 f x=0 ``` [Try it online!](https://tio.run/##nVDLasJAFN3PVxxCFwleIXcyURMaoYUWpIILlyI4wYRIrWmN4gP/PR1TbZNCW@hdDJc5z5lMF8/JclmWqb0PD06UTo6n4237QMe26u@nLRYp9pFbFlm@Xc7vE4Qh7Ic3aMI4y3fQDqI@NNqXYzCC7QiN2VUwQ4wTdBTFqCbC63Yz3qyHK1ijJ0ugOSfkmyxZ7xZFUqfewHq8GwxDWGi1YBeXaLNb@EhCnNTB2BHiRS9WxmSeVyEpJu603os/r8kjn7oNUNZBRV0KiF1iJpYNnlfjGVy6P6GKegYm7vxJoJ9NmGRVx6eOqdSrlSL2iBWxfzbgLrExCxo26svGr2T@9yD/30G/Op1dgqtYVbIeSY@kImkea/bA/F1D3xGifAc "Haskell – Try It Online") Saved 1 byte thanks to [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb) [Answer] # [Perl 5](https://www.perl.org/), 54 bytes 52 bytes of code +2 for `-ap` ``` {$_++;$p=shift@F;1while$F[0]<$p+5&&shift@F;@F&&redo} ``` [Try it online!](https://tio.run/##Ncm9CsIwGAXQV7lDyBIquW3TH6rQKZtPICKCkQaKCW3BQXx1P11cz8lhmZ3IS12MGVQ@rFO8b6Mf@JziHJQ/2fNeZeO0/s/otV7CLb1FLIgSFWo4NGjRoQd/SLAEK7AGHdiALdiB/SflLabHKsXR7SytFNf8BQ "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` æʒ¬s¥4›Ps_*}θg ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8LJTkw6tKT601ORRw66A4nit2nM70v//jzbQMdQx0THVsdQxNNQxNNIxNNExNNMxtNAxMtYxMtExMtMxArItdYwNYgE "05AB1E – Try It Online") [Answer] # [Ly](https://github.com/LyricLy/Ly), 29 bytes ``` &nr5+sp[[lL[pp2$]p5+sp>`<]]>` ``` [Try it online!](https://tio.run/##FcixCYAwFEXR/s4hNiL4ookK4gRuEAIWlkGCVk7/1fKc/JjV5@Wbu8SYt1iKq1L5ue5LSutu1iEcPQOewMjEjL4UcqhHA/IooBFNaMZ11h4v "Ly – Try It Online") It took a long time to get here. [Answer] # [Retina](https://github.com/m-ender/retina), ~~32~~ 26 bytes ``` .+ $*11 (1+)(¶1{1,4}\1)*\b ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRcvQkEvDUFtT49A2w2pDHZPaGENNrZik//8NuIy5TLjMuSy5DA24gIoMjQA "Retina – Try It Online") Explanation: ``` .+ $*11 ``` Convert to unary, but add 1, because 0 is a tricky concept in Retina. ``` (1+)(¶1{1,4}\1)*\b ``` Count the number of edits, but include all the grace edits in each match. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes ``` `ttX<4+>)t}@ ``` [Try it online!](https://tio.run/##y00syfn/P6GkJMLGRNtOs6TW4f//aAMdYx0THXMdSx1DAx1DQx1Do1gA) Or [verify all test cases](https://tio.run/##nY@xDsIwDER3/gRxQ85xmkRCiIFPYKhURSo7bFn59uCmRcDKdme/O9mPW723uc21jkc9nPb1eW5lvFzb5MpucvAIiJtSRGTQgQRlHZqRlVQk0@Dw67CtCekVAYPVpK8i0IMKhoVmBC2ZeyZ0JvxZ8YktkfwmtTMJ4iEKsQNNZ/ukvAA). ### Explanation ``` ` % Do..while t % Duplicate. Takes input (implicitly) the first time tX< % Duplicate and get minimum, i.e the first entry 4+ % Add 4 > % Greater than? Element-wise ) % Keep entries that fulfill that t % Duplicate. This is used as loop condition } % Finally (execute at the end of the loop) @ % Push number of iterations. This is the output % End (implicit). A new iteration is run if top of the stack is truthy ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 bytes ``` L&lbhyfg-Thb5b ``` This is a recursive function. Call it with `y[0 1 2 3 4 5 6 7 8)`, where `[...)` is your list. Alternatively, **[Try it here!](https://pyth.herokuapp.com/?code=L%26lbhyfg-Thb5b%3ByQ&input=%5B0%2C3%2C4%2C7%2C9%2C10%2C11%2C12%5D&debug=0)** or **[Verify all the test cases.](https://pyth.herokuapp.com/?code=L%26lbhyfg-Thb5b%3ByQ&input=%5B0%2C3%2C4%2C7%2C9%2C10%2C11%2C12%5D&test_suite=1&test_suite_input=%5B0%5D%0A%5B0%2C3%2C5%2C7%5D%0A%5B0%2C3%2C4%2C7%2C9%2C10%2C11%2C12%5D%0A%5B0%2C30%2C120%5D%0A%5B0%2C4%2C8%2C12%2C16%5D%0A%5B0%2C4%2C8%2C12%2C16%2C20%5D%0A%5B0%2C1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%2C11%2C12%2C13%2C14%2C15%2C16%2C17%2C18%2C19%5D%0A%5B0%2C5%2C10%2C15%2C20%5D%0A%5B0%2C1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%2C11%2C12%2C13%2C14%2C15%2C16%2C17%2C18%2C19%2C20%5D%0A%5B0%2C1%2C4%2C5%2C9%2C11%2C12%2C14%2C16%2C18%2C23%2C24%2C26%2C28%2C29%2C30%5D&debug=0)** --- # Explanation This is roughly equivalent to the Python solution. A translation would give the following results: ``` def y(b): return (len(b) and y(filter(lambda T:T>=b[0]+5,b)) + 1) ``` ### Code Breakdown ``` L&lbhyfg-Thb5b - Function called y that accepts a list parameter b. L - Define the function. lb - The length of b... & - ... Logical AND ... h - Increment by 1. y - The result given by calling the function recursively on the following: f b - b filtered... -Thb - ... For the elements whose difference compared to the first element... g 5 - ... Is greater than or equal to 5. ``` [Answer] # Java 8, ~~78~~ ~~61~~ ~~60~~ ~~59~~ 56 bytes ***Port of @JungHwanMin's answer*** ``` a->{int i=0;for(int l:a)if(l-a[i]>4)a[++i]=l;return-~i;} ``` [Try it online!](https://tio.run/##TY6xboMwEIZ3nsIjNIeFCY2aUhgrdeiUETG4xKCjxrbMkSqK6KtTUqGqN326@3X/18uLjK1Tpj9/Ljg464n1645PhJq3k2kIreEPeRC46UNjwxotx5G9SzTsFrBtRpK03l63/MubIdUpX9XANiyZYsUi4/KGhhgWSd5aH95ZP8sI21DHssK6zCJZ7XZYFzr3iiZv4m/M52Xtv/dsDlvdxeKZDatJeCKPpqtqJn03Rv/ETteR1MDtRNytEQoVl87pa2jUF/uzvCUgIINHOIIQIFIQGYgDiCdI95BmkB4gXfkI@2SOovz3@xzMyw8 "Java (OpenJDK 8) – Try It Online") [Answer] # C# .NET, 63 bytes ``` a=>{int e=0;foreach(int l in a)if(l-a[e]>4)a[++e]=l;return-~e;} ``` **Explanation:** [Try it here.](https://tio.run/##tZExT4UwFIV3fsUdIe9iaCkPSIXFxMk3OTiQNzS1T5tgSWjRGIJ/HQvR6AjDm9qbnPOde1ppY9n1ah6sNi/w@GmdeuOBbIW1cBoDAOuE0xLuByNvtXHNGcEfNUioZlHVox9AVQm/eIqQr@Eyt14CItKXsI1Fo841i0RzOKhz1fJeuaE38Zfi08yDv4D3Tj/DSWgTRksswF1nbNeqm6deO/WgjQplaNQHrEuMyRRFfIsOU8ww36FmmGOJJEFCkNDtRm@g27diWHg9kuN@B@6IIUjXShkefa3iXzEkKRKGJFuIJEfi6eVmbrZysiuusg@9YMtfGls5BdIUKUPqH8zfS/9DP8ApmOZv) ``` a=>{ // Method with integer-array parameter and integer return-type int e=0; // Amount of edits (starting at 0) foreach(int l in a) // Loop over the input-array if(l-a[e]>4) // If the current value minus the current edit is larger than 4: a[++e]=l; // Raise the edit-count by 1 first, // and set the current value to this next current edit // End of loop (implicit / single-line body) return-~e; // Return the amount of edits + 1 } // End of method ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 20 bytes ``` Fxg{Ix>i+4{++oi:x}}o ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZb3CrSqz0r7DK1Taq1tfMzrSpqa_MhUlAVN3WiDXQMdUx0THUsdQwNdQyNdAxNdAzNdAwtdIyMdYxMdIzMdIyAbEsdY4NYqCYA) #### Explanation ``` Fxg{Ix>i+4{++oi:x}}o # Implicit input on the command line Fxg{ } # for x in input: Ix>i+4{ } # if x > i+4: ++o # increment o (defaults to 1) i:x # i = x o # print o ``` [Answer] # Pyth, 25 bytes ``` J1K5FN.+Q=-KNIg0K=hJ=K5;J ``` Try it here: <http://pyth.herokuapp.com> [Answer] # [Proton](https://github.com/alexander-liao/proton), 40 bytes Heavily inspired by the [Python solution](https://codegolf.stackexchange.com/a/141955/59487). ``` f=a=>len(a)and-~f(filter(x=>x>a[0]+4,a)) ``` [Try it online!](https://tio.run/##Dcs7CoAwEAXA62zwCT6NvyK5iFgsaECQKCGFlVePtgNzpytfsZTg1Plzj6JG41a/QcJx5j3J4/zjdWnWykKNKXc6YpYgSwOiRQeLHgNGTJjBHwm2YAdasAcHcAQncF7//QE "Proton – Try It Online") [Answer] # Kotlin, 52 bytes *Posting as a function, if this is not acceptable I will change it to a method* ## Submission ``` {var x=it[0] var o=1 it.map{if(it>x+4){o++ x=it}} o} ``` ## Beautified ``` { // Last counted edit var x=it[0] // Current edit total var o = 1 // For each edit it.map{ // If it was 5 or more minutes ago if (it>x+4) { // Increase edit count o++ // Make it the last counted edit x=it } } // Return the edit count o } ``` ## Test ``` var r:(IntArray)->Int= {var x=it[0] var o=1 it.map{if(it>x+4){o++ x=it}} o} fun main(args: Array<String>) { println(r(intArrayOf(0))) println(r(intArrayOf(0,3,5,7))) println(r(intArrayOf(0,3,4,7,9,10,11,12))) println(r(intArrayOf(0,30,120))) println(r(intArrayOf(0,4,8,12,16))) println(r(intArrayOf(0,4,8,12,16,20))) println(r(intArrayOf(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19))) println(r(intArrayOf(0,5,10,15,20))) println(r(intArrayOf(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20))) println(r(intArrayOf(0,1,4,5,9,11,12,14,16,18,23,24,26,28,29,30))) } ``` [TryItOnline](https://tio.run/##rZAxT8MwFIR3/wqPtnKgPMdukopEYmRiYEQMXlJZtE5lDCqK8tuDHYHERDrg6Wzf@@70Xsd4dH75sIGHvXjw8T4E@ylv@iS7Zcrvl87F5/KFZT12xFy8Pdnz5AbhYn8ptJzGomDZNc9snJfh3fOTdV7YcHjb8xV49xSD84de8onxdM7pFo9eBOG@Ix8HUUop//hFBYN606NRowWVIAKpLXuyqa1cjSa5QLtrfdhEEtRa1WCX6ja/CoMqkAaZzKEalJjtBs2s0@bfY68BZlj7w9DrdANVQWmotIik27TljJmXLw) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 74 bytes ``` for($x,$y=$args[0];$y;$x,$y=$y){if($l-le$x-5){$i++;$l=$x}}$i+1+($l-le$x-5) ``` Iterative solution. Lengthy because of fenceposting on the `for` loop requiring an additional check on the end. *Golfing suggestions welcome.* We take input `$args[0]` as a literal array, peel off the first element into `$x` and the remaining into `$y`. Then, so long as there are elements still in `$y`, we loop. Each iteration, we check whether the current timestamp `$x` is `5` or more away from the `$l`ast edit timestamp. If so, we increment our counter `$i++` and set our timestamp to be current. Then, on the iteration of the loop, we peel off the next element into `$x` and leave the remaining in `$y`. Once we're out of the loop, we output `$i`, plus `1` for the initial edit, plus whether the final timestamp is more than five away from the last edit (with the Boolean value implicitly cast to integer). That result is left on the pipeline and output is implicit. [Try it online!](https://tio.run/##Tcm9CoMwGIXhm/kGQ46QE40/BKH3UTp0iK0QsMRBRbz21KFDt5fn/cxrSMs7xJjzOKdCNsg@yDO9lrt5eNn9T3Z1TGMhsYxBttKpQyatvcRBtvO8mvpv5pxvhQFhUaGGQ4MWHXrwQoIWrMAadGADtmAH9rBGfQE "PowerShell – Try It Online") [Answer] # [R](https://www.r-project.org/), 52 bytes ``` function(l){while(sum(l|1)){l=l[l-l[1]>=5] F=F+1} F} ``` [Try it online!](https://tio.run/##Dci9CoMwGAXQPU9RnBJ6hV41/kDTMS8hDkUaKnymUCsdrM@eesbzTuF0zVNY4/iZXlGL2b7PSR56WWctPxqziZNecuk53JwdlHf@zF35PQW9jPeocciQGaMuIAqUqGBRo0GLDjySYAGWYAVasAYbsAW79Ac "R – Try It Online") Simple anonymous function that iteratively removes elements from the list that are less than 5 away from the first element until the list is empty, then returns the counter. [Answer] ## Clojure, 53 bytes ``` #(count(set(reductions(fn[r v](if(<(- v r)5)r v))%))) ``` This keeps track of the "edit starting times", and then returns their distinct count. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` +4Ḣ<x@µÐĿL’ ``` [Try it online!](https://tio.run/##y0rNyan8/1/b5OGORTYVDoe2Hp5wZL/Po4aZ/w@3P2pa8/9/dLRBrI5CtIGOgrGOgqmOgjmCZwLk6ShY6igYAvmGhkBsBJMECRjBNALVWYD4QGyGRUhHAa4SaIYRzGigXWZgCyzQ7ABioApDoBJDU4h@Q6AqQ5B5llBzTKHqTalpNqpZEFMskTSaQDUAFRsBDTEC8o1AngPxLUFhEhsLAA) ## Explanation ``` +4Ḣ<x@µÐĿL’ Input: array A µÐĿ Repeat until the results converge +4 Add 4 Ḣ Head < Greater than x@ Copy only the true values L Length ’ Decrement ``` ## 12 bytes ``` ;I4<1;x@;ð/L ``` [Try it online!](https://tio.run/##y0rNyan8/9/a08TG0LrCwfrwBn2f/4fbHzWt@f8/OtogVkch2kBHwVhHwVRHwRzBMwHydBQsdRQMgXxDQyA2gkmCBIxgGoHqLEB8IDbDIqSjAFcJNMMIZjTQLjOwBRZodgAxUIUhUImhKUS/IVCVIcg8S6g5plD1ptQ0G9UsiCmWSBpNoBqAio2AhhgB@UYgz4H4lqAwiY0FAA "Jelly – Try It Online") ## Explanation ``` ;I4<1;x@;ð/L Input: array A ð/ Reduce A from left-to-right using ; Concatenate I Increment 4< Greater than 4 1; Prepend 1 x@ Times each of ; Concatenate L Length ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~62~~ 61 bytes *-1 byte thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ``` f(v,t,c)int*v;{for(t=c=0;*++v;)*v-t>4&&(t=*v)&++c;return-~c;} ``` [Try it online!](https://tio.run/##rZJhT4MwEIa/8ytOjEuBLqE45kjFP4J8MB2YRu0WxkgWgn8dr7RsTOcXXVJC7r33noPeifmrEH1fkobWVHhS1X7D23JTkToVacj9IGi45zfz@mkxm6HoN94sCASvinpfqfmn4F1/uy5KqQpQwELHQQZItd3Xu0zlWRTnkELbhhTCjoJ@31OIKTycCYtBSCgS8GH4RJO81qIJAd0rY2HL39SpH3nR2AZbL4dmqx/9GDoYWlhsEAxdTCOTEyq2JfHVO3zDGVAyqV3YGvRHyIkwjvSP6jgxtxR2HTcT2OxrOwJ9/cfPOx6D1586Vny8SEU8aB0AnD@QYY64AiAfFYcgkCYHoBMHpI4tZM6PeoV6Sez4Ze7ZTAmkgpsUDt4QA2wrdJfEvVuDOc/KpaAoHChUtqp43xWjHXHE3by5Q6pzOqfvsyzMKWSnhTpFF7ZpTJpVstF0Yy5IeiZW/vd8Ledsfa7FPmf9YXHy/As "C (gcc) – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 51 bytes Modified from [@Roberto Graham's Java answer](https://codegolf.stackexchange.com/a/141971/110802). Golfed version. [Try it online!](https://tio.run/##HcyxCoMwEIDh3ae4McEreNFKrY3g2KFPUDpcbYSUECUGaRGf3Uqn/5v@qWPH2/B8my7Cja0H84nGvyZoxxGWJEkAZnZgztCGwN/71ccH6Ab2goaNdbPMHMDqrO6HINzlwNL2wh1YWNkUksViU021XaV2tU1p3QDGYH10Xhjxn4oMCQs8YoVESAqpQCqRTqhyVAWqEtXuCvNMSpms2w8) ``` a=>{var i=0;for(l<-a)if(l-a(i)>4)a({i+=1;i})=l;i+1} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Ê©ÒßUfÈ-UΨ5 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yqnS31VmyC1Vzqg1&input=WwpbMF0KWzAsMyw1LDddClswLDMsNCw3LDksMTAsMTEsMTJdClswLDMwLDEyMF0KWzAsNCw4LDEyLDE2XQpbMCw0LDgsMTIsMTYsMjBdClswLDEsMiwzLDQsNSw2LDcsOCw5LDEwLDExLDEyLDEzLDE0LDE1LDE2LDE3LDE4LDE5XQpbMCw1LDEwLDE1LDIwXQpbMCwxLDIsMyw0LDUsNiw3LDgsOSwxMCwxMSwxMiwxMywxNCwxNSwxNiwxNywxOCwxOSwyMF0KWzAsMSw0LDUsOSwxMSwxMiwxNCwxNiwxOCwyMywyNCwyNiwyOCwyOSwzMF0KXS1tUg) [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 7 bytes ``` ˡ{C4+>‼ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FqtOL6x2NtG2e9SwZ0lxUnIxVHjBzc_RBrFc0QY6xjqmOuZQlomOuY6ljqGBjqGhjqERRBDIMYKoNNGxALJ1DM1QeTpQaUMdI7ARpjpmQGMskAzSMTTWMTTRMTQFqTY01zEE6rQE6zEFqzEl0wiENpAWS5hKE7AaCx0jYx0jEx0joAOBbEugT2IhfgcA) A port of [@Zgarb's Husk answer](https://codegolf.stackexchange.com/a/141957/9288). ``` ˡ{C4+>‼N ˡ{ Iterate the following block until it fails, and counts the number of iterations C Split the list into its head and tail 4+ Add 4 to the head >‼ Filter the tail by whether it is greater than the head + 4 ``` ]
[Question] [ The title of Numberphile's newest video, [13532385396179](https://www.youtube.com/watch?v=3IMAUm2WY70), is a fixed point of the following function \$f\$ on the positive integers: > > Let \$n\$ be a positive integer. Write the prime factorization in the usual way, e.g. \$60 = 2^2 \cdot 3 \cdot 5\$, in which the primes are written in increasing order, and exponents of 1 are omitted. Then bring exponents down to the line and omit all multiplication signs, obtaining a number \$f(n)\$. [...] for example, \$f(60) = f(2^2 \cdot 3 \cdot 5) = 2235\$. > > > (The above definition is taken from Problem 5 of [Five $1,000 Problems - John H. Conway](https://oeis.org/A248380/a248380.pdf)) Note that \$f(13532385396179) = f(13 \cdot 53^2 \cdot 3853 \cdot 96179) = 13532385396179\$. ## Task Take a positive composite integer \$n\$ as input, and output \$f(n)\$. ## Another example \$48 = 2^4 \cdot 3\$, so \$f (48) = 243\$. ## Testcases More testcases are available [here](https://pastebin.com/VKnL9eFF). ``` 4 -> 22 6 -> 23 8 -> 23 48 -> 243 52 -> 2213 60 -> 2235 999 -> 3337 9999 -> 3211101 ``` [Answer] # Python, ~~166~~ ~~162~~ 159 bytes You guys are much better. This is what I used! (the algorithm that solved it calls this) ``` from primefac import* def c(n): x=factorint(n) a='' for i in range(len(x)): l=min(x.keys()) a+=str(l) if x[l]>1:a+=str(x[l]) x.pop(l) return int(a) ``` [Answer] ## [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ÆFFḟ1V ``` [Try it online!](https://tio.run/##y0rNyan8//9wm5vbwx3zDcP@//9vCQQA "Jelly – Try It Online") ### Explanation ``` ÆF Get prime factorisation of input as prime-exponent pairs. F Flatten. ḟ1 Remove 1s. V Effectively flattens the list into a single integer. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ḋoọc;1xc ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7vyHu3uTrQ0rkv//t7S0/B8FAA "Brachylog – Try It Online") ### Explanation ``` Example input: 60 ḋ Prime decomposition: [5,3,2,2] o Order: [2,2,3,5] ọ Occurences: [[2,2],[3,1],[5,1]] c Concatenate: [2,2,3,1,5,1] ;1x Execute 1s: [2,2,3,5] c Concatenate: 2235 ``` You can use `ℕ₂ˢ` (*select all integers greater than or equal to 2*) instead of `;1x`, which is probably more readable and more in the spirit of Brachylog. [Answer] # [Mathics](http://mathics.github.io/), 34 bytes ``` Row[Join@@FactorInteger@#/.1->""]& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvs/KL882is/M8/BwS0xuSS/yDOvJDU9tchBWV/PUNdOSSlW7X9AUWZeiYJDmoMlEPwHAA "Mathics – Try It Online") -2 bytes from @sanchez [Answer] ## [CJam](https://sourceforge.net/p/cjam), 8 bytes ``` limF:~1- ``` [Try it online!](https://tio.run/##S85KzP1f/T8nM9fNqs5Q939sXq2F1n8TLjMuCy4TCy5TIy4zAy5LS0sQtgQA "CJam – Try It Online") ### Explanation ``` li e# Read input and convert to integer. mF e# Get prime factorisation as prime-exponent pairs. :~ e# Flatten. 1- e# Remove 1s. e# Implicitly print a flattened representation of the list. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` Òγʒ¬?gDië? ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8KRzm09NOrTGPt0l8/Bq@///LYEAAA "05AB1E – Try It Online") ``` Ò # Push list of prime factors with duplicates γ # Break into chunks of consecutive elements ʒ # For each ¬? # Print the first element gD # Push the length of this chunk twice ië # If not 1 ? # Print the length ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes ``` Òγvy¬sgD≠×J ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8KRzm8sqD60pTnd51Lng8HSv//9NLAA "05AB1E – Try It Online") **Explanation** ``` Ò # calculate prime factors with duplicates γ # group consecutive equal elements vy # for each group ¬ # get the head without popping sg # push the length of the group D≠× # repeat the length (length != 1) times J # join ``` [Answer] # Pyth, 12 bytes ``` smjk_>hddr8P ``` [Try it!](https://pyth.herokuapp.com/?code=smjk_%3Ehddr8P&input=9999&debug=0) ### alternative, 12 bytes ``` smjk<_AdGr8P ``` [Try that!](https://pyth.herokuapp.com/?code=smjk%3C_AdGr8P&input=9999&debug=0) ### explanation ``` smjk_>hddr8P PQ # prime factorization (already in correct order) of the implicit input: [3, 3, 11, 101] r8 # length encode: [[2, 3], [1, 11], [1, 101]] m # map over the length encoded list (lambda variable: d) >hdd # take the d[0] last elements of d (so only the last for d[0]==1 and all else) _ # reverse that list jk # join into a string s # conatenate the list of strings ``` [Answer] # Pyth, 11 bytes ``` jksm_-d1r8P ``` [Try here](http://pyth.herokuapp.com/?code=jksm_-d1r8P&test_suite=1&test_suite_input=4%0A6%0A8%0A48%0A52%0A60%0A999%0A9999&debug=0) [Answer] # [Python 2](https://docs.python.org/2/), 99 bytes ``` n=input() r='' p=2 while~-n: e=0 while n%p<1:e+=1;n/=p r+=str(p)*(e>0)+str(e)*(e>1);p+=1 print r ``` **[Try it online!](https://tio.run/##HcrBCoMwDIDhe54iF7G1iK236eLbBFoYWcgqsstevVP/2we/fmt@y9yaUBHdq/Ng1PegNMORy4t/oyyATBHwNkqnz7RwoLTKRApogT7VnPrB8RZ9uMA3kl/1/ECtSEVr7XH2Bw "Python 2 – Try It Online")** If inputs are restricted to be below `2147483659`, both `str(...)` may be replaced by ``...`` saving 6 bytes (this program will be **very** slow for numbers affected anyway!). [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), 11 bytes ``` o:_]D2<?O;J ``` [Try it online!](https://tio.run/##y8/I/f8/3yo@1sXIxt7f2uv/f0sgAAA "Ohm – Try It Online") ### Explanation ``` o:_]D2<?O;J o # Push prime factors with powers from input (Format [[prime,power],...] : # For each... _ # Push current element ] # flatten D # Duplicate power 2<? ; # Is the power smaller than 2? O # Delete top of stacks J # Join ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 19 bytes ``` k ó¥ ®¯1 pZlÃc fÉ q ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=ayDzpSCurzEgcFpsw2MgZskgcQ==&input=OTk5OQ==) ### Explanation ``` k ó¥ ® ¯ 1 pZlà c fÉ q Uk ó== mZ{Zs0,1 pZl} c f-1 q // Ungolfed // Implicit: U = input number Uk // Break U into its prime factors. ó== // Group into runs of equal items. mZ{ } // Map each item Z in this to Zs0,1 // Z.slice(0, 1) (the array of the first item), pZl // with Z.length added at the end. // This returns an array of prime-exponent pairs (Jelly's ÆF). c // Flatten. f-1 // Filter to the items X where X - 1 is truthy (removes '1's). q // Join the resulting array into a single string. // Implicit: output result of last expression ``` [Answer] # [PHP](https://php.net/), 88 bytes ``` for($i=2;1<$a=&$argn;)$a%$i?$i++:$a/=$i+!++$r[$i];foreach($r as$k=>$v)echo$k,$v<2?"":$v; ``` [Try it online!](https://tio.run/##HYtBCoMwFAX3nkLDU5QUpO7055uDSBcfsSYINaSQ66ehsxoYJriQjQ0uVJB4fljNBUX5fccenid6Ggh3/0gDpIW38FovkJGLNFojbvAvKschu@sRa/ni4hVpOHZ343ogmckqtSBRzj8 "PHP – Try It Online") [Answer] # [R](https://www.r-project.org/), 72 bytes ``` x=rle(pracma::factors(scan()));x$l[x$l<2]='';paste0(x$v,x$l,collapse='') ``` Requires the `pracma` package, which is not installed on TIO. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~15~~ 14 bytes Saved 1 byte thanks to @Adám ``` ∊⍕¨1~⍨∊⍉2⌂pco⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM9DUh0PeqdemiFYd2j3hVgTqfRo56mguT8R31TQUr@p3GZcKVxmQGxBRCbgAhTI5CIAZCwtLSEkJYA "APL (Dyalog Extended) – Try It Online") ``` ∊⍕¨1~⍨∊⍉2⌂pco⎕ ⎕ ⍝ Input 2⌂pco ⍝ Prime factors with exponents ⍉ ⍝ Transpose so the 1st column is factors, 2nd is exponents ∊ ⍝ Flatten 1~⍨ ⍝ Remove 1 ⍕¨ ⍝ Convert each to a string ∊ ⍝ Concatenate them together ``` [Answer] # C#, ~~206~~ 100 bytes ``` n=>{var r="";for(int d=1,c;++d<=n;){c=0;while(n%d<1){c++;n/=d;}r+=c>0?d+(c>1?c+"":""):"";}return r;} ``` Full/Formatted version: ``` using System; class P { static void Main() { Func<int, string> func = n => { var r = ""; for (int d = 1, c; ++d <= n;) { c = 0; while (n % d < 1) { c++; n /= d; } r += c > 0 ? d + (c > 1 ? c + "" : "") : ""; } return r; }; Console.WriteLine(func(4)); Console.WriteLine(func(6)); Console.WriteLine(func(8)); Console.WriteLine(func(48)); Console.WriteLine(func(52)); Console.WriteLine(func(60)); Console.WriteLine(func(999)); Console.WriteLine(func(9999)); Console.ReadLine(); } } ``` [Answer] # Javascript - 91 bytes ``` (x,r='',i=1,n)=>{while(x>i++){for(n=0;x%i<1;n++)x/=i;r+=(n>0?i+'':'')+(n>1?n:'')}return r} ``` ## Explanation ``` (x,r='',i=1,n)=>( // input x is the number to process, r, i, n are default values only while(x>i++){ // iterate over i until x for(n=0;x%i<1;n++) // iterate over n until i is not a factor of x x/=i; // factor i out of x r+=(n>0?i+'':'') // append i to r if n > 0 +(n>1?n:'') // append n to r if n > 1 // i+'' prevents adding i and n before appending to r } return r // return r by comma-operator and arrow function syntax ) ``` [Answer] # Java 8, 103 chars Pretty straightforward solution. ``` n->{String r="";int d=2,c;while(n>1){c=0;while(n%d<1){c++;n/=d;}if(c>0)r+=d;if(c>1)r+=c;d++;}return r;} ``` Ungolfed: ``` private static Function<Integer, String> f = n->{ String result = ""; int divisor = 2, count; while (n>1) { count = 0; while (n % divisor < 1) { count++; n /= divisor; } if (count > 0) result += divisor; if (count > 1) result += count; divisor++; } return result; }; ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 69 bytes ``` @(a)printf('%d',(f=[[~,c]=hist(b=factor(a),d=unique(b));d](:))(f~=1)) ``` [Try it online!](https://tio.run/##Dco5DoAgEADA1xh2EwptLDSb@A9CsVyRBpTD0q@jU0@2jR8/xgGMV4mpBRCTExICKfVKq@mMtYGhwLbl8i/pqKd4dw8GcXcaNkQILy2Ig1OFdcbxAQ "Octave – Try It Online") Ended up being quite long, but this will generate the desired output. Essentially we use the histogram function to count the number of occurrences of the unique values in the prime factorisation of the input value. * The result of the `factor()` function gives the prime factors in ascending order * we then find `unique()` values in that array * `hist()` returns the number of occurrences Once we have the two arrays (one for unique factors, one for counts), we concatenate the arrays vertically (one on top of the other), and then flatten. This interleaves the factors with counts. Finally we display the result as a string ensuring to skip any 1's in the final array. The only time 1's can appear is if the count was 1 because 1 will never be a prime factor. This elimination is done before converting to a string so it won't affect things like the number 10. [Answer] # [Ruby](https://www.ruby-lang.org/), 45 + 7 bytes Requires the flag `-rprime`. ``` ->n{(n.prime_division.flatten-[1]).join.to_i} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWiNPr6AoMzc1PiWzLLM4Mz9PLy0nsaQkNU832jBWUy8rPzNPryQ/PrP2f4FCWrQlEMQq2NoqGBsZGhoaGHJBBSFixsbm////yy8oARpT/F@3CGwwAA "Ruby – Try It Online") [Answer] # Pyth - 16 bytes ``` V{PQpNK/PQNItKpK ``` [Try it](https://pyth.herokuapp.com/?code=V%7BPQpNK%2FPQNItKpK&input=18&debug=0) Another solution: ``` sm`d-.nm(d/PQd){PQ1 ``` ]
[Question] [ Write a program that takes as its input a string that outputs a string with the following properties. * If a character in the string is an uppercase letter (ASCII 41-5A), then the character is replaced by a string containing every letter up to and including the original letter in upper case. For example, if the input string is `I`, then the output would be `ABCDEFGHI`. * Similarly, if a character is a lowercase letter (ASCII 61-7A), then the character is replaced in the same way. `i` would be replaced by `abcdefghi`. * If a character is a number (ASCII 30-39), then the character is replaced by every number starting from `0` and counting up to the number. * If the input contains concatenated individual characters, then the replacement sequences are concatenated together. * All other characters are printed without modification. *Sample inputs* (separated by blank lines) ``` AbC123 pi=3.14159 Hello, World! ``` *Sample outputs* ``` AabABC010120123 abcdefghijklmnopabcdefghi=0123.0101234010123450123456789 ABCDEFGHabcdeabcdefghijklabcdefghijklabcdefghijklmno, ABCDEFGHIJKLMNOPQRSTUVWabcdefghijklmnoabcdefghijklmnopqrabcdefghijklabcd! ``` This is code golf, fellas. Standard rules apply. Shortest code in bytes wins. --- To see the leaderboard, click "Show code snippet", scroll to the bottom and click "► Run code snippet". Snippet made by Optimizer. ``` /* Configuration */ var QUESTION_ID = 61940; // Obtain this from the url // It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 43444; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1; if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } 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="language-list"> <h2>Shortest Solution 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> <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> <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] # Pyth, 19 bytes ``` sXzsJ+rBG1jkUTs._MJ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?test_suite_input=AbC123%0Api%3D3.14159%0AHello%2C%20World%21&code=sXzsJ%2BrBG1jkUTs._MJ&input=AbC123&test_suite=0) or [Test Suite](http://pyth.herokuapp.com/?test_suite_input=AbC123%0Api%3D3.14159%0AHello%2C%20World%21&code=sXzsJ%2BrBG1jkUTs._MJ&input=AbC123&test_suite=1) ### Explanation ``` sXzsJ+rBG1jkUTs._MJ rBG1 the list ["abc...xyz", "ABC...XYZ"] + jkUT appends the string "0123456789" J save this list of 3 strings in J sJ join the strings in J ._MJ create all prefixes of the strings in J s and combine them to one list XzsJ s._MJ translate the input string, chars from sJ get translated to the correct prefix, chars that don't appear in sJ don't get translated s join all resulting translation strings ``` [Answer] # Python 2.7, ~~100~~ ~~98~~ 96 bytes ``` a=[] for c in raw_input():d=ord(c);a+=range(max(d&96|1,48),d)*c.isalnum()+[d] print bytearray(a) ``` [Answer] # [TeaScript](https://github.com/vihanb/TeaScript/), 24 bytes ~~26~~ ~~28~~ TeaScript is JavaScript for golfing ``` xl(#(i=lN()1)h(ii(l)+1)) ``` Pretty short [Try it online](http://vihanserver.tk/p/TeaScript/?code=xl(%23(i%3DlN()1).h(ii(l)%2B1))&input=AbC123) ### Explanation ``` x.l(# // Loops through each character of the string (i=l.N()1) // Determines whether a character is alphanumeric // Will return A-Z, a-z or 0-9 depending on result // Assigns to variable i .h( // Get characters up to... i.i // where the character is in "i" ) + 1 // Increased by one ) ``` [Answer] # Ruby, ~~137~~ ~~87~~ ~~82~~ ~~76~~ ~~67~~ 55 bytes Ungolfed, but you can see the pattern. ``` $><<gets.gsub(/[a-z0-9]/i){[*" 0Aa"[$&.ord/32]..$&]*""} ``` Edit: golfed down to only one regex. Edit 2: had a lot of extra spaces. Edit 3: Thanks to manatwork for golfing 12 bytes! [Answer] # Haskell, ~~95~~ ~~91~~ ~~86~~ 60 bytes ``` c#(a:o:r)|c<a||c>o=c#r|1<2=[a..c] c#_=[c] f=((#"AZaz09")=<<) ``` Usage example: `f "pi=3.14159"` -> `"abcdefghijklmnopabcdefghi=0123.0101234010123450123456789"` How it works: copy every char c in the input string unless c is in-between any of `A`/`Z`, `a`/`z` or `0`/`9` and if so take the list of `[<first char in pair> ... <c>]`. Edit: @Zgarb saved many many bytes. Thanks! [Answer] # JavaScript (ES6), ~~143~~ 138 bytes Uses string comparisons to test which characters to use. ``` s=>s.replace(/[A-Z0-9]/gi,c=>(a=btoa`Ó]·ã»óÖq×£Y§¢«²Û¯Ã³`,(c>'Z'?a:a.toUpperCase()).split``.filter(x=>x<=c&(x>'9'|c<'A')).join``)) ``` [Online demo.](https://jsfiddle.net/intrepidcoder/1f8LhL4y/) Tested in Firefox and Chrome. Edit: Saved 5 bytes by replacing `a='0123456789abcdefghijklmnopqrstuvwxyz'` with ``` a=btoa`Ó]·ã»óÖq×£Y§¢«²Û¯Ã³` ``` [Answer] # Python 2, ~~145~~ ~~140~~ ~~133~~ ~~103~~ 102 Bytes A not-so-sleek anonymous function using list comprehension. I feel like the logic should be much shorter, I'll try and figure something out. ``` lambda k:''.join([c,`map(chr,range(48+17*(c>'@')+32*(c>'`'),ord(c)+1))`[2::5]][c.isalnum()]for c in k) ``` Should be given a name to be used, i.e. `f=...` [Answer] # PHP, 146 bytes **Golfed** ``` function f($n,&$l){for(;$c=$n[$r],$b=0,$d=ord($c);$r++,$b?:$l.=$c)foreach([58=>48,91=>65,123=>97] as $m=>$i)while($d<$m&&$d>=$i)$b=$l.=chr($i++);} ``` **Revision 1:** put ord ranges directly into foreach. incremented ord range maxes and changed `$d<=$m` to `$d<$m`. using `for` to iterate chars instead of `foreach` and `str_split`. Removed all `{}` by moving code into `for` [**Ungolfed**](http://sandbox.onlinephpfunctions.com/code/fb88c7fefe02d81935b2359aa3aa1d60f4528df9) ``` function f($input,&$output){ foreach (str_split($input) as $char){ $ord = ord($char); $ords = [57=>48,90=>65,122=>97]; $b = 0; foreach ($ords as $max=>$min){ while ($ord<=$max&&$ord>=$min){ $b = $max; $output .= chr($min); $min++; } } $b ?: $output.=$char; } }; $output = NULL; $input = "pi=3.141592"; f($input,$output); echo $output; ``` **Explanation:** split string into array. If ascii value falls into a range (for a-z,A-Z,0-9), then increment a counter from the min of the range to the char's ascii value, appending each value until you reach the char's ascii value. I passed in `&$var` so output is done by reference rather than a `return` [Answer] ## Python, 143 bytes ``` lambda s:''.join(map(chr,sum(map(lambda a,r=range:r(65,a+1)if 64<a<97else r(97,a+1)if 96<a<123else r(48,a+1)if 47<a<58else[a],map(ord,s)),[]))) ``` [Try it online](http://ideone.com/6f7sQt) [Answer] ## Perl 6, 101 bytes Here is a first pass at it: ``` sub MAIN($_ is copy){ s:g/<[0..9]>/{(0..$/).join}/; s:g/<[a..z]>/{('a'..~$/).join}/; s:g/<[A..Z]>/{('A'..~$/).join}/; .say } ``` ``` sub MAIN($_ is copy){s:g/<[0..9]>/{(0..$/).join}/;s:g/<[a..z]>/{('a'..~$/).join}/;s:g/<[A..Z]>/{('A'..~$/).join}/;.say} ``` **119** --- Using `.trans` on `$_`to remove `is copy`. ``` sub MAIN($_){ .trans( /\d/ => {(0..$/).join}, /<[a..z]>/ => {('a'..~$/).join}, /<[A..Z]>/ => {('A'..~$/).join} ).say } ``` ``` sub MAIN($_){.trans(/\d/=>{(0..$/).join},/<[a..z]>/=>{('a'..~$/).join},/<[A..Z]>/=>{('A'..~$/).join}).say} ``` **106** --- Act on `@*ARGS` directly instead of defining a `MAIN` sub. (otherwise identical to previous example) ``` @*ARGS[0].trans(/\d/=>{(0..$/).join},/<[a..z]>/=>{('a'..~$/).join},/<[A..Z]>/=>{('A'..~$/).join}).say ``` **101** [Answer] # Scala, 111 91 bytes ``` val f=(_:String).flatMap(x=>if(x.isDigit)('0'to x)else if(x.isUpper)('A'to x)else('a'to x)) ``` [Answer] # Julia, ~~102~~ ~~98~~ ~~90~~ 84 bytes ``` s->join([(i=Int(c);join(map(Char,(64<c<91?65:96<c<123?97:47<c<58?48:i):i)))for c=s]) ``` This creates an unnamed function that accepts a string and returns a string. Ungolfed: ``` function f(s::AbstractString) # For each character in the input, get the codepoint and construct # a range of codepoints from the appropriate starting character to # the current character, convert these to characters, and join them # into a string x = [(i = Int(c); join(map(Char, (isupper(c) ? 65 : islower(c) ? 97 : isdigit(c) ? 48 : i):i)) ) for c in s] # Join the array of strings into a single string return join(x) end ``` [Answer] # PowerShell, 155 Bytes ``` ($args-split''|%{$b=$_;switch([int][char]$_){{$_-in(65..90)}{[char[]](65..$_)}{$_-in(97..122)}{[char[]](97..$_)}{$_-in(48..57)}{0..$b}default{$b}}})-join'' ``` *Technically* a one-liner, and PowerShell is all about those ;-) Splits the input, pipes that into a `ForEach-Object` loop, switches on the integer value of the cast character, then generates new `char[]` of the appropriate ranges. Note that we have to spend bytes to set a temp variable `$b` because the act of casting the input `$_` in the switch statement means that we can't just keep using `$_` or we'll get funky output. EDIT - I should point out that this will toss off errors since the first object being fed into `%{...}` is a null object. Since STDERR is [ignored by default](http://meta.codegolf.stackexchange.com/a/4781/42963), this shouldn't be an issue. If it's a problem, change the first bit to be `($args-split''-ne''|...` to eliminate the null object. [Answer] # JavaScript (ES6), ~~340~~ ~~258~~ ~~273~~ 271 bytes ``` a=s=>{s=s.split``;Q=x=>x.toUpperCase();A="ABCDEFGHIJKLMNOPQRSTUVWXYZ";D="0123456789";f="";for(i=0;i<s.length;i++){j=s[i];c="to"+(Q(j)==j?"Upper":"Lower")+"Case";j=Q(j);if(q=A.search(j)+1)f+=g=A.slice(0,q)[c]();else if(q=D.search(j)+1)f+=g=D.slice(0,q);else f+=j}return f} ``` [Answer] ## C (269 bytes) (line break added for clarity) ``` #include<stdio.h> #define F(x,y,z)if(c>=T[0][x]&&c<=T[1][y]){z} #define L(x,y)for(i=0;i<x;++i){y} main(){int c,i,n;char o,*T[]={"0Aa","9Zz"};while((c=getchar())!=EOF) {F(0,2,L(3,F(i,i,o=T[0][i],n=++c-o;L(n,putchar(o++));break;))else putchar(c);)}} ``` ## Ungolfed ``` #include<stdio.h> int main(void) { int c, i, n; char output; char *char_table[] = {"0Aa", "9Zz"}; while ((c = getchar()) != EOF) { if (c < '0' || c > 'z') { putchar(c); } else { for (i = 0; i < 3; ++i) { if (c >= char_table[0][i] && c <= char_table[1][i]) { output = char_table[0][1]; n = c - output; break; } } for (i = 0; i <= n; ++i) { putchar(output); ++output; } } } return(0); } ``` [Answer] # [Perl 5](https://www.perl.org/), ~~66~~ ~~61~~ (51 Bytes + 1) 52 Combining regexes with conditional operators worked out nice in this case. ~~With a join~~ Using map to combine the ranges into an array. ``` say map{(/\d/?0:/[A-Z]/?A:/[a-z]/?a:$_)..$_}split// ``` ### Test ``` $ echo "A0C1.a3c_2!" |perl -M5.010 -n count_and_spell_up.pl A0ABC01.a0123abc_012! ``` **Explanation** ``` say # print output map{ # loop through the array that's at the end of the other mustache. # outputs an array. ( /\d/?0 # if $_ is a digit then 0 :/[A-Z]/?A # else, if it's an uppercase character then A :/[a-z]/?a # else, if it's a lowercase character then a :$_ # else the current character )..$_ # generate a sequenced string of characters # that ends with the magic variable $_ # ($_ is currently a character from the array) }split// # split the magic variable $_ (currently the input string) # to an array of characters ``` [Answer] # JavaScript (ES7), 125 bytes There were already two JS answers focusing on encoding the strings, so I decided to go for a more algorithmic approach using `String.fromCharCode()`: ``` x=>x.replace(/[^\W_]/g,z=>(c=z.charCodeAt(),f=c<65?48:c<97?65:97,String.fromCharCode(...[for(i of Array(c-f).keys())i+f])+z)) ``` A bonus of using this method is that it takes any amount of char codes, so `join`ing the list is not necessary. This turned out shorter than any other technique, so I'm happy with the result. [Answer] # MUMPS, 131 bytes ``` u(l,h) i l'>a,a'>h f j=l:1:a s o=o_$C(j),f=0 q t(s) f i=1:1:$L(s) s a=$A(s,i),f=1 d u(48,57),u(65,90),u(97,122) s:f o=o_$C(a) q o ``` I did manage to save a good few bytes here thanks to [MUMPS's dynamic scoping](https://softwareengineering.stackexchange.com/questions/297088/how-do-you-safely-refactor-in-a-language-with-dynamic-scope). Here's a roughly-equivalent ungolfed version, which I sure would love to syntax highlight, if only [support for the MUMPS Prettify module were available](https://meta.stackexchange.com/questions/268376/add-the-lang-mumps-module-from-prettify). ``` convert(str) ; new asciiCode,flag,i,output for i=1:1:$LENGTH(str) do . set asciiCode=$ASCII(str,i) . set flag=1 . do helper(48,57) . do helper(65,90) . do helper(97,122) . if 'flag do . . set output=output_$CHAR(asciiCode) quit helper(low,high) ; if low'>asciiCode,asciiCode'>high do . for code=low:1:asciiCode do . . set output=output_$CHAR(code) . . set flag=0 quit ``` [Answer] # Perl 6, ~~78~~ 77 bytes ``` @*ARGS[0].trans(/\d/=>{[~] 0..$/},/<:L>/=>{[~] samecase("a",~$/)..~$/}).say ``` [Answer] # Mathematica, 102 bytes ``` FromCharacterCode@Flatten[Which[64<#<91,65,96<#<123,97,47<#<58,48,1>0,#]~Range~#&/@ToCharacterCode@#]& ``` Oh well... [Answer] # CJam, ~~32~~ 31 bytes ``` q_'[,_el^A,s+26/ff{_@#)<}:s\.e| ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q_'%5B%2C_el%5EA%2Cs%2B26%2Fff%7B_%40%23)%3C%7D%3As%5C.e%7C&input=pi%3D3.14159). ### How it works ``` q_ e# Push two copies of the user input. '[, e# Push the string of all ASCII characters up to Z. _el e# Push a copy and convert it to lowercase. ^ e# Perform symmetric difference this keeps only letters. A,s+ e# Append the string "0123456789". 26/ e# Split the result into chunks of length 26. ff{ e# For each character from input: For each chunk: _@ e# Copy the chunk and rotate the character on top of it. # e# Push the index of the character in the string (-1 for not found). )< e# Increment and keep that many characters from the left of the chunk. e# This pushes "" for index -1. } :s e# Flatten the resulting arrays of strings. e# The results will be empty strings iff the character wan't alphanumeric. \ e# Swap the result with the input string. .e| e# Perform vectorized logical OR. ``` [Answer] # Python 2, ~~135~~ 117 bytes ``` s='' for c in raw_input(): b=ord(c);e=b+1 if c.isalnum(): b=max(b&96,47)+1 for i in range(b,e):s+=chr(i) print s ``` [Answer] ## PHP - 291 bytes Pass the string to `GET["s"]`. ``` <?php $s=$_GET["s"];$m="array_map";echo implode($m(function($v){$i="in_array";$l="implode";$r="range";global$m;$a=ord($v);if($i($a,$r(48,57)))$v=$l($m("chr",$r(48,$a)));if($i($a,$r(65,90)))$v=$l($m("chr",$r(65,$a)));if($i($a,$r(97,122)))$v=$l($m("chr",$r(97,$a)));return$v;},str_split($s))); ``` [Answer] # C#, ~~251~~ ~~201~~ ~~184~~ ~~157~~ 154 Bytes ``` using System;class c{static void Main(string[] i){foreach(var c in i[0])for(var x=c>64&c<91?'A':c>96&c<123?'a':c>47&c<58?'0':c;x<=c;)Console.Write(x++);}} ``` edit: Strike! Shorter than PowerShell ;) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 37 bytes ``` (⊃,/){⎕A∊⍨⌈⍵:⍵…⍨'A'××⍵⋄⍵∊⎕D:'0'…⍵⋄⍵}¨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@NRV7OOvmb1o76pjo86uh71rnjU0/God6sVED9qWAbkqzuqH55@eDqI390CIoGq@qa6WKkbqIMVQIVrD634n/aobcKj3j6gkY961zzq3XJovfGjtolA1cFBzkAyxMMz@H@agrpjkrOhkbE6F5BZkGlrrGdoYmhqCeZ6pObk5OsohOcX5aQoqgMA "APL (Dyalog Extended) – Try It Online") A train that accepts a string as right argument. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žKD₂ô€η˜‡ ``` [Try it online](https://tio.run/##yy9OTMpM/f//6D5vl0dNTYe3PGpac2776TmPGhb@/6@kpOSY5GxoZMxVkGlrrGdoYmhqyeWRmpOTr6MQnl@Uk6IIVAEA). **Explanation:** ``` žK # Push "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" D # Duplicate it ₂ô # Split the copy into parts of size 26: ["abc...xyz","ABC...XYZ","012...789"] € # Map over each inner string: η # Get a list of its prefixes ˜ # Flatten this list of lists of strings # ["a","ab","abc",...,"A","AB","ABC",...,"0","01","012",...,"0123456789"] ‡ # Transliterate all characters in the (implicit) input-string from # "abc...xyzABC...XYZ012...789" to these prefixes at the same positions # (after which the result is output implicitly) ``` ]
[Question] [ A [**Walsh matrix**](https://en.wikipedia.org/wiki/Walsh_matrix) is a special kind of square matrix with [applications in quantum computing](https://en.wikipedia.org/wiki/Quantum_logic_gate#Hadamard_gate) (and probably elsewhere, but I only care about quantum computing). ### Properties of Walsh matrices The dimensions are the same power of 2. Therefore, we can refer to these matrices by two's exponent here, calling them`W(0)`, `W(1)`, `W(2)`... `W(0)` is defined as `[[1]]`. For `n>0`, `W(n)` looks like: ``` [[W(n-1) W(n-1)] [W(n-1) -W(n-1)]] ``` So `W(1)` is: ``` [[1 1] [1 -1]] ``` And `W(2)` is: ``` [[1 1 1 1] [1 -1 1 -1] [1 1 -1 -1] [1 -1 -1 1]] ``` The pattern continues... ### Your task Write a program or function that takes as input an integer `n` and prints/returns `W(n)` in any convenient format. This can be an array of arrays, a flattened array of booleans, a `.svg` image, you name it, as long as it's correct. [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/73884) are forbidden. ### A couple things: For `W(0)`, the `1` need not be wrapped even once. It can be a mere integer. You are allowed to 1-index results—`W(1)` would then be `[[1]]`. ### Test cases ``` 0 -> [[1]] 1 -> [[1 1] [1 -1]] 2 -> [[1 1 1 1] [1 -1 1 -1] [1 1 -1 -1] [1 -1 -1 1]] 3 -> [[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 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 1 -1]] ``` `8 ->` [Pastebin](https://pastebin.com/aYkjxk7w) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in each language wins! Happy golfing! [Answer] # [MATL](https://github.com/lmendo/MATL), 4 bytes ``` W4YL ``` [Try it online!](https://tio.run/##y00syfn/P9wk0uf/f2MA "MATL – Try It Online") **How it works:** ``` W % Push 2 raised to (implicit) input 4YL % (Walsh-)Hadamard matrix of that size. Display (implicit) ``` --- Without the built-in: **11 bytes** ``` 1i:"th1M_hv ``` [Try it online!](https://tio.run/##y00syfn/3zDTSqkkw9A3PqPs/39jAA) **How it works**: For each Walsh matrix **W**, the next matrix is computed as [**W** **W**; **W** −**W**], as is described in the challenge. The code does that `n` times, starting from the 1×1 matrix [1]. ``` 1 % Push 1. This is equivalent to the 1×1 matrix [1] i:" % Input n. Do the following n times t % Duplicate h % Concatenate horizontally 1M % Push the inputs of the latest function call _ % Negate h % Concatenate horizontally v % Concatenate vertically % End (implicit). Display (implicit) ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~63~~ ~~44~~ 40 bytes ``` {map {:3(.base(2))%2},[X+&] ^2**$_ xx 2} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OjexQKHaylhDLymxOFXDSFNT1ahWJzpCWy1WIc5IS0slXqGiQsGo9n9afpFCmoaxpl5Rfkl@kQZQylhToZqLs6AoM69EAajM3l5BXddQQV1BURFIgBggLSrx1jA1SjF5StZctf8B "Perl 6 – Try It Online") Non-recursive approach, exploiting the fact that the value at coordinates x,y is `(-1)**popcount(x&y)`. Returns a flattened array of Booleans. -4 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [bit parity trick](https://codegolf.stackexchange.com/a/144027/64121). [Answer] # [Haskell](https://www.haskell.org/), ~~57~~ 56 bytes ``` (iterate(\m->zipWith(++)(m++m)$m++(map(0-)<$>m))[[1]]!!) ``` [Try it online!](https://tio.run/##y0gszk7NyflfbhvzXyOzJLUosSRVIyZX164qsyA8syRDQ1tbUyNXWztXUwVIauQmFmgY6GraqNjlampGRxvGxioqav7PTczMU7BVAEr6KhQUZeaVKKgolCsY//@XnJaTmF78XzfCOSAAAA "Haskell – Try It Online") This implements the given recursive construction. *-1 byte thanks to [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%c3%98rjan-johansen)!* [Answer] # [Octave](https://www.gnu.org/software/octave/) with builtin, ~~18~~ 17 bytes ``` @(x)hadamard(2^x) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzIzElMTexKEXDKK5C83@ahoEmV5qGIYgwAhHGmv8B "Octave – Try It Online") # [Octave](https://www.gnu.org/software/octave/) without builtin, ~~56 51~~ 47 bytes ``` function r=f(x)r=1;if x,r=[x=f(x-1) x;x -x];end ``` [Try it online!](https://tio.run/##y08uSSxL/f8/rTQvuSQzP0@hyDZNo0KzyNbQOjNNoUKnyDa6AiSia6ipUGFdoaBbEWudmpfyH4i5uNI0DDSBhCGIMAIRxpr/AQ "Octave – Try It Online") Thanks to [@Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) for -4. # [Octave](https://www.gnu.org/software/octave/) with recursive lambda, ~~54 53 52~~ 48 bytes ``` f(f=@(f)@(x){@()[x=f(f)(x-1) x;x -x],1}{1+~x}()) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en9z9NI83WQSNN00GjQrPaQUMzusIWKKSpUaFrqKlQYV2hoFsRq2NYW22oXVdRq6GpCdRgoMmVpmEIIoxAhLHmfwA "Octave – Try It Online") Thanks to [this answer](https://codegolf.stackexchange.com/a/137547/32352) and [this question](https://codegolf.stackexchange.com/questions/164454/whats-the-shortest-way-to-define-an-anonymous-recursive-function-in-octave) for inspiration. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 bytes ``` (⍪⍨,⊢⍪-)⍣⎕⍪1 ``` [Try it online!](https://tio.run/##jY49DsIwDEb3nMJMbSUqUbgDJ@ACaWK1kfJTNc7ABRiQglgYWWBBHCsXKQH2qoOtJ33Pn8wHXcsj166bphTvcOgRhJN5cVsQtAhDIOhxRJABgRwQit4qwTVoZRRxUs761f96H7SGYXTdyA2UPrRGeZ/zCkrhjEFLKGd7KpZrvgNliu8UX@t0fmSqqxSf6XLL2LBffkBP@UmPnrEZd5PtjKdrUcx6zUJvu9DbfQA "APL (Dyalog Unicode) – Try It Online") Output is a 2-dimensional array. [Answer] # [Python 2](https://docs.python.org/2/), ~~75~~ 71 bytes ``` r=range(2**input()) print[[int(bin(x&y),13)%2or-1for x in r]for y in r] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8i2KDEvPVXDSEsrM6@gtERDU5OroCgzryQ6GkhoJGXmaVSoVWrqGBprqhrlF@kapuUXKVQoZOYpFMWCmJUQ5v//JgA "Python 2 – Try It Online") The Walsh Matrix seems to be related to the evil numbers. If `x&y` (bitwise and, 0-based coordinates) is an evil number, the value in the matrix is `1`, `-1` for odious numbers. The bit parity calculation `int(bin(n),13)%2` is taken from [Noodle9's](https://codegolf.stackexchange.com/users/9481/noodle9) comment on [this answer](https://codegolf.stackexchange.com/a/144027/64121). [Answer] # [R](https://www.r-project.org/), ~~61~~ ~~56~~ ~~53~~ 50 bytes ``` w=function(n)"if"(n,w(n-1)%x%matrix(1-2*!3:0,2),1) ``` [Try it online!](https://tio.run/##K/r/v9w2rTQvuSQzP08jT1MpM01JI0@nXCNP11BTtUI1N7GkKLNCw1DXSEvR2MpAx0hTx1Dzf7mGseZ/AA "R – Try It Online") Recursively calculates the matrix by Kronecker product, and returns 1 for `n=0` case (thanks to Giuseppe for pointing this out, and also to JAD for helping to golf the initial version). Additional -3 bytes again thanks to Giuseppe. [Answer] # [Haskell](https://www.haskell.org/), 41 bytes ``` (iterate([id<>id,id<>map(0-)]<*>)[[1]]!!) ``` [Try it online!](https://tio.run/##Fcm9DsIgEADg3ae4Jg5grNG4UhZdm3Q0QYaLgF7kL5Tn99TpG74Xrm8fI1OqpXW4YsfDXHIhB0IoLeUmTHcW1H3D7oUhpzS5/Z@EVRxHadVOS2NO1g6D5ISUYYLfzVAb5Q5bCHDmzyNEfK483i7L8gU "Haskell – Try It Online") The version of Haskell on TIO doesn't yet have `(<>)` in Prelude so I import it in the header. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` 1WW;"Ѐ,N$ẎƊ⁸¡ ``` [Try it online!](https://tio.run/##ASUA2v9qZWxsef//MVdXOyLDkOKCrCxOJOG6jsaK4oG4wqH/w4dH//8z "Jelly – Try It Online") Change the `G` to `ŒṘ` in the footer to see the actual output. [Answer] ## JavaScript (ES6), 77 bytes ``` n=>[...Array(1<<n)].map((_,i,a)=>a.map((_,j)=>1|-f(i&j)),f=n=>n&&n%2^f(n>>1)) ``` The naive calculation starts by taking `0 <= X, Y <= 2**N` in `W[N]`. The simple case is when either `X` or `Y` is less than `2**(N-1)`, in which case we recurse on `X%2**(N-1)` and `Y%2**(N-1)`. In the case of both `X` and `Y` being at least `2**(N-1)` the recursive call needs to be negated. If rather than comparing `X` or `Y` less than `2**(N-1)` a bitmask `X&Y&2**(N-1)` is taken then this is non-zero when the recursive call needs to be negated and zero when it does not. This also avoids having to reduce modulo `2**(N-1)`. The bits can of course be tested in reverse order for the same result. Then rather than doubling the bitmask each time we he coordinates can be halved instead, allowing the results to be XORed, whereby a final result of `0` means no negation and `1` means negation. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 41 bytes ``` f(n)=if(n,matconcat([m=f(n-1),m;m,-m]),1) ``` [Try it online!](https://tio.run/##FYwxCsAgDAC/EjoZSKBCt2I/UjqIYHFIFPH/aboc3A038mz8DrMaFFNzkuRVupa8wi3JA0ckOYVYHqSIVvsMCgl2goNgzKbLfQO@HP8G0T4 "Pari/GP – Try It Online") [Answer] # [K (ngn/k)](https://github.com/ngn/k), 18 bytes ``` {x{(x,x),'x,-x}/1} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqrqiWqNCp0JTR71CR7eiVt@w9n@aggFXmoIhEBsBsfF/AA "K (ngn/k) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` !¡§z+DS+†_;;1 ``` [Try it online!](https://tio.run/##yygtzv7/X/HQwkPLq7RdgrUfNSyIt7Y2/P//vzEA "Husk – Try It Online") 1-indexed. ### Explanation ``` !¡§z+DS+†_;;1 ¡ ;;1 Iterate the following function starting from the matrix [[1]] §z+ Concatenate horizontally D The matrix with its lines doubled S+†_ and the matrix concatenated vertically with its negation ! Finally, return the result after as many iterations as specified by the input (where the original matrix [[1]] is at index 1) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes ``` Nest[ArrayFlatten@{{#,#},{#,-#}}&,1,#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@1uCTasagosdItJ7GkJDXPobpaWUe5VgdI6irX1qrpGOoox6r9T4s2jv3/X7egKDOvBAA "Wolfram Language (Mathematica) – Try It Online") Almost directly copied from [this answer of mine](https://codegolf.stackexchange.com/a/259635/110698). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` Ø+ṗ&P¥þ` ``` [Try it online!](https://tio.run/##ASIA3f9qZWxsef//w5gr4bmXJlDCpcO@YP/Dh0cpauKBvgoK//8z "Jelly – Try It Online") ``` Ø+ṗ Take the Cartesian product of [1, -1] with itself n times. þ` Table that with itself by: & vectorizing bitwise AND (i.e. logical AND of sign bits!) P¥ then multiply the results. ``` A cell is -1 iff it has an odd number of 1 bits in the bitwise AND of its 0-indices. This effectively computes `[0 .. 2^n)`, tables that with itself by bitwise-AND-then-popcount, and raises -1 to each resulting power, but shortcuts all of those steps by representing 0 bits as 1 and 1 bits as -1 to begin with: `ṗ` provides the desired range without having to explicitly compute `2^n`, and the product is -1 iff there are an odd number of -1s, while thanks to the magic of zipwith-vectorization and two's complement representation the bitwise AND of two sign-list integers is still their bitwise AND as sign-list integers. [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 10 bytes ``` .;`,^2$.@^-1+``@`& ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWm_SsE3TijFT0HOJ0DbUTEhwS1CASUPkFC40hDAA) Uses the formula \$W\_{i,j} = \left(-1\right)^{\operatorname{popcount}(\operatorname{bitand}(i,j))}\$. [Answer] # [JavaScript (Node.js)](https://nodejs.org),100 89 79 bytes ``` f=n=>n?[...(m=F=>r.map(x=>[...x,...x.map(y=>y*F)]))(1,r=f(n-1)),...m(-1)]:[[1]] ``` [Try it online!](https://tio.run/##XZDBboMwDIbvPIVV7ZBMDlq226awWx9g2o1FgtGwUbUBEVpRVTx754S2wAQK9vf/tmO2@TF3RVs1nbD1xlxKRa9ViX1P4zhme7VWSRvv84b1KvGoR38EclLJ6XHNNedMYqtKZoXk3Ot7RpF@TVOp9SWKOuM6UMAq2yCYvuEqOUcAx7yF1jhSSi/xeFtXNvuy2dtVJOtH0ClYiFXJqFCpq4MTKmrr6p2Jd/UPW33@Vg781CJ3BprcObNZeZfZOeNHL/0ZtTFFZzbwcB47Dgjfhw7K@mA9pGFD5uuHaAjbsGek5QBBIkD4aozAEyEBkKi4Ewh0TsSVUJXmYz956zd5vBaWYE8Y/uQtffEpLh4dISHh4/kx4pCK0Skm/A/i3T2hpXsqmbtnzsVNpnvIcZnLHw "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` oFoL<N&b0м€g®smˆ ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/3y3fx8ZPLcngwp5HTWvSD60rzj3d9v@/MQA "05AB1E – Try It Online") **Explanation** ``` oF # for N in 2**input do: oL< # push range [1..2**input]-1 N& # bitwise AND with N b # convert to binary 0м # remove zeroes €g # length of each ®sm # raise -1 to the power of each ˆ # add to global array ``` I wish I knew a shorter way to compute the Hamming Weight. `1δ¢˜` is the same length as `0м€g`. [Answer] # [Stax](https://github.com/tomtheisen/stax), 20 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` àΩ2┤â#╣_ê|ª⌐╦è│╞►═∞H ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=85ea32b48323b95f887ca6a9cb8ab3c610cdec48&i=0%0A%0A1%0A%0A2%0A%0A3%0A%0A4%0A%0A5&a=1&m=1) Thought I'd give my own challenge a try after some time. Non-recursive approach. Not too competitive against other golfing languages... ### Unpacked (24 bytes) and explanation ``` |2c{ci{ci|&:B|+|1p}a*d}* |2 Power of 2 c Copy on the stack. { } Block: c Copy on stack. i Push iteration index (starts at 0). { } Block: ci Copy top of stack. Push iteration index. |& Bitwise and :B To binary digits |+ Sum |1 Power of -1 p Pop and print a Move third element (2^n) to top... * And execute block that many times. d Pop and discard * Execute block (2^n) times ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~80~~ 79 bytes ``` f=lambda n:n<1and[[1]]or[r*2for r in f(n-1)]+[r+[-x for x in r]for r in f(n-1)] ``` [Try it online!](https://tio.run/##XYxBCsIwFAWv8ndJLC0k7kRP8g00UoIp@lJ@I8TTR4pdiLthGGZ5l3uGay1eHuF5mwLhhLMNmJit91lYDi5mIaEEihq9Nb5j6bivtPm6efH/SVskoZC6Qg1zTtCKdhjrOMj8Wot25ufw5X1xNKZ9AA "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes Showcasing a couple of approaches using additional libraries. This one relies on a built-in in Scipy: ``` lambda n:hadamard(2**n) from scipy.linalg import* ``` [Try it online!](https://tio.run/##BcFLCoAgEADQfacYXKlEi2gldBM3U/YZ0FEmQTy9vVd6fTOvo@1@RExHQGD3YsCEEvRqLZvplpzgO6n0JRJjfIBSyVLtuLMAATEI8nPpzTgoQlyhaTKz8qzGDw "Python 2 – Try It Online") # [Python 2](https://docs.python.org/2/), 65 bytes And this one only uses Numpy, and solves by Kronecker product, analogously to my [R answer](https://codegolf.stackexchange.com/a/162303/78274): ``` from numpy import* w=lambda n:0**n or kron(w(n-1),[[1,1],[1,-1]]) ``` [Try it online!](https://tio.run/##DclBCsIwEAXQvacYukpCCo24KniSNosUrQ6aP2GIhJ4@dvM2rxz1Lbj2vqtkwi@XgzgX0eou7f5NeXskwjw5BxKljwpMMxiD9csSfIj@dAwx2r6fz8QgTXg9zc3OVJRRqRm2flgx9D8 "Python 2 – Try It Online") ]
[Question] [ ## Introduction Yesterday I saw a [birthday puzzle](https://codegolf.stackexchange.com/questions/57277/its-my-birthday-d). Congrats!! Also this week I watched an episode of the TV show *Bones* where a dead body was found buried under a tree. To calculate the time of death, they counted the tree rings. Tree rings form because trees grow slower during the winter and faster during the summer. Thus you can calculate the tree's age by counting the rings. Also you can see natural events like rainy or dry seasons. [![enter image description here](https://i.stack.imgur.com/2BqEX.png)](https://i.stack.imgur.com/2BqEX.png) ## Challenge Given an integer `n >= 1` as input, write a full program to output the tree age rings. Because rings can change of shape use three diferent characters ('0', '\*', '+') to show climate cycles. Age 1 ``` 0 ``` Age 2 ``` *** *0* *** ``` Age 3 ``` +++++ +***+ +*0*+ +***+ +++++ ``` Age 4 ``` 0000000 0+++++0 0+***+0 0+*0*+0 0+***+0 0+++++0 0000000 ``` Size of the tree is a square of sides `2*n - 1` ## Winning Shortest code in bytes wins. [Answer] # BBC Basic, 93 bytes ``` 1I.r:r=r-1:F.i=-r TOr:F.j=-r TOr:p=ABS(i):q=ABS(j):IFp<q TH.p=q 2V.48-(p MOD3)*6MOD7:N.:P.:N. ``` The abbreviated keywords help out a lot here. In line 2, I'm using the `VDU` command (equivalent to C's `putchar()`) to print each character. This is a lot more efficient than `P.MID$("0*+",p MOD3+1,1)`. Here it is running in BeebEm3 on a Mac: [![enter image description here](https://i.stack.imgur.com/8ho6U.gif)](https://i.stack.imgur.com/8ho6U.gif) [Answer] # CJam, 25 bytes ``` q~,_1>W%\+_ff{e>"0*+"=}N* ``` [Test it here.](http://cjam.aditsu.net/#code=q~%2C_1%3EW%25%5C%2B_ff%7Be%3E%220*%2B%22%3D%7DN*&input=7) ## Explanation ``` q~, e# Read input N, turn into range [0 1 ... N-1] _1> e# Duplicate and cut off the zero. W% e# Reverse. \+ e# Prepend to original range to give [N-1 ... 1 0 1 ... N-1] _ e# Duplicate ff{ e# Nested map for each pair of elements in that array. e> e# Take the maximum, i.e. chessboard distance from the centre. "0*+"= e# Select the right character using cyclic indexing into this string. } N* e# Join the lines with line feeds. ``` [Answer] # K5, ~~27~~ ~~30~~ ~~26~~ ~~25~~ 22 bytes ``` "0"{4(|+y,)/x}/"0*+"3!1_! ``` This approach iteratively "wraps" a core (beginning with `"0"`) on all four sides using some other character (`{4(|+y,)/x}`). The sequence of seasonal wrappings is determined by a modulo 3 (`3!`) sequence. It's a bit fiddly to get the base case to line up just right. ## edit: ``` "0*+"3!u|\:u:t,1_|t:|! ``` This alternative builds the entire rectangular array at once from the provided exclusive range (`!`) reversed and joined with itself after dropping an item (`t,1_|t:|`). We then take the cartesian product maximum (`u|\:u:`), take the entire matrix modulo 3 (`3!`) and index into the array of characters. In action: ``` "0*+"3!u|\:u:t,1_|t:|!1 ,,"0" "0*+"3!u|\:u:t,1_|t:|!3 ("+++++" "+***+" "+*0*+" "+***+" "+++++") "0*+"3!u|\:u:t,1_|t:|!5 ("*********" "*0000000*" "*0+++++0*" "*0+***+0*" "*0+*0*+0*" "*0+***+0*" "*0+++++0*" "*0000000*" "*********") ``` [Answer] ## Python 2, 83 bytes ``` I=n=input() while I+n-1:I-=1;i=abs(I);w=("O*+"*n)[i:n];print w[::-1]+w[0]*2*i+w[1:] ``` Prints line by line. Each line is chopped into three parts: * The left cycling part, including the first repeated char. * The repeating center part * The right cycling part. For `n=4`: ``` 0 000000 0+ ++++ 0 0+* ** +0 0+*0 *+0 0+* ** +0 0+ ++++ 0 0 000000 ``` We generate the left part in reverse as `w`, clone its last character `2*i` times, then add on the original version without the first character. [Answer] ## Matlab, 63 bytes ``` n=input('')-1;x='0*+';t=abs(-n:n);x(mod(bsxfun(@max,t,t'),3)+1) ``` Example: ``` >> n=input('')-1;x='0*+';t=abs(-n:n);x(mod(bsxfun(@max,t,t'),3)+1) 5 ans = ********* *0000000* *0+++++0* *0+***+0* *0+*0*+0* *0+***+0* *0+++++0* *0000000* ********* ``` [Answer] ## Python 2, 83 bytes ``` n=input() R=range(1-n,n) for i in R:print''.join('0*+'[max(i,-i,j,-j)%3]for j in R) ``` If we think of the tree as a coordinate grid, the symbol at `(i,j)` is determined by `max(abs(i),abs(j))%3`, or equivalently `max(i,-i,j,-j)%3`. For each row `i`, we join and print the symbols in that row. [Answer] # Pyth, 23 bytes ``` VK+_StQUQsm@"0*+"eS,dNK ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=VK%2B_StQUQsm%40%220%2A%2B%22eS%2CdNK&input=3&debug=0) ### Explanation: ``` VK+_StQUQsm@"0*+"eS,dNK implicit: Q = input number StQ the list [1, 2, ..., Q-1] _ reverse it [Q-1, ..., 2, 1] UQ the list [0, 1, ..., Q-1] + combine them [Q-1, ..., 1, 0, 1, ..., Q-1] K and store in K VK for each N in K: m K map each element d in K to: eS,dN the maximum of d and N @"0*+" and pick the corresponded char (modulo 3) s join the chars to a string and print ``` [Answer] # MATLAB, ~~80~~ ~~78~~ 73 bytes ## Thanks Luis Mendo for helping me shave 5 bytes! ``` A=eye(2*input('')-1);a='0*+';a(mod(bwdist(A.*rot90(A),'chessboard'),3)+1) ``` # Example ``` >> A=eye(2*input('')-1);a='0*+';a(mod(bwdist(A.*rot90(A),'chessboard'),3)+1) 5 ans = ********* *0000000* *0+++++0* *0+***+0* *0+*0*+0* *0+***+0* *0+++++0* *0000000* ********* ``` # Ungolfed and Code Explanation ``` %// Accepts an integer n from the user and creates a 2*n - 1 x 2*n - 1 identity matrix A=eye(2*input('')-1); %// Creates an array of three characters to print each level of the ring a='0*+'; %// By taking the identity matrix and element-wise multiplying with its 90 degree rotated %// version of itself, this creates a zero matrix except for the centre most %// value, which is 1 %// This takes the distance transform via the chessboard / Chebyshev distance %// from the centre element %// This mirrors what "level" each square would be at %// 1: https://en.wikipedia.org/wiki/Distance_transform %// 2: https://en.wikipedia.org/wiki/Chebyshev_distance b = bwdist(A.*rot90(A),'chessboard'); %// Because each level cycles through each of the characters in the %// character array a, we need to perform a mod operation so that %// all of the values cycle from 1 to 3 %// This changes the distance transform output so that we range %// from 1 to 3 instead c = mod(b,3) + 1; %// The values in the matrix c correspond exactly to the locations %// we need to sample from the array a and we display our result a(c) ``` # Minor Note [`bwdist`](http://www.mathworks.com/help/images/ref/bwdist.html) is a function that's part of the image processing toolbox, and can only be run in MATLAB. Octave (IIRC) does not have `bwdist` implemented yet so this can't be run in Octave. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 14 bytes ``` FN«B⊕⊗ι§0*+ιM↖ ``` [Try it online!](https://tio.run/##AS0A0v9jaGFyY29hbP//77ym77yuwqvvvKLiipXiipfOucKnMCorzrnvvK3ihpb//zU) ## explanation ``` FN #start a for loop, iterating n (input) times « #the loop contains 2 expressions so a body is opened B #draw a box ⊕⊗ι #size of box is 2*i+1 §0*+ι #character of the box is "0*+" index i M↖ #move up left 1 #the result is printed implicitly ``` ## 15 bytes ``` FN«B⊕ײι§0*+ιM↖ ``` Improved version by [Psuedo Nym](https://codegolf.stackexchange.com/users/80383/pseudo-nym) replaced `ײ` with `⊗`, the in-built doubled operator. [Answer] # [Pyke](https://pyke.catbus.co.uk/docs), 13 bytes ``` 0QV"0*+"[[email protected]](/cdn-cgi/l/email-protection) ``` Based on [this excellent Pyke answer on another challenge](https://codegolf.stackexchange.com/a/106757/52210), so make sure to upvote that one as well! [Try it online.](https://tio.run/##K6jMTv3/3yAwTMlAS1sp38FRL@L/fxMA) **Explanation:** ``` 0 # Start with a "0" in the center QV # Loop the input amount of times: "0*+" # Push string "0*+" o # Push index++ (0 by default; and increases by 1 after pushing) @ # And use it to index it into the string (0-based with automatic wraparound) A # Deep apply the following command: .X # Surround the string with this character around it # (after which the result is output implicitly) ``` [Answer] # Python 2, 134 bytes ``` def l(x,c=1): p="\n\x1b[%d"%c;d=p+";%dH"%c if x:s=x*2-1;d+=(p+"G").join(["0*+"[(x+1)%3]*s]*s)+l(x-1,c+1) return d print l(input()) ``` [Answer] # [Perl 5](https://www.perl.org/), 57 bytes Using the approach from [@xnor's answer](https://codegolf.stackexchange.com/a/57477/9365), please upvote them! ``` //,say map{qw(0 * +)[max(abs,abs$')%3]}@;for@;=- --$_..$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/19fX6c4sVIhN7GgurBcw0BBS0FbMzo3sUIjMalYB4hV1DVVjWNrHazT8oscrG11FXR1VeL19FTi//83@5dfUJKZn1f8Xzfvv66vqZ6hgZ4BkOGTWVxiZRVakpmjDTQIAA "Perl 5 – Try It Online") [Answer] # Matlab 92 ``` input('')-1;x=ones(2*n+1,1)*abs(-n:n);z=mod(max(x,x'),3);z(z>1)=2;z(z<1)=7;disp([z+41,'']) ``` [Answer] # Sed, ~~277~~ 252 characters (251 character code + 1 character command line option.) Expects input in [unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary) format. ``` :m s/1/0/ s/1/*/ s/1/+/ tm h s/^/:/ :r s/(.*):(.)/\2\1:/ tr s/:// G s/\n.// h : /^(.)\1*$/ba s/(.)(.)(\2*)\1/\1:\2\3:\1/ :c s/(:_*)[^_](.*:)/\1_\2/ tc :u s/(.)(:\1*)_/\1\2\1/ tu s/://g H b :a g s/[^\n]+/:/ :f s/(.*):(\n[^\n]+)/\2\1:/ tf s/:// G s/\n// ``` Sample run: ``` bash-4.3$ sed -rf treering.sed <<< 1 0 bash-4.3$ sed -rf treering.sed <<< 11 *** *0* *** bash-4.3$ sed -rf treering.sed <<< 111 +++++ +***+ +*0*+ +***+ +++++ bash-4.3$ sed -rf treering.sed <<< 1111 0000000 0+++++0 0+***+0 0+*0*+0 0+***+0 0+++++0 0000000 ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 68 bytes ``` $f={($l=($c='+0*'[$_--%3])+"$c$c"*$_) if($_){&$f $_|%{"$c$_$c"} $l}} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyXNtlpDJcdWQyXZVl3bQEs9WiVeV1fVOFZTW0klWSVZSUslXpMrM00DSFWrqaQpqMTXqFaDpOKBkrVcKjm1tf8N9fRMQaKO6alAeSVriDprdfXa/wA "PowerShell – Try It Online") Unrolled: ``` $f={ $_-- $char='+0*'[$_%3] $line=$char+"$char$char"*$_ Write-Output $line if($_){ &$f $_|ForEach-Object{ Write-Output "$char$_$char" } Write-Output $line } } ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 15 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` H0*+@¹2×╷:*;22╋ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjI4MCorJXVGRjIwJUI5JXVGRjEyJUQ3JXUyNTc3JXVGRjFBJXVGRjBBJXVGRjFCJXVGRjEyJXVGRjEyJXUyNTRC,i=MTY_,v=8) Can probably be shortened further. ## Explanation ``` H0*+@¹2×|:*;22╋ H push an empty art object, start a loop using input 0*+ string "0*+" @ get the nth element, circularly <-----------+ ¹ loop iteration | 2× double it | | decrement it | : duplicate it | * use that to box the character from here ----+ ; swap the box with the previous iteration 22╋ overlap at (2,2) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Ñ ÆP=Õû"0*+"gX=z)XÑÄ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=0SDGUD3V%2byIwKisiZ1g9eilY0cQ&input=NA) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=0SDGUD3V%2byIwKisiZ1g9eilY0cQ&footer=UmlVzA&input=WzEsMiwzLDRdCi1tUg) ``` Ñ ÆP=Õû"0*+"gX=z)XÑÄ :Implicit input of integer U Ñ :U*2 Æ :Map each X in the range [0,U*2) P= : Reassign to P (initially the empty string) Õ : Transpose P û : Centre pad with "0*+" : Literal string g : Get character at 0-based index X= : Reassign to X z : X floor divided by 2 ) : End get XÑÄ : To length X*2+1 ``` [Answer] # JavaScript (ES6), 114 Using alert for output - bad proportional font and the result is ugly. In the snippet below the alert is redirect to the snipped body, giving a better result. The newline inside backticks is significant and counted. Test running the snippet in Firefox. ``` /* Redefine alert for testing purpose */ alert=x=>O.innerHTML=x; [...'*+0'.repeat(n=prompt()-1)].map((c,i)=>i<n?b=[z=c.repeat(i-~i),...b,z].map(r=>c+r+c):0,b=[0]);alert(b.join` `) ``` ``` <pre id=O></pre> ``` [Answer] # Ruby, 85 characters ``` puts (m=0..(n=gets.to_i-1)*2).map{|i|m.map{|j|"0*+"[[(i-n).abs,(j-n).abs].max%3]}*""} ``` Sample run: ``` bash-4.3$ ruby -e 'puts (m=0..(n=gets.to_i-1)*2).map{|i|m.map{|j|"0*+"[[(i-n).abs,(j-n).abs].max%3]}*""}' <<< 4 0000000 0+++++0 0+***+0 0+*0*+0 0+***+0 0+++++0 0000000 ``` [Answer] # Moonscript - 104 bytes ``` m=io.read! n=2*m-1 for y=1,n io.write ({'0','*','+'})[(math.max y-m,x-m,m-y,m-x)%3+1]for x=1,n print! ``` [Answer] # C, 138 bytes ``` j,k,l;t(i){l=2*i;char*c=calloc(l,l);memset(c,10,l*(l-2));for(;k<i;++k)for(j=k;j<l-1-k;)memset(c+j++*l+k,"+0*"[(i-k)%3],l-2*k-1);puts(c);} ``` Function `t` taking one integer parameter - the age. Ungolfed (with `main` function to easily run the above one): ``` #include "stdlib.h" /* calloc - only necessary for 64-bit system */ j,k,l;t(i) { l=2*i; char*c=calloc(l,l); memset(c,10,l*(l-2)); /* fill with '\n' */ for(;k<i;++k)for(j=k;j<l-1-k;)memset(c+j++*l+k,"+0*"[(i-k)%3],l-2*k-1); puts(c); } main(int c,char**v) { t(atoi(v[1])); } ``` The `stdlib.h` may be necessary on some systems, because without it the return type of the undeclared function `calloc` would default to `int`. Because `int` and `char*` are not necessarily of same size, an invalid pointer could be written into `c`. In most 32-bit systems both `char*` and `int` have same size, but this is not true for 64-bit systems. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0¸sG…0*+Nè©δ.ø®N·>×.ø}» ``` [Try it online](https://tio.run/##yy9OTMpM/f/f4NCOYvdHDcsMtLT9Dq84tPLcFr3DOw6t8zu03e7wdCCz9tDu//9NAA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/R/iquSZV1BaYqWgZO@nw6XkX1oC4en4/Tc4tKPY/VHDMgMtbb/DKw6tPLdF7/COQ@v8Dm23OzwdyKw9tPu/zqFt9v8B). **Explanation:** ``` 0¸ # Start with a 0 wrapped in a list as the center: [0] sG # Loop `N` in the range [1, input): …0*+ # Push string "0*+" Nè # Use `N` to index into this string # (0-based with automatic wraparound) © # Store this character in variable `®` (without popping) δ.ø # Surround each line with this character N·> # Push 2 * `N` + 1 ® × # Repeat the character `®` that many times as string .ø # And surround the list with this string }» # After the loop: join all strings by newlines # (after which the resulting string is output implicitly as result) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 118 bytes ``` param($n)((--$n..0+1..$n|%{-join(($z=($x='0*+'*$n)[$n..$_])+"$($x[$_])"*2*$_+($z[($n-$_-1)..0],'')[$n-eq$_])}),0)[!$n] ``` [Try it online!](https://tio.run/##Fc1LDoIwGATgPadAMtoXbcDEleEkTdOwgKiBgrjQiD17/bubZL7MrMt72F63YZoSxm5Pa7/1M0cQnGuNYEyjWmMQfsddP5Z74BzfjuPTsUYqJgnarOCdUBWosDlW8izhFVlLWxpet4KmXM1Y9np4ZhVF3Qh7QHApFgXdXOjlhLGEv5aMxfQH "PowerShell – Try It Online") :( [Answer] # [J](http://jsoftware.com/), 22 bytes ``` '0*+'{~3|>./~&:|@i:@<: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1Q20tNWr64xr7PT069SsahwyrRxsrP5rcnGlJmfkK6QpGEIY6uowASN0AWN0AZP/AA "J – Try It Online") ]
[Question] [ Here's a pixelated 5 by 7 font for the digits 0 through 9: ``` .███. █...█ █...█ █...█ █...█ █...█ .███. ..█.. ███.. ..█.. ..█.. ..█.. ..█.. █████ .███. █...█ ....█ ...█. ..█.. .█... █████ .███. █...█ ....█ ..██. ....█ █...█ .███. █..█. █..█. █..█. █████ ...█. ...█. ...█. █████ █.... █.... .███. ....█ █...█ .███. .███. █...█ █.... ████. █...█ █...█ .███. █████ ....█ ....█ ...█. ...█. ..█.. ..█.. .███. █...█ █...█ .███. █...█ █...█ .███. .███. █...█ █...█ .████ ....█ █...█ .███. ``` *(This font and this page will probably look better if you run this JavaScipt code in your browsers console or in the URL bar prefixed by `javascript:`: `$('#question pre,.answer pre').css('line-height',1)`.)* Write two equal sized rectangular blocks of text, one to represent the empty spaces (`.`) in the font above, and one to represent the filled spaces (`█`). When these two text blocks are arranged into the same 5×7 pattern as one of the digits above, then the resulting large text block should be a program that prints that digit to stdout. This should work for all 10 digits. For example, if your `.` text block was ``` --- ''' ``` and your `█` text block was ``` ABC 123 ``` then the program ``` ---ABCABCABC--- '''123123123''' ABC---------ABC 123'''''''''123 ABC---------ABC 123'''''''''123 ABC---------ABC 123'''''''''123 ABC---------ABC 123'''''''''123 ABC---------ABC 123'''''''''123 ---ABCABCABC--- '''123123123''' ``` should output `0`. Similarly, the program ``` ------ABC------ ''''''123'''''' ABCABCABC------ 123123123'''''' ------ABC------ ''''''123'''''' ------ABC------ ''''''123'''''' ------ABC------ ''''''123'''''' ------ABC------ ''''''123'''''' ABCABCABCABCABC 123123123123123 ``` should output `1`, and so on up to the program for `9`. You can use this stack snippet to make the digit shaped programs: ``` <style>textarea{font-family:monospace;}</style><script>function go(){var t=parseInt(document.getElementById("digit").value[0]);if(isNaN(t))return void alert("Invalid digit.");for(var e=document.getElementById("empty").value.split("\n"),n=document.getElementById("filled").value.split("\n"),l=[],o=0;o<7*e.length;o++){l[o]="";for(var d=0;5>d;d++)l[o]+=font[t][Math.floor(o/e.length)][d]?n[o%n.length]:e[o%e.length]}document.getElementById("output").value=l.join("\n")}font=[[[0,1,1,1,0],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[0,1,1,1,0]],[[0,0,1,0,0],[1,1,1,0,0],[0,0,1,0,0],[0,0,1,0,0],[0,0,1,0,0],[0,0,1,0,0],[1,1,1,1,1]],[[0,1,1,1,0],[1,0,0,0,1],[0,0,0,0,1],[0,0,0,1,0],[0,0,1,0,0],[0,1,0,0,0],[1,1,1,1,1]],[[0,1,1,1,0],[1,0,0,0,1],[0,0,0,0,1],[0,0,1,1,0],[0,0,0,0,1],[1,0,0,0,1],[0,1,1,1,0]],[[1,0,0,1,0],[1,0,0,1,0],[1,0,0,1,0],[1,1,1,1,1],[0,0,0,1,0],[0,0,0,1,0],[0,0,0,1,0]],[[1,1,1,1,1],[1,0,0,0,0],[1,0,0,0,0],[0,1,1,1,0],[0,0,0,0,1],[1,0,0,0,1],[0,1,1,1,0]],[[0,1,1,1,0],[1,0,0,0,1],[1,0,0,0,0],[1,1,1,1,0],[1,0,0,0,1],[1,0,0,0,1],[0,1,1,1,0]],[[1,1,1,1,1],[0,0,0,0,1],[0,0,0,0,1],[0,0,0,1,0],[0,0,0,1,0],[0,0,1,0,0],[0,0,1,0,0]],[[0,1,1,1,0],[1,0,0,0,1],[1,0,0,0,1],[0,1,1,1,0],[1,0,0,0,1],[1,0,0,0,1],[0,1,1,1,0]],[[0,1,1,1,0],[1,0,0,0,1],[1,0,0,0,1],[0,1,1,1,1],[0,0,0,0,1],[1,0,0,0,1],[0,1,1,1,0]]]</script><textarea id='empty' rows='8' cols='32' placeholder='empty space text block...'></textarea><textarea id='filled' rows='8' cols='32' placeholder='filled space text block...'></textarea><br>Digit <input id='digit' type='text' value='0'> <button type='button' onclick='go()'>Generate</button><br><br><textarea id='output' rows='16' cols='64' placeholder='output...' style='background-color: #eee;' readonly></textarea> ``` # Details * None of the 10 large text block programs should require input. Only output the single digit plus an optional trailing newline. Output to stdout or a similar alternative. * None of the programs may read or access their own source code. Treat this like a strict [quine](http://en.wikipedia.org/wiki/Quine_%28computing%29) challenge. * The text blocks may not be identical and must have nonzero dimensions. * The text blocks may contain any characters except [line terminators](http://en.wikipedia.org/wiki/Newline#Unicode). * The 10 programs must be full-fledged programs written in the same language, they are not [REPL](http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) snippets. You may optionally add a trailing newline to all of them or none of them. # Scoring Your score is the area (width times height) of one of your text blocks. (They are the same size so there's no point in counting both blocks.) The area of the example is 3 by 2, for a score of 6. The lowest score wins. In case of ties, the highest-voted answer wins. [Answer] # [><> (Fish)](http://esolangs.org/wiki/Fish), 5 \* 10 = 50 ## Empty block ``` \ !9 4n; n/ 1n;\ \ 0n;n7\\\ ``` ## Solid block ``` \; n8/ /!/!v \ ;6 3n;\ ! /nn 2n;n5< 8; ``` This code contains **no logic or arithmetic** only uses static redirections of ><>'s 2D instruction pointer (IP) with 'mirrors' (`/` and `\`) and two 'arrows' (`<` and `v`). The only other flow-controller is the 'trampoline' (`!`) which jumps through the next character. The IP starts from the top left corner heading East. After some redirections it reaches a number it is pushed onto the stack and printed out with `n` and the program terminates with `;`. ## The program flow A block 'recognizes' the current state of the program from the fact that which point the IP came in and based on the state it decides which direction should it to let out the pointer (which block should be executed next) and in which exact position the pointer should left (which will be the new state). Of course the blocks don't do any logic all this behavior comes from the redirectors. [Answer] # CJam, ~~20~~ ~~18~~ ~~14~~ ~~13~~ 12 \* 1 = 12 Try it online: [0](http://cjam.aditsu.net/#code=%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25), [1](http://cjam.aditsu.net/#code=%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F), [2](http://cjam.aditsu.net/#code=%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F), [3](http://cjam.aditsu.net/#code=%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25), [4](http://cjam.aditsu.net/#code=%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25), [5](http://cjam.aditsu.net/#code=%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25), [6](http://cjam.aditsu.net/#code=%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25), [7](http://cjam.aditsu.net/#code=%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25), [8](http://cjam.aditsu.net/#code=%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25), [9](http://cjam.aditsu.net/#code=%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%0A%5D%3BBG*K%2B%20%3ABD%25%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BB9%2B33%25%3AB4%2F%5D%3BBG*K%2B%20%3ABD%25) **Empty block** ``` ];BG*K+ :BD% ``` **Solid block** ``` ];B9+33%:B4/ ``` ### Explanation I used a similar strategy to [Sp3000's solution](https://codegolf.stackexchange.com/a/47300/18144), such that each block performs a multiplication, an addition, and (possibly) a modulo operation on a variable and saves the value back. To find an optimal solution, I used good old brute force. I wrote a program that searches the space of all possible initial values (the initial values of CJam variables) and many millions of possible pairs of transformation functions such that the output for every digit form is unique. Then, I filtered the results for ones such that the final result for digit forms ending in an empty block, of which there are 8, can be mapped back to the correct result via another multiply, add, and modulo formula. After a couple of days of CPU time of searching, the best result so far is down to a size of 12! This solution starts with a value of `11`, the empty block transformation function is `x * 16 + 20`, the empty block result function is `x % 13`, the solid block transformation function is `(x + 9) % 33`, and the solid block result function is `x / 4`. [Answer] # CJam, ~~23~~ ~~22~~ 19 \* 1 = 19 **Empty block:** ``` ];G)B%:G"73860594"= ``` **Solid block:** ``` ];GW*B+3*D%:G 7- ``` [Try it online](http://cjam.aditsu.net/). I'm trying to get lucky with mathematical coincidences and failing, so here's a slightly different approach to uniqueness mapping from Martin's solution. Start with 16. Empty blocks add 1 and take modulo 11. Solid blocks multiply by -1, add 11, multiply by 3 then take modulo 13. This magically maps `03456789` (the digits which end on an empty block) to `41753026`, which we use indexing to get right. `12` maps neatly to `89`, which we can remedy by subtracting 7. [Answer] # CJam, ~~28~~ 27 x 1 = 27 Here is a start. **Empty block** ``` U):U; ``` **Solid block** ``` ];U):UW+:WF%"1302986_7_54"= ``` [Test it here.](http://cjam.aditsu.net/) I can't give you a permalink with the code, because the code is too long, so you'll have to copy it in manually from the snippet in the challenge. The idea is to hash the shape as follows: * For each "pixel" increment a counter `U`. * For each black "pixel" add `U` to a running total `W` (which starts at `-1`). At the end, we take this modulo `15`, which happens to give unique results, which use to index into a lookup string. [Answer] # [Zsh](https://www.zsh.org) `-F`, 1 \* 34 = 34 Empty block: ``` x+=0;X=5719060800034;(bye 2-x[2]); ``` Solid block: ``` x+=1;(bye X[1+0b$x%13]); ``` Outputs via exit code, which is the simplest way I could think of to get only the final block to output a value. `bye` exits with a status code, and `()` prevents the shell from actually exiting; it only sets the code, so the last value will be the exit code of the whole shell. Each block also appends either `0` or `1` to a string `x`; If the last block is solid (only the case for 1 and 2), the output is 2 - (the second digit of `x`). If the last block is empty, then `0b$x` converts `x` from binary, `%13` takes it modulo thirteen, and then that is indexed into the string `X` which is initialised earlier, to choose the correct output code. Attempt This Online: [0](https://ato.pxeger.com/run?1=m724qjhjwXKN4tQSBV23paUlaboWt1jWVGjbGlprJFWmKkREG2obJKlUqBoax2paK8ABUIWBdYStqbmhpYGZgYWBgYGxCUSHkW5FtBFQLZVUEHAHFzUMoZIKAu4YdeqoU4eSU4dICQAptDZpqtnpp6SW6eeV5uRw2djYqNhDJBYsgNAA) [1](https://ato.pxeger.com/run?1=m724qjhjwXKN4tQSBV23paUlaboWt1jWVGjbGlprJFWmKkREG2obJKlUqBoax2paK8ABUSoMrCNsTc0NLQ3MDCwMDAyMTSA6jHQroo2AaqlhCxdR1lBDBVWcOoRCddSpI9yp9MlWFKuAFFqbNNXs9FNSy_TzSnNyuGxsbFTsIRILFkBoAA) [2](https://ato.pxeger.com/run?1=m724qjhjwXKN4tQSBV23paUlaboWt1jWVGjbGlprJFWmKkREG2obJKlUqBoax2paK8ABUIWBdYStqbmhpYGZgYWBgYGxCUSHkW5FtBFQLZVUEHAHFzUMoZIKAu7goptDhpBTqZIABoVDqOXUQZGaictWg0IFpNDapKlmp5-SWqafV5qTw2VjY6NiD5FYsABCAwA) [3](https://ato.pxeger.com/run?1=m724qjhjwXKN4tQSBV23paUlaboWt1jWVGjbGlprJFWmKkREG2obJKlUqBoax2paK8ABUIWBdYStqbmhpYGZgYWBgYGxCUSHkW5FtBFQLZVUEHAHFzUMoZIKAu7goptDBo1T6ZQAhlCoDqu0OihKAEihtUlTzU4_JbVMP680J4fLxsZGxR4isWABhAYA) [4](https://ato.pxeger.com/run?1=m724qjhjwXKN4tQSBV23paUlaboWt1jWVGjbGlhH2JqaG1oamBlYGBgYGJtYayRVpioY6VZEG8VqWgNVGEJEIqINtQ2SVCpUDY2B4gpwQJQKim3hGnXqgDl1UKjgolKY0SlUR51KbadCCq1Nmmp2-impZfp5pTk5XDY2Nir2EIkFCyA0AA) [5](https://ato.pxeger.com/run?1=m724qjhjwXKN4tQSBV23paUlaboWt1jWVGjbGlhH2JqaG1oamBlYGBgYGJtYayRVpioY6VZEG8VqWg8WFVxEGWIIEYmINtQ2SFKpUDU0BoorwAF9VAwxpxI2hD4JgCpOpY-KIZRWiXDqEEkAkEJrk6aanX5Kapl-XmlODpeNjY2KPURiwQIIDQA) [6](https://ato.pxeger.com/run?1=m724qjhjwXKN4tQSBV23paUlaboWt1jWVGjbGlprJFWmKkREG2obJKlUqBoax2paK8ABUIWBdYStqbmhpYGZgYWBgYGxCUSHkW5FtBFQLZVUEHAHFzUMoZIKAu4YTE6lSqiOJoChmwCIcOoQKQEghdYmTTU7_ZTUMv280pwcLhsbGxV7iMSCBRAaAA) [7](https://ato.pxeger.com/run?1=m724qjhjwXKN4tQSBV23paUlaboWt1jWVGjbGlhH2JqaG1oamBlYGBgYGJtYayRVpioY6VZEG8VqWg8WFVxAJYYQoYhoQ22DJJUKVUNjoIQCHNBNxahTqe4QwmaMQKdS7JBh5VRIobVJU81OPyW1TD-vNCeHy8bGRsUeIrFgAYQGAA) [8](https://ato.pxeger.com/run?1=m724qjhjwXKN4tQSBV23paUlaboWt1jWVGjbGlprJFWmKkREG2obJKlUqBoax2paK8ABUIWBdYStqbmhpYGZgYWBgYGxCUSHkW5FtBFQLZVUEHAHFzUMoZIKAu4YYk4dTQCjCWAoJABIobVJU81OPyW1TD-vNCeHy8bGRsUeIrFgAYQGAA) [9](https://ato.pxeger.com/run?1=m724qjhjwXKN4tQSBV23paUlaboWt1jWVGjbGlprJFWmKkREG2obJKlUqBoax2paK8ABUIWBdYStqbmhpYGZgYWBgYGxCUSHkW5FtBFQLZVUEHAHFzUMoZIKAu4YYk4dLAmAKk4dNKE6mgCoXQJACq1Nmmp2-impZfp5pTk5XDY2Nir2EIkFCyA0AA) Here's the code for 5: ``` x+=0;X=5719060800034;(bye 2-x[2]);x+=0;X=5719060800034;(bye 2-x[2]);x+=0;X=5719060800034;(bye 2-x[2]);x+=0;X=5719060800034;(bye 2-x[2]);x+=0;X=5719060800034;(bye 2-x[2]); x+=0;X=5719060800034;(bye 2-x[2]);x+=1;(bye X[1+0b$x%13]); x+=1;(bye X[1+0b$x%13]); x+=1;(bye X[1+0b$x%13]); x+=1;(bye X[1+0b$x%13]); x+=0;X=5719060800034;(bye 2-x[2]);x+=1;(bye X[1+0b$x%13]); x+=1;(bye X[1+0b$x%13]); x+=1;(bye X[1+0b$x%13]); x+=1;(bye X[1+0b$x%13]); x+=1;(bye X[1+0b$x%13]); x+=0;X=5719060800034;(bye 2-x[2]);x+=0;X=5719060800034;(bye 2-x[2]);x+=0;X=5719060800034;(bye 2-x[2]);x+=1;(bye X[1+0b$x%13]); x+=1;(bye X[1+0b$x%13]); x+=1;(bye X[1+0b$x%13]); x+=1;(bye X[1+0b$x%13]); x+=1;(bye X[1+0b$x%13]); x+=0;X=5719060800034;(bye 2-x[2]); x+=0;X=5719060800034;(bye 2-x[2]);x+=1;(bye X[1+0b$x%13]); x+=1;(bye X[1+0b$x%13]); x+=1;(bye X[1+0b$x%13]); x+=0;X=5719060800034;(bye 2-x[2]); x+=1;(bye X[1+0b$x%13]); x+=0;X=5719060800034;(bye 2-x[2]);x+=0;X=5719060800034;(bye 2-x[2]);x+=0;X=5719060800034;(bye 2-x[2]);x+=1;(bye X[1+0b$x%13]); ``` Each block, read left-to-right, constructs the string `00000011110111110001111100111010001`, which is 519633361 in binary. This modulo 13 is 0, and then the 1+0'th character of `X` (`5719060800034`) is 5, so that's the exit code. [Answer] # [Python 3](https://docs.python.org/3/), 73 bytes ## empty code: ``` a,b=id and(0,1)or(2*a+0,b+1);id=b>34and print(b'XH"V;G F@D'.index(a%91)); ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P1EnyTYzRSExL0XDQMdQM79Iw0grUdtAJ0nbUNM6M8U2yc7YBCipUFCUmVeikaQe4aEUZu0u7ebgoq6XmZeSWqGRqGppqKlp/f8/AA "Python 3 – Try It Online") ## solid code: ``` a,b=id and(1,1)or(2*a+1,b+1);id=b>34and print(b'XH"V;G F@D'.index(a%91)); ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P1EnyTYzRSExL0XDUMdQM79Iw0grUdtQJ0nbUNM6M8U2yc7YBCipUFCUmVeikaQe4aEUZu0u7ebgoq6XmZeSWqGRqGppqKlp/f8/AA "Python 3 – Try It Online") both code contains unprintable chars ## How it works: * on the first occurence of either empty or solid: as `id` is a python built-in, it is evaluated as `True` so `id and <first> or <second>` will evaluate `<first>` which initialise `a` and `b`. Then `id` is set to `0` * `a` is the binary representation of the code with `0` for empty and `1` for solid * `b` is the number of bloc executed. * when b is equal to `35` (last bloc) it prints the result. * `print(b'XH"V;G F@D'.index(a%91))` prints the index of the char whose codepoint is equal to `a%91` (which is the right result) ]
[Question] [ Given an integer, output an upside-down tent. The input determines both the size of the tent (absolute value) and whether the entrance is on the left side (negative numbers) or the right side (positive numbers). ``` If input = -1: ____ \/_/ If input = -2: ________ \ / / \/___/ If input = -3: ____________ \ / / \ / / \/_____/ If input = 1: ____ \_\/ If input = 2: ________ \ \ / \___\/ If input = 3: ____________ \ \ / \ \ / \_____\/ et cetera ``` Note that the top of the tent (i.e. the last line) has `2 * abs(input) - 1` underscores. There can be *no* leading spaces, such that the first line directly starts with an underscore. Assume that the input will never be `0`. Your code should be as short as possible. *This challenge is based on a [chat mini challenge by Helka Homba](http://chat.stackexchange.com/transcript/240?m=24672370#24672370), which is allowed to be used in real challenges under the conditions of [Calvin's Hobbies Public License](http://chat.stackexchange.com/transcript/240?m=27296595#27296595)*. [Answer] # [MATL](http://github.com/lmendo/MATL), ~~55~~ ~~53~~ ~~52~~ 51 bytes ``` |95cy4*Y"DXytPEt0*yvG0>?P_]!'\/ 'w)95JG|G0<yEq:++&( ``` [Try it online!](http://matl.tryitonline.net/#code=fDk1Y3k0KlkiRFh5dFBFdDAqeXZHMD4_UF9dISdcLyAndyk5NUpHfEcwPHlFcTorKyYo&input=LTM) ### Explanation Let `N` denote the input. The code proceeds in three steps. **First**, the first line of `4*N` underscores is built as a string and is displayed (which removes it from the stack). **Second**, the "frame" of the tent is built using the two types of slashes. To do this, a numerical 2D array is created which contains `1` and `2` corresponding to the two types of slashes, and `0` for space. This is done concatenating four matrices: 1. An identity matrix of size `abs (N)`; 2. A matrix of the same size containing `2` in the antidiagonal; 3. A null matrix of the same size; 4. A copy of matrix 2. Concatenating these four matrices vertically gives, using `N=3` as an example, the following `4*N × N` matrix: ``` 1 0 0 0 1 0 0 0 1 0 0 2 0 2 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 2 0 2 0 0 ``` (which, transposed, begins to look like the tent). We now take care of the sign of the input. If it is positive we simply transpose the above matrix and index into the string `'\/ '`. Indexing is 1-based and modular, so `1` becomes `'\'`, `2` becomes `'/'` and `0` becomes `' '`, producing the 2D char array ``` \ / / \ / / \/ / ``` On the other hand, if the input is negative we vertically flip and arithmetically negate the `4*N × N` matrix, producing ``` -2 0 0 0 -2 0 0 0 -2 0 0 0 0 0 0 0 0 0 -2 0 0 0 -2 0 0 0 -2 0 0 -1 0 -1 0 -1 0 0 ``` Index `-1` now refers to `'/'` and `-2` to `'\'`. That is, the two types of slashes have been interchanged, as required. Again transposing and indexing into the string `'\/ '` thus gives the reversed tent: ``` \ \ / \ \ / \ \/ ``` **Third**, underscores need to be filled into part of the last row of the 2D char array. The horizontal position of this line depends on the sign of the input, and its lenght is `abs(N)`. Once the corresponding spaces have been replaced by underscores, the result is implicitly displayed, below the initial line of underscores that was already displayed in the first step. [Answer] ## Javascript (ES6), 139 bytes Builds the tent recursively: ``` f=(N,n=N>0?N:-N,i=0,r=(j,i)=>' _'[i||0].repeat(j),a=`\\${r(i)}/`,b=r(n*2+i-1,+!i))=>n--?f(N,n,i+2)+` `+r(n)+(N<0?a+b+'/':'\\'+b+a):r(i*2,1) ``` ### Ungolfed and commented ``` f = ( N, // N is the original parameter (remains unchanged) n = N > 0 ? N : -N, // n is initialized to abs(N) i = 0, // i is the row counter (*2) r = (j, i) => ' _'[i||0].repeat(j), // helper function to repeat ' ' or '_' j times a = `\\${r(i)}/`, // a = '\ /' pattern b = r(n*2+i-1, +!i) // b = padding pattern filled with ' ' or '_' ) => n-- ? // if we haven't made it yet to the top row: f(N, n, i+2) + `\n` + // - compute next row(s) / append line break r(n) + // - append leading spaces (N < 0 ? a+b+'/' : '\\'+b+a) // - append a/b patterns according to N sign : // else: r(i*2, 1) // - return top row, made of '_' characters ``` ### Examples ``` var f=(N,n=N>0?N:-N,i=0,r=(j,i)=>' _'[i||0].repeat(j),a=`\\${r(i)}/`,b=r(n*2+i-1,+!i))=>n--?f(N,n,i+2)+` `+r(n)+(N<0?a+b+'/':'\\'+b+a):r(i*2,1) console.log(f(3)); console.log(f(-4)); ``` [Answer] # Python 2, ~~143 141 139 138~~ 137 bytes -2 bytes thanks to @Sp3000 (no need to parenthesise exec in Python 2) -1 byte thanks to @Sp3000 (use `cmp`) ``` def f(n):d=cmp(n,0);a,b='\/'[::-d];s=n*d;x=2*s-1;y=4*s;print'_'*y;i=0;exec"print' '*i+(b+' '*(y-3-x-i-i)+a+'_ '[s-i>1]*x+a)[::d];i+=1;"*s ``` Test it at **[ideone](http://ideone.com/WemGmB)** First we see if `n` is negative and make `d` `+1` if it is and `-1` if not. Then we select the two slashes, `a` and `b`, using `d` such that `a='\', b='/'` when `n` is positive and `a='/', b='\'` when `n` is negative. Next we set `s=abs(n)` which may be achieved by `s=n*d`. Then we calculate the number of `_` at the top (bottom of the picture), which is also the number of in the side of the tent as `x=2*s-1`. Then we calculate the number of `_` at the base of the tent (top of the picture), and store it as `y=4*s` since it will be used in the loop to create the rest of the tent. Now we print the base of the tent using `print'_'*y`. Then we print the rest of the tent by executing `s` print statements with a looping variable `i` initialised to `0` which increments by `1` for each print statement. The rest of the tent then has `y-3-x-i-i` spaces in the door and `x` spaces in the body until the top is reached, when `s-i>1` evaluates to False, picking the `_` from `'_ '`. For a positive, left-door, tent the whole of the tent, excluding the leading spaces is back-to-front, so it is reversed while the positive, 'right-door', tent is not with `[::d]`. [Answer] ## Python 2, 121 bytes ``` def f(n):i=k=abs(n);print'_'*k*4;exec"print' '*(k-i)+r'\\\%%s%\*%c%%*sc/'[n<0::2]%(' _'[i<2]*(2*k-1))%(2*i-1,47);i-=1;"*k ``` Just a lot of string formatting. [Answer] # C#, ~~215~~ 214 bytes ``` string t(int N){var n=N<0;N=n?-N:N;var t=new string('_',4*N);for(int i=0;i<N;){string f=new string(i<N-1?' ':'_',2*N-1),p=new string(' ',2*N-2*i-2);t+='\n'+new string(' ',i++)+'\\'+(n?p+'/'+f:f+'\\'+p)+'/';}return t;} ``` There's a possibility to save a few bytes when using `using s=string;` beforehand. ``` s t(int N){var n=N<0;N=n?-N:N;var t=new s('_',4*N);for(int i=0;i<N;){s f=new s(i<N-1?' ':'_',2*N-1),p=new s(' ',2*N-2*i-2);t+='\n'+new s(' ',i++)+'\\'+(n?p+'/'+f:f+'\\'+p)+'/';}return t;} ``` which would be 15 (using) + 184 (method) = 199 bytes. [Answer] # TSQL, 195 bytes **Golfed:** ``` DECLARE @ INT=-2 DECLARE @b INT=ABS(@),@i INT=0PRINT REPLICATE('_',4*@b)z:SET @i+=1PRINT SPACE(@i-1)+'\'+STUFF(REPLICATE(IIF(@i<@b,' ','_'),4*@b-2*@i),@b*2-IIF(@<0,@i*2-1,0),1,IIF(@<0,'/','\'))+'/'IF @i<@b GOTO z ``` **Ungolfed:** ``` DECLARE @ INT=-2 DECLARE @b INT=ABS(@),@i INT=0 PRINT REPLICATE('_',4*@b) z: SET @i+=1 PRINT SPACE(@i-1)+'\' +STUFF(REPLICATE(IIF(@i<@b,' ','_'), 4*@b-2*@i),@b*2-IIF(@<0,@i*2-1,0),1,IIF(@<0,'/','\')) +'/' IF @i<@b GOTO z ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/539298/output-an-upside-down-tent)** [Answer] # [V](http://github.com/DJMcMayhem/V), 66 bytes ``` é /ä "aDoÀñá_>ñ^hr\A\/ò^hÄX$2é_Ó_/ òÄÒ_ñ/- ddÍܨ[ _]*©Ü¨ *©/ܲ¯± ``` [Try it online!](http://v.tryitonline.net/#code=w6kgL8OkCiJhRG8bw4DDscOhXz7DsV5oclxBXC8bw7JeaMOEWCQyw6lfw5NfLyDDssOEw5Jfw7EvLQpkZMONw5zCqFsgX10qwqnDnMKoICrCqS_DnMKywq_CsQ&input=LTQ) This is a pretty naive approach, so I'll try to golf it down further later today. This solution contains unprintable characters, so here is a hexdump: ``` 0000000: e920 2fe4 0a22 6144 6f1b c0f1 e15f 3ef1 . /.."aDo...._>. 0000010: 5e68 725c 415c 2f1b f25e 68c4 5824 32e9 ^hr\A\/..^h.X$2. 0000020: 5fd3 5f2f 20f2 c4d2 5ff1 2f2d 0a64 64cd _._/ ..._./-.dd. 0000030: dca8 5b20 5f5d 2aa9 dca8 202a a92f dcb2 ..[ _]*... *./.. 0000040: afb1 .. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 52 bytes ``` Ä©'_4®*×,FNð×'\®·<N>®Qi'_ëð}×®N>-·ð×®¹Qi'\ës'/}s'/J, ``` **Explanation** ``` # implicit input, call this A Ä© # store abs(A) in register for later use '_4®*×, # print 4*A underscores (tent floor) F # for each non-floor section in range(N) Nð×'\ # push N spaces at the beginning of the # row followed by a backslash N>®Qi'_ëð} # if we're on the last row push an # underscore, else a space ®·< × # repeat that char abs(A)*2-1 times ®N>-·ð× # push 2*(abs(A)-(N+1)) spaces ®¹Qi'\ës'/} # if input is positive push backslash # else push a slash s'/ # move that char between the 2 sections # of spaces J, # join the row and print ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w4TCqSdfNMKuKsOXLEZOw7DDlydcwq7CtzxOPsKuUWknX8Orw7B9w5fCrk4-LcK3w7DDl8KuwrlRaSdcw6tzJy99cycvSiw&input=Mw) [Answer] ## PowerShell v2+, ~~217~~ ~~205~~ ~~190~~ ~~187~~ 184 bytes ``` param($b)"_"*(($a=[math]::Abs($b))*4);$z,$y='/\'[($b=$b-lt0),!$b] ((($x=1..$a|%{($w=" "*($_-1))+$z+" "*(2*($a-$_))+$y+(' ','_')[$_-eq$a]*($a*2-1)+$y+$w})|%{-join$_[($a*4)..0]}),$x)[$b] ``` Takes input `$b` as an integer. Note that if `$b` is negative, you need to explicitly surround it with parens to cast it appropriately (see examples), else PowerShell will think it's a string. Regardless of which direction the tent is facing, the first line is the same, a bunch of underscores; exactly `4*abs(input)` many of them, actually. That number is also stored into `$a` for use later. Additionally, now that we have the absolute value of `$b` stored into `$a`, we turn `$b` into a Boolean for its sign, and choose our slashes stored into `$y` and `$z`. The next line is constructing and formulating the output, and it's a doozy, so let's break it down. We're essentially indexing into an array of two elements, `(big long calculations saved into $x)` or `$x`, based on `$b`. The calculations are where the tent body is constructed. We loop from `1..$a|%{...}`. Each iteration we're constructing a line of the tent body. We start with a number of spaces equal to the line # we're on `-1`, so that it's appropriately left-aligned. That's stored into `$w` for later, and concatenated with the appropriate slash ($z, based on `$b`), then the doorframe number of spaces, then the other slash `$y`, then either underscores or spaces depending upon if we're on the bottom line or not, then another slash `$y`, and finally the appropriate number of trailing spaces (`$w`) to construct a rectangular string. That resulting array of strings is stored into `$x`. If the left half of the array is selected (i.e., `$b` is `False` since the input was positive), then we need to loop through `$x` and reverse each line item -- this is where the trailing spaces come into play; it allows us to simply reverse the lines rather than re-calculate distances. If `$b` is `True`, then the right half of the array `$x` is selected instead. In either case, the pipeline now contains an array of strings. Implicit output via `Write-Output` happens at program completion, with default newline between elements. ### Examples ``` PS C:\Tools\Scripts\golfing> .\print-upside-down-tent.ps1 (-5) ____________________ \ / / \ / / \ / / \ / / \/_________/ PS C:\Tools\Scripts\golfing> .\print-upside-down-tent.ps1 (4) ________________ \ \ / \ \ / \ \ / \_______\/ ``` [Answer] # Haskell, ~~187~~ ~~184~~ 183 bytes ``` f x=unlines$[(n*4)%'_']++((' '#)<$>[0..n-2])++['_'#(n-1)]where m#i=i%' '++'\\':m!i++"/";m!i|x>0=(2*n-1)%m++'\\':(2*(n-i-1))%' '|q<-2*(n-i-1)=q%' '++'/':(2*n-1)%m;n=abs x;m%c=c<$[1..m] ``` I feel like this is not a great score for Haskell, so any ideas for improvement are welcome. * 3 bytes saved thanks to [@Myridium](https://codegolf.stackexchange.com/users/59657) * 1 byte saved thanks to [@nimi](https://codegolf.stackexchange.com/users/34531) **Ungolfed** ``` tent :: Int -> String tent x = unlines $ [replicate (n*4) '_'] ++ (row ' '<$>[0..n-2]) ++ [row '_' (n-1)] where row m i = replicate i ' ' ++ "\\" ++ dir m i ++ "/" -- direction selector dir m i | x > 0 = side m ++ "\\" ++ entrance i ' ' | 1 > 0 = entrance i ' ' ++ "/" ++ side m side = replicate (2*n-1) entrance i = replicate (2*(n-i-1)) n = abs x ``` [Answer] # C, ~~240~~ ~~207~~ 193 Bytes ``` #define P putchar a,j,l,m;g(x,y,z){for(m=y+z+1;m--;P(m^z?l?32:95:x));}f(n){g(32,(a=abs(n))*4,0);for(P(10),j=2*(l=a)-1;l--;){for(m=a;--m>l;P(32));P(92);m=n>0?g(92,j,l*2):g(47,l*2,j);puts("/");}} ``` This time I optimized the function g(...) to use a single for loop. ``` #define P putchar a,j,l,m;g(x,y,z){for(;y--;P(l?32:95));for(P(x);z--;P(l?32:95));}f(n){g(32,(a=abs(n))*4,0);l=a;j=2*a-1;P(10);for(;l--;){for(m=a;--m>l;P(32));P(92);m=n>0?g(92,j,l*2):g(47,l*2,j);puts("/");}} ``` This time macro X is better off as a function g(...) and since y and z are parameters in a new scope I can just decrement them in the scope of g. ``` #define P putchar #define X(x,y,z){for(k=0;k++<y;P(l?32:95));P(x);for(k=0;k++<z;P(l?32:95));} a,i,j,k,l,m;f(n){for(l=a=abs(n);i++<a*4;P(95));j=2*a-1;P(10);while(l--){for(m=a;--m>l;P(32));P(92);if(n>0)X(92,j,l*2)else X(47,l*2,j)puts("/");}} ``` Test with this main function; This should golf down much smaller. ``` main(c,v)char**v; { f(atoi(v[1])); } ``` [Answer] # C# 241 231 Bytes Saved 10 bytes thanks to @Kevin Cruijssen ``` using s=System.String;s f(int N){var f=N<0;N=N>0?N:-N;var o=new s('_',N*4);for(int j=0,z;j<N;){z=-2*j+2*N-2;var O=j>N-2?'_':' ';o+='\n'+new s(' ',j)+'\\'+new s(' ',z)+(f?'/':O)+new s(O,j++*2)+(f?O:'\\')+new s(' ',z)+'/';}return o;} ``` Old version: ``` string f(int N){var f=N<0;N=N>0?N:-N;var o=new string('_',N*4);for(int j=0;j<N;){int z=-2*j+2*N-2;var O=j>N-2?'_':' ';o+='\n'+new string(' ',j)+'\\'+new string(' ',z)+(f?'/':O)+new string(O,j++*2)+(f?O:'\\')+new string(' ',z)+'/';}return o;} ``` Originally had the `new string(...)` as a `Func<char,int,string>` but saved one byte using the constructor. I wish `int`->`char` was implicit Pretty sure my math can be fixed somehow too, but I can't see it [Answer] # Swift 2.2 421 bytes Well... This was an attempt. Golfed: ``` let t={(s:String,n:Int)->String in return String(count:n,repeatedValue:Character(s))};let e={(n:Int)in var w=[String]();w.append(t("_",abs(n)*4));let c = abs(n);let d = n>0 ? "/": "\\";let f = n>0 ? "\\": "/";for var i in 0...abs(n)-1 {w.append(t(" ",i)+d+t(" ",c*2-2-(2*i))+f+(i<c-1 ?t(" ",2*c-1)+f:t("_",2*c-1)+f)+(n>0 ?t(" ",i):""));};w=n<0 ?w:w.map(){String($0.characters.reverse())};print(w.joinWithSeparator("\n"))} ``` UnGolfed: ``` let t={(s:String,n:Int) -> String in return String(count:n,repeatedValue:Character(s)) }; let e={(n:Int) in var w=[String](); w.append(t("_",abs(n)*4)); let c = abs(n); let d = n>0 ? "/": "\\"; let f = n>0 ? "\\": "/"; for var i in 0...abs(n)-1 { w.append(t(" ",i)+d+t(" ",c*2-2-(2*i))+f+(i<c-1 ?t(" ",2*c-1)+f:t("_",2*c-1)+f)+(n>0 ?t(" ",i):"")); }; w=n<0 ?w:w.map(){String($0.characters.reverse())}; print(w.joinWithSeparator("\n")) } ``` [Answer] # PHP, 143 bytes ``` $t=str_repeat;echo$t(_,4*$s=$k=abs($n=$argv[1]));for(;$k--;$p.=" "){$f=$t(" ",$k);$r=$t($k?" ":_,2*$s-1);echo" $p\\",$n<0?"$f/$r/":"$r\\$f/";} ``` run with `php -r '<code>' <parameter>` **breakdown** ``` $t=str_repeat; // function name to variable saves 10-1 bytes echo$t(_,4*$s=$k=abs($n=$argv[1])); // print bottom for( ; $k--; // $k from abs($n-1) to 0 $p.=" " // create padding ) { $f=$t(" ",$k); // create front $r=$t($k?" ":_,2*$s-1); // create side/roof echo"\n$p\\",$n<0 ?"$f/$r/" // print, entrance left :"$r\\$f/" // print, entrance right ; } ``` [Answer] ## Batch, 289 bytes ``` @echo off set/pn= set u= for /l %%i in (2,1,%n:-=%)do call set u=_%%u%%_ echo _%u%__%u%_ set l= set m=%u%/_%u% if %n% gtr 0 set m=%u%_\%u% set m=%m:_= % for /l %%i in (2,1,%n:-=%)do call:l set m=%m: =_% :l echo %l%\%m%/ set l= %l% if %n% gtr 0 set m= %m:~0,-2% set m=%m:~2% ``` Takes input on STDIN. Starts by creating a string of `2*(abs(n)-1)` underscores. This is then repeated plus an additional 4 underscores for the base of the tent. The rest of the tent then consists of an indent (which increases by 1 on each line), a `\`, the middle of the tent, and a `/`. The middle of the tent starts as `2*(abs(n)-1)` spaces, plus either `\` or `/` plus a space (which I can't represent in Markdown), plus another `2*(abs(n)-1)` spaces. I reuse the underscore string and change them to spaces for convenience, but then change the spaces back to underscores for the last line. Each line removes two spaces from one side of the middle of the tent, although it's slightly golfier to move the two spaces to the start of the string first if necessary. [Answer] # [Canvas](https://github.com/dzaima/Canvas), 25 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ⤢\║l╵:╷:«_×╋l/+L_×;∔⁸0>?↔ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyOTIyJXVGRjNDJXUyNTUxJXVGRjRDJXUyNTc1JXVGRjFBJXUyNTc3JXVGRjFBJUFCXyVENyV1MjU0QiV1RkY0QyV1RkYwRiV1RkYwQiV1RkYyQ18lRDcldUZGMUIldTIyMTQldTIwNzgldUZGMTAldUZGMUUldUZGMUYldTIxOTQ_,i=LTU_,v=8) ]
[Question] [ Find the longest run of true in a list of booleans. Return the same list, with all other trues falsified. ## Input, output A list; any usual format (e.g., a delimited list as a string). ## Details True and false can be anything your language typically uses for those values, or the integers 1 and 0. If you use single characters, the list can be a concatenation (e.g., `10001`). If there's a tie for longest run, keep all tying runs true, and falsify all shorter runs. ## Examples ``` input ↦ output 1,0,1,0,1 ↦ 1,0,1,0,1 1,1,0,1,1,0,1 ↦ 1,1,0,1,1,0,0 1,1,0,1,1,1,0,1,1 ↦ 0,0,0,1,1,1,0,0,0 1,1,1 ↦ 1,1,1 0,0,1 ↦ 0,0,1 0,0 ↦ 0,0 1,1,1,0,0,0,1,1,1,1,0,1,0,0,1,1,0,1,1,1,1,0,0,1,0 ↦ 0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0 ``` (directly from <https://stackoverflow.com/q/37447114>) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṣ0¬¬M¦j0 ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmjMMKswqxNwqZqMA&input=&args=MSwxLDEsMCwwLDAsMSwxLDEsMSwwLDEsMCwwLDEsMSwwLDEsMSwxLDEsMCwwLDEsMA) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmjMMKswqxNwqZqMArDh-KCrEc&input=&args=W1sxLDAsMSwwLDFdLCBbMSwxLDAsMSwxLDAsMV0sIFsxLDEsMCwxLDEsMSwwLDEsMV0sIFsxLDEsMV0sIFswLDAsMV0sIFswLDBdLCBbMSwxLDEsMCwwLDAsMSwxLDEsMSwwLDEsMCwwLDEsMSwwLDEsMSwxLDEsMCwwLDEsMF1d). ### How it works ``` ṣ0¬¬M¦j0 Main link. Argument: A (list of Booleans) ṣ0 Split at zeroes. This leaves a 2D list of ones. ¬ Negate each 1, replacing it with 0. ¦ Conditional application: M Yield all maximal indices. In lexicographical list comparison, a shorter list of zeroes is less than a longer one, so this identifies the longest runs. ¬ Negate the items in those lists, changing zeroes back to ones. j0 Join, separating by single zeroes. ``` [Answer] # Haskell, ~~59~~, ~~58~~, ~~55~~, 64 bytes ``` import Data.List ((=<<)=<<(=<<)(<$).(==).maximum.([1<2]:)).group ``` Fun note, this works on any list of values where `falsy < truthy`. So `False/True`, `0/1`, `'f'/'t'`, etc. ### Note: As several people have pointed out (including `@proud haskeller` and `@nimi`), the previous version failed on a list of all falsy values. The addition of `.([1<2]:)` has fixed this, as suggested by `@proud haskeller`. I'm leaving the explanation the same for now, because I think it still makes sense. If anyone comments, asking for an explanation of the edit, I'll edit. ## Explanation: I'll first desugar without the `group`, and then add it back. First, I find that words are often easier on the eyes than symbols, so I'll make a few substitutions. (Note that `=<<` is 'classy' so it applies differently for lists and functions. I'm calling `bind` the version of `=<<` for functions.) ``` bind :: (a -> b -> c) -> (b -> a) -> b -> c bind k f = k =<< f bind k f = \ r -> k (f r) r f = ((=<<)=<<(=<<)(<$).(==).maximum) f = ((bind) concatMap (bind)(<$).equals.maximum) f = (bind concatMap (bind (<$) . equals . maximum)) f = bind concatMap ((bind (<$)) . equals . maximum)) f = bind concatMap ((\f r -> (<$) (f r) r) . equals . maximum)) f = bind concatMap ((\f r -> (f r) <$ r) . equals . maximum) f = bind concatMap ((\g r -> (g r) <$ r) . equals . maximum) f = (\h r -> concatMap (h r) r) ((\g r -> (g r) <$ r) . equals . maximum) f = \r -> concatMap (((\g r -> (g r) <$ r) . equals . maximum) r) r f = \r -> concatMap (((\g r -> (g r) <$ r) . equals) (maximum r)) r f = \r -> concatMap (((\g s -> (g s) <$ s)) (equals (maximum r))) r f = \r -> concatMap (((\s -> ((equals (maximum r)) s) <$ s))) r f = \r -> concatMap (\s -> (s == (maximum r)) <$ s) r f . group = ((=<<)=<<(=<<)(<$).(==).maximum).group f . group = \r -> concatMap (\s -> (s == (maximum (group r))) <$ s) (group r) ``` The last details are that `x <$ list` replaces every element of the `list` with `x` and `group list` splits the `list` up into chunks of equal elements. So `group [1, 1, 2, 3, 3, 3] == [[1, 1], [2], [3, 3, 3]]`. To sum it all up, the function splits the list of values into groups of only true and groups of only false. Then for each group, replace each element with the result of the statement `this is the biggest group` (the largest group of `true`'s will be the biggest) and concatenate the groups. Four bytes saved by `@Zgarb` [Answer] # Retina, ~~47~~ ~~43~~ 36 ``` 0 ! T`p`0`\b(1+)\b(?<=(?=.*1\1).*)|! ``` [Try it online!](http://retina.tryitonline.net/#code=MAohClRgcGAwYFxiKDErKVxiKD88PSg_PS4qMVwxKS4qKXwh&input=MTExMDAwMTExMTAxMDAxMTAxMTExMDAxMA) or [try all the test cases](http://retina.tryitonline.net/#code=JShHYAowCiEKVGBwYDBgXGIoMSspXGIoPzw9KD89LioxXDEpLiopfCE&input=MTExMDAwMTExMTAxMDAxMTAxMTExMDAxMAoxMDEwMQoxMTAxMTAxCjExMDExMTAxMQoxMTEKMDAxCjAw) Thanks to msh210 for golfing 4 bytes! Also big thanks to Martin for 7 bytes! ### Explanation: ``` 0 ! ``` Replace all `0`s with `!`s. This is done to make matching groups of `1`s shorter, as now `1!` and `!1` will have a word boundary (`\b`) between them, which also matches either the start or the end of the string. ``` T`p`0` ``` This is a configuration option saying that after applying the regex after the backtick to the input, in every match translate every printable ascii character into a `0` character. ``` \b(1+)\b(?<=(?=.*1\1).*)|! ``` This regex matches groups of `1`s that are surrounded by zeroes, but do cannot match a `1` followed by itself anywhere in the string. These are the non-maximal groups that will be falsified. In addition, this also matches the `!` characters we added to convert them back into `0`s. [Answer] # MATL, 14 bytes ``` Y'yy*X>y=b*wY" ``` [**Try it Online!**](http://matl.tryitonline.net/#code=WSd5eSpYPnk9Yip3WSI&input=WzEsMSwxLDAsMCwwLDEsMSwxLDEsMCwxLDAsMCwxLDEsMCwxLDEsMSwxLDAsMCwxLDBd) [Modified version with all test cases](http://matl.tryitonline.net/#code=YFkneXkqWD55PWIqd1kiRFRd&input=WzEsMCwxLDAsMV0KWzEsMSwwLDEsMSwwLDFdClsxLDEsMCwxLDEsMSwwLDEsMV0KWzEsMSwxXQpbMCwwLDFdClswLDBdClsxLDEsMSwwLDAsMCwxLDEsMSwxLDAsMSwwLDAsMSwxLDAsMSwxLDEsMSwwLDAsMSwwXQ) **Explanation** ``` % Implicitly grab the input as an array Y' % Perform run-length encoding of the input. Yields an array of values and an array % of run-lengths yy % Copy these outputs * % Multiply the values (booleans) by the run-lengths. This will zero-out all % zero-valued runs so we don't consider them when computing the longest run. X> % Compute the longest run of 1's y % Copy the run lengths vector = % Determine which runs are the same length as the longest run of ones b* % Bubble-up the values from the run-length encoding and multiply element-wise % With this boolean. This substitutes all 1's that are not in the longest run % of ones with 0's w % Flip the run-lengths and values on the stack Y" % Perform run-length decoding using these substituted values % Implicitly display the resulting boolean ``` [Answer] # Python 2, 62 bytes ``` lambda s:'0'.join(`1-(t+'1'in s)`*len(t)for t in s.split('0')) ``` Test it on [Ideone](http://ideone.com/Ea7lOx). ### How it works `s.split('0')` splits the input string **s** into runs of zero or more **1**'s For each run **t**, we check whether `t+'1'` is a substring of **s**. * If it is, the run isn't maximal, `t+'1'in s` return **True**, `1-(t+'1'in s)` return **1 - True = 0** and the run is replaced with a run of **0**'s of the same length. * If it isn't, the run is maximal, `t+'1'in s` return **False**, `1-(t+'1'in s)` return **1 - False = 1** and the run is replaced with a run of **1**'s of the same length, i.e., by itself. Finally, `'0'.join` restores all removed **0**'s. [Answer] ## J, 25 bytes ``` [:(}.=>./)@;0<@(*#);.1@,] ``` This is a monadic verb that takes and returns a 0-1 array. Use it like this: ``` f =: [:(}.=>./)@;0<@(*#);.1@,] f 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 0 0 ``` ## Explanation ``` [:(}.=>./)@;0<@(*#);.1@,] Input is y. 0 ,] Prepend 0 to y, and ;.1@ cut the result along occurrences of 0, so that each piece begins with a 0. (*#) Multiply each piece element-wise by its length, <@ and put it in a box. Without the boxing, the pieces would go in a 0-padded array. ; Join the pieces back together. Now all runs of 1 have been replaced by runs of (1+length of run). [:( )@ Apply verb in parentheses: }. remove the prepended 0, = form the 0-1 array of equality with >./ the maximum value. ``` [Answer] # Pyth, ~~26~~ ~~24~~ ~~23~~ 21 bytes ``` M,G&HGJrgMrQ8 9qReSJJ ``` [Test suite.](http://pyth.herokuapp.com/?code=M%2CG%26HGJrgMrQ8+9qReSJJ&test_suite=1&test_suite_input=[1%2C0%2C1%2C0%2C1]%0A[1%2C1%2C0%2C1%2C1%2C0%2C1]%0A[1%2C1%2C0%2C1%2C1%2C1%2C0%2C1%2C1]%0A[1%2C1%2C1]%0A[0%2C0%2C1]%0A[0%2C0]%0A[1%2C1%2C1%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C0%2C1%2C0%2C0%2C1%2C1%2C0%2C1%2C1%2C1%2C1%2C0%2C0%2C1%2C0]&debug=0) * Uses `1/0` or `true/false` in input. * Uses `true/false` in output. ### Explanation ``` M,G&HGJrgMrQ8 9qReSJJ Q input r 8 run-length encode gM convert each run of 1 to their length for example: [1,1,1,0,1,1] will be converted to [3,3,3,0,2,2] in the run-length encoded version [1,1,1,0,1,1] will be [[3,1],[1,0],[2,1]] [3,3,3,0,2,2] will be [[3,3],[1,0],[2,2]] therefore basically [G,H] becomes [G,H and G] which is what the code below does: M,G&HG def g(G,H): return [G,H and G] r 9 run-length decode J store to J qReSJJ R J in each element of J q eSJ check if equal to maximum of J ``` ### Previous 23-byte ``` M,G&HGJrgMrQ8 9msqdeSJJ ``` [Test suite.](http://pyth.herokuapp.com/?code=M%2CG%26HGJrgMrQ8+9msqdeSJJ&test_suite=1&test_suite_input=[1%2C0%2C1%2C0%2C1]%0A[1%2C1%2C0%2C1%2C1%2C0%2C1]%0A[1%2C1%2C0%2C1%2C1%2C1%2C0%2C1%2C1]%0A[1%2C1%2C1]%0A[0%2C0%2C1]%0A[0%2C0]%0A[1%2C1%2C1%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C0%2C1%2C0%2C0%2C1%2C1%2C0%2C1%2C1%2C1%2C1%2C0%2C0%2C1%2C0]&debug=0) * Uses `1/0` or `true/false` in input. * Uses `1/0` in output. ### Previous 24-byte ``` Jrm,hd&edhdrQ8 9msqdeSJJ ``` [Test suite.](http://pyth.herokuapp.com/?code=Jrm%2Chd%26edhdrQ8+9msqdeSJJ&test_suite=1&test_suite_input=[1%2C0%2C1%2C0%2C1]%0A[1%2C1%2C0%2C1%2C1%2C0%2C1]%0A[1%2C1%2C0%2C1%2C1%2C1%2C0%2C1%2C1]%0A[1%2C1%2C1]%0A[0%2C0%2C1]%0A[0%2C0]%0A[1%2C1%2C1%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C0%2C1%2C0%2C0%2C1%2C1%2C0%2C1%2C1%2C1%2C1%2C0%2C0%2C1%2C0]&debug=0) * Uses `1/0` or `true/false` in input. * Uses `1/0` in output. ### Previous 26-byte ``` rm?nhdeS.u&YhNQ0,hd0drQ8 9 ``` [Test suite.](http://pyth.herokuapp.com/?code=rm%3FnhdeS.u%26YhNQ0%2Chd0drQ8+9&test_suite=1&test_suite_input=[1%2C0%2C1%2C0%2C1]%0A[1%2C1%2C0%2C1%2C1%2C0%2C1]%0A[1%2C1%2C0%2C1%2C1%2C1%2C0%2C1%2C1]%0A[1%2C1%2C1]%0A[0%2C0%2C1]%0A[0%2C0]%0A[1%2C1%2C1%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C0%2C1%2C0%2C0%2C1%2C1%2C0%2C1%2C1%2C1%2C1%2C0%2C0%2C1%2C0]&debug=0) * Uses `1/0` or `true/false` in input. * Uses `1/0` in output. [Answer] # Oracle SQL 12.1, ~~137~~ 135 bytes ``` SELECT REPLACE(REPLACE(REPLACE(:1,m,2),1,0),2,m)FROM(SELECT MAX(TRIM(COLUMN_VALUE))m FROM XMLTABLE(('"'||REPLACE(:1,0,'",0,"')||'"'))); ``` Un-golfed ``` -- Replace the max value with 2 -- Then replace every 1 with 0 -- Then replace 2 with the max value SELECT REPLACE(REPLACE(REPLACE(:1,m,2),1,0),2,m) FROM ( -- Split on 0 and keep the max value SELECT MAX(TRIM(COLUMN_VALUE))m FROM XMLTABLE(('"'||REPLACE(:1,'0','",0,"')||'"')) ); ``` Input use single characters. Ex: '1100111' [Answer] ## *Mathematica*, ~~46~~ 41 ``` 1-Join@@Sign[1~Max~#-#]&[#*Tr/@#]&@*Split ``` Works on lists of `0` and `1`. I thought I had done pretty well until I looked at the other answers! --- *Explanation for 46 character version; I shall update when I cannot improve it further.* An explanation of this code was requested. A non-code-golf equivalent (using version 10 operator forms) is: ``` RightComposition[ Split, Map[# Tr@# &], # - Max[1, #] &, UnitStep, Apply[Join] ] ``` This means a function made up of five steps (sub-functions) applied in order from top to bottom. * `Split`: break up into runs of identical elements: {1,1,0,1,1,0,1} ↦ {{1,1}, {0}, {1,1}, {0,0}} * `Map[# Tr@# &]`: For each sub-list (`Map`) multiply it (`#`) by its sum (vector trace, `Tr`): {1,1} ↦ {2, 2} * `# - Max[1, #] &` subtract from every element the maximum value appearing anywhere in the list of lists, or one, whichever is higher. (The one handles the case of all zeros.) * `UnitStep`: equal to 0 for x < 0 and 1 for x >= 0, applied to every element. * `Apply[Join]`: join the sub-lists into a single list. Could also be done with `Flatten` or `Catenate`, but in short form `Join@@` is more terse. [Answer] # C, 135 129 bytes [**Try Online**](http://ideone.com/sVaAQy) ``` m,c,i,d,j;f(int*l,int s){while(i<s)c=l[i++]?c+1:0,m=c>m?c:m;while(j<s)if(l[j++])d=d+1;else if(d<m)while(d)l[j-1-d--]=0;else d=0;} ``` **Ungolfed** ``` m,c,i; f(int*l,int s) { // obtain max while(i<s) c = l[i++] ? c+1 : 0, m = c>m ? c : m; c=0,i=0; // remove smaller segments while(i<s) if(l[i++]) c=c+1; else if(c<m) while(c) l[(i-1)-c--]=0; else c=0; } ``` [Answer] ## JavaScript (ES6), 56 bytes ``` s=>s.replace(/1+/g,t=>t.replace(/1/g,+!~s.indexOf(t+1))) ``` Works by checking all runs of 1s and replacing the characters with 0s unless the run is (equally) longest, as measured by searching the string for a longer run of 1s. Previous 72-byte recursive solution: ``` f=s=>/11/.test(s)?f(s.replace(/1(1*)/g,"0$1")).replace(/0(1+)/g,"1$1"):s ``` Does nothing if there are no runs of 1s (i.e. single 1s at most). Otherwise, subtracts one `1` from each `1` or run thereof, then calls itself recursively on the shorter runs, then adds one `1` back on the (now equally longest) runs. The number of recursive calls is one less than the length of the longest run. [Answer] # Julia, 51 bytes ``` s->replace(s,r"1+",t->map(c->c-contains(s,"1"t),t)) ``` [Try it online!](http://julia.tryitonline.net/#code=ZiA9IHMtPnJlcGxhY2UocyxyIjErIix0LT5tYXAoYy0-Yy1jb250YWlucyhzLCIxInQpLHQpKQoKZm9yIHMgaW4gKCIxMDEwMSIsICIxMTAxMTAxIiwgIjExMDExMTAxMSIsICIxMTEiLCAiMDAxIiwgIjAwIiwgIjExMTAwMDExMTEwMTAwMTEwMTExMTAwMTAiKQogICAgcHJpbnRsbihmKHMpKQplbmQ&input=) ### How it works `replace` finds all all runs of one or more **1**'s in the input string **s** via the regex `r"1+"` and calls the lambda `t->map(c->c-contains(s,"1"t),t)` to determine the replacement string. The lambda maps `c->c-contains(s,"1"t)` over all characters in the run of ones **t**. * If `"1"t` (concatenation) is a substring of **s**, the run isn't maximal, `contains` returns **true** and `c-contains(s,"1"t)` returns **'1' - true = '0'**, replacing all **1**'s in that run with **0**'s. * If `"1"t` (concatenation) is not a substring of **s**, the run is maximal, `contains` returns **false** and `c-contains(s,"1"t)` returns **'1' - false = '1'**, leaving the run unmodified. [Answer] ## APL, 22 chars ``` (⊣=⌈/)∊(⊣×+/¨)(~⊂⊣)0,⎕ ``` In English (from right to left in blocks): * prepend 0 to the input * box starting with each 0 * multiply each box by its sum * flatten * 1 if number equal to the max, 0 otherwise [Answer] # Java 8, 205 bytes This is a lambda expression for a `Function<String,String>`: ``` s->{int x=s.length();for(String t="1",f="0";s.indexOf(t+1)>=0;t+=1){s=s.replaceAll(0+t+0,0+f+0);if(s.indexOf(t+0)==0)s=s.replaceFirst(t,f);if(s.lastIndexOf(0+t)==--x-1)s=s.substring(0,x)+f;f+=0;}return s;} ``` input/output is a `String` where true is represented by 1 and false is represented by 0. There are no delimiter characters separating the values. code with explanation: ``` inputString -> { int x = inputString.length(); //starting with the truth combination "1", //loop until the input string does not contain the combination appended with another "1" //with each consecutive loop appending a "1" to the combination for( String truthCombo = "1", falseCombo = "0"; inputString.indexOf( truthCombo + 1 ) >= 0; truthCombo += 1 ) { //all instances in the input string //where the combination has a "0" on either side of it //are replaced by "0"'s inputString = inputString.replaceAll( 0 + truthCombo + 0, 0 + falseCombo + 0 ); //if the combination followed by a "0" //is found at the beginning of the input string //replace it with "0"'s if( inputString.indexOf( truthCombo + 0 ) == 0 ) inputString = inputString.replaceFirst( truthCombo , falseCombo ); //if the combination preceeded by a "0" //is found at the end of the input string //replace it with "0"'s if( inputString.lastIndexOf( 0 + truthCombo ) == --x - 1 ) inputString = inputString.substring( 0, x ) + falseCombo; falseCombo += 0; } return inputString; } ``` see [ideone](http://ideone.com/slriak) for the test cases [Answer] ## Clojure, 137 bytes ``` #(let[v(map(juxt first count)(partition-by #{1}%))](mapcat(fn[t](repeat(t 1)(if(=[1(apply max(map(fn[[f c]](if(= 1 f)c 0))v))]t)1 0)))v)) ``` First partitions the input into consecutive zeros and ones and maps these into "tuples" of partitions' first element and the count of elements. It then repeats the needed number of zeros or ones, depending if this is the max-length sequence of ones or not. Less golfed: ``` (def f #(let [v(map(juxt first count)(partition-by #{1}%)) m(apply max(map(fn[[f c]](if(= 1 f)c 0))v))] (mapcat (fn[[f c]](repeat c(if(=[1 m][f c])1 0))) v))) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 99 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 12.375 bytes ``` 0€‹:ÞG£ƛ¥⁼ß›;0j ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwiMOKCrOKAuTrDnkfCo8abwqXigbzDn+KAujswaiIsIiIsIlsxLDEsMCwxLDEsMSwwLDEsMV0iXQ==) Bitstring: ``` 001111010110101010011111011100100110010001011001110011110001101100100100110001000010011101000000010 ``` port of jelly [Answer] # Perl 5, 68 bytes 67, plus 1 for `-pe` instead of `-e` ``` y/0/ /;$_<${[sort@a]}[-1]&&y/1/0/for@a=split/\b/;$_=join"",@a;y; ;0 ``` Expects and prints a string (concatenation) of 0s and 1s. ]
[Question] [ A newspaper is made of several sheets; for the purposes of this question, each sheet of newsprint holds four pages of the final newspaper. Here is an example of three sheets of newsprint making up a newspaper with twelve pages: ``` ___________ |2 | 11| | ___|_____|_ | |4 | 9| |_| ___|_____|_ | |6 | 7| |_| | | | | | |_____|_____| ``` (Pages 1, 3, 5, 8, 10 and 12 are on the reverse of these sheets so you can't see them here.) Your challenge, should you choose to accept it, is to output all the sets of pages that are on each sheet of a given newspaper. You can take either the number of sheets (which is always a positive integer) or the number of pages (which is always a positive multiple of 4), but please indicate which. You can output the sets of pages in any reasonable order, as long as it is clear which pages belong in which set. For example, given an input of 3 sheets or 12 pages, you could output (1, 2, 11, 12), (3, 4, 9, 10) and (5, 6, 7, 8); or you could output (8, 5, 7, 6), (10, 3, 9, 4) and (12, 1, 11, 2); or any variant thereof, but you cannot of course output 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12. This is code golf, so please make your program or function as short as possible. (I will even accept the shortest overall program as the answer on request of its author if doing so will earn me a Winter Bash hat.) [Answer] # [convey](http://xn--wxa.land/convey/), 34 bytes ``` } /1:`%""{ ^1"v4!< +"+v}+1 ^<","-} ``` [Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoifVxuLzE6YCVcIlwie1xuXjFcInY0ITxcbitcIit2fSsxXG5ePFwiLFwiLX0iLCJ2IjoxLCJpIjoiMTIifQ==) [![left loop](https://i.stack.imgur.com/D1PLS.gif)](https://i.stack.imgur.com/D1PLS.gif) Pushes `n` and `n+1` to the right per loop. [![right part](https://i.stack.imgur.com/OAhO1.gif)](https://i.stack.imgur.com/OAhO1.gif) For each value outputs `i` and `i-pages+1`. [![all together](https://i.stack.imgur.com/Jvni3.gif)](https://i.stack.imgur.com/Jvni3.gif) Whenever the left loop passes through the top part, output a newline `/}`. Allow `n` to pass the loop only `pages % 4` times. [Answer] # [J](http://jsoftware.com/), 18 bytes Takes number of sheets as input ``` _4>:\2/:@(,|.)@#i. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/403srGKM9K0cNHRq9DQdlDP1/mtypSZn5CtoWKdpKhgisY2Q2MZIbJP/AA "J – Try It Online") ``` _4>:\2/:@(,|.)@#i. i. 0…n: 0 1 2 2 # repeat each 2 times: 0 0 1 1 2 2 (,|.)@ append its rotated version: 0 0 1 1 2 2 2 2 1 1 0 0 /:@ get the indices to sort: 0 1 10 11 2 3 8 9 4 5 6 7 _4 \ group by 4: 0 1 10 11, 2 3 8 9, 4 5 6 7 >: and increment: 1 2 11 12, 3 4 9 10, 5 6 7 8 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` ←½Sz+↔C2ḣ ``` [Try it online!](https://tio.run/##yygtzv7//1HbhEN7g6u0H7VNcTZ6uGPx////DY0A "Husk – Try It Online") Argument is the number of pages. ``` ḣ # list of all the page numbers 1..input C2 # split into groups of two S # hook: S(fgx) means f(x,g(x)) z # zip together + # by combining elements from both lists # x = the list of groups of two) ↔ # and itself reversed ←½ # now take just the first half of this list # of lists of 4-pages per sheet ``` [Answer] # [Perl 5](https://www.perl.org/) `-n`, 38 bytes ``` $,=$";say$.++,$.++,$_--,$_--while$_>$. ``` [Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZFybo4sVJFT1tbB0LE6@qCifKMzJxUlXg7Fb3//w2N/uUXlGTm5xX/1/U11TMwNPivmwcA "Perl 5 – Try It Online") Takes the number of pages as input [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~16~~ 14 bytes ``` ¯1 4⍴⍋2/,∘⌽⍨…⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97f@h9YYKJo96tzzq7TbS13nUMeNRz95HvSseNSx71DcVpOR/GpcRAA "APL (Dyalog Extended) – Try It Online"), [Stax](https://staxlang.xyz/#p=854aaf5cc29ce02fe98c14f424&i=12) A port of xash's solution. a full program which returns a matrix. -2 bytes from Bubbler. [Answer] # [R](https://www.r-project.org/), 48 bytes ``` function(N)split(rbind(x<-1:N,N:1)[x],(x-1)%/%4) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NPs7ggJ7NEoygpMy9Fo8JG19DKT8fPylAzuiJWR6NC11BTVV/VRPN/moahkeZ/AA "R – Try It Online") Takes input as the number of pages. # [R](https://www.r-project.org/), 51 bytes ``` function(N)split(1:(4*N),c(x<-rep(1:N,e=2),rev(x))) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NPs7ggJ7NEw9BKw0TLT1MnWaPCRrcotQAo4KeTamukqVOUWqZRoamp@T9Nw1jzPwA "R – Try It Online") Takes input as number of sheets. [Answer] # Scala, 37 bytes ``` p=>1.to(p/2)zip p.to(p/2,-1)grouped 2 ``` [Try it online!](https://scastie.scala-lang.org/SpYcaEVyRSuW5EkPjXaOOw) Returns an iterator of 2-element vectors, each containing a 2-tuple of page numbers opposite each other. [Answer] # [Python 2](https://docs.python.org/2/), 46 bytes ``` def f(n,i=2):i>n>_;print~-i,i,n-1,n;f(n-2,i+2) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI08n09ZI0yrTLs8u3rqgKDOvpE43UydTJ0/XUCfPGiiva6STqW2k@T9NwxBIAgA "Python 2 – Try It Online") Takes the number of pages `n` as input. A function that prints and terminates with error. If we avoid errors, many different ways to structure the code come out very close. **50 bytes**: [Try it online!](https://tio.run/##K6gsycjPM/r/P9M2zzYzr6C0REOTqzwjMydVIVPLyC7PKlPX1si6oCgzr0S3LlMnU9tIJ08byMjTzfz/39AIAA "Python 2 – Try It Online") ``` i=n=input() while i*2>n:i-=2;print-~i,i+2,n+~i,n-i ``` **50 bytes**: [Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERDkyvT1pCrPCMzJ1Uh0ybPqqAoM69Ety5TJ1MnT9dQJ886U9vWyDpP1xaox9AIAA "Python 2 – Try It Online") ``` n=input() i=1 while i<n:print-~i,i,n-1,n;i+=2;n-=2 ``` **51 bytes**: [Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERDkyvT1pCrPCMzJ1UhU8vIJs@qoCgzr0S3LlMnUydPF4y1Da0ztW2BmgyNAA "Python 2 – Try It Online") ``` n=input() i=1 while i*2<n:print-~i,i,n-i,n-i+1;i+=2 ``` **51 bytes**: [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU8n09bQKk8/UyvaIDYxLyVaI1MnU9tQJ08XiDVjtdM08nSNgCJGmv8LijLzShTSNEw0uWBMCwTTEKgCAA "Python 2 – Try It Online") ``` f=lambda n,i=1:n/i*[0]and[(i,i+1,n-1,n)]+f(n-2,i+2) ``` **51 bytes**: [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKlojUydT21AnTzcThLUNNdPyixQyFTLzFIoS89JTNYBS@kY6Rpqx/wuKMvNKFNI0TDS5YEwLBNPQSPM/AA "Python 2 – Try It Online") ``` lambda n:[(i,i+1,n-i,n-i+1)for i in range(1,n/2,2)] ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~21~~ 19 bytes -2 bytes thanks to coltim ``` {1+0N 4#<x,|x:&x#2} ``` [Try it online!](https://tio.run/##y9bNz/7/P82q2lDbwE/BRNmmQqemwkqtQtmo9n@1RoV1mkKFZq2DuqGCkYKxgsl/AA "K (oK) – Try It Online") A port of [xash's J solution](https://codegolf.stackexchange.com/a/216596/75681) - please upvote it too! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḶạÞH‘s4 ``` A monadic Link accepting the number of pages (four times the number of sheets) which yields a list of lists of the page numbers belonging to each sheet. **[Try it online!](https://tio.run/##ARoA5f9qZWxsef//4bi24bqhw55I4oCYczT///8yOA "Jelly – Try It Online")** ### How? ``` ḶạÞH‘s4 - Link: integer, P e.g. 12 Ḷ - lowered range (P) [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11] H - halve (P) 6 Þ - sort by: ạ - absolute difference ( [ 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5] ) - -> [ 6, 5, 7, 4, 8, 3, 9, 2,10, 1,11, 0] ‘ - increment [ 7, 6, 8, 5, 9, 4,10, 3,11, 2,12, 1] 4 - four 4 s - split into chunks [[7,6,8,5],[9,4,10,3],[11,2,12,1]] ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 46 43 bytes ``` x=$1{for(;y<x;)$++v=++y","++y","x--","x--}1 ``` Takes the number of pages. ``` x=$1{ ``` Set `x` to the number of pages. That will always evaluate to true given the rules, so the block of code will always run. ``` for(;y<x;) ``` Loop until the forward page counter `x` is larger then the backwards page counter `y`. It's effectively looping once for every 4 pages, since `x` and `y` both change by 2 each time through the loop. ``` $++v=++y","++y","x--","x-- ``` Set positional argument `v` (incremented before it's used) to the next set of 4 pages, adjusting the forward and backwards counters as they are used. ``` } ``` Ends the code block. ``` 1 ``` An unconditionally true test with no defined code block causes the default action, which is to print all the positional arguments joined by the `OFS` variable. The default for that is a space. [Try it online!](https://tio.run/##SyzP/v@/wlbFsDotv0jDutKmwlpTRVu7zFZbu1JJRwlCVujqQshaw///jY0A "AWK – Try It Online") [Answer] # JavaScript (ES6), 47 bytes ``` f=(n,N=1)=>N<n?[[N,N+1,n-1,n],...f(n-2,N+2)]:[] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjT8fP1lDT1s7PJs8@OtpPx0/bUCdPF4hjdfT09NI08nSNgGJGmrFW0bH/k/PzivNzUvVy8tM10jQMjTT1svIz8zTUFfQV1DU1uVCljQxQpf8DAA "JavaScript (Node.js) – Try It Online") [Answer] # [Ruby 2.7](https://www.ruby-lang.org/), 43 bytes ``` ->n{((1..n/2)%2).map{|v|[v,v+1,n-v,n-v+1]}} ``` No TIO link, as TIO supports an older version of Ruby. --- # [Ruby](https://www.ruby-lang.org/), 45 bytes ``` f=->n,k=1{k<n ?[[k,k+1,n-1,n]]+f[n-2,k+2]:[]} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y5PJ9vWsDrbJk/BPjo6Wydb21AnTxeIY2O106LzdI2AIkaxVtGxtf/Tog2NYvVyEwuqa8pqChTKav8DAA "Ruby – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~72~~ 70 bytes * -2 bytes thanks to ceilingcat Takes the number of physical pages. I compute the last page and then loop through each physical page, getting the distance from the bounds for each one starting from the last page (the middle page numbers). ``` f(n,i,j){for(i=n*4;n--;)printf("%d/%d/%d/%d ",j+1,i-j,++j,i-j,j=n*2);} ``` [Try it online!](https://tio.run/##NU3ZCsIwEHzfr1giSmITtbUeEPVLfCmJ1Q2alh6@lH57TAvCwAzDHEY9jQmh5F6SdGIoq4bT1a9z7ZXSom7IdyVnS7v9A5l0SSpJOZkkbmYXC5nQY1iQN@/ePvDSdpaqzesGEAfwU5Dn34qswAEQJ4s0RDXdaWxN4eeTu2cSVyRuO41137WcMSFiLAY5CQ1jSCGDPeRwgCOc4PwD "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes Input is the number of pages, output is in a different order, both the pages on each sheet and the sheets. ``` Lι€Âøιн ``` [Try it online!](https://tio.run/##ARoA5f9vc2FiaWX//0zOueKCrMOCw7jOudC9//8yNA "05AB1E – Try It Online") ``` # implicit input 8 L # push the range [1..input] [1, 2, 3, 4, 5, 6, 7, 8] ι # uninterleave, push [a[0::2],a[1::2]] [[1, 3, 5, 7], [2, 4, 6, 8]] €Â # duplicate and reverse each list [[7, 5, 3, 1], [1, 3, 5, 7], [8, 6, 4, 2], [2, 4, 6, 8]] ø # transpose the list of lists [[7, 1, 8, 2], [5, 3, 6, 4], [3, 5, 4, 6], [1, 7, 2, 8]] ι # uninterleave [[[7, 1, 8, 2], [3, 5, 4, 6]], [[5, 3, 6, 4], [1, 7, 2, 8]]] н # take the first element [[7, 1, 8, 2], [3, 5, 4, 6]] ``` --- # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes Takes the number of pages as an input. Output is in the natural order. ``` Lι€Âø€{Ù ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f59zOR01rDjcd3gGkqg/P/P/f0AgA "05AB1E – Try It Online") ``` # implicit input 8 L # push the range [1..input] [1, 2, 3, 4, 5, 6, 7, 8] ι # uninterleave, push [a[0::2],a[1::2]] [[1, 3, 5, 7], [2, 4, 6, 8]] €Â # duplicate and reverse each list [[7, 5, 3, 1], [1, 3, 5, 7], [8, 6, 4, 2], [2, 4, 6, 8]] ø # transpose the list of lists [[7, 1, 8, 2], [5, 3, 6, 4], [3, 5, 4, 6], [1, 7, 2, 8]] €{ # sort each list [[1, 2, 7, 8], [3, 4, 5, 6], [3, 4, 5, 6], [1, 2, 7, 8]] Ù # uniquify the list of lists [[1, 2, 7, 8], [3, 4, 5, 6]] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~17~~ 14 bytes Thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) for -3 bytes! ``` IE⪪…⁰⊘θ²⁺⊕ι⁻θι ``` [Try it online!](https://tio.run/##DYxBCoAgEEWv4nIEheoG0aYWbeoEgw4lmKlZ15/mw9u8B9@dWN2NkXnCp8GKGfYcQ4MN00HQGTVj/MhD0dqoQRi9hyW5ShelJiGIW0N6HyhGBS1j7ge2n5xam7M7fg) Link is to verbose version of code. Input is (now) the number of pages. ### Explanation ``` I Cast to string E Map (forEach) ⪪ ² Split on 2 (split into slices of length 2) …⁰ Range from 0... ⊘θ ...to half of first input (θ) ⁺⊕ι Add (concatenate) ι (current item, which is the slice), with every element incremented... ⁻θι ...to first input (θ) minus the slice (ι) ``` [Answer] # PowerShell, 56 52 49 bytes -4 bytes thanks to Neil! -3 bytes thanks to mazzy! Takes input as the number of pages: ``` param($x)for(;$x-$y){++$y,++$y,$x--,$x---join","} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQ6VCMy2/SMNapUJXpVKzWltbpVIHTAAFdMGEblZ@Zp6SjlLt////jUwA "PowerShell – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `Ṁ`, ~~14~~ 13 bytes ``` ƛd›D⁰4*ε:›^›W ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=%E1%B9%80&code=%C6%9Bd%E2%80%BAD%E2%81%B04*%CE%B5%3A%E2%80%BA%5E%E2%80%BAW&inputs=3&header=&footer=) [Answer] # [Bash](https://www.gnu.org/software/bash/), 42 bytes ***-1 bytes** from @pxeger* ``` for((x=$1;x>y;)){ echo {,}$[++y]\ $[x--];} ``` ~~[Try it online!](https://tio.run/##S0oszvifpqGp8T8tv0hDo8JWxdC6wq7SWlOzWiE1OSNfoVqntlolWlu7MlZHJbpCVze21rr2vyYXV5qCodF/AA "Bash – Try It Online")~~ [Try it online!](https://tio.run/##S0oszvifpqGp8T8tv0hDo8JWxdC6wq7SWlOzWiE1OSNfoVqnViVaW7syNkZBJbpCVzfWuva/JhdXmoKh0X8A "Bash – Try It Online") I'm usually the Zsh guy, but here Bash wins by a few bytes because it evaluates brace expansion **before** parameter expansion: ``` echo {,}{$[++y],$[x--]} echo $[++y] $[x--] $[++y] $[x--] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` Żx2m0Ụs4 ``` [Try it online!](https://tio.run/##y0rNyan8///o7gqjXIOHu5cUm/z//98IAA "Jelly – Try It Online") Another port of xash’s answer, drop that an upvote as well ## How it works ``` Żx2m0Ụs4 - Main link. Takes n on the left Ż - [0,1,2,...,n] x2 - [0, 0, 1, 1, 2, 2, ..., n, n] m0 - Append its reverse Ụ - Grade up; sort the indices by values s4 - Split into runs of 4 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) -1 thanks to [ovs](https://codegolf.stackexchange.com/users/64121)! ``` LΣ<I;α}4ô ``` **[Try it online!](https://tio.run/##yy9OTMpM/f/f59xiG0/rcxtrTQ5v@f/fyAIA "05AB1E – Try It Online")** Port of my Jelly answer. Input is the number of pages (four times the number of sheets). ``` LΣ<I;α}4ô L - range Σ } - sort by: < - decrement I - push input ; - halve α - absolute difference 4 - push four ô - split into chunks ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ 11 bytes ``` L2ô2ä`Rδ«Å\ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fx@jwFqPDSxKCzm05tPpwa8z//xYA "05AB1E – Try It Online") *-9 thanks to @ovs* ]
[Question] [ ## Challenge Given a list of **unique** colour names as input, sort them in the order that they first appear in [Joseph's Amazing Technicolour Dreamcoat](https://youtu.be/snYP49EAIWg?t=2m51s). --- ## Example ``` Input: green, blue, red, brown Output: red, green, brown, blue ``` The full list of colours, in order, is: ``` 1. red 2. yellow 3. green 4. brown 5. scarlet 6. black 7. ochre 8. peach 9. ruby 10. olive 11. violet 12. fawn 13. lilac 14. gold 15. chocolate 16. mauve 17. cream 18. crimson 19. silver 20. rose 21. azure 22. lemon 23. russet 24. grey 25. purple 26. white 27. pink 28. orange 29. blue ``` Or as an array of strings: ``` ["red","yellow","green","brown","scarlet","black","ochre","peach","ruby","olive","violet","fawn","lilac","gold","chocolate","mauve","cream","crimson","silver","rose","azure","lemon","russet","grey","purple","white","pink","orange","blue"] ``` --- ## Rules * You may take input by any reasonable, convenient means (e.g., an array of strings, a delimited string, individual strings) as long as it's permitted by [our standard I/O rules](https://codegolf.meta.stackexchange.com/q/2447/58974), but please specify your input method in your answer. * You may do the same for your output. * The input will only ever contain colours from the above list. * Your solution should be able to handle empty inputs. * You may choose whether all words in the input are consistently uppercase, lowercase or title case but your output's casing *must* match your input's. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so lowest byte count in each language wins. * As always, [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. --- ## Test cases ``` Input: [] Output: [] Input: ["green", "blue", "red", "brown"] Output: ["red", "green", "brown", "blue"] Input: ["gold", "grey", "green"] Output: ["green", "gold", "grey"] Input: ["ruby","yellow","red","grey"] Output: ["red", "yellow", "ruby", "grey"] Input: ["gold", "green", "fawn", "white", "azure", "rose", "black", "purple", "orange", "silver", "ruby", "blue", "lilac", "crimson", "pink", "cream", "lemon", "russet", "grey", "olive", "violet", "mauve", "chocolate", "yellow", "peach", "brown", "ochre", "scarlet", "red"] Output: ["red", "yellow", "green", "brown", "scarlet", "black", "ochre", "peach", "ruby", "olive", "violet", "fawn", "lilac", "gold", "chocolate", "mauve", "cream", "crimson", "silver", "rose", "azure", "lemon", "russet", "grey", "purple", "white", "pink", "orange", "blue"] ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~262~~ ~~155~~ ~~151~~ ~~127~~ ~~125~~ 95 bytes ``` $args|sort{"rlyegwbrscbrocpyrvo lvnfaldgccvmacmcvseraolsrygpptwkpnoeb".indexof((-join$_[3,0]))} ``` [Try it online!](https://tio.run/##JcVRCsIwDADQq8gYdAMVweOISJdmtZo2JRmdRT17Hfh@XuYVRe9I1FpvxetHWZZ3J1TRr5MoTMKQqxTeUUmzJecBSrQQoSiKZVKpPudlfebEOHXHkBy@eB6Gw4ND6m@X8/50Hcdva814Jme2BOs/TNsgISon8wM "PowerShell – Try It Online") ~~Naive approach.~~ PowerShell `sort-object` can sort based on a script block that gets executed for every object. Here we're simply getting the `.IndexOf()` the color from a string, which will assign a numerical value to each color, and then sorts based on those numbers. The string is constructed from the fourth and first letters of each color to ensure uniqueness. Output is implicit. *-4 bytes thanks to Shaggy.* *-2 bytes thanks to mazzy.* *A whopping -30 bytes thanks to KGlasier.* [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), ~~104~~ 101 bytes *"When in doubt, just hash the bloody input."* ``` a=>a.sort((a,b)=>(g=s=>'mgo0dakbrfs0h0000j9c412603e870500p0l0niq'[parseInt(s,36)%657%53%42])(a)>g(b)) ``` [Try it online!](https://tio.run/##jZPLbsIwEEX3fAWKhGpLlLrl0YcU9u2iXXSJWEyMk7g4tmsnIPrzNNg4CaIPssnE9tyZOdf5gA1Yargur63mK2YKJddst0/jPcRzGFllSoRgmOB4jrLYxvOrIlNkBevEpJbkpH4@Hunk9m5GxuzhnkwJ0UQQyT@vFhqMZc@yRHY4nuHBbHo/mI4Hk7slRoDnGUow3lMlrRJsJFSGXt7fXke2NFxmPN2hFC2WGOPezU3/rSp1VT71F8te7@@MKDOMyWjYjxJRscPbsJX7NGorozPBsN2muXMh/4J6SgSBXSt0XqcpcJLwv76pklo32jEh1LYOXL/H5N@GCYf7x@yLi3V6882m4GFsc146mvBVGY9VWeYxAV0fAl0ZLdySMiAzF1kuNsx0GwmuCF7nHYL68hVWuSKay7VfYlC4Q6zwO6aylpVdzErwjRPa8Hoet1VA5ZdorqgS4BtuWWgGND@xWNHcD2MpmKPKAeEFYM/vS0ejYdIUaGoHDj/0H1g3aIIbJ/O0UwZKHYId3kd7Gr/@YNk619gcrGit9L/D/hs "JavaScript (SpiderMonkey) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes ``` “½Ṗ©cƘʂẒẹMMỤẓHP’Œ?“ðÑþQ’,ḥµÞ ``` [Try it online!](https://tio.run/##PU@xSsRAEO3zFfMB/oOtIAdaWm72xmS9zU7YvU2I1XGNtSeIglhpIViIKNzl0CJBC/9i8yNxkhObgTfvzXtvzlDrqu@7xV3zETbXzZP8vvlZhnoV6s1kErYPob46OOoWt1@rfRa1L@1l@3nMeC@sH5v39r4P2zcI69du@QztxTAPh3HS91FiEQ3E2iNYnEJsqTRRQnoKzFQw0pH1cQUVt6ByVA3Uv4jPT0VpoEzVHEGce8tW5JBNhZxB7m2uEcgKkyA4pQu0MBqOoVqxCqRVmSMDuTIzBigy0JjxwnrncL7rQloVCIUizZtMeAYyJUlacO5fuxyFTHdfAMmUqzgp7HDAvX8B "Jelly – Try It Online") ### How it works `µ` turns everything to its left into a monadic chain, which `Þ` maps over the input array and sorts the input according to the generated values. `“½Ṗ©cƘʂẒẹMMỤẓHP’` sets the return value to 176073885534954276199526358143331. `Œ?` generates the 176073885534954276199526358143331th permutation of the positive integers (without the sorted tail), yielding \$\small[20,28,15,3,5,26,18,16,8,30,4,25,2,21,22,11,24,1,23,10,29,12,17,27,14,9,6,13,7,19]\$. `“ðÑþQ’` yields 391695582; `,` prepends it to the permutation. Then, `ḥ`c ompute Jelly's 391695582th hash function, mapping the resulting buckets to the integers of the permutation. The magic constant 391695582 was found by [Jelly's utils](https://github.com/DennisMitchell/jellylanguage/tree/master/utils "jellylanguage/utils at master · DennisMitchell/jellylanguage"). ``` dennis-home:utils$ time ./findhash 30 29 <<< '["red","yellow","green","brown","scarlet","black","ochre","peach","ruby","olive","violet","fawn","lilac","gold","chocolate","mauve","cream","crimson","silver","rose","azure","lemon","russet","grey","purple","white","pink","orange","blue"]' 391695582 real 0m2.058s user 0m15.077s sys 0m0.023s ``` [Answer] # [Python 3](https://docs.python.org/3/), 93 bytes ``` lambda r:sorted(r,key=lambda s:'iV^ZzwnFM@pYuOobXGAKyf[tUR]E'.find(chr(int(s,36)%127%60+64))) ``` [Try it online!](https://tio.run/##ZVFNS8QwEL37K0phaaNF1JUVFhb0oB5EBEFZ7VZI02kbNk3CpB90/3xtky4reJrJmzfvzUx0X5dKLodisxsErdKMerg2CmvIQoz20G9m1KwD/vnzfejk0@u9/mreVLp9fnjp87j@eE8eg8ucyyxkJYZc1qGJliuyuL65W6yuLla3hJBB41Q4D4uwJV6u0Gs9Lr04TqIzL/YLBJB@5PmpaGCKCJl9ouqkP3OUsNjI7ecIxxo26Yj5PQihujGx7Y75r9kZ5bSzsSt5bR3poUFnrQy4USjbT4luUAsLKaSysJnhogW0dGt9mlzwsW9KGPLKKGuiudw7CGhlSVC5CjbGQP13LSV4a4VaroQrVbRxECsVU4K6gY/LjvJAWXk61yQy/oSbk1GcVaabJAmJDOhNsJMBGX4B "Python 3 – Try It Online") Reads each color as a base-36 `int`. Brute-forced the moduli and chose an arbitrary offset among the 19 that didn't require escapes. [Answer] # Powershell, ~~124~~ ~~120~~ ~~124~~ ~~119~~ ~~118~~ 102 bytes ``` $args|sort{$c=$_ 'bluOrPiWPuG*yRusLeARoSiCriCrMCGoLFVOlRuPOBlSBGYR'-csplit'(?=[A-Z])'|%{$c-like"$_*"}} ``` [Try It Online!](https://tio.run/##fVNha9swEP3uXyFUd7aL8wcGYWkLy5eOhBQ2tjGKolxtEcXyJCteluS3p5JsyS6ECuM7n969072zatGCVCVwfolf0RQdLzGRhTopIZtjTKfxS5SsuV7IJfux1PO7w0qrJ7hfiWf2KM3z7XEunr5@X/CVXi4e@PPD/OcqmVBVc9Yk6Zfp7/vJrz9Zcro1ZBPOtoDjlzt8Pl/OUTRLI2RWnqJZmuX2hTIfSZNCAlRJjmx5sFbCxn1K0VaJwac@MiDdlk8Zs@FC8A3OETbYQ2@hwpald21sjHmXLfXaZOGDkUm0xjGFzbvDWQr3jcI@6hOuUY2KdFVfSetsW7IGrEP@a@kcKZSza07o1jq1ljV3ISFJVThPMb4HOa5pm7eWM5NnHSrZTglXpGbVtgsB2TkQ7LodqZWCZiyR4GzviPZM8G5rR3QXoqWggpPuwEPbNRBaujPYSTgSWnbNKEpkz2LVynIniVlX1AvaBJpRdlAjUIeqXoErJ/cqB1H8HN51MvTn9RlpN1K6H0yY1AcqDjMLA/ZDGIboRmZ/kwyd0C06Om1iVtV5DP9qoA1szN00d9HFJSjNGxP4ZK7szKAQukHmxpGmYVXhMDhOcY/DE/iLAw3OPnsCHJ0vbw) Explanation: 1. The data string contains the first significant letters of the color labels in descending order. Except for the `Grey` label - `G*y` is shorter. 2. `-csplit'(?=[A-Z])'` splits the data string to the array `(blu,Or,Pi,W,Pu,G*y,Rus,Le,A,Ro,Si,Cri,Cr,M,C,Go,L,F,V,Ol,Ru,P,O,Bl,S,B,G,Y,R)` 3. `|%{$c-like"$_*"}` maps the string array to the array of boolean. Where `True` means "a color label starts from this string" (like is case-insensitive operator, csplit - case-sensitive. [see doc](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators)). 4. `sort{}` sorts a color lables by the arrays of boolean in [ascending order](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/sort-object). The sorting by array is a very interesting feature in the Powershell. In this script all arrays have the same length and contain Boolean values only. This sorting is performed in the lexographic order of boolean arrays. Therefore, the string can contain one-letter abbreviations for the last labels. If there is a match at the beginning of the array, the matches at the end have no effect. ``` blu Or Pi W Pu G*y Rus Le A Ro Si Cri Cr M C Go L F V Ol Ru P O Bl S B G Y R green: - - - - - - - - - - - - - - - - - - - - - - - - - - T - - gold : - - - - - - - - - - - - - - - T - - - - - - - - - - T - - grey : - - - - - T - - - - - - - - - - - - - - - - - - - - T - - : green < gold < grey ``` Where `T` is `true` and `-` is `false`. --- Test script: ``` $f = { $args|sort{$c=$_ 'bluOrPiWPuG*yRusLeARoSiCriCrMCGoLFVOlRuPOBlSBGYR'-csplit'(?=[A-Z])'|%{$c-like"$_*"}} } @( ,( @(), @() ) ,( ('green', 'blue', 'red', 'brown'), ('red', 'green', 'brown', 'blue') ) ,( ("gold", "grey", "green"), ("green", "gold", "grey") ) ,( ("ruby","yellow","red","grey"), ("red", "yellow", "ruby", "grey") ) ,( ("gold", "green", "fawn", "white", "azure", "rose", "black", "purple", "orange", "silver", "ruby", "blue", "lilac", "crimson", "pink", "cream", "lemon", "russet", "grey", "olive", "violet", "mauve", "chocolate", "yellow", "peach", "brown", "ochre", "scarlet", "red"), ("red", "yellow", "green", "brown", "scarlet", "black", "ochre", "peach", "ruby", "olive", "violet", "fawn", "lilac", "gold", "chocolate", "mauve", "cream", "crimson", "silver", "rose", "azure", "lemon", "russet", "grey", "purple", "white", "pink", "orange", "blue") ) ) | % { $inp,$expected = $_ $result = &$f @inp # splatting "$("$result"-eq"$expected"): $result" } ``` Output: ``` True: True: red green brown blue True: green gold grey True: red yellow ruby grey True: red yellow green brown scarlet black ochre peach ruby olive violet fawn lilac gold chocolate mauve cream crimson silver rose azure lemon russet grey purple white pink orange blue ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~121~~ 119 bytes ``` #define j(i)index(".MH^>SALcD8Z!)3TF(RNe*aQU<,'",(**i^377)%75+30) s(**a,**b){return j(a)-j(b);}f(*t,n){qsort(t,n,8,s);} ``` [Try it online!](https://tio.run/##lZRdb9MwFIbv@yuMUYWdejCaVp3ohoSEEBeAxNcN0ya57snq4djFTlq2qr@9OLZbmm6oIjd@fXLO@xwfRxEnQnF9s9k8nUIhNaBbIqnUU/hN8POP769ff33zQbw9@/GE5t/ekS@fIOOfv5@zZ5iRLJPX@WhEu6NhLz@lHecjnGXZhK4sVLXV3ovTk1syoeN1QbKKabr65YytiJfsjDkf3yyMnKKllRUQMeM2Q5qXwFDQGRJGGesYkrryutYVRasOQnPrAwXBXfcKs1BBxz5cGItIkyovTsdInocKL3o96t/@LUNd58ui96W8CrXzunIEY6/XnU5oqgJX/U9PjcGulXgiLLUP71gs5YdeycNYKrLgavV4VavLkktNIjy22XT88vIKXaAVWjfp4Qg4hL1dWBly8h5MQcKOohfbfbCg3rll1092@MYCaG@CJ6qGZrUwDVtrlhof4voJ12/h@kdx@Q5nVLD32Lu0wkNMnjB5C5MfxQy2GFtPvD2@A6XM0otwqAg9ZA0Sa9BiDY6yhlsWv68txAly8XN/lHGGXoiZ8XfOqxAVFngZhSydCQkFj4l744m3EucUvvLDBysoY7WSntyIkteLwDBiFnsySqaI9b@DoObAxSwIqUO789rO1f7dW@PgX9A42WZ1DpqPGTvBrUpSqgXYRi2kSbHlTMZzp8s4nP8wzX/Ymv/wsfmvN38A "C (clang) – Try It Online") -2 bytes thanks ceilingcat! [Answer] *I will improve the string compression in a while* # [Japt](https://github.com/ETHproductions/japt), ~~88~~ ~~78~~ 71 bytes ``` ñ@`䊐âwrÒ.cÖ¨acru½ivo¤faØngoÒqauvœamsolv€osz¨e¶s gœrpl–tpˆ„g½u`bXé4 ¯3 ``` [Try it online!](https://tio.run/##y0osKPn///BGh4TDSw51HZpweFF50eFJesmHpx1akZhcVHpob2ZZ/qElaYmHZ@Sl5x@eVJhYWnZoTmJucX5O2aGG/OKqQytSD20rPrQg/dCcooKcQ9NKCg51HGpJP7S3NCEp4vBKE4VD643//49WSs/PSVHSUVBKL0qthNKpeUqxAA "Japt – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 186 bytes ``` lambda a:[y for x,y in sorted((max(" y gree br sc bla oc pe rub ol v f li go ch m cre cri si ro a le rus grey pu w pi or blu ".find(" %s "%c[:i+1])for i,j in enumerate(c)),c)for c in a)] ``` [Try it online!](https://tio.run/##fVPbrpswEHwuXzFCOhKoqFL7GClfQnkwzhLcY2xkQ3Loz6e@xIa0R31ALN7Znd0ZPG/LqNWPx3D@@ZBs6i8M7NRuGLTBR7NBKFhtFrpU1cQ@qhIbroYIvYHl6CWD5pgJZu2hJW4YIAWuGnzEBG7IPQJWwGgwSA@0vsOGecUds4Aj6uWK8tsg1MURvFmUb7w9ia/fu9qPIZpffgxS60SGLVTxum54SHGfYHX3WMguFme0RdV2TdF2dVO4sPSzqrJB6SjIvw1dwqfRd1V6ZDrZkSGVSnIjLRNs2@GhQa58waRCJ4wrKDeSUt9dEOiekAN9yuNZ8FeXQ@vINbA45H0US1iM/V5N3FBbiuMz/u6DeTWzDEfaMHUNkRXyRuZIlwSSwtX5wPk2WR1IZqHe4xGxKYBoihnnpqXlKIyW4hYa3YSWMTWxNR7xUXMtWRx433gmxscX6TUf4zKWM/Ps4oX6XLF/rTuUZRlyz0yXVv9k5CRvViMZ8LLCvlgS5iDaQeKnI9mi/8i3m5WdTerv7uU/sysKfw3839/AkF3l4m9EuA2n4stshFowVP67blJwPkfk4w8 "Python 2 – Try It Online") Finds all matches for progressive character substrings (Ex: "green" will check for "g", "gr", "gre", "gree", and "green") in the identifier string, and keeps the maximum index. "red" is always first, anf find() returns -1 for missing matches, so there is no identifier for red specifically. Once the colors are turned into (index, color) pairs, sorts array on first item of pair and then discards first item of each pair. [Answer] # Wolfram Language ~~255 213~~ 199 bytes Fourteen bytes saved by Dennis, who avoided the " marks, using symbols instead of strings. ``` SortBy[#,{yellow,green,brown,scarlet,black,ochre,peach,ruby,olive,violet,fawn,lilac,gold,chocolate,mauve,cream,crimson,silver,rose,azure,lemon,russet,grey,purple,white,pink,orange,blue}~Position~#&]& ``` [Try It Online!](https://tio.run/##dVLBbsIwDL3vK6wiceILJiFNO3BG4og4hOC10dK6clOqDsGvd7ZDN4a0S@Mkz6/vPad2qcLapeDdtIHX9bQjTu/jfrHaJQ5NuWtjSG@XYsQYaYCSERs4Mg0NdN5xxATH6PwnkK8YoUXnK@D@OALFcEY4B1LMh5OGGAQJJcUT@Io8RZcQatcLzDO6Wr6h7kiYQzwjA1OH4L564Y1Yyzn3XSdkImKEtuc2IgxVEJI2NKKAXVOiyOmxuN621IUUqLktlofltBUvab/ZX66Hw8vPpjA7xQoKa5KV8WRbNVg8YUW33unf7ys@Y9S43uW0Hgit6V@@rEEz0tUsaWHWjUSCyColaS2yea2yaa1yaAa/q5hNWe5a3PM1BkksH0nwBtKEc7eG/OjUJqlFHqZWNjXrnwf517a9g98klUTfh@nMz2YOR0KZvgE) [Answer] # [Python 3](https://docs.python.org/3/), 130 bytes ``` lambda*a:sorted(a,key=lambda c:("r,ylgebwsrtbcorpcryovvlfnlagdccamvca cmnsvrearlorsgyppwtpkonbe".find(c[::3]+" "*(c=="cream")),c)) ``` [Try it online!](https://tio.run/##JVDLbsQgEDs3X4E4wTZatdpbpHzJdlUBmSRogUFDHkp/PgVy8sh4bA/xWGYMj3Psf06nvB7UTXUJaYFBqPYNR3@xzHSCU3u4CfSeaNEGKRo6cNvcGJyaBmOU30wW@pA2AkUOKU1HjPsS3xg08PtowyDMs@ser0/O@E2Yvucmaz2XsjVSntbHnM1IhQF90yjWsycnGHjLD3AO9zxMBBAyasK9YDI5C5bCOGXeGdHMBBkjKDNnpFUfhXZ2K/Rm8dKPqho4m/eKMboSZGY06NRSpF6tdeUqWdD6hDXVug2omGMqCvW31kwHvr7TmlINyXVLeFwpuiLYZ1utow21a751glp@Bf5qGp1vVs8uTyMS@2U2sCoR31@yaz6ur7mneR1HB0LL5iOSDYsYxU1L1udlef4D "Python 3 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~321~~ ~~219~~ ~~210~~ ~~161~~ ~~159~~ 138 bytes ``` n=>n.OrderBy(a=>a!="grey"?"yelgrebroscablaochperuboliviofawlilgolchomaucrecrisilrosazulemruspurwhipinorablu".IndexOf(a.Substring(0,3)):65) ``` [Try it online!](https://tio.run/##TY5PS8QwEMXP7aeoOaXQLYLowd1WUBQWFvbgwXOaTttZ0qRMkv5R/Ow1dRE8vQfz3ryftDtpcY3jxhAI2fFRUHJJUCcz1zAlJ7TuYB2hbssv1gs/AstYpfwmsjPSKOE23xIsQQhq9p2mcRS9GG2NgvyD0MEJNfBLuo@j2DrhUCZvXsvD/@/Z8Uw1hP6r9j2QqBT8ncq5WHVR6vw38bxwUZTiprhuPrEFVHAVGStDSxjZDUC@MgpHNI2YFKrWqAAb8CWBJLSoQlp8egU9eTt4mjocUJtt1rP8qGuYzw0X@buvrhD8NrtL08eH@3Tdrz8 "C# (Visual C# Interactive Compiler) – Try It Online") *-3 bytes thanks to Shaggy, -18 thanks to TheLethalCoder* Takes input as a `List<string>`, returns an `IOrderedEnumerable<string>` How this works is that it orders the list by each string's index in the original string. The original string has every color except for grey turned to it's first three letters. Grey is not there, since green and grey would cause ambiguity. Red isn't there either, since `IndexOf` returns -1 if the string doesn't appear. # Shorter version taking IOrderedEnumerable as input, 137 bytes ``` n=>n.ThenBy(a=>a!="grey"?"yelgrebroscablaochperuboliviofawlilgolchomaucrecrisilrosazulemruspurwhipinorablu".IndexOf(a.Substring(0,3)):65) ``` Takes advantage of the fact that `ThenBy` is 1 byte shorter than `OrderBy`, but `ThenBy` only operates on `IOrderedEnumerable`s though. [Try it online!](https://tio.run/##dY9PS8QwEMXP209Re0qglgXRg7utoCgsLOxBwXOaTttZ0qRMkv5R/Ow1dfG4p/dg5vF7T9pbaXGJotoQCNmyQVB8jlHHE9Mwxke0bm8doW6K76QTfoAkTUrlV5GtkUYJt/qGYA5CUCU/2YkqoOeZybzYcs6jzebFaGsUZJ@EDo6ogZ35LtpE1gmHMn7zWu4PfzGoXrXvgESp4J@cXj8VU77ovNDZRws6IEVeiJv8UucpmUEFV5KxMoSEkW0P5EujcEBTi1GhaowKO8IySSAJLarwLb68go687T2NLfaozUr1SXbQFUynmons3ZeXDmyb3nH@@HDPl93yCw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~69~~ ~~68~~ ~~63~~ ~~56~~ 52 bytes ``` F⪪”&⌊Oτe¿k⟲ⅈζLbψ#>φuC№ς…X◧9gF→G⌈H≡M*e{-”²Φθ⁼ι⁺§κ⁰§κ³ ``` [Try it online!](https://tio.run/##TcyxDsIgFEDRXyFMkGBidHRy0MStiWPTAShF0legD0rt16N18m5nufolUQcJtQ4BCXtGcJlRxA2sUWtCpQNGjVsoBQYP0vZaT0VLPaWCRiIETHaLcc1xDF4ZKsiJc9Kg85ndHWSDbBbkNi8SEnOCNLAkds0P35s3GwU5ckH@eOZ7l1rbllo0xn@HVMGyjyma/kcMq6ddVw8FPg "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Now a port of @Sok's Pyth answer. ``` F⪪”&⌊Oτe¿k⟲ⅈζLbψ#>φuC№ς…X◧9gF→G⌈H≡M*e{-”² ``` Take the compressed string `rrylgebwsrbcorpcryovvlfnlagdccmvcacmsvrearlorsgyppwtpkonbe` and loop over each substring of length 2. ``` Φθ⁼ι⁺§κ⁰§κ³ ``` For each substring print those input strings whose first and fourth (cyclically) characters equal the substring. [Answer] # Pyth, 66 [bytes](https://mothereff.in/byte-counter#oxc.%22ay%1C%C3%87%C3%A6%C2%82%C2%A3%C3%B0%C2%98%04%C3%90%C2%A5%7E%40%C2%87iF%5B2%C2%9B%C2%9EB%C3%8D%C3%90%3A%C2%98Y%C3%AB%29%5EksTT%C3%A3%1A%222s%40LN%2C03) ``` oxc."ayÇæ£ðÐ¥~@iF[2BÍÐ:Yë)^ksTTã"2s@LN,03 ``` Try it online [here](https://pyth.herokuapp.com/?code=oxc.%22ay%1C%C3%87%C3%A6%C2%82%C2%A3%C3%B0%C2%98%04%C3%90%C2%A5%7E%40%C2%87iF%5B2%C2%9B%C2%9EB%C3%8D%C3%90%3A%C2%98Y%C3%AB%29%5EksTT%C3%A3%1A%222s%40LN%2C03&input=%5B%22ruby%22%2C%22yellow%22%2C%22red%22%2C%22grey%22%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=oxc.%22ay%1C%C3%87%C3%A6%C2%82%C2%A3%C3%B0%C2%98%04%C3%90%C2%A5%7E%40%C2%87iF%5B2%C2%9B%C2%9EB%C3%8D%C3%90%3A%C2%98Y%C3%AB%29%5EksTT%C3%A3%1A%222s%40LN%2C03&test_suite=1&test_suite_input=%5B%5D%0A%5B%22green%22%2C%20%22blue%22%2C%20%22red%22%2C%20%22brown%22%5D%0A%5B%22gold%22%2C%20%22grey%22%2C%20%22green%22%5D%0A%5B%22ruby%22%2C%22yellow%22%2C%22red%22%2C%22grey%22%5D%0A%5B%22gold%22%2C%20%22green%22%2C%20%22fawn%22%2C%20%22white%22%2C%20%22azure%22%2C%20%22rose%22%2C%20%22black%22%2C%20%22purple%22%2C%20%22orange%22%2C%20%22silver%22%2C%20%22ruby%22%2C%20%22blue%22%2C%20%22lilac%22%2C%20%22crimson%22%2C%20%22pink%22%2C%20%22cream%22%2C%20%22lemon%22%2C%20%22russet%22%2C%20%22grey%22%2C%20%22olive%22%2C%20%22violet%22%2C%20%22mauve%22%2C%20%22chocolate%22%2C%20%22yellow%22%2C%20%22peach%22%2C%20%22brown%22%2C%20%22ochre%22%2C%20%22scarlet%22%2C%20%22red%22%5D&debug=0). The colours in the list can be uniquely identified by taking the characters at index `0` and `3`, assuming modular indexing. This results in the following mapping: ``` rr -> red yl -> yellow ge -> green bw -> brown sr -> scarlet bc -> black or -> ochre pc -> peach ry -> ruby ov -> olive vl -> violet fn -> fawn la -> lilac gd -> gold cc -> chocolate mv -> mauve ca -> cream cm -> crimson sv -> silver re -> rose ar -> azure lo -> lemon rs -> russet gy -> grey pp -> purple wt -> white pk -> pink on -> orange be -> blue ``` Full explanation: ``` oxc."..."2s@LN,03Q Implicit: Q=eval(input()) Trailing Q inferred, dictionary string replaced with ... for brevity o Q Order the elements of Q, as N, using: ,03 [0,3] @LN Get the characters at the above indices in N s Concatenate into a string The above is result {1} ."..." The compressed dictionary string c 2 Split into chunks of length 2 x Get the index of {1} in the above Implicit print of sorted list ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 48 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Σ.•Aå₂мÕh∊þèmvƶ\kΛ1YŠíJ>J#θ₁2©€,Ù{η¦ù-•2ôy¬s3è«k ``` Same solution as most other answers. Will try to golf it down from here later. [Try it online](https://tio.run/##JU67TsQwEPyX0B5IHD0S7f0BAgrHmMTKJhutz4kCDaRC9BSIBoFAhzg6xENCV8SCMuIb8iPB62s8O@OZ0aARsVbj2D9sDef3e@5xaNu/b3edDpdXbuUWefX7fpj1t9v7P3fudbY72@g/h/Zi2j0P7XLibs76j@7JfW368NS9Nd3S7LhF95KN40EEKscimkR1qufKY0xYMyc0TI2GSpE/cmErFkolZOpRks5NSMYgZOYRQQcHkigSPsgao@bsTVEiiNBf6oLNpI79K04tsZiQUlwF2neteeOhUQBY8wopCEIV2Zh/EgTOVxrXcgyWe05E2F5aKiFMkWnol6REHh39Aw) or [verify all test cases](https://tio.run/##XVGxTsMwFPyVKqwBibIxgBjpwoxKBzeYxooTR3acKCAkyITYGRALAoGKKBsqICGGWDBGfEN@JMSO7VZMzz6/e/fuTBgYI9ikzm4U82Sz57i56@zxxFya6n6tPrvbEQ91Ufx@iiu/vrgUX2Iapj/zg6C6Wd//vhUvg63BSvVeF@f98qkuZq64PqneykfxsdqS@@I1L2dsQ0zL56A5dcv5djMcjtze0JlQCCPHdcaYw7ZQeCgvlGSR070TLJG2Le8K1A@UjyWSQ4xJZpmq7x9RzT8CmSyZjxKpA445VXqEQaUOvKCtMacxlgChIJrIA0M4hVR2dnp6T4xaRls9ikJG5OQYRYECIAhlAwwVTDljMFk4IBilckCKCFZ4CLgCPJ94BAO1nTUVQ@D5NpCW7flqbeYB2tGlbeXXCBqHhqIdWh9Gz4xeODAhmBVtBtbD8o7abxe7idOkbeLRpq2fpb27OPUv2TR0vPq3Ft@hfXfpjkZ/). **Explanation:** ``` Σ # Sort the (implicit) input-list by: .•Aå₂мÕh∊þèmvƶ\kΛ1YŠíJ>J#θ₁2©€,Ù{η¦ù-• # Push compressed string "rrylgebwsrbcorpcryovvlfnlagdccmvcacmsvrearlorsgyppwtpkonbe" 2ô # Split into parts of size 2 y # Push the current string of the list we're sorting ¬ # Push its head (without popping) s # Swap so the string is at the top of the stack again 3è # Get the character at index 3 (with automatic wraparound) « # Merge both characters together k # And get the index in the compressed string to sort on ``` [See this 05AB1E tip (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how `.•Aå₂мÕh∊þèmvƶ\kΛ1YŠíJ>J#θ₁2©€,Ù{η¦ù-•` is `"rrylgebwsrbcorpcryovvlfnlagdccmvcacmsvrearlorsgyppwtpkonbe"`. ]
[Question] [ Write three different programs such that when any one program is provided as input to one of the other two, you get the source of the remaining program as output. More explicitly, given programs \$A\$, \$B\$, and \$C\$, where \$f(g)\$ denotes the output obtained from inputting the text of program \$g\$ into program \$f\$, ***all*** of the following must hold: * \$ A(B) = C \$ * \$ A(C) = B \$ * \$ B(A) = C \$ * \$ B(C) = A \$ * \$ C(A) = B \$ * \$ C(B) = A \$ # Rules and Scoring * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program length total, in bytes wins. * Standard quine rules apply. * Each program must be at least one byte different from the other two * Each program can be in any language. Any number of them may share languages or each may use a different language. * Use any convenient IO format as long as each program uses a consistent convention. + Functions are allowed, as this counts as "any convenient IO". * The result of feeding a program its own source code is undefined * The result of feeding anything other than program text of either of the other two programs is undefined. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 + 5 + 5 = 15 bytes ``` CxCz1 ``` ``` CxCz2 ``` ``` CxCx3 ``` Try [A(B)](https://tio.run/##K6gsyfj/37nCucoQQhkBAA "Pyth – Try It Online"), [A(C)](https://tio.run/##K6gsyfj/37nCucoQQhkDAA "Pyth – Try It Online"), [B(A)](https://tio.run/##K6gsyfj/37nCucoIQhkCAA "Pyth – Try It Online"), [B(C)](https://tio.run/##K6gsyfj/37nCucoIQhkDAA "Pyth – Try It Online"), [C(A)](https://tio.run/##K6gsyfj/37nCucoYQhkCAA "Pyth – Try It Online"), [C(B)](https://tio.run/##K6gsyfj/37nCucoYQhkBAA "Pyth – Try It Online") online! ## Explanation ``` CxCz_ Cz # convert input from base-256 to int x _ # xor 1, 2 or 3 based on program C # convert from int to base-256 ``` [Answer] # C, ~~243~~ ~~240~~ ~~180~~ ~~132~~ 57 bytes ``` f(int*v){ v[4]^=1;} ``` ``` f(int*v){ v[4]^=2;} ``` ``` f(int*v){ v[4]^=3;} ``` Try it online: [A](https://tio.run/##S9ZNT07@/z9NIzOvRKtMs1qhLNokNs7W0Lr2f3JGYpFCcX5pUXJqdKytEroSI@taJWsuLqCgQm5iZp6GZjWXQpoGRL2mNZdCQWlJMYJb@x8A) [B](https://tio.run/##S9ZNT07@/z9NIzOvRKtMs1qhLNokNs7WyLr2f3JGYpFCcX5pUXJqdKytEroSY@taJWsuLqCgQm5iZp6GZjWXQpoGRL2mNZdCQWlJMYJb@x8A) [C](https://tio.run/##S9ZNT07@/z9NIzOvRKtMs1qhLNokNs7W2Lr2f3JGYpFCcX5pUXJqdKytEroSQ@taJWsuLqCgQm5iZp6GZjWXQpoGRL2mNZdCQWlJMYJb@x8A) The input program can be passed as a `char*` to the function `f`, and is implicitly converted to an `int*`. -60 bytes thanks to @Neil -48 bytes thanks to @Bubbler -72 bytes thanks to @AZTECCO [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 33+34+35=102 bytes Perhaps one of a few answers that has the length of the 3 programs not equal. (\*) ``` +␀>>,<,[<+>,]<-----[+>>.<<].,[.,] ++␀>>,<,[<+>,]<-----[+>>.<<].,[.,] +++␀>>,<,[<+>,]<-----[+>>.<<].,[.,] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fm8HOTsdGJ9pG204n1kYXBKK17ez0bGxi9XSi9XRigUoIqgEA "brainfuck – Try It Online") The ␀ (`␀`) represents a null character. Alternatives: * `+␀>,>,[<<+>>,]<<-----[+>.<].,[.,]` * `-␀>,>,[<<->>,]<<+++++[->.<].,[.,]` (\*): The only one at the time of posting. BF is the only used language that doesn't have integer literal. --- Explanation: ``` + Set a cell (call this cell 1) to X (depends on the current program, may be 1, 2 or 3) <NUL> No operation >, Read the first byte of the input (must be a "+") and store it in cell 2 >,[<<+>>,] Increment cell 1 by (-1+(the number of remaining "+" in the input until the <NUL>)) (use cell 3 as temporary storage) <<----- Decrement cell 1 by 5 [+>.<] Print (-(that many)) (cell 2) (must be +) . Print a NUL byte ,[.,] Copies the rest of the input to the output ``` [Answer] ## JavaScript + Python 3 + Bash, 938 bytes ### JavaScript, 465 bytes ``` a=3-2-1//True;a=str(a);alert,eval,prompt=print,exec,input;String=JSON=__builtins__;JSON.stringify=repr;JSON.fromCharCode=chr s=String.fromCharCode;j=JSON.stringify;r="t='tr '+s(48)+s(49)+' '+s(49)+s(48)";eval(r);d="alert([t,'a=3-2-'+a+'//True;a=str(a);alert,eval,prompt=print,exec,input;String=JSON=__builtins__;JSON.stringify=repr;JSON.fromCharCode=chr\\ns=String.fromCharCode;j=JSON.stringify;r='+j(r)+';eval(r);d='+j(d)+';eval(d)'][+(prompt()[2]<s(33))])";eval(d) ``` ### Python 3, 465 bytes ``` a=3-2-0//True;a=str(a);alert,eval,prompt=print,exec,input;String=JSON=__builtins__;JSON.stringify=repr;JSON.fromCharCode=chr s=String.fromCharCode;j=JSON.stringify;r="t='tr '+s(48)+s(49)+' '+s(49)+s(48)";eval(r);d="alert([t,'a=3-2-'+a+'//True;a=str(a);alert,eval,prompt=print,exec,input;String=JSON=__builtins__;JSON.stringify=repr;JSON.fromCharCode=chr\\ns=String.fromCharCode;j=JSON.stringify;r='+j(r)+';eval(r);d='+j(d)+';eval(d)'][+(prompt()[2]<s(33))])";eval(d) ``` ### Bash, 8 bytes ``` tr 01 10 ``` ## TIO links [Javascript(Bash)](https://tio.run/##xZCxTsMwEIZ3nqLKYltOaNMwtDI3dWOAoWxpFJnYpY5Cap2dCJ4@OLVAdGPrctJ9J/36v2vlKF2Dxvps3EyThCJbZ/ly@YqDFhKcRyqZkJ1Gn@pRdqnF84f1YNH0gXzqJjW9HbzY@0De4Wn/8gx1/TaYzpve1bWYyb27XM3xC1BbjOwYknYnibuz0tCc8M5BDLm6iBauEwRC4oF4XBDu6MOGzXPLOIn7lkWaiLkuRSYUJJf@tPQpiYKES05uInk49P/WJLwN/Tn5YzIj9YsUI1XJaWxLWbmuHh0tCsaqH33Fpil8apUv8tU3 "JavaScript (V8) – Try It Online") [Javascript(Python)](https://tio.run/##7ZGxTsMwFEV3vgJlsZ@cUGgYWpk3dWOAoWxpFJnYpY5Caj07EXx9SWoV0Y2tEmKx5POkq3t0GzUoX5N1IRsWh4PCPJtnd7PZC/VGKvSBuAKpWkMhNYNqU0f7dxfQke1G8mHq1HauD3IdRvKGj@vnJ6yq1962wXa@quREbvzxarefSMZRZNsxabVTtNprg/WOrjzGkLOLbPA8QRImAVmgayY8v1/A9C5BsPhfQqSJnOpyAqkxOfbnRUhZFGRCCXYRyc2m@7UmE83YX7AfJhPS30gDKwvBY1sOxbx88DzPAcqTvobTprf/m/6ZTb8A "JavaScript (V8) – Try It Online") [Python(Bash)](https://tio.run/##xZCxTsMwEIZ3nqLKYltOadowUJmbujHQoWxpFJnaJa6CY52dij59cGqB6MbGctJ9J/36v3OX0Pa2HEcJ5Xw1LxaLVxy0kOADUsmE7DSGXJ9llzvsP1wAh8ZG8qkPubFuCGIXInmH5932BZrmbTBdMNY3jZjIvb9ezfECqB0mdoxJm1biplcaDi3eeUghNxdxgtsEgZAFIAFnhHv68MimuWacpH3NEs3EVJciEwqya39ahZwkQcIlJ/8iud/bP2sSfor9OfllMiH1gxQjdcVpaktZtaqfPC1LxupvfcXGMX6qWM6WxRc "Python 3 – Try It Online") [Python(Javascript)](https://tio.run/##7ZGxTsMwFEX3fgXKYltOKTQMVOZN3RhgKFsaRaZ2iavgWM8viH59SWoV0Y2tEmKx5POkq3t0w56azheHg4ZiOp/ezGYv2FulIRJyLZRuLVJuP3SbB@zeA0FA5wfyaTe586EntaKBvMHj6vkJ6vq1dy05H@tajeQ6Hq9uuwe0ARPbDknLRuOyMxY2DU4ipJCzi9rBeYJCyAgY4RWTkd/di/FdCMnSfyESzdRYl6NQBrJjf15SzpIgk1qyi0iu1/7Xmkzuhv6S/TAZkflGRrCqlDy15aKcVw@RF4UQ1UnfiNOmt/@b/plNJ18 "Python 3 – Try It Online") [Bash(Javascript)](https://tio.run/##xY@9bsIwFEZ3ngJlsa8cfkI6FLl3YuvQDnQLUWSwaYxCsK6dqn36NMFqVbZuLJZ8rvTpnL3ydd8Hmi6zabbse4X5bDXLFos36oxU6ANxBVI1hkJqPlSTOrqcXUBHth3IpzmktnVdkNswkHd83r6@YFXtO9sE2/qqkiOZ@@vVHr@QjKPIjsPSpla0uWiDh5omHuPIzUWe8HZBEiYB2eDMhOcPjzC@axAs/tcQaSJHXU4gNSZXf16ElMVAJpRgd4nc7dp/ZzJxGvwF@1MyIv2LNLCyEDzacihW5ZPneQ5Q/uRrmHwD "Bash – Try It Online") [Bash(Python)](https://tio.run/##xY8xb8IwEEZ3fgXKYp8cIJAORe5NbB3agW4higw2jVEI1tmp2l@fJlitytaNxZLfSZ/e2ytf932gabacLrO@V5jPVrNssXijzkiFPhBXIFVjKKTmQzWpo8vZBXRk24F8mkNqW9cFuQ0Decfn7esLVtW@s02wra8qOZK5v17t8QvJOIrsOCxtakWbizZ4qGniMY7cXOQJbxckYRKQDc5MeP7wCOO7BsHifw2RJnLU5QRSY3L150VIWQxkQgl2l8jdrv13JhOnwV@wPyUj0r9IAysLwaMth2JVPnme5wDlT76GyTc "Bash – Try It Online") For some reason, TIO doesn't understand Javascript's `alert` function, but you can try it in your browser console. ## Explanation: The JavaScript and Python codes are 1 byte apart. The only difference is that the JS code starts with `a=3-2-1` where the Python code has `a=3-2-0`. This is a polyglot pseudo-quine. The output is *almost* identical to the source code, but if the source code has a `1` in that statement, the output has a `0`, and vice versa. This is because the pseudo-quine puts the current value of `a` into the string that describes how `a` is initialized. In other words, the JavaScript code constructs the Python code and vice versa, and it's completely arbitrary which one is considered JavaScript and which is considered Python. Both programs are valid in either language. Here's the JS/Python code without the quine construction, and with spaces and line breaks to make it more readable: ``` a=3-2-1//True; a=str(a); alert,eval,prompt=print,exec,input; String=JSON=__builtins__; JSON.stringify=repr; JSON.fromCharCode=chr s=String.fromCharCode; j=JSON.stringify; r="t='tr '+s(48)+s(49)+' '+s(49)+s(48)"; eval(r); d="alert([t, <pseudo-quine>][+(prompt()[2]<s(33))])"; eval(d) ``` The JavaScript version ignores all the redefinitions after `//` on the top line, and redefines the verbose `String.fromCharCode` and `JSON.stringify` functions to single characters. It then constructs the string `tr 01 10` and the pseudo-quine and puts both in a list. To access the list, it checks whether the third character in the input is less than `!` and casts the result to an integer with `+(bool)`. If the input is `tr 01 10` (or anything else with a space as the third character), this check is true and it prints the pseudo-quine. If the input is the Python code, this condition is false, and it prints `tr 01 10`. The Python logic is identical, but it renames some functions and creates dummy `JSON` and `String` namespaces for compatibility with JavaScript. It also casts `a` to a string so Python won't complain about concatenation. The redefinitions are possible because `//` is a comment in JavaScript, but floor division in Python. `a//True` is the same as `a//1`, but I'm avoiding the use of `1` and `0` everywhere except the first statement. Finally, `tr 01 10` simply changes `0` to `1` and vice versa. This has the same effect as running the JS/Python code with the other version as input. I initially chose Python and Javascript because they have a lot of overlapping syntax and `//` made it easy to add compatibility logic, but I ended up having to redefine more functions than I expected. There's probably a better pair of languages for this approach (maybe Python and Ruby?). I guess I could have cheated by using Python 2 and 3 as my "different languages", but that's hardly the most interesting approach :) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` ≔0η⭆θ⎇⊖κι⁻⁻³ηι ≔1η⭆θ⎇⊖κι⁻⁻³ηι ≔2η⭆θ⎇⊖κι⁻⁻³ηι ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9R5xSDc9sfrW07t@NRX/ujrmnndp3b@ahxNxAd2nxu@7mdYCWGeJUAAA "Charcoal – Try It Online") Link shows `A` passed `B` and printing `C`. Explanation: ``` ≔0η ``` Store either `0`, `1` or `2` in a variable as appropriate. ``` ⭆θ ``` Map over the parameter. ``` ⎇⊖κι ``` Leave all characters except the second unchanged. ``` ⁻⁻³ηι ``` Subtract the variable and the second character from 3. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 30 [bytes](https://github.com/abrudz/SBCS) ``` (⍕3-0+⍎)@5 (⍕3-1+⍎)@5 (⍕3-2+⍎)@5 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@NR71RjXQPtR719mg6mXBCuISrXCMr9n/aobYI6qg51rnSEoCFcMAMhCNOt/j/jUedCoFhfmmY6F4ydrpkGNAEmngFnZwDF0@BqMuDsDM10AA "APL (Dyalog Unicode) – Try It Online") Three functions that change the 5th character (from the left, 1-based) from the input string. Link shows that all six requirements (`f(g)≡h` etc.) are satisfied. ``` (⍕3-n+⍎)@5 ⍝ All functions share the same format ( )@5 ⍝ Apply to the 5th character only... ⍎ ⍝ Eval the character; m←0 or 1 or 2 3-n+ ⍝ 3-(n+m) ⍕ ⍝ Stringify the above ``` [Answer] # JavaScript (ES6), 75 bytes (3 x 25) Uses the same approach as most other answers. ``` // f1 s=>s.replace(/\d/,x=>x^1) // f2 s=>s.replace(/\d/,x=>x^2) // f3 s=>s.replace(/\d/,x=>x^3) ``` [Try it online!](https://tio.run/##fc5BCsMgEIXhvSdxoDXorM0lsg0FMU5IESeolNzeZJ0S19/74X3dzxWft72@Ey@hkbat2LGoHPbofJDDvAyvw47HR0MjY8WDGhCEj4oghOdUOAYVeZWkJRlVeap5S6sEgD/GDptr0edejf0a79faCQ "JavaScript (Node.js) – Try It Online") [Answer] **[Python 3](https://www.python.org/downloads/release/python-380/), 3\*51 = 153 bytes [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/v8I2M6@gtERD07qgKDOvRKNCryi1ICcxOVWjIlrXJFanuKRIAywO4mnGGWlqapKsyRioCQA "Python 3.8 (pre-release) – Try It Online")** ``` x=input();print(x.replace(x[-4],str(int(x[-4])^1))) x=input();print(x.replace(x[-4],str(int(x[-4])^2))) x=input();print(x.replace(x[-4],str(int(x[-4])^3))) ``` Adapted @aidan0626 answer, got the same length --- Although, this would return the actual function if in/out would be functions instead of programs. ``` def a(x):return b if x==c else c def b(x):return c if x==a else a def c(x):return a if x==b else b ``` works for inputs like c(c(c(b(a(c(a)))))) -> b [Answer] # [Japt](https://github.com/ETHproductions/japt), 3\*3 = 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Uses the convenient I/O format of an array of characters. ``` o^1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=cQ&code=b14x&input=Im9eMiIKLVA) [Answer] # [J](http://jsoftware.com/), 72 51 bytes ``` 0&(3-+)&.".@{.,}. 1&(3-+)&.".@{.,}. 2&(3-+)&.".@{.,}. ``` [Try it online!](https://tio.run/##y/r/30BNw1hXW1NNT0nPoVpPp1aPyxBDxAhd5H@irR6mxiRbPUy9ybZ6GNq5uIqBBqhjmKDOVQw0Q90QizjQGHUjTHGu1OSMfIXiZAVdK4VEheIkKD8Jyk@G8hNB/CQEPxnKT0RWn4zgJ0L5Sf8B "J – Try It Online") *-21 bytes thanks to Bubbler!* ## original # [J](http://jsoftware.com/), 72 bytes ``` a=.(0{3":@-0+8".@{])`8:`]}~ b=.(0{3":@-1+8".@{])`8:`]}~ c=.(0{3":@-2+8".@{])`8:`]}~ ``` [Try it online!](https://tio.run/##dcxBCoAgEIXhvaeQNhZRpG1CCLpI0MwQRJsWLqOubgUDitLy53u83XsY27I7@8JOTVcPRTudc7UMdpmvW2AwnRoFM4l54d5X9XerhMOIdc4UsclYrLQd0pFsrATpkBu5iRu@xtDEDfGeQgM3@gc "J – Try It Online") *Heavily inspired by [Bubbler's clever answer](https://codegolf.stackexchange.com/a/209761/15469).* *Note: -11 off stated TIO score for the `a=.`, `b=.`, `c=.` pieces, and line breaks* [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 11+11+11=~~45~~ 33 bytes ``` {S{\d}+^=1} {S{\d}+^=2} {S{\d}+^=3} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq4OialVjvO1qj2f3FipUKaRnpqiSZC2LAWAA) Xors the first digit in the input with the current program's index. [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 6 + 6 + 6 = 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` d\d_^1 ``` ``` d\d_^2 ``` ``` d\d_^3 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=ZFxkX14x&input=ImRcZF9eMiI) ## Explanation ``` d\d_^? d // Replace occurrences \d // of a digit _^? // with the digit xor 1, 2 or 3 based on program ``` [Answer] # [PHP](https://php.net/), 30 \* 3 = 90 bytes ``` $argn[9]=1^$argn[9];echo$argn; $argn[9]=2^$argn[9];echo$argn; $argn[9]=3^$argn[9];echo$argn; ``` [Try it online!](https://tio.run/##lY/BCoJAEIbv@xSLLGiHWNJTbhK7g0EgEaknLYiI7LIu1fO3mSIouFq3Geb7Zv5RhdKrtSoUul6KElvb3T5N8CGM0yjxc2kxTc6Pm8yWx2Bxakv2ZeuGaUo5IhwH2B4HbYYQpQIR0WNdMwuIQI/1TGwTPZe55FGEgcdh7Fv1Du6IGarBahMBhlu0Go/nbWzo2OJPWzi8Y/Nh2zXbMJ3caMMvtz2zLab/HrT1eLR3qV73Uj71fPMB "PHP – Try It Online") Uses the XOR approach, because he's the space sheriff [Answer] # [Python 2](https://docs.python.org/2/), ~~186~~ 153 bytes -33 bytes thanks to @Neil ``` x=raw_input();print x.replace(x[48],`int(x[48])^1`) x=raw_input();print x.replace(x[48],`int(x[48])^2`) x=raw_input();print x.replace(x[48],`int(x[48])^3`) ``` [Example](https://tio.run/##K6gsycjPM/r/v8K2KLE8PjOvoLREQ9O6oCgzr0ShQq8otSAnMTlVoyLaxCJWJwEoCGFqxhkmaJKuyThBEwA) Takes input from the user using `raw_input()` and changes the number after the `^` symbol and prints it out [Answer] # [Befunge-98](https://esolangs.org/wiki/Funge-98), 3 \* ~~15~~ 14 = ~~45~~ 42 bytes *-1 \* 3 bytes thanks to @Jo King!* ``` 0'c\~+-#;,#@~; 1'c\~+-#;,#@~; 2'c\~+-#;,#@~; ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//83Uk@OqdPWVbbWUXaos/7/3wCFDwA) Uses the subtraction method. ### Explanation ``` X'c\~+-#;,#@~; X # Push X (the number of the program, either 0, 1, or 2) 'c # Push 99 \ # Swap 99 and X ~ # Get the first character of the input (which is 48+Y, where Y is the number of the second program) + # Add (the stack now looks like [99, 48+X+Y]) - # Subtract 48+X+Y from 99, leaving 51-X-Y #; # (skipped) # (begin loop) , # First iteration: Output 51-X-Y, the first character of the third program #@ # (skipped) ~ # Get the next character of the input ; ; # Jump to the start of the loop , # Output the character unchanged # (repeat) ~ # On EOF, reverse direction @ # End the program ``` [Answer] # [Lua](https://www.lua.org/), 64\*3=192 bytes ``` print(((...):gsub('%d',load"return ('').char((...):byte()~1)"))) ``` [Try it online!](https://tio.run/##pVJda4MwFH2ev@LSUWLACuqbw4e@DAZjFPooUqKmTohJyQeslO6vuxjTCn0a24t6zkmO9557mSEjEw1hIKkK5q@j4Y3uBYeT7Lk@KG3qMI5jHDwRpajU4fPFwisUBSSWtBehAMsElLfe4iRFN7GXshydSxg6i7xT1gytWxQxQdqVpNpIDiFCOG4@ifSn6rOmIf5O8ApjPFbVS1CWwd99UucT/NsnW3yuwWNYmiodTn1LMkRAZGcGynUE9OtEG03bg83JMG0D22zgQ2iagyY1ozAYpaERXJOeA2EMOiZqwhQYRVuoz3AWRoJ3vs9gKtf9TpVeqiLgPfOPy6TbAUyvaB6kRctArxj727dKK1uZjwbtZkdYt0snDtyagbkZy@WwVgjnRyEH8pv@I3D7UswrUj6oFRDeAtpt93sEQgJ63b69I5v5tFqBiziJII0gw3eUWcIjKySLljot8ShzWrqg6TAefwA "Lua – Try It Online") (includes test cases) Other two programs: ``` print(((...):gsub('%d',load"return ('').char((...):byte()~2)"))) print(((...):gsub('%d',load"return ('').char((...):byte()~3)"))) ``` Use xor like many other programs [Answer] # [Python 2](https://docs.python.org/2/), 123 bytes ``` lambda x:x.replace(x[-4],`int(x[-4])^1`)# lambda x:x.replace(x[-4],`int(x[-4])^2`)# lambda x:x.replace(x[-4],`int(x[-4])^3`)# ``` [Try it online!](https://tio.run/##jY9BbsMgEEX3nALRRUCikZJ2FckLZo7huA5tLdUScZGNKvf07gRkQ6susoLPPD3@@O/w8TkcF9NOYdQc0oG3g1dcCLE4e319t3w@zfux886@dXKuH58bfemHkK7q5XBRD@wu8ng3@UTkQg32k3d9cP3QTVLVh1PDmKGm1JIaXq2X3Zd1mtf/rNAoYlsgzsj4rihijJgig9ZQBmlShjiGbYxxjOsYowxXGfMjFeaC7Irez0FoTv9pvjuHXbzyqkpVMooFihnFGxq9m5ZabSz1XNlY@Y8WCi1kLSSt@aXFQotZi0kLpRaLxTAvhmmxqF1@AA "Python 2 – Try It Online") Note that the comment at the end is required since otherwise the index will have to be either `-3` or `37` instead of `-4` which will mess things up when replacing 3 ]
[Question] [ ## Challenge: There's a silly puzzle circulating on social networks that reads: ``` 8 + 2 = 16106 5 + 4 = 2091 9 + 6 = ? ``` Implement a function or operator that, when given two positive integer numbers `x` and `y` such that `x > y > 0`, yields the correct answer as an **integer**, where the answer's digits are the digits of `x * y` followed by the digits of `x + y` followed by the digits of `x - y`. Very simple. ## Rules: * [Standard loopholes are disallowed.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins. * Input data validation is **not** required. This program may crash or return garbage when given invalid input. * You're allowed to use numeric functions and operators (including integer and floating point, math library functions, and other functions that accept and return numbers). * You're allowed to use a function that returns the number of digits of a number, if applicable. * You're **not** allowed to use strings or any kind of concatenation anywhere in your code. * The result may be returned or pushed to the stack, whichever applies in the language. The result must be an integer number, not a string. ## Sample code: **[Dyalog APL](http://tryapl.org/):** The following code creates a dyadic operator named `X`. > > X←{(⍺-⍵)+((⍺+⍵)×10\*1+⌊10⍟⍺-⍵)+⍺×⍵×10\*(2+⌊10⍟⍺+⍵)+⌊10⍟⍺-⍵} > > > Explanation: * In APL, you evaluate from right to left. * `⍺ and ⍵` are the left and right operand, respectively * `⌊10⍟⍺-⍵` reads: `floor of log10(⍺-⍵)`. First performs substraction then logarithm then floor. From right to left. log10 is done in order to count the digits of `⍺-⍵` (you must sum 1 afterwards). * `⍺×⍵×10*(...)` reads: `10 to the (...)th power, multiplied by ⍵, multiplied by ⍺` * Hence, `⍺×⍵×10*(2+⌊10⍟⍺+⍵)+⌊10⍟⍺-⍵` is the product, shifted to the left by the sum of the number of digits of the sum and the difference. Multiplying by a power of 10 will shift an integer to the left. * `((⍺+⍵)×10*1+⌊10⍟⍺-⍵)` is the sum, shifted to the left by the number of digits of the difference. * `(⍺-⍵)` is the difference. No shifting is necessary here. * `X←{...}` is how you define an operator in APL. Examples: ``` 8 X 2 16106 5 X 4 2091 9 X 6 54153 ``` **GNU dc:** The following code creates a macro named `a`: ``` [sysx10lxly-dseZdsclxly+dsd+Z1+^lxly**10lc^ld*+le+]sa ``` Explanation: * `sx` and `sy` pop an element from the stack and save it on the registers `x` and `y`, respectively. * `lx` and `ly` load an element from registers `x` and `y` respectively and push it to the stack. * `d` duplicates the last element in the stack. * `^` computes the power of two numbers. * `Z` pops a number and returns its number of digits. This is done because `dc` has no logarithm function. * `[...]sa` stores a macro in register `a`. `la` loads it. `x` executes the macro at the top of the stack. Examples: ``` 8 2 laxn 16106 5 4 laxn 2091 9 6 laxn 54153 ``` [Answer] # JavaScript (ES7), ~~63~~ ~~61~~ 59 bytes Saved 4 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil). ``` (a,b)=>[a*b,a+b,a-b].reduce((p,c)=>p*10**-~Math.log10(c)+c) ``` ``` <input id=a type=number oninput="c.innerText=((a,b)=>[a*b,a+b,a-b].reduce((p,c)=>p*10**-~Math.log10(c)+c))(+a.value,+b.value)"> <input id=b type=number oninput="c.innerText=((a,b)=>[a*b,a+b,a-b].reduce((p,c)=>p*10**-!Math.log10(c)+c))(+a.value,+b.value)"> <p id=c> ``` [Answer] # C, ~~79~~ 75 bytes *Thanks to @G B for saving 4 bytes!* ``` #define X for(c=1;(c*=10)<=a c,d;f(a,b){X+b;);d=c*a*b+a+b;X-b;);a=d*c+a-b;} ``` [Try it online!](https://tio.run/nexus/c-gcc#JYjBCsIwEETv@YpQEXaTFayoVGL@Iwcvm6SBHBql9Fb67THVgeHNvHqIY8pllE6m9wzB9gaCsv0Zn5ZFoGgSMHlcnfYGTbRBsfKa23On3bCNKmhue6u5LHLiXADFKmTLZ24qQXeMr/JvRzLBQBfceaPrjw@6Ixqx1S8) [Answer] # Bash, 66 * 2 bytes saved thanks to @chepner. ``` f()(s=$[$1+$2] d=$[$1-$2] echo $[($1*$2*10**${#s}+s)*10**${#d}+d]) ``` [Try it online](https://tio.run/nexus/bash#@5@moalRbKsSrWKorWIUy5UCZuqCmKnJGfkKKtEaKoZaKkZahgZaWirVysW12sWaME5KrXZKrOb/NAULBSOuNAVTBRMgaalg9h8A). [Answer] # EXCEL, 61 Bytes ``` =A1-B1+(A1+B1)*10^LEN(A1-B1)+A1*B1*10^(LEN(A1-B1)+LEN(A1+B1)) ``` Excel, 18 Bytes not valid ``` =A1*B1&A1+B1&A1-B1 ``` [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 36 bytes ``` ,@A$(*+-){!A...n!}"!{%y#'10\^x*y+}#\ ``` [Try it online!](https://tio.run/nexus/stacked#s1Aw@q/j4KiioaWtq1mt6Kinp5enWKukWK1aqaxuaBATV6FVqV2rHPM/v7TkPwA "Stacked – TIO Nexus") Previously: `,@A$(-+*){!A...n!}"!:inits$#'"!$summap:[[email protected]](/cdn-cgi/l/email-protection)\^1\,\*sum` I'm going to try to squeeze out a byte or two before writing an explanation. (`#'` = size of, and `"` is "do on each", no strings attached here.) Noncompeting at 26 bytes: `$(*+-)#!!:{%y#'10\^x*y+}#\`. [Answer] # TI-Basic, ~~34~~ 33 bytes ``` Prompt A,B A-B+(A+B)10^(1+int(log(A-B Ans+AB10^(1+int(log(Ans ``` [Answer] # GNU dc, 36 Defines a macro `m` that takes the top two members of the stack, applies the macro and leaves the result on the stack (as per the example in the question): ``` [sadsbla-dZAr^lalb+*+dZAr^lalb**+]sm ``` [Try it online](https://tio.run/nexus/dc#@x9dnJhSnJSTqJsS5VgUl5OYk6StpQ1na2lpxxbn/rdQMFLIya0o4DJVMIEwLBXMwIz/AA). [Answer] # [Perl 6](https://perl6.org), ~~81 61~~ 58 bytes ``` ->\x,\y{($/=($/=x- y)+(x+y)*({10**$++}...*>$/).tail)+x*y*({10**$++}...*>$/).tail} ``` [Try it](https://tio.run/nexus/perl6#dY7NCoJAHMTv@xR/ZIn9cv2gJBHXHsSLqYGgCa3FLuKTdevFbC06dpjDb2YY5q5beCSyztBgYVePTQv56qvSiNLOBAf5JuODpZwYbikjcxQyhjlfpJRM4YDKqep6yg2z/8JldeOnqdWThhz67tpqQl9PWY/DmQRlwwOaIXQZb7@Sr4BgI7AVuKAwIwBdWfA@FuQKPLE9/VYoWtYjcIjddJREYYIOjvaO4jCNUOogcVC8AQ "Perl 6 – TIO Nexus") ``` ->\x,\y{(x*y,x+y,x- y).reduce:{$^a*10**Int(1+log10($^b))+$b}} ``` [Try it](https://tio.run/nexus/perl6#NY7fCoIwHIXv9xQ/ZMTmpm5Soz9o3fYOEqSuCErBWWyIT9ZdL2ar6OJcfIePw7kbDQ8VVxt0czCr2lpDNkV5YXnhBmJDxy3zicDRuNP1vdLrAR@OoRRhuG96Itm1PUtB8KGklOFyHCc/tOu16Q1kcL002hD6esZVeytJUtQsoRuETm33l6IcCLYcO463FAYEYI4Ogm8FWQ4B/7z6KRSN0xIYpH5aKikUWniae0rFSqKVB@Vh@wY "Perl 6 – TIO Nexus") ``` ->\x,\y{[[&({$^a*10**Int(1+$^b.log10)+$b})]] x*y,x+y,x- y} ``` [Try it](https://tio.run/nexus/perl6#NY7LCoJAGIX38xQ/MsTcNCdKktDa9gxeQM0iKAcaixnEJ2vXi9lUtDiL7/BxOHfdwiMKmg26Wpg16tBCMvlpbkRuhyybkQGXFZMhY/uuJ5Ljsg4u6iRDynE90qIAw6ww3MUHO05uZde3uteQwOXctZrQ1zNo1LUm8/zA53SD0FHd/pKfAsFGYCvwlsKAAHRlwftWkKTgic@ln0LROK2Bw8JNy0iGEVo5WjpahLFEsYPIwfYN "Perl 6 – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` +,ạ,.1Fl⁵Ḟ‘€Ṛ+\⁵* ạ,+,×Fæ.ç ``` Defines a dyadic link / function, callable with `ç`. Takes two integers as input and returns an integer. It has the added bonus of being able to take x`<`y or x`>`y by using absolute difference. [Try it online!](https://tio.run/nexus/jelly#@6@t83DXQh09Q7ecR41bH@6Y96hhxqOmNQ93ztKOAQpocYFktXUOT3c7vEzv8PL/pgqHlyuY/AcA "Jelly – TIO Nexus") Explanation: ``` +,ạ,.1Fl⁵Ḟ‘€Ṛ+\⁵* -- Create link which computes what order of magnitude to multiply the difference, sum, and product by ạ,+,×Fæ.ç -- Main link, applies this using dot product ``` Details: ``` +,ạ,.1Fl⁵Ḟ‘€Ṛ+\⁵* -- Create dyadic like which does the following: l⁵Ḟ‘ -- Create operation which computes number of digits (log base 10 (⁵ is the literal 10), floored, incremented) € -- Apply this to each element in +,ạ,.1F -- ... the list [sum,difference,.1] R -- Reverse the list +\ -- Add up first n elements to get list. ⁵* -- Raise 10 (⁵ is literal 10) to the power of each element ạ,+,×Fæ.ç -- Main link, applies above link ạ,+,×F -- The list [difference, sum, product] æ. -- Dot product (multiply corresponding elements) with ç -- The above link. ``` [Answer] # PHP, ~~79~~ 75 bytes two versions: ``` [,$a,$b]=$argv;echo(10**strlen($s=$a+$b)*$a*$b+$s)*10**strlen($d=$a-$b)+$d; [,$a,$b]=$argv;echo(10**strlen($a+$b)*$a*$b+$a+$b)*10**strlen($a-$b)+$a-$b; ``` takes input from command line arguments; run with `-r`. I guess `strlen` qualifies as "function that returns the number of digits", although it uses the number as a string. Let me know if not. [Answer] # [C (gcc)](https://gcc.gnu.org/), 70 bytes ``` #define _ for(c=1;a+b>=(c*=10););d=c*d+a-(b=-b); c,d;f(a,b){d=a*b;_ _} ``` [Try it online!](https://tio.run/nexus/c-gcc#JYzLCsIwEEX3@YqhIsykU7CiooTxS4SQRwNZNEpxV/rtMeqBy4G7OHUXp5TLBBbSc8Ego3G9vwsGLeOBDJkoQcfeDehl8GRU4GgSOva0RnHaGwt2q7m8YXa5IKlVQeO1tCtht4@P8l/HkPDKR/r6zKefb3yhFt3qBw "C (gcc) – TIO Nexus") based on [Steadybox](https://codegolf.stackexchange.com/a/115402/18535) answer, putting everything in a macro to golf it a little more. (Note: assigning the result to `d` instead of `a` works, unexpectedly. I had a look at the generated assembly code and it seems to be ok.) [Answer] # Haskell, 54 bytes ``` a%0=a a%b=10*a%div b 10+mod b 10 a#b=(a*b)%(a+b)%(a-b) ``` The puzzle is implemented via an infix function `#`, e.g. `8#2 = 16106`. The other function, `%`, defines base-10 concatenation (assuming the RHS is greater than 0). [Answer] # Dyalog APL, 31 bytes [`{a⊥⍨10*1+⌊10⍟a←(⍺×⍵)(⍺+⍵)(⍺-⍵)}`](http://tryapl.org/?a=f%u2190%7Ba%u22A5%u236810*1+%u230A10%u235Fa%u2190%28%u237A%D7%u2375%29%28%u237A+%u2375%29%28%u237A-%u2375%29%7D%20%u22C4%20f/%A8%288%202%29%285%204%29%289%206%29&run) based on the sample APL code from the problem statement [Answer] # PHP, 87 Bytes ``` [,$a,$b]=$argv;echo($s=$a-$b)+($t=$a+$b)*10**($l=strlen($s))+$a*$b*10**($l+strlen($t)); ``` and a not valid solution for 37 Bytes ``` [,$a,$b]=$argv;echo$a*$b,$a+$b,$a-$b; ``` [Answer] # Ruby, 61 bytes ``` ->a,b{[a*b,a+b,a-b].reduce{|x,y|z=y;x*=10while(z>z/=10);x+y}} ``` Which suspiciously looks a lot like [this](https://codegolf.stackexchange.com/a/115432/18535) Javascript answer, but without using a logarithm. [Answer] # Python, 92 91 Chars ``` def g(x,y): l=lambda x,i=0:l(x/10,i+1)if x else 10**i a=x-y a+=(x+y)*l(a) return x*y*l(a)+a ``` Thanks to Wizards suggestion;) [Answer] # R (3.3.1), 104 bytes ``` function(x,y)Reduce(function(p,q)p*10^(floor(log10(q)+1))+q,lapply(c(`*`,`+`,`-`),function(z)z(x,y)),0) ``` returns an anonymous function. This is my first golfing attempt, so any feedback is appreciated. [Answer] ## REXX, 70 bytes ``` f:arg a b c=a-b c=(a+b)*10**length(c)+c c=a*b*10**length(c)+c return c ``` Of course, the native way would be much shorter: ``` f:arg a b return a*b||a+b||a-b ``` [Answer] ## PowerShell, 88 Bytes ``` param($x,$y)$l=2;if(($a=$x+$y)-gt9){$l++};($x*$y)*[math]::Pow(10,$l)+$a*10+$x-$y ``` PowerShell does not have a to the power operator which does not help. Also can't count the length of an integer unless you count it as a string, which we can not do, so I check to see if it is `-gt` 9 to get know the length. Likely could be more terse but I have to get back to work. [Answer] ## Python 2.7, ~~109~~ 96 bytes ``` import math a=lambda n:10**int(math.log10(10*n)) b,c=input() d=b-c+(b+c)*a(b-c) print d+b*c*a(d) ``` Corrected after following rules of contest. Credits to [mbomb007](https://codegolf.stackexchange.com/users/34718/mbomb007) for bringing down the code from 109 bytes to [96 bytes](https://tio.run/nexus/python2#FctNCoAgEEDhvadwOaMVugkKPMyMQgn@EXZ@s93jgzdibvXpMlO/BblEmQPJclqjVCwdft9SvayBSQVR8OJdLO3tgCI4Xr0G1h4VwWwU7ZmbDJqVnxRwjGPZPw) [Answer] # [J](http://www.jsoftware.com), 25 bytes ``` X=.10#.[:;10#.inv&.>*;+;- ``` 1. `*;+;-` Box the results of each operation. 2. `10#.inv&.>` Convert each result into an array of base-10 digits. (`inv` is `^:_1`) 3. `[:;` Unbox and join the arrays. 4. `10#.` Convert array of base-10 digits into an integer. 5. `X=.` define the above as the operator `X`. Results: ``` 8 X 2 16106 5 X 4 2091 9 X 6 54153 ``` [Answer] # Mathematica, 67 bytes ``` c=Ceiling;l=Log10;#-#2+(#+#2)10^(c@l[#-#2]/. 0->1)+10^c@l[2#]10#2#& ``` Takes `x-y`, then takes the log10 of `x-y`, rounds it up, calculates 10 to the power of that and then multiplies it by `x+y`. But we also need to consider `log10(x-y)` being 0, so we replace 0 with 1. Then we take the log10 of `2x`, rounded up, plus 1, and find 10 to the power of that. Multiply that by `xy`, and add that on. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ ~~22~~ 16 bytes ``` -Dg°¹²+*Dg°¹²**O ``` [Try it online!](https://tio.run/nexus/05ab1e#@6/rkn5ow6GdhzZpa8FYWlr@//@bcVkCAA "05AB1E – TIO Nexus") We could have saved a few bytes if we'd been allowed to use strings in the program (but not in calculations) by looping over a string containing the operations `"-+*"`, as the code performed for each operation is the same. Of course, if we'd been allowed to use concatenation we'd saved a lot more. [Answer] ## R, 64 bytes ``` x=scan();(b=(a=diff(-x))+10^nchar(a)*sum(x))+10^nchar(b)*prod(x) ``` Usage: ``` > x=scan();(b=(a=diff(-x))+10^nchar(a)*sum(x))+10^nchar(b)*prod(x) 1: 8 2 3: Read 2 items [1] 16106 ``` ]
[Question] [ Mini-Flak is a subset of the [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) language, where the `<>`, `<...>` and `[]` operations are disallowed. Strictly speaking it must *not match* the following regex: ``` .*(<|>|\[]) ``` Mini-Flak is the smallest known Turing complete subset of Brain-Flak. --- A little while ago I was able to make a [Quine](https://en.wikipedia.org/wiki/Quine_(computing)) in [Mini-Flak](https://codegolf.stackexchange.com/a/102623/56656), but it was too slow to run in the lifetime of the universe. So my challenge to you is to make a faster Quine. --- # Scoring To score your code put a `@cy` flag at the end of your code and run it in the [Ruby interpreter](https://github.com/DJMcMayhem/Brain-Flak) ([Try it online](https://tio.run/nexus/brain-flak) uses the ruby interpreter) using the `-d` flag. Your score should print to STDERR as follows: ``` @cy <score> ``` This is the number of cycles your program takes before terminating and is the same between runs. Since each cycle takes about the same amount of time to be run your score should be directly correlated to the time it takes to run your program. If your Quine is too long for you to reasonably run on your computer you can calculate the number of cycles by hand. Calculating the number of cycles is not very difficult. The number of cycles is equivalent to 2 times the number of monads run plus the number of nilads run. This is the same as replacing every nilad with a single character and counting the number of characters run in total. ## Example scoring * `(()()())` scores 5 because it has 1 monad and 3 nilads. * `(()()()){({}[()])}` scores 29 because the first part is the same as before and scores 5 while the loop contains 6 monads and 2 nilads scoring 8. The loop is run 3 times so we count its score 3 times. `1*5 + 3*8 = 29` --- # Requirements Your program must... * Be at least 2 bytes * Print its source code when executed in Brain-Flak using the `-A` flag * Not match the regex `.*(<|>|\[])` --- # Tips * The [Crane-Flak](https://github.com/Flakheads/CraneFlak) interpreter is categorically faster than the ruby interpreter but lacks some of the features. I would recommend testing your code using Crane-Flak first and then score it in the ruby interpreter when you know it works. I would also highly recommend not running your program in TIO. Not only is TIO slower than the desktop interpreter, but it will also timeout in about a minute. It would be extremely impressive if someone managed to score low enough to run their program before TIO timed out. * `[(...)]{}` and `(...)[{}]` work the same as `<...>` but do not break the restricted source requirement * You can check out [Brain-Flak](https://codegolf.stackexchange.com/a/95296/56656) and [Mini-Flak](https://codegolf.stackexchange.com/a/102623/56656) Quines if you want an idea of how to approach this challenge. [Answer] # Mini-Flak, 6851113 cycles ## The program (literally) I know most people aren't likely expecting a Mini-Flak quine to be using unprintable characters and even multi-byte characters (making the encoding relevant). However, this quine does, and the unprintables, combined with the size of the quine (93919 characters encoded as 102646 bytes of UTF-8), make it fairly difficult to place the program into this post. However, the program is very repetitive, and as such, compresses *really* well. So that the entire program is available literally from Stack Exchange, there's an `xxd` reversible hexdump of a `gzip`-compressed version of the full quine hidden behind the collapsible below: ``` 00000000: 1f8b 0808 bea3 045c 0203 7175 696e 652e .......\..quine. 00000010: 6d69 6e69 666c 616b 00ed d9db 6a13 4118 miniflak....j.A. 00000020: 0060 2f8b f808 0d64 a1c1 1dc8 4202 c973 .`/....d....B..s 00000030: 4829 4524 0409 22e2 5529 a194 1242 1129 H)E$..".U)...B.) 00000040: d2d7 ca93 f9cf 4c4c d45b 9536 e6db 6967 ......LL.[.6..ig 00000050: 770e 3bc9 ffed eca9 edb7 b1a4 9ad2 6a1d w.;...........j. 00000060: bfab 75db c6c6 6c5f 3d4f a5a6 8da6 dcd8 ..u...l_=O...... 00000070: 465b d4a5 5a28 4bd9 719d 727b aa79 f9c9 F[..Z(K.q.r{.y.. 00000080: 43b6 b9d7 8b17 cd45 7f79 d3f4 fb65 7519 C......E.y...eu. 00000090: 59ac 9a65 bfdf 8f86 e6b2 69a2 bc5c 4675 Y..e......i..\Fu 000000a0: d4e4 bcd9 5637 17b9 7099 9b73 7dd3 fcb2 ....V7..p..s}... 000000b0: 4773 b9bc e9bd b9ba 3eed 9df7 aeaf 229d Gs......>.....". 000000c0: e6ed 5eae 3aef 9d46 21b2 5e4d bd28 942e ..^.:..F!.^M.(.. 000000d0: 6917 d71f a6bf 348c 819f 6260 dfd9 77fe i.....4...b`..w. 000000e0: df86 3e84 74e4 e19b b70e 9af0 111c fa0d ..>.t........... 000000f0: d29c 75ab 21e3 71d7 77f6 9d8f f902 6db2 ..u.!.q.w.....m. 00000100: b8e1 0adf e9e0 9009 1f81 f011 18d8 1b33 ...............3 00000110: 72af 762e aac2 4760 6003 1bd8 698c c043 r.v...G``...i..C 00000120: 8879 6bde 9245 207c 04ae 5ce6 2d02 e1bb .yk..E |..\.-... 00000130: 7291 4540 57f8 fe0d 6546 f89b a70b 8da9 [[email protected]](/cdn-cgi/l/email-protection)...... 00000140: f5e7 03ff 8b8f 3ad6 a367 d60b f980 679d ......:..g....g. 00000150: d3d6 1c16 f2ff a767 e608 57c8 c27d c697 .......g..W..}.. 00000160: 4207 c140 9e47 9d57 2e50 6e8e c215 b270 [[email protected]](/cdn-cgi/l/email-protection) 00000170: bdf6 9926 9e47 9d05 ce02 0ff0 5ea7 109a ...&.G......^... 00000180: 8ba6 b5db 880b 970b 9749 2864 47d8 1b92 .........I(dG... 00000190: 39e7 9aec 8f0e 9e93 117a 6773 b710 ae53 9........zgs...S 000001a0: cd01 17ee b30e d9c1 15e6 6186 7a5c dc26 ..........a.z\.& 000001b0: 9750 1d51 610a d594 10ea f3be 4b7a 2c37 .P.Qa.......Kz,7 000001c0: 2f85 7a14 8fc4 a696 304d 4bdf c143 8db3 /.z.....0MK..C.. 000001d0: d785 8a96 3085 2acc 274a a358 c635 8d37 ....0.*.'J.X.5.7 000001e0: 5f37 0f25 8ff5 6854 4a1f f6ad 1fc7 dbba _7.%..hTJ....... 000001f0: 51ed 517b 8da2 4b34 8d77 e5b2 ec46 7a18 Q.Q{..K4.w...Fz. 00000200: ffe8 3ade 6fed b2f2 99a3 bae3 c949 9ab5 ..:.o........I.. 00000210: ab75 d897 d53c b258 a555 1b07 63d6 a679 .u...<.X.U..c..y 00000220: 4a51 5ead a23a 6a72 9eb6 d569 960b f3dc JQ^..:jr...i.... 00000230: 9ceb 53fa 658f 345f ad07 6f6f efce 06ef ..S.e.4_..oo.... 00000240: 0677 b791 cef2 f620 57bd 1b9c 4521 b241 .w..... W...E!.A 00000250: 4d83 2894 2eaf a140 8102 050a 1428 50a0 M.(....@.....(P. 00000260: 4081 0205 0a14 2850 a040 8102 050a 1428 @.....(P.@.....( 00000270: 50a0 4081 0205 0a14 2850 a040 8102 050a P.@.....(P.@.... 00000280: 1428 50a0 4081 0205 0a14 2850 a040 8102 .(P.@.....(P.@.. 00000290: 050a 1428 50a0 4081 0205 0a14 2850 a040 ...(P.@.....(P.@ 000002a0: 8102 050a 1428 50a0 4081 0205 0a14 2850 .....(P.@.....(P 000002b0: a040 8102 050a 1428 50a0 4081 0205 0a14 .@.....(P.@..... 000002c0: 2850 a040 8102 050a 1428 50a0 4081 0205 (P.@.....(P.@... 000002d0: 0a14 2850 a040 8102 050a 1428 50a0 4081 ..(P.@.....(P.@. 000002e0: 0205 0a14 2850 a040 8102 050a 1428 50a0 ....(P.@.....(P. 000002f0: 4081 0205 0a14 2850 a040 8102 050a 1428 @.....(P.@.....( 00000300: 50a0 4081 0205 0a14 2850 a040 8102 050a P.@.....(P.@.... 00000310: 1428 50a0 4081 0205 0a14 2850 a040 8102 .(P.@.....(P.@.. 00000320: 050a 1428 50a0 4081 0205 0a14 2850 a040 ...(P.@.....(P.@ 00000330: 8102 050a 1428 50a0 4081 0205 0a14 2850 .....(P.@.....(P 00000340: a040 8102 050a 1428 50a0 4081 0205 0a14 .@.....(P.@..... 00000350: 2850 a040 8102 050a 1428 50a0 4081 0205 (P.@.....(P.@... 00000360: 0a14 2850 a040 8102 050a 1428 50a0 4081 ..(P.@.....(P.@. 00000370: 0205 0a14 2850 a01c 14ca 7012 cbb4 a6e9 ....(P....p..... 00000380: e6db e6b1 e4b1 9e4c 4ae9 d3be f5f3 745b .......LJ.....t[ 00000390: 37a9 3d6a af49 7489 a6e9 ae5c 96dd 488f 7.=j.It....\..H. 000003a0: d31f 5da7 fbad 5d56 3e73 5277 7cf5 aa7b ..]...]V>sRw|..{ 000003b0: 3fbc df7c e986 c3ba 5ee4 3c6f 74f7 c3e1 ?..|....^.<ot... 000003c0: 301a bb45 d795 9afb fbdc 1495 65d5 6d9b 0..E........e.m. 000003d0: baf7 a5b4 a87d 4a5b d7fd b667 b788 ec27 .....}J[...g...' 000003e0: c5d8 28bc b96a 9eda 7a50 524d 290a a5cb ..(..j..zPRM)... 000003f0: cbef 38cb c3ad f690 0100 ..8....... ``` (Yes, it's so repetitive that you can even see the repeats *after* it's been compressed). The question says "I would also highly recommend not running your program in TIO. Not only is TIO slower than the desktop interpreter, but it will also timeout in about a minute. It would be extremely impressive if someone managed to score low enough to run their program before TIO timed out." I can do that! It takes about 20 seconds to run on TIO, using the Ruby interpreter: [Try it online!](https://tio.run/##pVdrcxXHEf3Or2hciQ2paJj3g9jE2CWweVSEHTsPbGCeQgQQ1iMYYX47Ob1390rcyC5Xaat0tdLdOdtz@vTpnpIPn75/X/MR3aCfjvdedvFi7@XeeJ7/I3ZPxM8/t0v4oa2D8788b9Gl3eOXJ3uvzvni8Gk@PH6x8cWlg@Pyhq7tvzq6Vg7y3sst/ufq9vG08KDQ1nNaHqetmxsASwxb@8dHr46PToHPvm7zy/fv5XxdJzViIRllpNKzIWldJamloaCCI598J@90JxKr6wchVhFcWiEoYPjmE/nOH95X8soDUvZGLbVCPitDVqlI630w0DNxc8HQwJDSS9IczOBgZPOWsqqKVKuRrJaaagoGcTy5xssbf3whxOGMYYBho05knbbYhkykddfkHP6XVbKktNWkFP6kr65u/0GIj8R3VyeQqzOGBUbTLVDNydBIdZCttlKzrlByxlP3vKHkw8LHvXviofBC7O3OGA4YIchOptREY4CFDjjqrQQqKltKuWkmpRG9Fn8Rp9ezhQ8PjDJyoeDwuuqrJ1/dINPsoOyyp9jw0WqLHMcx1j5//NnfVigzRmA@POJuNjtyWYPE0hLSmhoFHQrlHBJvEnzceijEv6/cFT@Jg7fizRojMoYpnkoCKbEoMAMuKAysbGZYGsXjT6eA8eXq9du8XvTjBSMBw6VcsW08WkYbFEdkJgtYSFlTqZCc9VAb/QsrVzB7UNqt4xkjc15st3gUO3DeBFKhYC8yJUoFqgitIWEVkFNevg9CvII23p3yUXgvAY@WVCr1VBrfZTIdGUptBMo9D2gG9NDtw1UUN6bPjxaMCozu8bzrGQnOfWCl9aQVXuy6BWQDz8mu6uWRuC7Ercvi0X1xZR1H43pJYLIFhWT6grTaWCmqNMhrFEEbnKYwgLE3vd/ipzwR4vWC0ZkPJtH0aCkwM12lQoV1l/KQkLmqNLJsHMcNcXRGZTPGmLSeKrIHoWnVueKRZbzYY1dxQBqoOehdrzR2Gep4PSG8mDEU@0eJXZHMSGtPXVJCxtlTFA2pULwRElXFmLV/LJeZMdg/ggbzwYO1nKtGmsCCR0ljJZb7BHqqtMA4EP/F0ttPnqwU8uWMwf4RIzTpSwMBGhLVMsDHLNLkakeGGvbSVSmI4w3sZ5t@YSvbWvOhzBRHUvAPK8mFEWl08OcdEjwi2M1BFi68xHFsf/4Plvmts5wq9o/heiBpBmReQKLJzVM2MIzmsXykiK2F1BY@oJBd/r27YLB/NINF8D68WAMoByzvHq7oAryw6tBgCmntQYyAaN6t42D/gGOiWhESpW4DMuoC6e7w9h47MBSKUQdJBA/9XNwGwM5Lxno1Y7B/lMZaSNovGNJR7WBSDmgMRYA6lClPcXwMjOl6dMoH@0cscKrCPhYjCEhh@rBw5wiHt2HSR9Jn9PH1lXb7FIP9wyRwmnJHlQxWeIc7KxUymOSCDkqieB30kRaMk12u4G9nDPaP2iTkGHqnYoDRErcWB2l4hUIKGR7UKnZ6RqdZnPwgPp4x2D9SAH@qOYVFMlNz3FVkzzRM6bBXRKSr4bzsiAd5Rrl78ucwY7B/oMXBMbOy2EtFi0MzISNhHXDnwQkz0FjBXq6Jk2m9vH8XSl/zwf7RAjBinlbiTudaSQebITQHfXiDb5uZ9SHFn8Qnd8Q/hRNLHOwfbuABOTQeHQONPjpkI8OShs8NFVyh2AJ/pMdB/FGIp3@/84F/KPYPp9gLYcVcFqjbYrCrFiBWB9fo1TKx3PcfiAdvwYSdDOTWyYyh2T/QISNXCcYM7pVFDw3JYRIpGZZUE5SScnG8l@tif62RJQ7N/pELmkeLqIjmTAUGWMjOOSgLReC5mjKKDhjcKj8FF98JUYV4M2Owf6BLKpZ0o6wNlJUD4ujofc1hrklT8ZpWie48gMKvPztYWdA6DvaPVHshZwaWO659i56dG4cwPPxx1E7So2lgL9@i0dnHQuzvn8Fg/5DQNCQNI6odVAyv2Y3QrVAllYcbhf1ZBYyVGRP70PZlcXPGYP@wLRrUF9SpuadldoGouG4dZKssehRuUPtTY@L65@vKzhLH5B8SHo4UOZg7xKojpJ/l/wPRevF8M2Owf0wv@R1AtCM@RJkx2D9Oo/1tIDoTwnQzY7B/bGz7V4Hog43gZsZg/ziPv/OAaIOOnRmD/eM8/s4Dog06lr1M/vFridgAog06Fgz2j9/O6CkQbdCxYLB//A5prDS2QceCMS6uMSMvrjGjLq4xoy@uMWMurjFjL64x4y6uMeMvrjETztMYhlpla8bgr3AcLIX7Z09rjYlp6j@NI07zOkYPHDYUdYsPDDJw0dz5/IKePdAGMUC7su7791Z97ujhjDHNHwFDH7oIGuxAPwo2ptWLMXXgYOMbuneE4VMQnz0TXx/N5@Svljim84tBb3UNI9MoaDIObQXjO8YXp2H4oaIH40A2xfEjlv/4/Y3Db15jSH07Y7B/mIGjC44qfH7B0FIN@rPrmP5NRX8JFoeYajCO01@F@GU1i326f3TKB/uHwThEYA4NMyTHpwU0ttKYWPzpERdmfky7JPksN199PfMb9o@S@bjkmP6IWRStE8fMMNC9vefmFSOav17m03d3Hq5mVPHJjMH@UR0mPx2xoZJAbOot8xSGZqcxDMG2QbarEx9X@GgsTna@uX/1dC/sH7WgmZqIpyomCPTKJIlPJbR5CRHnnfwP "Bash – Try It Online") ## The program (readably) Now I've given a version of the program that computers can read, let's try a version that humans can read. I've converted the bytes that make up the quine into codepage 437 (if they have the high bit set) or Unicode control pictures (if they're ASCII control codes), added whitespace (any pre-existing whitespace was converted to control pictures), run-length-encoded using the syntax `«string×length»`, and some data-heavy bits elided: ``` ␠ (((()()()()){})) {{} (({})[(()()()())]) (({})( {{}{}((()[()]))}{} (((((((({})){}){}{})){}{}){}){}()) { ({}( (␀␀!S␠su! … many more comment characters … oq␝qoqoq) («()×35» («()×44» («()×44» («()×44» («()×44» («()×45» … much more data encoded the same way … («()×117»(«()×115»(«()×117» «000010101011┬â┬ … many more comment characters … ┬â0┬â┬à00␈␈ )[({})( ([({})]({}{})) { ((()[()])) }{} { { ({}(((({}())[()])))[{}()]) }{} (({})) ((()[()])) }{} )]{} %Wwy$%Y%ywywy$wy$%%%WwyY%$$wy%$$%$%$%$%%wy%ywywy'×almost 241» ,444454545455┬ç┬ … many more comment characters … -a--┬ü␡┬ü-a␡┬ü )[{}()]) }{} {}({}()) )[{}]) (({})(()()()()){}) }{}{}␊ ``` (The "almost 241" is because the 241st copy is missing the trailing `'`, but is otherwise identical to the other 240.) ## Explanation ### About the comments The first thing to explain is, what's up with the unprintable characters and other junk that isn't Mini-Flak commands? You may think that adding comments to the quine just makes things harder, but this is a speed competition (not a size competition), meaning that comments don't hurt the speed of the program. Meanwhile, Brain-Flak, and thus Mini-Flak, just dump the contents of the stack to standard output; if you had to ensure that the stack contained *only* the characters that made up the commands of your program, you'd have to spend cycles cleaning the stack. As it is, Brain-Flak ignores most characters, so as long as we ensure that junk stack elements aren't valid Brain-Flak commands (making this a Brain-Flak/Mini-Flak polyglot), and aren't negative or outside the Unicode range, we can just leave them on the stack, allow them to be output, and put the same character in our program at the same place to retain the quine property. There's one particularly important way we can take advantage of this. The quine works by using a long data string, and basically all the output from the quine is produced by formatting the data string in various ways. There's only one data string, despite the fact that the program has multiple pieces; so we need to be able to use the same data string to print different parts of the program. The "junk data doesn't matter" trick lets us do this in a very simple way; we store the characters that make up the program in the data string by adding or subtracting a value to or from their ASCII code. Specifically, the characters making up the start of the program are stored as their ASCII code + 4, the characters making up the section that's repeated almost 241 times as their ASCII code − 4, and the characters making up the end of the program are stored as their ASCII code − 8. We can then print any of these three parts of the program via printing *every* character of the data string with an offset; if, for example, we print it with 4 added to every character code, we get one repeat of the repeated section, with some comments before and after. (Those comments are simply the other sections of the program, with character codes shifted so that they don't form any valid Brain-Flak commands, because the wrong offset was added. We have to dodge Brain-Flak commands, not just Mini-Flak commands, to avoid violating the [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") part of the question; the choice of offsets was designed to ensure this.) Because of this comment trick, we actually only need to be able to output the data string formatted in two different ways: a) encoded the same way as in the source, b) as character codes with a specified offset added to every code. That's a huge simplification that makes the added length totally worth it. ### Program structure This program consists of four parts: the intro, the data string, the data string formatter, and the outro. The intro and outro are basically responsible for running the data string and its formatter in a loop, specifying the appropriate format each time (i.e. whether to encode or offset, and what offset to use). The data string is just data, and is the only part of the quine for which the characters that make it up are not specified literally in the data string (doing that would obviously be impossible, as it would have to be longer than itself); it's thus written in a way that's particularly easy to regenerate from itself. The data string formatter is made of 241 almost identical parts, each of which formats a specific datum out of the 241 in the data string. Each part of the program can be produced via the data string and its formatter as follows: * To produce the outro, format the data string with offset +8 * To produce the data string formatter, format the data string with offset +4, 241 times * To produce the data string, format the data string via encoding it into the source format * To produce the intro, format the data string with offset -4 So all we have to do is to look at how these parts of the program work. ### The data string ``` («()×35» («()×44» («()×44» («()×44» («()×44» («()×45» … ``` We need a simple encoding for the data string as we have to be able to reverse the encoding in Mini-Flak code. You can't get much simpler than this! The key idea behind this quine (apart from the comment trick) is to note that there's basically only one place we can store large amounts of data: the "sums of command return values" within the various nesting levels of the program source. (This is commonly known as the [third stack](https://codegolf.stackexchange.com/questions/95403/tips-for-golfing-in-brain-flak/109859#109859), although Mini-Flak doesn't have a second stack, so "working stack" is likely a better name in the Mini-Flak context.) The other possibilities for storing data would be the main/first stack (which doesn't work because that's where our output has to go, and we can't move the output past the storage in a remotely efficient way), and encoded into a bignum in a single stack element (which is unsuitable for this problem because it takes exponential time to extract data from it); when you eliminate those, the working stack is the only remaining location. In order to "store" data on this stack, we use unbalanced commands (in this case, the first half of a `(…)` command), which will be balanced within the data string formatter later on. Each time we close one of these commands within the formatter, it'll push the sum of a datum taken from the data string, and the return values of all the commands at that nesting level within the formatter; we can ensure that the latter add to zero, so the formatter simply sees single values taken from the data string. The format is very simple: `(`, followed by *n* copies of `()`, where *n* is the number we want to store. (Note that this means we can only store non-negative numbers, and the last element of the data string needs to be positive.) One slightly unintuitive point about the data string is which order it's in. The "start" of the data string is the end nearer the start of the program, i.e. the outermost nesting level; this part gets formatted last (as the formatter runs from innermost to outermost nesting levels). However, despite being formatted last, it gets *printed* first, because values pushed onto the stack first are printed last by the Mini-Flak interpreter. The same principle applies to the program as a whole; we need to format the outro first, then the data string formatter, then the data string, then the intro, i.e. the reverse of the order in which they are stored in the program. ### The data string formatter ``` )[({})( ([({})]({}{})) { ((()[()])) }{} { { ({}(((({}())[()])))[{}()]) }{} (({})) ((()[()])) }{} )]{} ``` The data string formatter is made out of 241 sections which each have identical code (one section has a marginally different comment), each of which formats one specific character of the data string. (We couldn't use a loop here: we need an unbalanced `)` to read the data string via matching its unbalanced `(`, and we can't put one of those inside a `{…}` loop, the only form of loop that exists. So instead, we "unroll" the formatter, and simply get the intro/outro to output the data string with the formatter's offset 241 times.) ``` )[({})( … )]{} ``` The outermost part of a formatter element reads one element of the data string; the simplicity of the data string's encoding leads to a little complexity in reading it. We start by closing the unmatched `(…)` in the data string, then negate (`[…]`) two values: the datum we just read from the data string (`({})`) and the return value of the rest of the program. We copy the return value of the rest of the formatter element with `(…)` and add the copy to the negated version with `{}`. The end result is that the return value of the data string element and formatter element together is the datum minus the datum minus the return value plus the return value, or 0; this is necessary to make the next data string element out produce the correct value. ``` ([({})]({}{})) ``` The formatter uses the top stack element to know which mode it's in (0 = format in data string formatting, any other value = the offset to output with). However, just having read the data string, the datum is on top of the format on the stack, and we want them the other way round. This code is a shorter variant of the Brain-Flak swap code, taking *a* above *b* to *b* above *a* + *b*; not only is it shorter, it's also (in this specific case) more useful, because the side effect of adding *b* to *a* is not problematic when *b* is 0, and when *b* is not 0, it does the offset calculation for us. ``` { ((()[()])) }{} { … ((()[()])) }{} ``` Brain-Flak only has one control flow structure, so if we want anything other than a `while` loop, it'll take a bit of work. This is a "negate" structure; if there's a 0 on top of the stack, it removes it, otherwise it places a 0 on top of the stack. (It works pretty simply: as long as there isn't a 0 on top of the stack, push 1 − 1 to the stack twice; when you're done, pop the top stack element.) It's possible to place code inside a negate structure, as seen here. The code will only run if the top of the stack was nonzero; so if we have two negate structures, assuming the top two stack elements aren't *both* zero, they'll cancel each other out, but any code inside the first structure will run only if the top stack element was nonzero, and the code inside the second structure will run only if the top stack element was zero. In other words, this is the equivalent of an if-then-else statement. In the "then" clause, which runs if the format is nonzero, we actually have nothing to do; what we want is to push the data+offset to the main stack (so that it can be output at the end of the program), but it's there already. So we only have to deal with the case of encoding the data string element in source form. ``` { ({}(((({}())[()])))[{}()]) }{} (({})) ``` Here's how we do that. The `{({}( … )[{}()])}{}` structure should be familiar as a loop with a specific number of iterations (which works by moving the loop counter to the working stack and holding it there; it'll be safe from any other code, because access to the working stack is tied to the nesting level of the program). The body of the loop is `((({}())[()]))`, which makes three copies of the top stack element and adds 1 to the lowest. In other words, it transforms a 40 on top of the stack into 40 above 40 above 41, or viewed as ASCII, `(` into `(()`; running this repeatedly will make `(` into `(()` into `(()()` into `(()()()` and so on, and thus is a simple way to generate our data string (assuming that there's a `(` on top of the stack already). Once we're done with the loop, `(({}))` duplicates the top of the stack (so that it now starts `((()…` rather than `(()…`. The leading `(` will be used by the next copy of the data string formatter to format the next character (it'll expand it into `(()(()…` then `(()()(()…`, and so on, so this generates the separating `(` in the data string). ``` %Wwy$%Y%ywywy$wy$%%%WwyY%$$wy%$$%$%$%$%%wy%ywywy' ``` There's one last bit of interest in the data string formatter. OK, so mostly this is just the outro shifted 4 codepoints downwards; however, that apostrophe at the end may look out of place. `'` (codepoint 39) would shift into `+` (codepoint 43), which isn't a Brain-Flak command, so you may have guessed that it's there for some other purpose. The reason this is here is because the data string formatter expects there to be a `(` on the stack already (it doesn't contain a literal 40 anywhere). The `'` is actually at the start of the block that's repeated to make up the data string formatter, not the end, so after the characters of the data string formatter have been pushed onto the stack (and the code is about to move onto printing the data string itself), the outro adjusts the 39 on top of the stack into a 40, ready for the formatter (the running formatter itself this time, not its representation in the source) to make use of it. That's why we have "almost 241" copies of the formatter; the first copy is missing its first character. And that character, the apostrophe, is one of only three characters in the data string that don't correspond to Mini-Flak code somewhere in the program; it's there purely as a method of providing a constant. ### The intro and outro ``` (((()()()()){})) {{} (({})[(()()()())]) (({})( {{}{}((()[()]))}{} (((((((({})){}){}{})){}{}){}){}()) { ({}( (␀␀!S␠su! … many more comment characters … oq␝qoqoq) … )[{}()]) }{} {}({}()) )[{}]) (({})(()()()()){}) }{}{}␊ ``` The intro and outro are conceptually the same part of the program; the only reason we draw a distinction is that the outro needs to be output before the data string and its formatter are (so that it prints after them), whereas the intro needs to be output after them (printing before them). ``` (((()()()()){})) ``` We start by placing two copies of 8 on the stack. This is the offset for the first iteration. The second copy is because the main loop expects there to be a junk element on top of the stack above the offset, left behind from the test that decides whether to exist the main loop, and so we need to put a junk element there so that it doesn't throw away the element we actually want; a copy is the tersest (thus fastest to output) way to do that. There are other representations of the number 8 that are no longer than this one. However, when going for fastest code, this is definitely the best option. For one thing, using `()()()()` is faster than, say, `(()()){}`, because despite both being 8 characters long, the former is a cycle faster, because `(…)` is counted as 2 cycles, but `()` only as one. Saving one cycle is negligible compared to a much bigger consideration for a [quine](/questions/tagged/quine "show questions tagged 'quine'"), though: `(` and `)` have much lower codepoints than `{` and `}`, so generating the data fragment for them will be much faster (and the data fragment will take up less space in the code, too). ``` {{} … }{}{} ``` The main loop. This doesn't count iterations (it's a `while` loop, not a `for` loop, and uses a test to break out). Once it exits, we discard the top two stack elements; the top element is a harmless 0, but the element below will be the "format to use on the next iteration", which (being a negative offset) is a negative number, and if there are any negative numbers on the stack when the Mini-Flak program exits, the interpreter crashes trying to output them. Because this loop uses an explicit test to break out, the result of that test will be left on the stack, so we discard it as the first thing we do (its value isn't useful). ``` (({})[(()()()())]) ``` This code pushes 4 and *f* − 4 above a stack element *f*, whilst leaving that element in place. We're calculating the format for the next iteration in advance (while we have the constant 4 handy), and simultaneously getting the stack into the correct order for the next few parts of the program: we'll be using *f* as the format for this iteration, and the 4 is needed before that. ``` (({})( … )[{}]) ``` This saves a copy of *f* − 4 on the working stack, so that we can use it for the next iteration. (The value of *f* will still be present at that point, but it'll be in an awkward place on the stack, and even if we could manoeuvre it to the correct place, we'd have to spend cycles subtracting 4 from it, and cycles printing the code to do that subtraction. Far easier simply to store it now.) ``` {{}{}((()[()]))}{} ``` A test to see if the offset is 4 (i.e. *f* − 4 is 0). If it is, we're printing the data string formatter, so we need to run the data string and its formatter 241 times rather than just once at this offset. The code is fairly simple: if *f* − 4 is nonzero, replace the *f* − 4 and the 4 itself with a pair of zeros; then in either case, pop the top stack element. We now have a number above *f* on the stack, either 4 (if we want to print this iteration 241 times) or 0 (if we want to print it only once). ``` ( ((((((({})){}){}{})){}{}){}){} () ) ``` This is an interesting sort of Brain-Flak/Mini-Flak constant; the long line here represents the number 60. You may be confused at the lack of `()`, which are normally all over the place in Brain-Flak constants; this isn't a regular number, but a Church numeral, which interprets numbers as a duplication operation. For example, the Church numeral for 60, seen here, makes 60 copies of its input and combines them all together into a single value; in Brain-Flak, the only things we can combine are regular numbers, by addition, so we end up adding 60 copies of the top of the stack and thus multiplying the top of the stack by 60. As a side note, you can use an [Underload numeral finder](https://codegolf.stackexchange.com/questions/26207/shortest-representation-of-an-underload-number), which generates Church numerals in Underload syntax, to find the appropriate number in Mini-Flak too. Underload numerals (other than zero) use the operations "duplicate top stack element" `:` and "combine top two stack elements" `*`; both those operations exist in Brain-Flak, so you just translate `:` to `)`, `*` to `{}`, prepend a `{}`, and add enough `(` at the start to balance (this is using a weird mix of the main stack and working stack, but it works). This particular code fragment uses the church numeral 60 (effectively a "multiply by 60" snippet), together with an increment, to generate the expression 60*x* + 1. So if we had a 4 from the previous step, this gives us a value of 241, or if we had a 0, we just get a value of 1, i.e. this correctly calculates the number of iterations we need. The choice of 241 is not coincidental; it was a value chosen to be a) approximately the length at which the program would end up anyway and b) 1 more than 4 times a round number. Round numbers, 60 in this case, tend to have shorter representations as Church numerals because you have more flexibility in factors to copy. The program contains padding later on to bring the length up to 241 exactly. ``` { ({}( … )[{}()]) }{} ``` This is a for loop, like the one seen earlier, which simply runs the code inside it a number of times equal to the top of the main stack (which it consumes; the loop counter itself is stored on the working stack, but visibility of that is tied to the program's nesting level and thus it's impossible for anything but the for loop itself to interact with it). This actually runs the data string and its formatter 1 or 241 times, and as we've now popped all the values we were using for our control flow calculation from the main stack, we have the format to use on top of it, ready for the formatter to use. ``` (␀␀!S␠su! … many more comment characters … oq␝qoqoq) ``` The comment here isn't entirely without interest. For one thing, there are a couple of Brain-Flak commands; the `)` at the end is naturally generated as a side effect of the way the transitions between the various segments of the program work, so the `(` at the start was manually added to balance it (and despite the length of the comment inside, putting a comment inside a `()` command is still a `()` command, so all it does is add 1 to the return value of the data string and its formatter, something that the for loop entirely ignores). More notably, those NUL characters at the start of the comment clearly aren't offsets from anything (even the difference between +8 and -4 isn't enough to turn a `(` into a NUL). Those are pure padding to bring the 239-element data string up to 241 elements (which easily pay for themselves: it would take much more than two bytes to generate 1 vs. 239 rather than 1 vs. 241 when calculating the number of iterations required). NUL was used as the padding character because it has the lowest possible codepoint (making the source code for the data string shorter and thus faster to output). ``` {}({}()) ``` Drop the top stack element (the format we're using), add 1 to the next (the last character to be output, i.e. the first character to be printed, of the program section we just formatted). We don't need the old format any more (the new format is hiding on the working stack); and the increment is harmless in most cases, and changes the `'` at one end of the source representation of the data string formatter into a `(` (which is required on the stack for next time we run the formatter, to format the data string itself). We need a transformation like that in the outro or intro, because forcing each data string formatter element to start with `(` would make it somewhat more complex (as we'd need to close the `(` and then undo its effect later), *and* we'd somehow need to generate an extra `(` somewhere because we only have *almost* 241 copies of the formatter, not all 241 (so it's best that a harmless character like `'` is the one that's missing). ``` (({})(()()()()){}) ``` Finally, the loop exit test. The current top of the main stack is the format we need for the next iteration (which just came back off the working stack). This copies it and adds 8 to the copy; the resulting value will be discarded next time round the loop. However, if we just printed the intro, the offset was -4 so the offset for the "next iteration" will be -8; -8 + 8 is 0, so the loop will exit rather than continuing onto the iteration afterwards. [Answer] # 128,673,515 cycles [Try it online](https://tio.run/nexus/brain-flak#7d1rkqQgDAfw73sSOJPlSaw@@6w8xH5OzczOlo38rH1YNgESYkj@BPwIYQpxDjGuf5awXKYQ8r9xjuttzD8tqdByWS5xXv/G9aY9WYusBdrz79P@Bv1v1PBvdfyc9gjKd5HaUdwfqa/9yesobo8bpV457tEOjW3/@p67SIAOHW192JDje9HfuL/T6PVnuXrzrLR6zlb5PXyXXucu@Av8Bf4Cf4G/wF/4IXwY@AsbwocdwSfj@/czWqNQalWr7xUPvQvChQMY7ajjz8uRD9hDFMM@sU/sE/t0PpRFFCmyYvdxQHdFpN4bHh@P7/wWVhzMKrKKrKI4WDSrVbOkbCcRKF/rHL4Wf0MsyFKMtsNNHbKle7dho/tN0BknLYx1ygO/7Qw@jB3e749H2clvxyJ7aPRYVliE2NsKlVYh6nwAiDrJkx4fQOzixD0n7jlxz4l7MjmcuOfEPSfusSF8WJxDTWTPyJ6RPQMjhlWMGNH1iBbYAQgxQ0l/4ZBn@AK18bIeiYMRV33MoFrlLZi52P3@9pqMjkbCxHgm7AKL0ru2jtQqGYsI@48lec44ELfSGllEaNHa08cyypPyJWUe99nyIexxNP/YUSR3FSV01/zI54eh0bgz7OETw1iTgtKyNc6C4T@ScR/5ek5MkOPqHeHXOumNNfJ@WR0992knvoUtW9/76JxPX3ngy531S1f2/7GecgRkNGi1/y8fysHAAfxPPgD/E9rAp4KesaEsGa0x/5v/zaf0g1U1F/Mm6K51BTm74@TAGCFeDkrzkpUseAbvmR8LFzGfsLEiazbVvjL2UXYq@8RKspIQSb66@Q96YwbCgZ2wvltlpc3ZD7w7UuaP0gatQsD5pVZvyE0sY4bmT2gV6mdOpTWwYjsXeShW4Hzp0FyMAxG6nYsifCtJdi7aucin5MfyqfgGtAbG5Bs7vq2LFi1atGjRokWLFm0f6OUZ4kiY8/mRWIi3fUsyhM6LA0KgeR40t8c8PScZ9fnVcOs33mJ5uvYDadXav4wRGSP29DhXTpbIuPnXI55qaR6yrxE@zxqNGq3RC3phPnZiHqxGq3Ap8QBUh43gk9Bt0bpTFOiY/qMUQWiVz4wDe@DRokX7/2jzzdcq2Oin5TLH@GDJvtyRrZ5UthCEfO31rUXLn0y1bIVWovj4qJE2snL7SPuC@oqP3NOdNvdvb/WSrtLzkAolRrIw5vx7epa5j2FJ/2dGc1OJ/V1Irb2p1VSk80MpPunPLtjckcLkFEK4ldY1y6ny8EIcechTVbmyrDD5SS63PU7X1QiUm8zcft1Iv9QUq8wa89ONNuz15dpCEWahrfXP190o4ohhH4C49Xna5DqXsW/SmTbtSD/kNsrT2448KNhcyLaCpUON@a3AVH9sItnoayOp1/VlqspcCt@OTasmxtZ@GZOmLVvp@W5E7gb52dDF169g7eqjOD7j9UkFr3l90JjK5reu@erdq10smrK9c7uCVXGll@hTfatsld7c6VMWSX21bm6ygJ/UlqvKWlQVuKhZ1dhrK3ZnAO@vPx8ffwE) ## Explanation The reason that Miniflak quines are destined to be slow is Miniflak's lack of random access. To get around this I create a block of code that takes in a number and returns a datum. Each datum represents a single character like before and the main code simply queries this block for each one at a time. This essentially works as a block of random access memory. --- This block of code has two requirements. * It must take a number and output only the character code for that character * It must be easy to reproduce the lookup table bit by bit in Brain-Flak To construct this block I actually reused a method from my proof that Miniflak is Turing complete. For each datum there is a block of code that looks like this: ``` (({}[()])[(())]()){(([({}{})]{}))}{}{(([({}{}(%s))]{}))}{} ``` This subtracts one from the number on top of the stack and if zero pushes `%s` the datum beneath it. Since each piece decrements the size by one if you start with n on the stack you will get back the nth datum. This is nice and modular, so it can be written by a program easily. --- Next we have to set up the machine that actually translates this memory into the source. This consists of 3 parts as such: ``` (([()]())()) {({}[( -Look up table- )]{}) 1. (({}[()])[(())]()){(([({}{})]{}))}{}{([({}{}(([{}]))(()()()()()))]{})}{} 2. (({}[()])[(())]()){(([({}{})]{}))}{}{([({}{} (({}[( ({}[()(((((()()()()()){}){}){}))]{}){({}[()(({}()))]{}){({}[()(({}((((()()()){}){}){}()){}))]{}){({}[()(({}()()))]{}){({}[()(({}(((()()()()())){}{}){}))]{}){([(({}{}()))]{})}}}}}{} (({}({}))[({}[{}])]) )]{}({})[()])) ({[()]([({}({}[({})]))]{})}{}()()()()()[(({}({})))]{}) )]{})}{} 3. (({}[()])[(())]()){(([({}{})]{}))}{}{([({}{} (({}(({}({}))[({}[{}])][( ({}[()( ([()](((()()[(((((((()()()){})())){}{}){}){})]((((()()()()())){}{}){})([{}]([()()](({})(([{}](()()([()()](((((({}){}){}())){}){}{})))))))))))) )]{}) {({}[()(((({})())[()]))]{})}{} (([(((((()()()()){}){}()))){}{}([({})]((({})){}{}))]()()([()()]({}(({})([()]([({}())](({})([({}[()])]()(({})(([()](([({}()())]()({}([()](([((((((()()()())()){}){}){}()){})]({}()(([(((((({})){}){}())){}{})]({}([((((({}())){}){}){}()){}()](([()()])(()()({}(((((({}())())){}{}){}){}([((((({}))){}()){}){}]([((({}[()])){}{}){}]([()()](((((({}())){}{}){}){})(([{}](()()([()()](()()(((((()()()()()){}){}){}()){}()(([((((((()()()())){}){}())){}{})]({}([((((({})()){}){}){}()){}()](([()()])(()()({}(((((({}){}){}())){}){}{}(({}))))))))))))))))))))))))))))))))))))))))))))))) )]{})[()]))({()()()([({})]{})}{}()) )]{})}{} ({}[()]) }{}{}{} (([(((((()()()()){}){}())){}{})]((({}))([()]([({}())]({}()([()]((()([()]((()([({})((((()()()()){}){}()){})]()())([({})]({}([()()]({}({}((((()()()()()){}){}){})))))))))))))))))) ``` The machine consists of four parts that are run in order starting with 1 and ending with 3. I have labeled them in the code above. Each section also uses the same lookup table format I use for the encoding. This is because the entire program is contained in a loop and we don't want to run every section every time we run through the loop so we put in the same RA structure and query the section we desire each time. ### 1 Section 1 is a simple set up section. The program tells first queries section 1 and datum 0. Datum 0 does not exist so instead of returning that value it simply decrements the query once for each datum. This is useful because we can use the result to determine the number of data, which will become important in future sections. Section 1 records the number of data by negativizing the result and queries Section 2 and the last datum. The only problem is we cannot query section 2 directly. Since there is another decrement left we need to query a non-existant section 5. In fact this will be the case every time we query a section within another section. I will ignore this in my explanation however if you are looking a the code just remember 5 means go back a section and 4 means run the same section again. ### 2 Section 2 decodes the data into the characters that make up the code after the data block. Each time it expects the stack to appear as so: ``` Previous query Result of query Number of data Junk we shouldn't touch... ``` It maps each possible result (a number from 1 to 6) to one of the six valid Miniflak characters (`(){}[]`) and places it below the number of data with the "Junk we shouldn't touch". This gets us a stack like: ``` Previous query Number of data Junk we shouldn't touch... ``` From here we need to either query the next datum or if we have queried them all move to section 3. Previous query is not actually the exact query sent out but rather the query minus the number of data in the block. This is because each datum decrements the query by one so the query comes out quite mangled. To generate the next query we add a copy of the number of data and subtract one. Now our stack looks like: ``` Next query Number of data Junk we shouldn't touch... ``` If our next query is zero we have read all the memory needed in section 3 so we add the number of data to the query again and slap a 4 on top of the stack to move onto section 3. If the next query is not zero we put a 5 on the stack to run section 2 again. ### 3 Section 3 makes the block of data by querying our RAM just as section 3 does. For the sake of brevity I will omit most of the details of how section 3 works. It is almost identical to section 2 except instead of translating each datum into one character it translates each into a lengthy chunk of code representing its entry in the RAM. When section 3 is done it tells the program to exit the loop. --- After the loop has been run the program just needs to push the first bit of the quine `([()]())(()()()()){({}[(`. I does this with the following code implementing standard Kolmogorov-complexity techniques. ``` (([(((((()()()()){}){}())){}{})]((({}))([()]([({}())]({}()([()]((()([()]((()([({})((((()()()()){}){}()){})]()())([({})]({}([()()]({}({}((((()()()()()){}){}){})))))))))))))))))) ``` --- I hope this was clear. Please comment if you are confused about anything. ]
[Question] [ I came up with a series of numbers the other day and decided to check what the OEIS number for it was. Much to my surprise, the sequence did not appear to be in the OEIS database, so I decided to name the sequence after myself (note that someone else who's a lot smarter than me has probably already come up with this, and if someone finds the actual name of this sequence, please comment and I'll change the question title). As I couldn't find the sequence anywhere, I decided to name it after myself, hence "Gryphon Numbers". EDIT: Thanks to @Surb for bringing to my attention the fact that this sequence is equal to OEIS sequence [A053696](https://oeis.org/A053696) - 1. A Gryphon number is a number of the form \$a+a^2+...+a^x\$, where both \$a\$ and \$x\$ are integers greater than or equal to two, and the Gryphon sequence is the set of all Gryphon numbers in ascending order. If there are multiple ways of forming a Gryphon number (the first example is \$30\$, which is both \$2+2^2+2^3+2^4\$ and \$5+5^2\$) the number is only counted once in the sequence. The first few Gryphon numbers are: \$6, 12, 14, 20, 30, 39, 42, 56, 62, 72\$. ## Your Task: Write a program or function that receives an integer \$n\$ as input and outputs the \$n\$th Gryphon number. ## Input: An integer between 0 and 10000 (inclusive). You may treat the sequence as either 0-indexed or 1-indexed, whichever you prefer. Please state which indexing system you use in your answer to avoid confusion. ## Output: The Gryphon number corresponding to the input. ## Test Cases: Please note that this assumes the sequence is 0-indexed. If your program assumes a 1-indexed sequence, don't forget to increment all the input numbers. ``` Input: Output: 0 ---> 6 3 ---> 20 4 ---> 30 10 ---> 84 99 ---> 4692 9999 --> 87525380 ``` ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` bṖ’ḅi-µ#Ṫ ``` A full program which reads a (1-indexed) integer from STDIN and prints the result. **[Try it online!](https://tio.run/##AR0A4v9qZWxsef//YuG5luKAmeG4hWktwrUj4bmq//8xMQ "Jelly – Try It Online")** ### How? A Gryphon number is a number which is expressible in a base less than itself such that all the digits are ones except the least significant, which is a zero. For example: \$30=1\times 2^4+1\times 2^3+1\times2^2+1\times2^1+0\times2^0 \rightarrow 30\_2 = 11110\$ \$84=1\times 4^3+1\times 4^2+1\times 4^1+0\times 4^0 \rightarrow 84\_4 = 1110\$ This program takes `n`, then starts at `v=0` and tests for this property and increments `v` until it finds `n` such numbers, then outputs the final one. To test a base `b` number it subtracts one from every digit, converts from base `v`, and then checks if the result is \$-1\$. (Note that `b` is less than `v`) \$30\_2 \rightarrow 0\times 30^4+0\times 30^3+0\times30^2+0\times30^1+(-1)\times30^0 = -1\$ \$84\_4 \rightarrow 0\times 84^3+0\times 84^2+0\times 84^1+(-1)\times 84^0 = -1\$ ``` bṖ’ḅi-µ#Ṫ - Main Link: no arguments # - set v=0 then count up collecting n=STDIN matches of: µ - the monadic link -- i.e. f(v): e.g. v=6 Ṗ - pop (implicit range of v) [1,2,3,4,5] b - to base (vectorises) [[1,1,1,1,1,1],[1,1,0],[2,0],[1,2],[1,1]] ’ - decrement (vectorises) [[0,0,0,0,0,0],[0,0,-1],[1,-1],[0,1],[0,0]] ḅ - from base (v) (vectorises) [0,-1,5,1,0] - - literal -1 -1 i - first index of (zero if not found) 2 - } e.g. n=11 -> [6,12,14,20,30,39,42,56,62,72,84] Ṫ - tail -> 84 - implicit print ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~16~~ 13 bytes ``` :Qtt!^Ys+uSG) ``` 1-based. [**Try it online!**](https://tio.run/##y00syfn/3yqwpEQxLrJYuzTYXfP/f0NDAA) ### Explanation Consider input `n = 3` as an example. ``` : % Implicit input: n. Range % STACK: [1 2 3] Q % Add 1, element-wise % STACK: [2 3 4] tt % Duplicate twice, transpose % STACK: [2 3 4], [2 3 4], [2; 3; 4] ^ % Power, element-wise with broadcast % STACK: [2 3 4], [ 4 9 16; 8 27 64; 16 81 256] Ys % Cumulative sum of each column % STACK: [2 3 4], [ 4 9 16; 12 36 80; 28 117 336] + % Add, element-wise with broadcast (*) % STACK: [ 6 12 20; 14 39 84 30 120 340] u % Unique elements. Gives a column vector % STACK: [ 6; 14; 30; 12; ··· 340] S % Sort % STACK: [ 6; 12 14; 20; ··· 340] G) % Push input again, index. This gets the n-th element. Implicit display % STACK: 14 ``` The matrix obtained in step (\*) contains possibly repeated Gryphon numbers. In particular, it contains `n` distinct Gryphon numbers in its first row. These are not necessarily the `n` smallest Gryphon numbers. However, the lower-left entry `2+2^+···+2^n` exceeds the upper-right entry `n+n^2`, and thus all the numbers in the last row exceed those in the first row. This implies that extending the matrix rightward or downward would not contribute any Gryphon number lower than the lowest `n` numbers in the matrix. Therefore, the matrix is guaranteed to contain the `n` smallest Gryphon numbers. Consequently, its `n`-th lowest unique element is the solution. [Answer] # [Haskell](https://www.haskell.org/), 53 bytes ``` ([n|n<-[6..],or[a^y+n==n*a+a|a<-[2..n],y<-[3..n]]]!!) ``` [Try it online!](https://tio.run/##jYxBDoIwAATvvGIhHkBagmI8iS/Qk8dStUEEYykEMNKEt1uLL3BPk93JVqJ/FlKaMs2Mz9SkdpRto4iTpmPirEOVpmopQjEJO6yjSHGiLSUzce66ganFQyHFrXHgX2vRHi9XsJggIdgQrGIeYIFsBN1bB7IYoK1eYnTwR9rXcBq6g4LfV80bI8IQHqg982b8lTown/wuRdkbmrftFw "Haskell – Try It Online") \$\newcommand{\ta}{{a}}\newcommand{\ti}{{i}}\newcommand{\tx}{{x}}\newcommand{\tn}{{n}}\newcommand{\ty}{{y}}\$A number \$\tn\$ is Gryphon if there exist integers \$\ta \geq 2\$ and \$\tx \geq 2\$ such that \$\tn=\sum\_{i=1}^\tx \ta^i\$. We generate an infinite list of all \$\tn \geq 6\$ such that a brute-force search shows this is the case. The answer is a (zero-indexed) index function into this list, denoted in Haskell as `(list!!)`. ## Why is `a^y+n==n*a+a` correct? From [the formula for summing a geometric progression](https://en.wikipedia.org/wiki/Geometric_progression#Geometric_series): > > $$\sum\_{i=1}^\nu \alpha \rho^{i-1} = \frac{\alpha(1-\rho^\nu)}{1-\rho}$$ > > > we have, letting \$(\alpha, \rho, \nu) = (\ta, \ta, \tx)\$: $$\tn = \sum\_{\ti=1}^\tx \ta^\ti = \frac{\ta(1-\ta^\tx)}{1-\ta} = \frac{\ta-\ta^{\tx+1}}{1-\ta}.$$ Rearranging the equation, we get \$n(1-a) = a - a^{x+1}\$. Rearranging that even further, we get \$\ta^{\tx+1}+n = \tn \ta + \ta\$. A substitution \$\ty = \tx+1\$ in the brute-force search yields the final expression `a^y+n=n*a+a`. ## Is searching until `n` enough? * If \$\ta > \tn\$ (in other words, \$\ta \geq \tn+1\$), then $$\ta^\ty + \tn > \ta^2 \geq (\tn+1)\ta = \tn\ta + \ta$$ which proves \$\ta^\ty+\tn \neq \tn\ta+\ta\$. So there's no sense checking any of the values \$\ta > \tn\$. * Similarly: if \$\ty > \tn\$, then $$\ta^\ty + \tn > \ta^\tn = \ta^{\tn-1}\ta \geq 2^{\tn-1}\ta \stackrel{\color{red}\*}> (\tn+1)\ta = \tn\ta + \ta,$$ again proving \$\ta^\ty + \tn \neq \tn\ta + \ta\$. \$\color{red}{{}^{\*}}\$We can assume \$2^{n-1}>n+1\$ because we know \$n \geq 6\$, the smallest Gryphon number. [Answer] # [Python 3.8 (Pre-release)](https://docs.python.org/3.8/), 98 92 89 78 71 bytes ``` lambda n:sorted({a*~-a**x//~-a for a in(r:=range(2,n+3))for x in r})[n] ``` [Try it online!](https://tio.run/##HYpBCsIwEEX3nmKWM1FpaTYS6EnUxUibNqCTMM2iInr1mPZvHo/30zvPUewlafH9rTz59RgYxC1R8zjgh83vzMasTVMJPiowBEF1vbJMI3YnOVqiLaw1gH7pKveyedh9f9mW3AHqkgbJ6DEQlT8 "Python 3 – Try It Online") 0-indexed. Integer division must be used here because f(10000) overflows floats. Generates all Gryphon numbers where \$2 \leq a \leq n+2\$ and \$2 \leq x \leq n+2\$, sorts them, and selects the \$n\$th element. -6 bytes thanks to Jonathan Allan -3 bytes thanks to ArBo. I almost did as he suggested myself, but tried to use `{*(...)}` which didn't save space anyway -11 bytes thanks to mathmandan -7 bytes thanks to ArBo ## Mathematical Proof of Validity Using 0-indexing for the sake of this proof, even though mathematical convention is 1-indexed. * Let \$G\_n\$ be the \$n\$th Gryphon number * Let \$g(a,x) = a + a^2 + ... + a^x\$ (The Gryphon number from \$a\$ and \$x\$) * Let \$A\_n\$ be the set of all Gryphon numbers where \$2 \leq a \leq n+2\$ and \$2 \leq x \leq n+2\$ * We know that \$A\_0 = \{ g(2,2) \} = \{ 6 \} = \{ G\_0 \}\$ * \$A\_{n+1} = \{ g(a, x), g(a+1, x), g(a, x+1), g(a+1, x+1) | g(a, x) \in A\_n \} \$ * \$g(a+1, x) < g(a+1, x+1)\$ for all \$a\$ and \$x\$ * \$g(a, x+1) < g(a+1, x+1)\$ for all \$a\$ and \$x\$ * Therefore \$G\_{n+1} \neq g(a+1, x+1)\$ if \$G\_n = g(a, x)\$ * \$g(a+1, x) < g(a+2, x)\$ for all \$a\$ and \$x\$ * \$g(a, x+1) < g(a, x+2)\$ for all \$a\$ and \$x\$ * Therefore \$G\_{n+1}\$ must either be \$g(a+1, x)\$ or \$g(a, x+1)\$ if \$G\_n = g(a, x)\$ since no other possibilities exist. * We can use this information to conclude that \$G\_{n+1} \in A\_{n+1}\$ if \$G\_n \in A\_n\$ * Since we know that \$G\_0 \in A\_0\$, we can use this rule to induce that \$G\_n \in A\_n\$ for all \$n\$ * Since this can be applied from \$G\_0\$ to \$G\_n\$, then \$G\_n\$ must be at index \$n\$ of \$A\_n\$ if \$A\_n\$ is ordered from smallest to largest [Answer] # [J](http://jsoftware.com/), ~~35~~ 32 bytes *-3 bytes thanks to FrownyFrog* ``` 3 :'y{/:~~.,}.+/\(^~/>:)1+i.y+2' ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jRWs1Cur9a3q6vR0avW09WM04ur07aw0DbUz9Sq1jdT/a3KlJmfkK5gp2CqkKRhAOEYGYJ4xhGcM4ZlAeBYmYJ6hwX8A "J – Try It Online") Explanation is same as original. Simply uses explicit form to save bytes be removing the multiple `@`. ## original answer, tacit, with explanation: 35 bytes ``` {[:/:~@~.@,@}.[:+/\@(^~/>:)1+i.@+&2 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/q6Ot9K3qHOr0HHQcavWirbT1Yxw04ur07aw0DbUz9Ry01Yz@a3KlJmfkK5gp2CqkKRhAOEYGYJ4xhGcM4ZlAeBYmYJ6hwX8A "J – Try It Online") Similar to Luis Mendo's approach, we create a "power table" (like a times table) with top row `2 3 ... n` and left column `1 2 ... n` resulting in: ``` 2 3 4 5 6 7 4 9 16 25 36 49 8 27 64 125 216 343 16 81 256 625 1296 2401 32 243 1024 3125 7776 16807 64 729 4096 15625 46656 117649 ``` `^~/ >:` creates the table, and `1+i.@+&2` creates the `1... n` sequences, and we add 2 (`+&2`) to the input to ensure we always have enough elements to create a table even for 0 or 1 inputs. After we have the table above the solution is trivial. We just scan sum the rows `+/\`, and then remove the first row, flatten, take unique, and sort `/:~@~.@,@}.`. Finally `{` uses the original input to index into that result, producing the answer. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 18 bytes ``` )┅:1D¤*‡+⊣¦tv<_uȯE ``` [Try it online!](https://tio.run/##ASQA2/9nYWlh//8p4pSFOjFEwqQq4oChK@KKo8KmdHY8X3XIr0X//zM "Gaia – Try It Online") 1-based index. This is a rather sad answer with a long nose: `)┅:` It probably wishes it could be golfed down further. Copies the algorithm given by [Luis Mendo's answer](https://codegolf.stackexchange.com/a/183493/67312) [Answer] # [R](https://www.r-project.org/), ~~65~~ 62 bytes -1 byte thanks to Giuseppe. ``` n=scan();unique(sort(diffinv(t(outer(2:n,1:n,"^")))[3:n,]))[n] ``` [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTujQvs7A0VaM4v6hEIyUzLS0zr0yjRCO/tCS1SMPIKk/HEIiV4pQ0NTWjjYHMWCCdF/vf0PA/AA "R – Try It Online") 1-indexed. Generates a matrix of all values of the form \$a^i\$, takes the cumulative sum, removes the first row (0s) and the second row (entries corresponding to \$x=1\$), then takes the unique sorted values. Note that `sort(unique(...))` would not work, as `unique` would give unique rows of the matrix, and not unique entries. Using `unique(sort(...))` works because `sort` converts to vector. [Answer] # JavaScript (ES7), 76 bytes 1-indexed. ``` f=(n,a=[i=2])=>(n-=a.some(j=>a.some(k=>(s+=j**k)==i,s=j)))?f(n,[...a,++i]):i ``` [Try it online!](https://tio.run/##LctBDoIwEIXhPaeYZYeWRlmKgwchLBpsTQvOEGrcGM9eu3D1/rzkS@7t8nLE/dWx3H0pgRQbR1OkfkYaFXfkbJanV4nGf631z5pS265IFE2mhIi3UOVkrXVG6zjjJZYgh2IgOA/AcIX@VFdrhE8DsAhn2bzd5FEdVIw4NN/yAw "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES7), 89 bytes 1-indexed. ``` n=>eval('for(a=[i=1e4];--i>1;)for(s=1e8+i,x=1;a[s+=i**++x]=x<26;);Object.keys(a)[n]-1e8') ``` [Try it online!](https://tio.run/##ZctBDsIgEIXhvRcpU6QRU40JTq/gAZouRqSGSsCUpsHTIy5N3/LL@ydaKerZvhfhw8PkEbPHzqzkWDWGmRH2FqVpByWE7aSCH8YiF273CaWiPnK0dc15GjBdj2cF6nafjF6al/lERtD7QZR/BVkHH4MzjQtPNjIJsPuXdiOnjchtJg9lAPkL "JavaScript (Node.js) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 51 bytes ``` (Union@@Array[Sum[(#2+1)^k,{k,#+1}]&,{30,#}])[[#]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277XyM0LzM/z8HBsagosTI6uDQ3WkPZSNtQMy5bpzpbR1nbsDZWTafa2EBHuTZWMzpaOTZW7X9AUWZeiYNWuoK@g0K1oY6RjomOqY6hoY6hARDU/v8PAA "Wolfram Language (Mathematica) – Try It Online") 1-indexed *-8 bytes from @attinat* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` NθFθFθ⊞υ÷⁻X⁺²ι⁺³κ⁺²ι⊕ιF⊖θ≔Φυ›κ⌊υυI⌊υ ``` [Try it online!](https://tio.run/##TY0xDsIwDEV3TpHRlsICbJ0QFagDKFcIbaAWSUqTuBw/pIgKJj/7y/@1vQ7toG3OjX9yurC7mgAjVqvbEEQBsUzFsQeWovGppok6A2fyHEENr/KhbMGNFIRSfHgrxQOX5Rs0vg3GGZ9MB4S4SGrzO4@IYh8j3T0cyabSXJSnYPSMDymKkxw7YJzLuVSoQD7BQccE/2GV8y6vJ/sG "Charcoal – Try It Online") Link is to verbose version of code. 1-indexed. Uses Luis Mendo's algorithm. Explanation: ``` Nθ ``` Input \$ n \$. ``` FθFθ⊞υ ``` Create an \$ n \$-by-\$ n \$ grid of Gryphon numbers and push each one to the predefined list. ``` ÷⁻X⁺²ι⁺³κ⁺²ι⊕ι ``` Calculate the Gryphon number using the fact that \$ \sum\_1^x a^i = \frac{a^{x+1}-a}{a-1} \$. ``` F⊖θ≔Φυ›κ⌊υυ ``` Remove the lowest \$ n-1 \$ Gryphon numbers. ``` I⌊υ ``` Print the lowest remaining Gryphon number. [Answer] # [Japt](https://github.com/ETHproductions/japt), 23 bytes Dear Jebus! Either I *really* have forgotten how to golf or the booze is finally taking its toll! Not a direct port of Jonathan's solution but very much inspired by his observation. ``` @ÈÇXìZ mÉ ìZÃeÄ}fXÄ}gNÅ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QMjHWOxaIG3JIOxaw2XEfWZYxH1nTsU&input=MTA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` L¦ãε`LmO}êIè ``` 0-indexed [Try it online](https://tio.run/##yy9OTMpM/f/f59Cyw4vPbU3wyfWvPbzK8/CK//8NDQA) or [verify the first \$n\$ items](https://tio.run/##yy9OTMpM/f/f59Cyw4vPbU3wyfWvPbzK89Di//@NTAE). **Explanation:** ``` L # Create a list in the range [1, (implicit) input-integer] # i.e. 4 → [1,2,3,4] ¦ # Remove the first item to make the range [2, input-integer] # i.e. [1,2,3,4] → [2,3,4] ã # Create each possible pair of this list by using the cartesian product # i.e. [2,3,4] → [[2,2],[2,3],[2,4],[3,2],[3,3],[3,4],[4,2],[4,3],[4,4]] ε # Map each pair to: ` # Push the values of the pair separately to the stack # i.e. [4,3] → 4 and 3 L # Take the list [1, value] for the second value of the two # i.e. 3 → [1,2,3] m # And then take the first value to the power of each integer in this list # i.e. 4 and [1,2,3] → [4,16,64] O # After which we sum the list # i.e. [4,16,64] → 84 }ê # After the map: uniquify and sort the values # i.e. [6,14,30,12,39,120,20,84,340] → [6,12,14,20,30,39,84,120,340] Iè # And index the input-integer into it # i.e. [6,12,14,20,30,39,84,120,340] and 4 → 30 # (after which the result is output implicitly) ``` ]
[Question] [ In English, nouns can take on two different forms depending on whether they are singular (one) or plural (anything else). For example, we would say "1 dog" but "2 dogs", "0 dogs", "57 dogs" and so forth. In Russian, there are three categories. Instead of "1 dog, 2 dogs, 5 dogs", in Russian it would be "1 собака, 2 собаки, 5 собак". The categories are divided according to the following logic: * "Singular": used for 1 and any number ending in 1, except for numbers ending in 11. + Examples: 1 собака, 21 собака, 101 собака * "Few": used for 2, 3, and 4, and any number ending in 2, 3, or 4 except for numbers ending in 12, 13, and 14. + Examples: 2 собаки, 3 собаки, 4 собаки, 32 собаки, 43 собаки, 104 собаки * "Many": anything that is not considered "Singular" or "Few". + Examples: 0 собак, 5 собак, 11 собак, 13 собак, 25 собак, 111 собак, 114 собак ## The challenge Given an integer input in the range [0, 1000], return `1` if it belongs to the "singular" category, `2` if it belongs to the "few" category, and `5` if it belongs to the "many" category. Your program may be a function or it can use STDIN. You may print to STDOUT or return a value from the function This is a **code golf** challenge, so the solution with the fewest number of bytes wins. [Answer] # [Python 2](https://docs.python.org/2/), 36 bytes ``` lambda n:'5521'[n%~9/-3>>n/10%~9/-9] ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQZ6VuampkqB6dp1pnqa9rbGeXp29oAGZbxv5Pyy9SyFPIzFMoSsxLT9UwNDAw0LTiUigoyswrUcjTUde1U9dJ08jT/A8A "Python 2 – TIO Nexus") Same length arithmetically: ``` lambda n:5/(n%~9/-3>>n/10%~9/-9or 1) ``` Let's first look at simpler code that doesn't account for teens. ``` lambda n:'5521'[n%~9/-3] ``` Here, we want a mapping of the one's digit to an output that works like ``` [5, 1, 2, 2, 2, 5, 5, 5, 5, 5][n%10] ``` But, rather than take `n` modulo 10 (`%10`), we can do `n%-10`, which maps to the intervals `[-9..0]` to give remainders: ``` > [n%~9 for n in range(10)] [0, -9, -8, -7, -6, -5, -4, -3, -2, -1] ``` This is promising because the first two entries `0` and `-9` are far apart, and they need to be sent to different outputs. Also, `-10` can be shortened to `~9`. From here, floor-dividing by `/-3` gives chunks of 3 with the right starting spot ``` > [n%~9/-3 for n in range(10)] [0, 3, 2, 2, 2, 1, 1, 1, 0, 0] ``` To get the desired output, we now just need to map `0->5, 1->5, 2->2, 1->1`, which we do with the string selection `'5521'[_]`. Now, we also need numbers ending in 11 to 15 to always give `5`. We first do this by detecting whether then tens digit is `1`. Taking `n/10` to remove the last digit, we then apply `%~9` as before to get the outcomes ``` [0, -9, -8, -7, -6, -5, -4, -3, -2, -1] ``` for respective final digits. The digit of 1 that we want to detect is mapped to the extremal value `-9`. Floor-dividing by `-9` turns it to 1 and everything else to 0. ``` > [k%~9/-9 for k in range(10)] [0, 1, 0, 0, 0, 0, 0, 0, 0, 0] ``` Finally, we make this indicator being `1` always give output 5. This is done by bit-shifting the result of `n%~9/-3` right by the indicator. The result of `0,1,2,3` always bit-shifts right to 0 or 1, which gives an output of 5 as desired. [Answer] # [Python 2](https://docs.python.org/2/), 45 bytes ``` lambda n,s='5122255555':(s+'5'*10+s*8)[n%100] ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQp1Nsq25qaGRkZAoC6lYaxdrqpupahgbaxVoWmtF5qoYGBrH/0/KLFDIVMvMUihLz0lM1jAwMNK24FAqKMvNKFDJ11HXt1HXSNDI1/wMA "Python 2 – TIO Nexus") [Answer] # [Perl 5](https://www.perl.org/), 26 bytes 25 bytes of code + `-p` flag. ``` $_=/1.$|[5-90]$/?5:2-/1$/ ``` [Try it online!](https://tio.run/nexus/perl5#FYk7DoAwDMX2dwoQWUuaTwcqIQ6CEBMbQ8XM3UuYbMvT2K7nHlLrdK4sM717SUs@iLdSNbEQ9y5QgeQADA5TuEU7MgoklkF/CRP/AA) For one more byte, there is `$_=/(?<!1)[1-4]$/?2-/1$/:5`. **Explanations:** (on the 27 bytes version; the 26 is quite symmetrical) Both "singular" and "few" end with "not a 1 followed by a digit from 1 to 4" (tested with `(?<!1)[1-4]$/`). In those case, the result is 2, minus 1 if the number ends with 1 (`2-/1$/`). Otherwise, the result if 5. [Answer] # JavaScript (ES6), ~~53~~ ~~49~~ ~~48~~ ~~40~~ ~~39~~ ~~38~~ ~~37~~ 36 bytes ``` n=>/[05-9]$|1.$/.test(n)?5:1+(n%5>1) ``` * Saved 8 bytes thanks to [CalculatorFeline](https://codegolf.stackexchange.com/users/51443/calculatorfeline). * Saved 1 byte thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions). * Saved 1 byte thanks to [Johan](https://codegolf.stackexchange.com/users/55822/johan-karlsson) --- ## Try it ``` f= n=>/[05-9]$|1.$/.test(n)?5:1+(n%5>1) oninput=_=>o.innerText=f(+i.value);o.innerText=f(i.value=0) ``` ``` <input id=i type=number><pre id=o> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` DµṖṚi1’ȧṪị“M;ọ6’D¤ ``` A monadic link taking and returning non-negative integers. **[Try it online!](https://tio.run/nexus/jelly#ASsA1P//RMK14bmW4bmaaTHigJnIp@G5quG7i@KAnE074buNNuKAmUTCpP///zIx)** or see the three groups from 0 to 1000 inclusive in this [test suite](https://tio.run/nexus/jelly#ATgAx///RMK14bmW4bmaaTHigJnIp@G5quG7i@KAnE074buNNuKAmUTCpP8wcsi3w4figqzEoOKAmUf//w). ### How? ``` DµṖṚi1’ȧṪị“M;ọ6’D¤ - Main link: non-negative number, n e.g. 301 311 313 D - cast to decimal list [3,0,1] [3,1,1] [1,3,3] µ - monadic chain separation, call that d Ṗ - pop d [3,0] [3,1] [1,3] Ṛ - reverse [0,3] [1,3] [3,1] 1 - literal 1 i - first index of (0 if not found) 0 1 2 ’ - decrement -1 0 1 Ṫ - tail d 1 1 3 ȧ - logical and 1 0 3 ¤ - nilad followed by link(s) as a nilad: “M;ọ6’ - base 250 literal = 1222555555 D - cast to decimal list [1,2,2,2,5,5,5,5,5,5] ị - index into (1-based and modular) 1 5 2 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~38~~ 19 bytes Uses the index-trick from [Rod's python answer](https://codegolf.stackexchange.com/a/123764/47066) ``` •1rꢰ•©5T×®9×JIт%è ``` [Try it online!](https://tio.run/nexus/05ab1e#qyn7/6hhkWHR4VWHFh3aAGQeWmkacnj6oXWWh6d7VV5sUj284n@l0uH9VgqH9yvp/DfkMjLkMjQAUlzGXCZcxkZcJsZAvgmXAZcplyFQypjLCMQAsgxNAA "05AB1E – TIO Nexus") **Explanation** ``` •1rꢰ• # push the number 5122255555 © # store a copy in register 5T× # push 5 repeated 10 times ® # retrieve the first number from register 9× # repeat it 9 times J # join everything to string Iт% # push input mod 100 è # use this to index into the string of digits ``` [Answer] # PHP>=7.1, 44 Bytes ``` <?=$argn[-2]!=1&($m=($argn+9)%10)<4?2-!$m:5; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/377f9e09acab09f7789f54d418e75fb25096876a) [Answer] # [MCxxxx Assembly](http://store.steampowered.com/app/504210/SHENZHEN_IO/), 123 Bytes ``` e:slx x0 mov x0 acc dst 2 0 tlt acc 11 -tgt acc 14 -jmp v +dgt 0 teq acc 1 +mov 1 x1 +jmp e tlt acc 5 +mov 2 x1 v:-mov 5 x1 ``` ### Note: TiO doesn't support this language, which is used in the Zachtronics game [Shenzhen I/O](http://store.steampowered.com/app/504210/SHENZHEN_IO/), so there's no link to test this. ## Explanation: This is a function that takes input through XBus port x0, and outputs through port x1. It's too long to execute on an MC4000, but fits nicely into the memory of an MC6000. XBus ports, for those unfamiliar, allow the transmission of discrete packets of digital data. One piece of information that may be helpful in reading this: in MCxxxx assembly, test instructions set a flag that indicates which branch should be taken. Lines that begin with `+` are only executed if the most recent test returned true, and lines that begin with `-` are only executed if the test was false. Line by line: ``` e:slx x0 # Label this line e, then sleep until input is available on XBus port x0 mov x0 acc # Move the input into register acc dst 2 0 # Set the leftmost digit of the input to 0 tlt acc 11 # Test if the value in acc is less than 11 -tgt acc 14 # If it's not, check if it's greater than 14 -jmp v # If it's not, jump to the line labeled v (the last line) +dgt 0 # If either of the previous tests returned true, # set acc to the value of acc's rightmost digit teq acc 1 # Test if acc equals 1 +mov 1 x1 # If it does, return 1 +jmp e # Then jump to label e, which ends execution tlt acc 5 # Test if acc is less than 5 +mov 2 x1 # If it is, return 2 v:-mov 5 x1 # If the previous test is false, return 5 ``` A note about scoring: MCxxxx assembly doesn't have functions per se, but this is as close to a function as you can get - it's a program that fits in a single execution node, takes input through one port and outputs through another. As a result, I've scored this like a function (i.e. without counting the bytes necessary to make a valid MCxxxx emulator file). [Answer] # [Retina](https://github.com/m-ender/retina), ~~25~~ 21 bytes ``` 1.$ 5 T`d`512225 !`.$ ``` [Try it online!](https://tio.run/##Dcm7CYBAEAXA/HUhnGB0@PaDdmADFrCCBiYGYv/rpjPv9d3PkeO0RbI3OPY4wykijiF6y5xBCBRWuYAEFVJkkBXqJUU0UPQH "Retina – Try It Online") -4 bytes thanks to Neil. [Answer] # [Haskell](https://www.haskell.org/), 62 58 bytes ``` f n|s<-"5122255555"=(s++('5'<$[0..9])++cycle s)!!mod n 100 ``` [Try it online!](https://tio.run/##1Y9BCsMgFESv8hMKUWxFBRdCPElwIYnBUDWhv1AKvbttui50287bvZnNRI/nkFKtM5QH9qdWS6WU3tNagoyRTnf9YRCcG0cZG@9jCoC0afI6QQEpRM1@KXa7LOUKJPsNZhgk59IYB9bCbkgMfgIOGNcbfbVH9UZ/4dPu193f/XC0PgE "Haskell – Try It Online") ## Explanation This builds the following string: 5122255555555555555551222555555122255555512225555551222555555122255555512225555551222555555122255555... Which is a table where cell `n` contains the answer for the `nth` number. The table is only correct for the first 100 elements, hence the `mod`. [Answer] **Scala, 110 bytes** ``` n=>Stream.iterate("512225555555555555555")(_=>"1222555555").flatMap(_.toCharArray).map(_.toInt).take(n-1).head ``` [Answer] # Turtlèd, 35 bytes ``` !--.(1#0#)+.@3(1@1)(2@2)(3@2)(4@2), ``` [Try it online!](https://tio.run/##KyktKslJTfn/X1FXV0/DUNlAWVNbz8FYw9DBUFPDyMFIU8MYRJgACZ3//@0MAQ "Turtlèd – Try It Online") This function requires that the input starts with a >, which I guess is ok because python2 uses input semi regularly, and that needs quotes. Explanation: ``` ! input the number as a string, complete with the > --. wrap around to the end of the string, and then move one back. if this is a single digit, we end up on the >, otherwise we end up on the second to last digit. write the digit/> (1#0#) if it is 1, set the string to 0. this way it will always write 3 at the end. +. write the last digit (or 0 if the second last digit was 1) @3 set the character variable to 3. this means if what was written was not in (1, 2, 3, 4), then it will write 3 at the end (1@1) if the character written was a 1, set the character to be written at the end to 1 (2@2)(3@2)(4@2) if it is any of 2,3,4, set the character to be written at the end to 2 , write the character that was set ``` [Answer] # [Lexurgy](https://www.lexurgy.com/sc), 88 bytes ``` s: \1=>\1/_ $//\1 _ $ else: {\2,\3,\4}=>\2/_//\1 _ $ else: []=>\5 c: []=>*/_//_ $ ``` Ungolfed explanation: ``` singular: # 1 to 1 if no 1 preceding 1 \1=>\1/_ $//\1 _ $ else: # 2,3,4 to 2 if no preceding 1 {\2,\3,\4}=>\2/_ $//\1 _ $ else: # everything else to 5 []=>\5/_ $ clean: # keep only the last digit []=>*/_//_ $ ``` Trivia: the technical linguistics terms for `one, few, many` is `singular, paucal, plural`. ]
[Question] [ Write a complete program that takes a boolean or non-negative integer input. It must: * Output its own source code if the input value is falsy * Output its own source code in reverse if the input value is truthy Your program cannot be palindromic, nor can it read its own source code by any means. This is code golf - shortest code in bytes wins. [Answer] ## CJam, ~~17~~ 16 bytes ``` {`"_~"+Wq~g#%}_~ ``` [Test it here.](http://cjam.aditsu.net/#code=%7B%60%22_~%22%2BWq~g%23%25%7D_~&input=0) A fairly straight-forward modification of the standard quine. Other solutions for 17 bytes: ``` {`"_~"+q~{W%}&}_~ {`"_~"+q~!2*(%}_~ ``` If I can assume that the input is only 0 or 1 (as a stand-in for a boolean, which there is no dedicated type for in CJam), I get 15 by omitting the `g`: ``` {`"_~"+Wq~#%}_~ ``` ### Explanation ``` {`"_~"+ e# Standard generalised quine framework. Leaves the source code on the stack. W e# Push a -1. q~ e# Read and evaluate input. g e# signum, turning truthy values into 1 (leaving 0 unchanged). # e# Power. -1^0 == 1, -1^1 == -1. % e# Select every Nth element: a no-op for 1 and reverses the string for -1. }_~ ``` [Answer] # [Gol><>](https://github.com/Sp3000/Golfish/wiki), 9 bytes ``` 'rd3*I?rH ``` I feel a little awkward posting this, since we already have ><>, Vitsy and Minkolang answers. The only additions to the standard quine are `I` (read integer input), `?` (execute next if truthy) and `r` (reverse stack). [Try it online](https://golfish.herokuapp.com/?code='rd3%2aI%3FrH&input=1&debug=false). [Answer] # Pyth, 17 bytes ``` _WQjN*2]"_WQjN*2] ``` A straightforward modification of the standard Pyth quine. [Answer] ## ><>, 17 Bytes Requires the -v flag (+1 byte) for pushing input onto the stack (or for you to put input on the stack beforehand on the online interpreter). ``` 'rd3*$?rol?!;70. ``` You could do the below for the same amount of bytes (without the flag) if integer inputs only were allowed (i.e. 0 for falsy, 1 for truthy). ``` 'rd3*ic%?rol?!;80. ``` [Try it online](http://fishlanguage.com/playground) Truthy/falsy for ><> are anything not 0 and 0, respectively. [Answer] # [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), 15 Bytes ...I'm... I'm beating CJam! (shouts over) *Mom! Look, ma, I deed it!* ``` 'rd3*i86*-)rl\O ``` Explanation: ``` 'rd3*i86*-(rl\O Standard quine, but with a twist: ' Capture the source code as a string rd3* Create the ' character in ASCII i86*- Get the input character as ASCII then subtract 48 from it. If it's zero, it'll the if statement will skip the next instruction. (r If the top item of the stack is zero, do not do the next item. The next item here is reverse. l\O Print out the stack. ``` ## Newer Version of [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), 11 Bytes ``` v'rd3*}v)rZ v Capture the input as a variable. ' Capture the source until encountering another ' r Reverse the stack. d3* Push ' to the stack. } Rotate the stack to the right one. v) Push the variable (input) to the stack and test if it is not zero. r If so, reverse the stack. Z Output everything in the stack. ``` [Answer] ## Python 2, 51 bytes ``` s="print('s=%r;exec s'%s)[::1-2*0**input()]";exec s ``` [Answer] # Javascript (ES6), 42 bytes ``` $=_=>'$='+(_?$:[...''+$].reverse().join``) ``` This is a modification of my [Bling Quine](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/60148#60148). It's twice as long, too. [Answer] ## Burlesque, 40 bytes ``` ri#Q2 SH ~- "ri#Q" \/ .+ j "<-" ps if sh ``` **Explanation:** Burlesque has advanced stack and code manipulation built-ins. In fact, you can't access the source code of the program but you can access the remaining code that is to be executed in the future. This means `#Q` will return all the code that follows it which is why we have to add everything up to `#Q` to that code which is what we're doing with `ri#Q`. ``` blsq ) #Q1 2++ 12 -- this is the result of 1 2++ {1 2 ++} -- this is the result of #Q ``` `++1 2` is technically illegal code since it's stack based. But we can manipulate the code to make it execute as `1 2++`: ``` blsq ) #Q<-#q++1 2 12 ``` Working with these built-ins is incredibly tricky and nobody has yet used them for anything productive except for quine related things. If you reverse `++1 2` you get `2 1++` which would produce `21` and not `12`. The reason the code above produces `12` is because `#Q` also includes the `<-` so in the end we end up executing a lot more than just `2 1++` :p. We end up executing `2 1++#q<-` which produces `12`. We can actually replace things in our code for example this code replaces all occurences of `?+` in itself with `?*` ``` blsq ) #Q(?+)(?*)r~5.-#q5 5?+ 25 ``` **Usage:** ``` $ echo "1" | blsq --stdin 'ri#Q2 SH ~- "ri#Q" \/ .+ j "<-" ps if sh' hs fi sp "-<" j +. /\ "Q#ir" -~ HS 2Q#ir $ echo "0" | blsq --stdin 'ri#Q2 SH ~- "ri#Q" \/ .+ j "<-" ps if sh' ri#Q2 SH ~- "ri#Q" \/ .+ j "<-" ps if sh ``` [Answer] ## Haskell, ~~126~~ ~~118~~ 108 bytes ``` main=readLn>>=putStr.([t,reverse t]!!);t=s++show s;s="main=readLn>>=putStr.([t,reverse t]!!);t=s++show s;s=" ``` Expects `0` or `1` as input. [Answer] ## [Minkolang 0.10](http://play.starmaninnovations.com/minkolang/?code=%2266*2-n%3Fr%24O%2E&input=1), 13 bytes ``` "66*2-n,?r$O. ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=%2266*2-n%2C%3Fr%24O%2E&input=1) This is exactly like the standard quine except for these four characters: `n,?r`. `n` takes an integer from input, `,` inverts it, so `?` skips `r` if the input is truthy. Otherwise, `r` reverses the stack so that it is output in reverse order. [Answer] # Java 10 (full program), 282 bytes ``` interface N{static void main(String[]a){var s="interface N{static void main(String[]a){var s=%c%s%1$c;s=s.format(s,34,s);System.out.print(new Boolean(a[0])?new StringBuffer(s).reverse():s);}}";s=s.format(s,34,s);System.out.print(new Boolean(a[0])?new StringBuffer(s).reverse():s);}} ``` [Try it online.](https://tio.run/##tcxBCsIwEIXhq4RiIYEaFF1ZitADuOmydDG0E0m1iWSmFSk9e6x4AhduH//7ephg23e3GK1jDAZaFJeZGNi2YvK2EwNYJysO1l3rBtQ8QRBUJL/laZtSut@0ORWkjQ8DsKTscMxI5dWLGAftR9aP9cbS4VOU3t8RnIR616jzZ/ma5WgMBklKB5wwEEp1Wo1lSf5Hxxg5jPgG) # Java 10 (as lambda function), 154 bytes ``` b->{var s="b->{var s=%c%s%1$c;s=s.format(s,34,s);return b?new StringBuffer(s).reverse():s;}";s=s.format(s,34,s);return b?new StringBuffer(s).reverse():s;} ``` [Try it online.](https://tio.run/##pY9BS8NAEIXv@RVDMbAL7YLoyRAF79ZDj@Jhsp2UjclumZlEpOS3x60tePLkZZjhvTe8r8MJN93@Y/E9isALhngqAEJU4hY9wfZ8Arw2HXkFb5qUesIIja2yMBd5iKIGD1uIUMPSbB5PEzJIvfpdS19KeXvjK6nFtYkHVCPru/u12IpJR84PnyJ9wk45xMPz2LbERqxjmoiFjH2Qal79L75U57bHselz22vpKYU9DJnaXKJv74D2grz7EqXBpVHdMUvaRxOdNy32QvaH/k@P8ni1zMW8fAM) **Explanation:** ``` interface N{ // Class static void main(String[]a){ // Mandatory main-method var s="interface N{static void main(String[]a){var s=%c%s%1$c;s=s.format(s,34,s);System.out.print(new Boolean(a[0])?new StringBuffer(s).reverse():s);}}"; // Unformatted source code s=s.format(s,34,s); // Format the source code (the quine-String) System.out.print( // Print: new Boolean(a[0])? // If the input is true: new StringBuffer(s).reverse() // Print the quine-String reversed : // Else: s);}} // Print the quine-String as is ``` **[quine](/questions/tagged/quine "show questions tagged 'quine'") explanation:** * The `var s` contains the unformatted source code * `%s` is used to put this String into itself with `s.format(...)` * `%c`, `%1$c`, and `34` are used to format the double-quotes * `s.format(s,34,s)` puts it all together And then `new StringBuffer(s).reverse()` is used to reverse the quine-String if necessary based on the input-boolean. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0"D34çý‚sè"D34çý‚sè ``` [Try it online.](https://tio.run/##yy9OTMpM/f/fQMnF2OTw8sN7Dzc9aphVfHgFOv//f0MA) Modification of the default [quine](/questions/tagged/quine "show questions tagged 'quine'") [`0"D34çý"D34çý`](https://codegolf.stackexchange.com/a/97899/52210) by adding `‚sè`. **Explanation:** ``` 0 # Push 0 to the stack # STACK: [0] "D34çý‚sè" # Push the string 'D34çý‚sè' to the stack # STACK: [0, 'D34çý‚sè'] D # Duplicate this string # STACK: [0, 'D34çý‚sè', 'D34çý‚sè'] 34ç # Push '"' to the stack # STACK: [0, 'D34çý‚sè', 'D34çý‚sè', '"'] ý # Join the stack with '"' delimiter # STACK: ['0"D34çý‚sè"D34çý‚sè']  # Bifurcate (short for Duplicate & Reverse) # STACK: ['0"D34çý‚sè"D34çý‚sè', 'ès‚Âýç43D"ès‚Âýç43D"0'] ‚ # Pair them up: # STACK: [['0"D34çý‚sè"D34çý‚sè','ès‚Âýç43D"ès‚Âýç43D"0']] s # Swap to get the boolean input (0 or 1) # STACK: [['0"D34çý‚sè"D34çý‚sè','ès‚Âýç43D"ès‚Âýç43D"0'], 1] è # Index the input into the list # STACK: ['ès‚Âýç43D"ès‚Âýç43D"0'] # (Output the top of the stack implicitly) ``` PS: Automatically prints a trailing newline. If this should be reversed as well, it's 23 bytes instead: ``` 0"D34çý‚sè?"D34çý‚sè? ``` [Try it online.](https://tio.run/##yy9OTMpM/f/fQMnF2OTw8sN7Dzc9aphVfHiFPYbA//@GAA) (`?` is an explicit *Print without new-line*) ]
[Question] [ Keeping this challenge short. You are given 4 numbers: p1, p2, p3 and p4. The magic sum of the numbers are defined as follows: ``` magic_sum = |p1 - p2| + |p2 - p3| + |p3 - p4| + |p4 - p1| ``` You are only allowed to change one of the above integer values (p1, p2, p3 or p4). You need to change the value such that the magic sum of the values attains its minimum value. For example: p1, p2, p3, p4 = 17, -6, 15, 33. The value of the magic sum is 78 in this case. You can change the -6 here to 16, and the value of the magic sum will become 36, which is the minimum attainable value. Do keep in mind that numbers can be positive or negative integers. This is code-golf, so least bytes in code wins. Brownie points for using a Practical Language over a Recreational language. May the 4th be with you. To reiterate: ### Sample 1 **Input 1** ``` 17 -6 15 33 ``` **Output 1** ``` 36 ``` **Explanation 1** > > The -6 can be replaced with 16 and that gives us the minimum attainable > magic sum possible. > > > ### Sample 2 **Input 2** ``` 10 10 10 10 ``` **Output 2** ``` 0 or 2 ``` either is acceptable **Explanation 2** > > The minimum attainable magic sum is 0 since the minimum sum of 4 positive > integers is 0. If a number has to be changed, then one of the 10's can be > changed to a 9 and thus yielding the output 2. > > > ## Sample 3 **Input 3** ``` 1 2 3 4 ``` **Output 3** ``` 4 ``` **Explanation 3** > > The input by itself yields 6 as its magic sum. Changing the 4 to 1 and the minimum magic sum is attained, which is 4. > > > [Answer] # [Python 2](https://docs.python.org/2/), 44 bytes ``` a,b,c,d=sorted(input()) print min(c-a,d-b)*2 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzP1EnSSdZJ8W2OL@oJDVFIzOvoLREQ1OTq6AoM69EITczTyNZN1EnRTdJU8vo//9oQ3MdBV0zHQVDUx0FY@NYAA "Python 2 – Try It Online") Sorts the input as `a,b,c,d,` in ascending order, takes the smaller of `c-a` and `d-b`, and doubles it. Why does this work? First, note that when we change an element to maximize to total cyclic sum of distances, it's optimal (or tied for optimal) to change it to equal a neighbor, such as `17, -6, 15, 33 -> 17, 17, 15, 33`. That's because its new total distance to its left and right cyclic neighbors is at least the distance between those neighbors, so making these be equal is the best we can do. Now, deleting one of two adjacent copies of a number gives the same cyclic sum of distances. In the example, this is `17, 15, 33`, giving distances `2 + 18 + 16`. So instead of replacing one of the four numbers, it's equivalent to just delete it leaving three numbers, and using the sum of their cyclic distances. Notice that with 3 numbers, the largest distance is the sum of the two smaller ones. This is because if we sort the numbers to have `a ≤ b ≤ c`, then `|a - c| = |a - b| + |b - c|`. In other words, we travel between the largest and smallest number twice, using the medium number as a pit stop one of the times. So, the sum of the three distances is just twice the distance between the minimum and maximum, so `(c-a)*2`. So, the question is which number we delete to get the smallest distance between the minimum and maximum of the three numbers that remains. Clearly we delete either the smallest or the largest of the numbers. Calling them `a, b, c, d` in sorted order, deleting `a` leaves `d - b`, and deleting `d` leaves `c - a`, and the final result is double whichever is smaller. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ṢŒœIṂḤ ``` [Try it online!](https://tio.run/##ASMA3P9qZWxsef//4bmixZLFk0nhuYLhuKT///8xNywtNiwxNSwzMw "Jelly – Try It Online") A port of my [Python answer](https://codegolf.stackexchange.com/a/185189/20260). ``` (input) [17, -6, 15, 33] Ṣ sort [-6, 15, 17, 33] Œœ odd-even elts [[-6, 17], [15, 33]] I increments [23, 18] M minimum 18 Ḥ double 36 ``` [Answer] # [R](https://www.r-project.org/), ~~66~~ 33 bytes ``` function(x)2*min(diff(sort(x),2)) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQtNIKzczTyMlMy1Nozi/qAQoomOkqfk/TSNZw9BcR9dMx9BUx9gYKAIA "R – Try It Online") Much shorter with [xnor's algorithm](https://codegolf.stackexchange.com/a/185189/86301) (go read their explanation and upvote their post!). Old version: # [R](https://www.r-project.org/), 66 bytes ``` function(x,m=matrix(x,3,4))min(colSums(abs(diff(rbind(m,m[1,]))))) ``` [Try it online!](https://tio.run/##FchJCsAgDEDR60RIF2KHlafosnThQCDQKKgFb2/tXz1@GWQHvSk0zgk6ihXXCvdJg6tSwglCfs5XKjhfITIRFM8pgqBcGm/1NwgC6AOXHfWGxszzAQ "R – Try It Online") Takes input as a vector of 4 integers. This works because the minimum can be attained by setting one of the numbers as equal to one of its neighbours (it is not the only way of attaining the minimum). To see why this is true, find a configuration which achieves the minimum; say we have changed \$p\_2\$. Any value of \$p\_2\$ such that \$p\_1\leq p\_2\leq p\_3\$ will give the same sum (\$|p\_1-p\_2|+|p\_2-p\_3|\$ remains constant), so we can choose \$p\_2=p\_1\$. There are 4 ways of choosing which number we change; for each of these, we only have to compute the sum of 3 absolute differences. The code sets the values in a \$3\times4\$ matrix, where each column represents a subset of size 3 of the 4 numbers. Copy the first row to a 4th row with `rbind` and compute the absolute differences, then take the minimum of the column sums. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes ``` I;SASƲ$-ƤṂ ``` [Try it online!](https://tio.run/##y0rNyan8/9/TOtgx@NgmFd1jSx7ubPr//7@huY6umY6hqY6xMQA "Jelly – Try It Online") A monadic link that takes a list if integers as input. Should work for arbitrary list size. Works on the basis that the minimum sum can be obtained by testing removing each number from the list, calculating the magic sum and taking the minimum. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṁ-Ƥ⁸IA§Ṃ ``` A monadic Link accepting a list of integers\* which yields an integer \* can be any number so long as there are more than 1; using same style magic formula summing the neighbours differences wrapping around. **[Try it online!](https://tio.run/##ASUA2v9qZWxsef//4bmBLcak4oG4SUHCp@G5gv///zE3LC02LDE1LDMz "Jelly – Try It Online")** ### How? ``` ṁ-Ƥ⁸IA§Ṃ - Link: list of integers, X e.g. [17,-6,15,33] -Ƥ - for overlapping "outfixes" of length length(X)-1: - [[-6,15,33],[17,15,33],[17,-6,33],[17,-6,15]] ṁ ⁸ - mould like X [[-6,15,33,-6],[17,15,33,17],[17,-6,33,17],[17,-6,15,17]] I - incremental differences [[21,18,-39],[-2,18,-16],[-23,39,-16],[-23,21,2]] A - absolute (vectorises) [[21,18,39],[2,18,16],[23,39,16],[23,21,2]] § - sums [78,36,78,46] Ṃ - minimum 36 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-Q`](https://codegolf.meta.stackexchange.com/a/14339/), 11 bytes ``` ñÍó ®r- ÑÃn ``` Uses @xnor's algorithm, which saved me 4 bytes. Saved 5 bytes thanks to @Shaggy [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVE&code=8c3zIK5yLSDRw24&input=WzE3LCAtNiwgMTUsIDMzXQ) [Answer] # [J](http://jsoftware.com/), ~~24~~ ~~20~~ ~~18~~ 17 bytes alternative version using xnor algorithm: ``` 2*[:<./2 2-/@$\:~ ``` ## how Two times `2 *` the min of `[:<./` the 2nd row subtracted from the first row `[:-/` of the 2x2 matrix formed by shaping `2 2$` the input sorted down `\:~` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jbSirWz09I0UjHT1HVRirOr@a3JxpSZn5CsYmynYKqQpGJorxJspGJoqGBv/BwA "J – Try It Online") ## original answer: [J](http://jsoftware.com/), 24 bytes ``` [:<./1(1#.2|@-/\],{.)\.] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o61s9PQNNQyV9YxqHHT1Y2J1qvU0Y/Ri/2tycaUmZ@QrGJsp2CqkKRiaK8SbKRiaKhgb/wcA "J – Try It Online") Using Nick Kennedy's idea. * `1(...)\.]` apply the verb in parens to all outfixes of length 1 (an outfix of length n is a list with n contiguous elements removed, so this produces every possible list with 1 elm removed) * `(1 #. 2 |@-/\ ] , {.)` this calculates the magic sum by appending the first elm to the input `] , {.` and applying the abs difference `|@-/` to infixes of length 2 `2 ...\`, and summing the result `1 #.`. * `[:<./` returns the min [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) Port of [*@xnor*'s Jelly answer](https://codegolf.stackexchange.com/a/185190/52210). -4 bytes thanks to *@Emigna* and *@Grimy*. ``` {2ô`αß· ``` [Try it online.](https://tio.run/##yy9OTMpM/f@/2ujwloRzGw/PP7T9//9oQ3MdXTMdQ1MdY@NYAA) **7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative** which only works in the legacy version of 05AB1E (would require a `€` before the `¥` in the new version): ``` {2ôø¥W· ``` [Try it online.](https://tio.run/##MzBNTDJM/f@/2ujwlsM7Di0NP7T9//9oQ3MdXTMdQ1MdY@NYAA) **Explanation:** ``` { # Sort the (implicit) input-list # i.e. [17,-6,15,33] → [-6,15,17,33] 2ô # Split this list into parts of size 2 # → [[-6,15],[17,33]] ` # Push both separated to the stack α # And take their absolute differences # → [23,18] ß # Pop and push the minimum # → 18 · # Double it (and output implicitly as result) # → 36 { # Sort the (implicit) input-list # i.e. [17,-6,15,33] → [-6,15,17,33] 2ô # Split this list into parts of size 2 # → [[-6,15],[17,33]] ø # Zip/transpose, swapping rows/columns # → [[-6,17],[15,33]] ¥ # Get the deltas/forward differences of the inner lists # → [[23],[18]] W # Get the flattened minimum (without popping) # → 18 · # Double it (and output implicitly as result) # → 36 ``` [Answer] # [C++ (gcc)](https://gcc.gnu.org/) ## full program: 138 bytes ``` #include<iostream> #include<regex> using namespace std;int main(){int a[4];for(int&b:a)cin>>b;sort(a,a+4);cout<<min(a[2]-*a,a[3]-a[1])*2;} ``` [Try it online!](https://tio.run/##PYtLCsIwFAD3PUVAkKaaRX8KpuQiIYvX11gCzYckBUE8e6wbdzMDgyGwFbGUk3G47YuejE85arCi@qeoV/0S1Z6MW4kDq1MA1CTlhRuXiQXjavr@IchB8aeP9SHn@QEUjRNi5snHXMMVLgPl6Pc8TfZ4QHaKNUeWvWIgW0Wbjn9Kae@E3Ug7kn78Ag "C++ (gcc) – Try It Online") ## core function: 84 bytes ``` #include<regex> int m(int*a){std::sort(a,a+4);return std::min(a[2]-*a,a[3]-a[1])*2;} ``` [Try it online!](https://tio.run/##RU5LCoMwFFybUwQKxdhm4a8FI14kZBFiKg9qIjFCQTy7TbTQzcDMvJl5aprooNS@X8Co99Lr1ulBfzoExuMxDZhJss6@b5rZOp/Ku7xVhDntF2fwoY9gUskLQbNg8lJQyXNBsoJt/1Kws3dajr9eGSIErSiJDMy0eF4JhpKXdXHyiqE5VHIuKDBdB8E/mV1828bf4gVD254/MX3gvMZl/QU "C++ (gcc) – Try It Online") Also using the algorithm *xnor* explained in his Python 2 post. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` I⌊EEθΦθ⁻κμΣEι↔⁻λ§ι⊕μ ``` [Try it online!](https://tio.run/##LUs9C8IwEP0rN17gOpRSHZxEEDoUhI6lQ0wDHianJqn472OjffDgfZqbDuahXc6XwJLwpGPCnoX94rHXzx9fBGd2yYai1nKJeCfwSimCYdsxwfEa8d@61aROZvspeScmWG8l2RnLacMh53Gs9wTVjqBuCZpmmnL1dl8 "Charcoal – Try It Online") Link is to verbose version of code. Turns out I'm using @NickKennedy's idea. Explanation: ``` Eθ Map over input array Φθ Filter over input array where ⁻κμ Outer and inner indices differ E Map over resulting list of lists Eι Map over remaining values in list §ι⊕μ Get the next value in the list ↔⁻λ Compute the absolute difference with the current value Σ Take the sum of absolute differences ⌊ Take the minimum sum I Cast to string and implicitly print ``` [Answer] # JavaScript (ES6), 51 bytes Using [xnor's much more clever method](https://codegolf.stackexchange.com/a/185189/58563): ``` a=>([a,b,c,d]=a.sort((a,b)=>a-b),b+c<a+d?c-a:d-b)*2 ``` [Try it online!](https://tio.run/##bYrLDoIwEADvfsUet7IllvpIjMUPIRy2LRgMoYYSf7/uyYPxMJeZefKbc1in16aXFIcyusKuxY7JU6DYO65zWjdEEcq1rL0iX4UbV/EeNF@jiH1TQlpymod6Tg8csTMXAn0mMCcCa3uldr/DQeKXPwMYAmgEKxxlKB8 "JavaScript (Node.js) – Try It Online") --- # Original answer, 96 bytes Takes input as an array of 4 integers. ~~Probably~~ Definitely not the shortest approach. ``` a=>a.map(m=x=>a.map((y,i)=>a[m=a.map(v=>s+=Math.abs(p-(p=v)),a[i]=x,p=a[3],s=0)|m<s?m:s,i]=y))|m ``` [Try it online!](https://tio.run/##bYpLCsIwEIb3niLLDE5La3yAOPUEniB0MdZWK00TTCktePcYEF2Iiw/@x3fnkX31aN2Q9PZSh4YCU8GpYScNTZ8oZ2whFm3oPYxU@CWdeLilfPbSJdLRCICs25ImdMRalegpg6c5@KPZe4zHDLGGyvbednXa2atspM53KJItinyDQqkSYPErZPH88kcQOQqxiqjIOgrhBQ "JavaScript (Node.js) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes A port of @xnor's algorithm ``` 2{#3-#}~Min~{#4-#2}&@@Sort@#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n27736ha2VhXubbONzOvrlrZRFfZqFbNwSE4v6jEQVntf0BRZl6JgkN6dLWhuY6umY6hqY6xcW0sF5K4gQ4MoYrrGOkY65jUxv7/DwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Java 8](https://docs.oracle.com/javase/8/docs/), 235 bytes A port of @xnor's [Python answer and algorithm](https://codegolf.stackexchange.com/questions/185168/make-me-a-minimum-magic-sum/185189#185189 "xnor's answer") ``` import java.util.*;interface M{static void main(String[]A){Scanner I=new Scanner(System.in);int a[]={0,0,0,0};for(int i=0;i<4;a[i++]=I.nextInt());java.util.Arrays.sort(a);System.out.print(2*(a[2]-a[0]>a[3]-a[1]?a[3]-a[1]:a[2]-a[0]));}} ``` [Try it online!](https://repl.it/repls/DelayedBaggyDaemons "Java 8 – Try It Online") ### [Java 10](https://docs.oracle.com/javase/10/), unproven, 222 bytes With Java 10, I should be able to replace left side of Scanner declaration with `var`, although I could not compile it online and thus I can only add it as a trivia. Sorry. ``` interface M{static void main(String[]A){var I=new java.util.Scanner(System.in);int a[]={0,0,0,0};for(int i=3;i<4;a[i++]=I.nextInt());java.util.Arrays.sort(a);System.out.print(2*(a[2]-a[0]>a[3]-a[1]?a[3]-a[1]:a[2]-a[0]));}} ``` ]
[Question] [ You will need to generate the smallest prime with `n` digits, and it will only contain digits specified in the list `k`. ### Examples: Input: ``` 4 1 2 ``` For this, you must generate the smallest prime with `4` digits, and that prime must only contain the digits `1` and `2`. Output: ``` 2111 ``` Input: ``` 10 0 4 7 ``` Output: ``` 4000000007 ``` Input: ``` 6 5 5 5 5 5 5 5 5 5 5 1 5 5 5 5 5 5 5 5 5 5 ``` Output: ``` 115151 ``` You can guarantee that the input will always be in the format you specify, and you can do anything if you get invalid input (such as the input being a single digit `n`, without `k`.) If no such solution to an input exists, your program is allowed to do any of the following: * Print `banana` * Throw an error * Run forever * Anything else Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), try to aim for the shortest code. The input can be in any format you specify. For example, if you want your input to be like any of the following, that is fine. ``` 4 [1, 2] [1,2]4 1,2 4 4 12 ``` You can either write a program or a function, and it must either return the correct value or print it. Whitespace is allowed anywhere. This challenge inspired by [A036229](https://oeis.org/A036229). [Answer] # Bash + bsd-games package, 28 bytes * 18 bytes saved thanks to @Dennis. ``` primes 1|egrep -wm1 [$2]{$1} ``` Input given at the command-line as n followed by k as a non-delimited list of digits. [Try it online.](https://tio.run/nexus/bash#S8svUihJLS5JTixOVcjMU1AyUTA0UlJQMlMwhQNDBFPJWiEln6s4tURBBabrf0FRZm5qsYJhTWp6UWqBgm55rqFCtIpRbLWKYe3/lPy81P//zf5jNQ0A) [Answer] # [Python 2](https://docs.python.org/2/), 66 bytes ``` f=lambda n,s,k=1,p=1:10**~-n<p%k*k<s>=set(`k`)or-~f(n,s,k+1,p*k*k) ``` [Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJCnU6yTbWuoU2BraGVooKVVp5tnU6CarZVtU2xnW5xaopGQnaCZX6Rbl6YBVqoNVKoFlNb8X1CUmVeikKZhrFOtbqmuo24MxBbqtZr/AQ "Python 2 – TIO Nexus") Takes input like `f(3,{'9','3','8'})`. Python has no built-ins for primes, so the function generates them using [Wilson's Theorem](https://codegolf.stackexchange.com/a/27022/20260) to check each potential value for `k` in turn for being prime. The chained inequality `10**~-n<p%k*k<s>=set(`k`)` combines three conditions on `k`: * `10**~-n<k`: `k` contains at least `n` digits. We don't need to check exactly since if we reach more digits, there must have been no solution * `p%k>0`: `k` is prime, via the Wilson's Theorem condition with `p=(n-1)!^2`. Since `p%k` is 0 or 1, this can be combined with the previous condition as `10**~-n<p%k*k` * `s>=set(`k`)`: All digits in `k` are in the set `s`. This can be spliced in because Python 2 considers sets as bigger than numbers. If the current `k` doesn't satisfy all of these, the function recurses onto `k+1`, adding 1 to the resulting output. Since the output terminates with `True` which equals `1`, and `k` starts at `1`, the output is `k`. This parallel tracking of `k` beats outputting `k` directly on success. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (2), 8 bytes ``` j₍oᵐ∋ᵐcṗ ``` [Try it online!](https://tio.run/nexus/brachylog2#@5/1qKk3/@HWCY86uoFk8sOd0///jzbTiY421cGEhjrYRE1jY2P/RwEA "Brachylog – TIO Nexus") Very slow on problems which have a lot of possible digits, or which contain a 0 in the set of possible digits (it does *work* in this case; it's just that it's so much slower that TIO times out unless the problem's very simple). As usual for Brachylog, this is a function, not a full program. Input is taken in the format `[ndigits,[list of digits]]`, e.g. `[10,[[0,4,7]]]`. ## Explanation ``` j₍oᵐ∋ᵐcṗ j₍ Make a number of copies of the second element equal to the first element oᵐ Sort each (ᵐ) of those copies (evaluation order hint) ∋ᵐ Take one element from each of those copies c Concatenate those elements to form an integer (asserts no leading 0) ṗ producing a prime number ``` Seen from the purely declarative point of view, this says "find a prime number, with the given number of digits, where all digits are one of the given digits". In order to find the *smallest* such number, we use evaluation order hints in order to ensure the order in which we test the numbers is smallest to largest; in this case, `ᵐ` makes decisions near the start of the list less prone to changing than decisions near the end (this is its natural order, which happens to be the same as lexicographic and thus numerical order on integers), and thus `{o∋}ᵐ` has two evaluation order hints, "vary the last few digits first" (from the `ᵐ`'s natural order) as the more important hint, and "check smaller digits before larger digits" (from the `o` before the `∋`, which acts as a hint in this context) as the tiebreak. `{o∋}ᵐ` can be written as the equivalent `oᵐ∋ᵐ` to save a byte. [Answer] ## JavaScript (ES7), 100 bytes Takes input as number of digits `n` and string of allowed digits `s` in currying syntax `(n)(s)`. Returns `undefined` if no solution is found. Works rather quickly for up to 6 digits, might work for 7 and definitely too slow -- and memory hungry -- beyond that. ``` n=>s=>(a=[...Array(10**n).keys()]).find(i=>eval(`/[${s}]{${n}}/`).test(i)&&a.every(j=>j<2|j==i|i%j)) ``` ### Test ``` let f = n=>s=>(a=[...Array(10**n).keys()]).find(i=>eval(`/[${s}]{${n}}/`).test(i)&&a.every(j=>j<2|j==i|i%j)) console.log(f(5)("247")) // 22247 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` DLׯP ṗḌÇÐṀṂ ``` Takes a set and an integer as command-line arguments. Prints **0** if no solution exists. [Try it online!](https://tio.run/nexus/jelly#@@/ic3j64bYAroc7pz/c0XO4/fCEhzsbHu5s@n94uZK7wsMd2x81zFHwTSwoVijJSFXITczMU8jJzMtWyC9LLVJIzi8qSi0uyM9LycxLV0gsSi/NTc0rKdb7/7/aUMeoVkeh2kDHRMccwgCK6BgDuaYgrqkOJjTEImZa@18BCEx0FMDA0ADKgAI0Ln5ghmACAA "Jelly – TIO Nexus") ### How it works ``` ṗḌÇÐṀṂ Main link. Left argument: A (digit set/array). Right argument: n (integer) ṗ Cartesian power; yield all arrays of length n that consist only of elements of the array A. Ḍ Undecimal; convert all generated digit arrays to integers. ÇÐṀ Keep only elements for which the helper link returns a maximal result. Ṃ Take the minimum. DLׯP Helper link. Argument: k (integer) D Decimal; convert k into the array of its base 10 digits. L Take the length. ÆP Test if k is a prime number. Yields 1 or 0. × Multiply the length and the Boolean. ``` [Answer] ## Pyke, ~~18~~ 16 bytes ``` j;~p#`ljqi`Q-!)h ``` [Try it here!](http://pyke.catbus.co.uk/?code=j%3B%7Ep%23%60ljqi%60Q-%21%29h&input=1+2%0A4) Runs forever if no values found [Answer] ## Mathematica, 64 bytes ``` FirstCase[Tuples@##,x:{f_,___}/;f>0&&PrimeQ[y=FromDigits@x]:>y]& ``` Pure function where the first argument is the (sorted) list of allowed digits and the second argument is the allowed length. `Tuples@##` computes all lists of the allowed digits of the allowed length, then we find the `FirstCase` which matches `x:{f_,___}` such that the first digit `f` is not `0` and the integer `y=FromDigits@x` is prime and replaces it with `y`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes ``` tL∧?h~lṗ.dẹp⊆L∧ ``` [Try it online!](https://tio.run/nexus/brachylog2#@1/i86hjuX1GXc7DndP1Uh7u2lnwqKsNJPb/f7SZTrSpDggagsjY2P9RAA "Brachylog – TIO Nexus") This is fairly slow. ### Explanation ``` tL Input = [H, L] ∧ ?h~l . The Output is a variable of length H ṗ. The Output is a prime number ẹ The Output's digits... .d ...when removing duplicate digits... p ...is a permutation... ⊆L ...of an ordered subset of L ∧ ``` [Answer] # JavaScript (ES6), 86 bytes Takes input via the currying syntax, e.g., `(4)('12')` ``` n=>(d,F=(i,P=j=>i%--j?P(j):1==j)=>P(i)&&`${i}`.match(`^[${d}]{${n}}$`)?i:F(i+1))=>F(2) ``` ``` 'use strict'; const G=n=>(d,F=(i,P=j=>i%--j?P(j):1==j)=>P(i)&&`${i}`.match(`^[${d}]{${n}}$`)?i:F(i+1))=>F(2) const submit = () => { console.clear(); console.log(G(+n.value)(d.value)); } button.onclick = submit; submit(); ``` ``` <input id="n" type="number" min="1" value="4" /> <input id="d" type="text" value="12" /> <button id="button">Submit</button> ``` To be run in strict mode (for [tail call optimisation [TCO]](http://www.ecma-international.org/ecma-262/6.0/#sec-tail-position-calls)). If your environment doesn't support TCO it will result in a stack overflow error for primes larger than the environments stack. For invalid inputs it will run forever. **Note:** * Chrome (>= 51) users can go to `chrome://flags/#enable-javascript-harmony` and enable this flag to run the above snippet with TCO support. * Safari (>= 10) supports TCO [Answer] # MATL, 17 bytes ``` wlwX"1GXNUStZp)l) ``` This function accepts two inputs, an integer specifying the number of digits and a character array indicating the possible values. In the case of no primes, an error is shown. [**Try it Online!**](https://tio.run/nexus/matl#@1@eUx6hZOge4RcaXBJVoJmj@f@/CZe6oZE6AA) **Explanation** ``` % Implicitly grab two inputs. First as an integer (N), second as a string (OPTS) w % Reverse the order of the inputs l % Push the literal 1 to the stack w % Pull N back to the top of the stack X" % Repeat OPTS N times 1G % Explicitly grab N again XN % Get all N-character combinations of the repeated version of OPTS U % Convert each row from a string to a number S % Sort them in ascending order tZp) % Grab only those that are primes l) % Retrieve the first prime % Implicitly print the result ``` [Answer] # Pyth - ~~13~~ 12 bytes ``` f&P_T!-Tz^Tt ``` [Test Suite](http://pyth.herokuapp.com/?code=f%26P_T%21-Tz%5ETt&test_suite=1&test_suite_input=4%0A%5B1%2C+2%5D%0A6%0A%5B5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+1%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%5D&debug=0&input_size=2). [Answer] # Sage, 62 bytes ``` lambda l,d:[p for p in primes(10^(l-1),10^l)if set(`p`)<=d][0] ``` Takes input of the form: `f( 4 , {'1','2'} )` [Answer] # [Perl 6](http://perl6.org/), 43 bytes ``` ->\n,@k {first *.is-prime&/^@k**{n}$/,^∞} ``` Runs forever if no solution exists. [Answer] ## Ruby, ~~77~~ 76 bytes ``` ->n,l{(10**~-n..10**n).find{|n|(2...n).none?{|x|n%x<1}&&!n.to_s[/[^#{l}]/]}} ``` Input format: a number and a string. ### Example: ``` ->n,l{...see above...} [6,"555555555515555555555"] => 115151 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` [¾ØÐ¼g¹QiS²Kg0Qiq ``` [Try it online!](https://tio.run/nexus/05ab1e#ASEA3v//W8K@w5jDkMK8Z8K5UWlTwrJLZzBRaXH//zQKWzEsMl0 "05AB1E – TIO Nexus") ``` [¾Ø ¼ # Infinite loop over all primes Ð # Push two extra copies on the stack g¹Qi # If the length of this prime == the first input... S²K # Push this prime without any of the digits in the second input g0Qi # If the length of what remains is 0... q # quit # implicitly print this prime ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ ~~19~~ 18 bytes (-1 @Riley) ``` [NØ©S¹Kg0Q®g²Q&i®q ``` [Try it online!](https://tio.run/nexus/05ab1e#ASwA0///W07DmMKpU8K5S2cwUcKuZ8KyUSZpwq4scf//WzEsM10KNPVuby1jYWNoZQ "05AB1E – TIO Nexus") ``` [ # infinite loop. NØ© # push nth prime. S¹Kg0Q # see if, without banned digits, it's 0 length. ®g²Q& # see if, it is originally also the length specified. i®q # if true, print result and exit. ``` [Answer] # [R](https://www.r-project.org/), 88 bytes *Note: as a special 'Language of the month' treat for anyone contemplating starting to golf in R (and I hope there are many of you...), I've written a short commentary of the various iterations that led to this answer in the [R golfing chatroom](https://chat.stackexchange.com/rooms/112541/the-r-project-for-statistical-golfing).* ``` function(n,k)for(x in 1:10^n)if(sum(x%/%10^(1:n-1)%%10%in%k)==n&(sum(!x%%1:x)<3))stop(x) ``` [Try it online!](https://tio.run/##hY5RasMwEET/c4oNQUULCrXatAVTX6UmVeRmSbQy0oqop3dVX8B/OzOPnUlLDuf73WcZ@UI/JOOcKPjxQXIdVyMPy1TYCUXWbG44xaQrEIPtbffFSJPOJeiqnlXT2vZ8tKjarYjVDYeBn1ZgX5vZV/x8RcwSZ11xu1ufjO1fEA4Qi8xFgDJ8/4JPKSYDOYKLIXgWkGtLGgMSIRWG7F3kC0h7Du6c/R5gt932bpx@MxZxd4Bt2nYN78zJfPwPlBavE5Y/ "R – Try It Online") Outputs as an error message. No output when there is no solution. Checks all numbers in the range `1:10^n` (obviously 10^n is not a prime, so we don't need to worry about the end case): * `x%/%10^(1:n-1)%%10` extracts the digits, and `%in% k` checks whether each digit is in the list. If the `sum` is `==n` then we know that all the digits are Ok. * `(sum(!x%%1:x)<3)` checks for primality (a prime should have only 2 factors including 1 and itself). When we find the first solution, we exit with `stop(x)` to output the answer as an error message. `return(x)` would be the friendlier solution to output to STDOUT, but it costs +2 bytes. [Answer] **APL (NARS2000 0.5.14), 31 characters:** ``` {A←⍺⋄((1∘π)⍣{∧/A∊⍨⍎¨⍕⍺})10*⍵-1} ``` **Example:** ``` 1 2 {A←⍺⋄((1∘π)⍣{∧/A∊⍨⍎¨⍕⍺})10*⍵-1} 4 2111 5 5 5 5 5 5 5 5 5 5 1 5 5 5 5 5 5 5 5 5 5 {A←⍺⋄((1∘π)⍣{∧/A∊⍨⍎¨⍕⍺})10*⍵-1} 6 115151 ``` **How it works:** `A←⍺` captures left argument, that is, the required digits composing target prime. `10*⍵-1` generates the least number have `⍵` digits e.g. `10*(4-1) = 1000` `1∘π` finds next prime number of right argument; So on first iteration, `(1∘π)1000` yields `1009` `⍣` operator recursively applies (1∘π) to result from above, unless the inner function `{∧/A∊⍨⍎¨⍕⍺}`, when applied to `1009`, evaluates to `1` i.e. boolean true, where it does not; Thus recurse. The inner function `{∧/A∊⍨⍎¨⍕⍺}` takes `⍺`, result of current iteration, as argument and test if every digit of it is an element of vector A. **Limitations:** Non-termination if no such prime of `n` digit exist. Runs very slowly using the `n = 10` example, not able to return even after 30 seconds. [Answer] # Perl5, 77 bytes ``` ($n,$d)=@ARGV;/^[$d]{$n}$/&&("x"x$_)!~/^(..+?)\1+$/&&print&&die for 2..10**$n ``` Run like this: ``` perl -le '($n,$d)=@ARGV;/^[$d]{$n}$/&&("x"x$_)!~/^(..+?)\1+$/&&print&&die for 2..10**$n' 4 12 ``` [Answer] # [Perl 6](https://perl6.org), 68 bytes ``` ->\n,\k{first {.is-prime&&/.**{n}/},+«[X~] 0,|(k.unique.sort xx n)} ``` [Try it](https://tio.run/nexus/perl6#bZDBboJAEIbv@xRzIGRXh5U1oIkE4kP00KQ2DcFVN@hC2cVgKH2hvkXfqWeKSry0818m//z58mdqI@G84FlE6mF7ksZG5HQBNyu2EuLeSzYaN3m7U5Wx0HJlvLJSJ@m6Mz6ZtLqbdTj9/np5/nwFHz9ozmut3mvJTVFZaBrQrOsH3toOZIiBEgAaIBU4ZwziBOZCCLyawkfqY4DLux/44yxv1wXSEP9K/OOFd4AQ4SAkLCLlMdUwvVWIyK6oxjZeAs4bUFjl8kKpo3GdM4awOqfHWlJHNqXMrNwyYNAOHZSB61PGIMIjgMD3yljS9T@68LI0O8hf "Perl 6 – TIO Nexus") Returns `Nil` if no such prime can be found. ## Expanded: ``` -> \n, # number of digits \k # list of digits { first { .is-prime && / . ** {n} / # exactly 「n」 digits ( in case 「k」 has a 0 ) }, +«\ # turn the following into a list of numbers [X[~]] # cross the following with &infix:<~> 0, # append a 0 in case 「n」 was 1 |( # slip this list in (flatten) k # the input list of possible digits .unique # only one of each to reduce the search space (optional) .sort # sort it so that the cross meta op returns them sorted xx # list repeat n # 「n」 times ) } ``` [Answer] # Python 2 + [primefac](https://pypi.python.org/pypi/primefac), ~~91~~ 85 bytes ``` import primefac as P n,k=input() p=10**~-n while set(`p`)!=k:p=P.nextprime(p) print p ``` [**Try it online**](https://repl.it/Fnpe/1) Input is like `4,{'1','2'}`. [Answer] # PHP, 82 bytes ``` for($n=10**--$argv[1];$i-1||a&trim($n,$argv[2]);)for($i=++$n;--$i&&$n%$i;);echo$n; ``` Takes a number and a string of digits from command line arguments. Run with `-nr`. **breakdown** ``` for($n=10**--$argv[1]; // $n = smallest number with (argument1) digits $i-1|| // loop while $n is not prime or a&trim($n,$argv[2]); // $n without all digits from (argument2) is not empty ) for($i=++$n;--$i&&$n%$i;); // $i=largest divisor of $n smaller than $n (1 for primes) echo$n; // print ``` [Answer] # Java 7, ~~139~~ 141 bytes ``` long c(int a,String b){for(long n=2,i,x;;n++){for(x=n,i=2;i<x;x=x%i++<1?0:x);if(x>1&(n+"").length()==a&(n+"").matches("["+b+"]+"))return n;}} ``` +2 bytes by supporting numbers above 32-bit (changed `int` to `long`) **Input format:** An integer (i.e. `4`) and a String (i.e. `"12"`) **Explanation:** ``` long c(int a, String b){ // Method with the two input parameters specified above for(long n = 2, i, x; ; n++){ // Loop from 2 going upwards for(x = n, i = 2; i < x; x = x % i++ < 1 ? 0 : x); // Prime check for `n` if (x > 1 // if `n` is a prime (if `x` > 1 after the loop above it means `n` is a prime) & (n+"").length() == a // AND if `n` has a length equal to the input integer & (n+"").matches("["+b+"]+")){ // AND if `n` only contains the specified digits of the input String (using a regex) return n; // Then we have our answer } } // If no answer is available for the given input, it continues looping } ``` **Test code:** [Try it here.](https://ideone.com/5Q6olw) NOTE: The second test case is disabled because it loops for a very long time.. ``` class M{ static long c(int a,String b){for(long n=2,i,x;;n++){for(x=n,i=2;i<x;x=x%i++<1?0:x);if(x>1&(n+"").length()==a&(n+"").matches("["+b+"]+"))return n;}} public static void main(String[] a){ System.out.println(c(4, "12")); //System.out.println(c(10, "047")); System.out.println(c(6, "555555555515555555555")); } } ``` **Output:** ``` 2111 115151 ``` [Answer] # [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 245 bytes ``` > Input > Input > 10 > 0 >> ≺1 >> 3*1 >> 3*5 >> 7…6 >> L’ >> Select∧ 9 8 >> L⊥3 >> L∖2 >> Each 11 10 >> Each 12 13 >> #L >> L=4 >> Each 15 14 >> Each 16 17 >> L⋅R >> Each 19 13 18 >> Select∧ 15 20 >> 21ⁿ4 >> 22⊤3 >> Output 23 ``` [Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hAtBGxoACSC2U3jUucsQRBtrQSlTEGX@qGGZGYjh86hhJogOTs1JTS551LFcwVLBAiLRtdQYwuiYZgRiuCYmZygYGoLNhvGMFAzBipR9wEptTRBSpgqGSDwzBUNziGndrUEIYUugfgVDC1QXALUage0wMnzUuB9siJHRo64lYJv8S0uAXlQwMv7/34Qr2lBHwSgWAA "Whispers v2 – Try It Online") ## How it works Assuming the two inputs are \$n\$ (the number of digits) and \$S\$ (the set of digits), the program works as follows: First we generate the range \$A = \{10^{n-1}\dots10^n\}\$ and remove all composite numbers in this range. Next, we take the set difference of each value and the input set \$S\$, which gives \$\{\}\$ for all numbers which have the same digits as \$S\$ and a non-empty set for those that don't. We then take the length of each set, and if it is \$0\$, we keep the values in the set. Finally, of the filtered values, we select the first value i.e. the lowest value. This outputs the lowest value in the set of prime numbers between \$10^{n-1}\$ and \$10^n\$, where the digits are in \$S\$. ]
[Question] [ What general tips do you have for golfing in brainfuck? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to brainfuck (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] Putting one tip per answer would be way too many answers. * Learn to think in Brainfuck. It's very different than anything else. Read and write, and rewrite, and rewrite lots of brainfuck programs. The language doesn't give you much to work with, so it's important to use what it does give you flexibly and efficiently. Don't let any abstractions get between you and the language--get in there and grapple with it. * Get very comfortable with nondestructive flow control. To get out of a decision loop, rather than zeroing the starting cell by copying it elsewhere and then copying it back after leaving the loop, it's often better to move the pointer to a pre-existing zero nearby. Yes, this means the pointer will be in different places depending on whether you went through the loop, but that also means those places probably have different arrangements of nearby zeros and nonzeros, which you can use to resynch the pointer location using another loop. This technique is fundamental to good Brainfuck programming, and various forms of it will constantly prove useful. * That and the fact that every `>` or `<` costs mean that the details of memory layout are important. Try out as many variations of your layout as you have patience for. And remember, your memory layout does not have to be a rigid mapping of data to locations. It can morph over the course of execution. * On a larger scale, consider and even try implementing a variety of different algorithms. Initially it will not be obvious exactly what algorithm will be best; it may not even be obvious what basic approach will be best, and it will probably be something different than what would be best in a normal language. * If you're dealing with large or variable-sized data, see if there's any way you can possibly deal with it locally, without having to keep track of how big it is or your numerical location within it. * The same data can be two different things. (Most often, a number or character and also a nonzero positional marker. But see [random.b](https://github.com/apankrat/bff/blob/master/samples/random.b), where a bit counter doubles as the value of one cell of a cellular automaton.) * The same code can do two different things, and it's a lot easier to make it do so in a language where code is as generic as `<+<`. Be alert to such possibilities. In fact, you may occasionally notice, even in what seems to be a well-written program, that there are small portions that could be deleted entirely, nothing added, and the thing would, by happenstance, still run flawlessly. * In most languages, you use a compiler or interpreter frequently to check your program's behavior. The Brainfuck language demands greater conceptual control; if you need a compiler to tell you what your program does, you don't have a firm enough grasp of your program, and you probably need to stare at it some more--at least if you want to have a clear enough image of the conceptual halo of similar programs to be good at golf. With practice, you'll be producing a dozen versions of your program before you try running one, and by that point you'll be 95% sure that your shortest one will run correctly. * Good luck! Very few people bother to write Brainfuck concisely, but I think that's the only way the language can possibly justify continuing attention--as a stunningly obscure art form. [Answer] A few tips here: ## Constants: The [Esolangs' constants page](https://esolangs.org/wiki/Brainfuck_constants) has an extremely useful list of the shortest ways to create specific values. I find myself consulting this page at least twice per program. ## The start of everything: ``` +++[[<+>>++<-]>] ``` This sets up the tape in the format 3\*n^2, which looks like 3 6 12 24 48 96 192 128 0 0' Why is this so important? Let's go down the list: * 3 and 6 are boring * 12: Close to 10 (newline) or 13 (carriage return). Can also be used for the counter for 0-9 * 24: Close to 26, the number of letters in the alphabet * 48: ASCII for `0` * 96: Close to 97, ASCII for `a` * 196 and 128: 196-128=64, close to 65, the ASCII for `A`. From this one algorithm, we're at the start of practically every sequence in the ASCII range, along with a counter for each and a newline in easy reach. A practical example: **Printing all uppercase and lowercase letters and digits.** With algorithm: ``` +++[[<+>>++<-]>]<<[-<->]<<<<++[->>+.>+.<<<]<--[>>.+<<-] ``` Without: ``` +++++++++++++[->+++++++>++>+++++>++++>+<<<<<]>+++++>[-<+.>>.+<]>>---->---[-<.+>] ``` We spend most of the bytes just *initialising* the tape in the second example. Some of this it offset by the extra movements in the first example, but this method clearly has the advantage. A couple of other interesting algorithms in the same vein: 3\*2^n+1: ``` +++[[<+>>++<-]+>] Tape: 4 7 13 25 49 65 197 129 1 0' ``` This offsets the values by 1, which accomplishes a few things. It makes the 12 a carriage return, the 64 the actual start of the uppercase alphabet, and the 24 one closer to 26. 2^n: ``` +[[<+>>++<-]>] Tape: 1 2 4 8 16 32 64 128 ``` Because 64 is good for uppercase letters, 32 is the ASCII for space, and 128 can be used as the counter for 26 (130/5 = 26). This can save bytes in certain situations where digits and lowercase letters aren't needed. ## Choose the implementation that suits the question: * Negative cells are almost *always* useful, and there's no reason to avoid them (unless it doesn't change your bytecount) * Almost the exact same thing with wrapping cells, even more so because many constants use wrapping. * Arbitrary cell sizes are useful for infinite math sequences, such as calculating the Fibonacci sequence infinitely (`+[[-<+>>+>+<<]>]`), or processing larger/negative numbers. The downside is that some common methods, such as `[-]` and `[->+<]` can't be relied upon, just in case the number is negative. * EOF as 0, -1 or no change. 0 is usually preferable, as you can loop over an entire input without extra checks. -1 is useful when looping over array structures. I haven't yet found a use for no change :(. ## Keep track of what the frick is going on: At all times you should have comments on where the pointer should be in relation to the data around it, and make sure that you know the range of possible values of each cell. This is *especially* important when you've split the pointer before a loop, because you'll want to join the two possibilities back together afterwards. At any point, my code is littered with comments on every other line that look like this: ``` *0 *dat a_1 ? 0' !0 0* or *0 *dat 0' ap1 0 !0 0* ``` Some extra advice is to assign symbols special meanings. In the above example, `'` is where the pointer is, `*` means repetition in that direction, `?` means a cell with unknown value, `!0` means a non-zero cell, `_` is a substitute for `-` and `p` is a substitute for `+`. `or` implies that the tape could look like either of representations, and needs to be handled as such. Your symbol scheme doesn't necessarily have to be the same as mine (which has a few flaws), it just has to be consistent. This is also extremely useful when debugging, because you can run it up to that point and compare the actual tape to what you *should* have, which can point out potential flaws in your code. [Answer] My principal piece of advice would be **don't.** OK, fine, you want something more useful than that. BF is already a very terse language, but what really kills you is arithmetic, which effectively needs to be done in unary. It's worth reading over the [constants](http://esolangs.org/wiki/Brainfuck_constants) page in Esolang to pick out exactly how to write large numbers efficiently, and to exploit wrapping wherever possible. Memory access is also very expensive. Since you're reading from a tape, you need to keep in mind where your head is moving at any given time. Unlike other languages where you can just write `a`, `b`, `c`, in bf you have to explicitly move the head some number of bytes left or right, so you must be mindful of where you store what. I'm pretty sure that organising your memory in the optimal way is NP-hard, so good luck with that one. [Answer] In this answer I'm going to refer to a specific cell on the tape many times. It doesn't matter which cell it is, but it's the same cell throughout the entire answer. For the purposes of this post, I'll call that cell "Todd". When trying to set a cell to a constant value, it sometimes pays to not finish it immediately. For example, say you wanted Todd to contain 30. Later on in your code (which may modify Todd's value but never reads it) you come back to Todd. If Todd's value is 0, the program exits. Otherwise, Todd's value is printed forever. According to the [esolangs.org page of brainfuck constants](https://esolangs.org/wiki/Brainfuck_constants) (which could probably be the subject of a tip on its own!) the shortest way to get 30 is `>+[--[<]>>+<-]>+`. That leading `>` is only there to ensure that nothing to the left of the pointer is modified, but in this case we'll assume we don't care about that and drop it. Using that code, your code would look something like this: ``` +[--[<]>>+<-]>+(MISC. CODE)(GO TO TODD)[.] ``` You can think of the first chunk of code like this: ``` (SET TODD TO 30)(MISC. CODE)(GO TO TODD)[.] ``` But remember the last two characters in that chunk: `>+`. It's just as valid to think of it this way: ``` (SET TODD TO 29)(GO TO TODD)(ADD 1 TO TODD)(MISC. CODE)(GO TO TODD)[.] ``` Notice that you `(GO TO TODD)` twice! You could instead write your code this way: ``` (SET TODD TO 29)(MISC. CODE)(GO TO TODD)(ADD 1 TO TODD)[.] +[--[<]>>+<-](MISC. CODE)(GO TO TODD)+[.] ``` Assuming that the number of bytes it takes to `(GO TO TODD)` is the same before, one less move == one less byte! Sometimes the fact that your starting position has changed does take that benefit away, but not always. [Answer] A tiny little tip for challenges without input. You can use `,` instead of `[-]`, if you need to clear the cell quickly, as most of the interpreters (including the TIO.run one) will set the cell contents to EOF representation being zero. This makes programs a tiny bit unportable, but who cares about it in code golf anyway? ]
[Question] [ Ruby has a strange operator, `..`, called [flip-flop](https://ruby-doc.org/core-3.1.2/doc/syntax/control_expressions_rdoc.html#label-Flip-Flop) (not to be confused with the range operator, which looks the same). Used in a loop, flip-flop takes two conditions as operands and will return `false` until the first operand is truthy, then return `true` until the second operand is truthy, whereupon it returns `true` one more time and restarts the cycle with `false`. ``` 0.upto 10 do |i| if (i==2)..(i==8) puts i end end # Prints 2, 3, 4, 5, 6, 7, and 8 ``` [Attempt This Online](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3LQ30SgtK8hUMDRRS8hVqMmu4FBQy0xQ0Mm1tjTT19EC0hSZQTEGhoLSkWCETyEzNS-ECYogBC6AUlAYA) Your task is to implement a higher-order function (or something equivalent in your language) that behaves like flip-flop. It must take two predicate functions as arguments and return a new function that takes an argument and returns falsey until the first predicate returns `true` given the argument, continues to return `true` until the second predicate returns `true`, whereupon the flip-flop returns `true` one more time (think of it like an inclusive range) and thereafter returns `false`, until the first predicate returns `true` again and so on. Below is an example of such a function called `make_flip_flop`, which takes two predicate lambdas and returns a new lambda, `flip_flop`, to be used in the following loop. ``` flip_flop = make_flip_flop(->i{ i==2 }, ->{ i == 8 }) 0.upto 10 do |i| if flip_flop.(i) puts i end end # Prints 2, 3, 4, 5, 6, 7, and 8 ``` Here's another example with a different set of predicates: ``` flip_flop = make_flip_flop(->i{ i % 5 == 0 }, ->i{ i % 5 == 2 }) 0.upto 10 do |i| if flip_flop.(i) puts i end end # Prints 0, 1, 2, 5, 6, 7, and 10 ``` ## Rules * Please include a brief example or description of how your solution works. * Since not all languages have first-class functions, the definition of "predicate" is loose. You could take the names of previously-defined functions to be called or a string to be eval'd, for example. Your solution may not, however, just take primitive values like `true` and `false`. It must be your language’s equivalent of a higher-order function. * Your predicate functions should take at least one argument, of any type that's convenient, as long as it's reasonable. (A predicate that only takes the specific value `1` is not reasonable, for example.) * Built-ins are allowed, but only if they fit the spec (it must be a function or similar, etc.). You can’t post **Ruby, 2 bytes, `..`**. * [Default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/) apply, [standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) apply, and [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * This is code golf. Shortest answer in bytes wins. [Answer] # JavaScript (ES6), 26 bytes Expects `[ first_predicate, second_predicate ]`, where both predicates are functions taking a single parameter. Returns a flip-flop function which itself returns either 0 or 1. ``` (p,k=0)=>v=>k|(k^=p[k](v)) ``` [Try it online!](https://tio.run/##rY7BCsIwEETv@Yq9CBtapRYEoW6P/YlSodRUYmIT2tKL9ttjoijFixcvuzuPnWEu9VQPTS/tuO7MSbhrrUShpS20sUAObawo4ZRPlKs7qiPZUlU4ce60GKH9fMLSiCVIoDwMgjReiD1UPGOsNT0Gv2eQZH4dCLbhiCIONwYgW3xno@QvBtCYbjBabLQ5e5p5NrOZLekz/FepFexClyT@Aun/y7kH "JavaScript (Node.js) – Try It Online") ### Commented ``` ( // flip-flop generator taking: p, // p[] = pair of predicate functions k = 0 // k = flip-flop status, initialized to 0 ) => // v => // anonymous function taking a parameter v k | ( // always return 1 if k is already set // (because we must still return 1 when the 2nd // predicate is triggered) k ^= p[k](v) // toggle k if the result of p[k](v) is true ) // ``` [Answer] # [Python](https://www.python.org), 59 bytes ``` lambda a,b:lambda x,t={0}:t.add((o:=t.pop()|a(x))>b(x))or o ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3rXMSc5NSEhUSdZKsoMwKnRLbaoNaqxK9xJQUDY18K9sSvYL8Ag3NmkSNCk1NuyQQmV-kkA81YmJBUWZeiYZWbmKBBpChA6LTNDRgpllV2Noaaeqg8C00NXWKEvPSUzUMDTWBgIuQEQqqCqYKtrYKBigGwUSN0IyDOGzBAggNAA) Anonymous function returning an anonymous function that keeps state in a mutable initialiser. [Answer] # [Raku](https://raku.org/), 18 bytes ``` ->\f,\g{&{f ff g}} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtf1y4mTScmvVqtOk0hLU0hvbb2f3FipUJ6UWqBQppGjUq8po6CgZ6eoYFCWn6RgoaWgq2tgpGOApi2AMoBRVQVTEE8A5AolG2k@R8A "Perl 6 – Try It Online") Raku has a built-in operator `ff` that does exactly what's asked for. My answer is mostly just setting up the functional plumbing around it. * `-> \f, \g { ... }` is an anonymous subroutine taking two arguments. * `&{ ... }` is the anonymous subroutine the top-level subroutine returns. Not having an explicit signature, it takes its argument in the topic variable `$_`, which the flip-flop operator implicitly checks against. * `f ff g` returns false until the topic variable smartmatches against `f`, that is, `$_ ~~ f`, then keeps returning true until `$_ ~~ g`. Since `f` and `g` are functions, those smartmatches are equivalent to `f($_)` and `g($_)`. [Answer] # [Factor](https://factorcode.org/), 33 bytes ``` [ '[ _ _ bi on t get swap off ] ] ``` [Try it online!](https://tio.run/##jY9BSwNBDIXv8yvezXrYQ4WCbFGP0ksv4mlZynQ3sx2anRlnUqT@@TXtKqInE0gI4XvJc7aTmKfXl832uYbLZxwpB2KMVg4IdqSSbEcFHDvLBSmTyDllHwQ@Ym022xpDZGdMDaEilWOftMSEBd5OUVBVuDXQWC5R3m3CTYP@lLCDKjIapFluz2h16rOiLbzTQrY7VLqjgTLW8IF9IGMaJjFTcxHaae49YoBgIJkPRHeB26l@VBtH@nlJUdzj4Xrn7tp/7@eP/tgIrNQKY@y/mO/pg3J8@peGMa2ZPgE "Factor – Try It Online") Expects the false-making predicate first and the true-making predicate second. * `[ ... ]` A quotation (anonymous function)... * `'[ ... ]` ...that creates a quotation (anonymous function). * `_ _` Slot the predicates into the holes. * `bi` Call both predicates on the inner quotation's input value (integer). * `on` Here's where it gets tricky. In Factor, you can use any value as a variable (key) to store something. So what I am doing here is using the result of the true-making predicate to store the value `t`. It's a little strange to use a canonical boolean value to store a possibly different boolean value, but this is code golf. It's not supposed to make sense, it's just supposed to be short. * `t get` Get the value that is stored in `t`. This is the result that will be returned from the quotation. This must be done after storing the result of the true-making predicate but before storing the result of the false-making predicate in order to get the 'inclusive' behavior we are looking for. * `swap` Bring the result of the false-making predicate to the top of the stack. * `off` Store `f` in the result of the false-making predicate. [Answer] # [R](https://www.r-project.org/), 54 bytes ``` {x=F;function(f,g)function(y){x<<-(z=x|f(y))&!g(y);z}} ``` [Try it online!](https://tio.run/##hY5NC4JAEIbP7a/YFGIHFFIoJN1rv6KLbI5txK7YSpsfv93Wg5FeYg7vPLwwz9Qj8rGz/Jxio4SRWjEMSvjCGzqbZSFrue3REey2pYu0HYbRp/fmaahWBcWHrEKtaK6uP4xIUNdMUqlodIr30JGNROZmPm/Bch4HS06ASYCqlsq4hQyEiNww76I8IMRfuCYHNS8pClrk4vZfxyYf9P2U0QGCVZXM1RHWT4wf "R – Try It Online") (or [52 bytes](https://tio.run/##hY7LCsIwEEXX5itiC5KBFmxBKdps/Qo3JXZqRJJSU4x9fHtMFxXrRmZx7@EuzjQOucNWCSO1YhhV8IEX9DbPY9ZxO6An2KwrH8duJJafXEhv7cNQrUqKd1nHWtFCXb4YkaBumKRS0eSQbqEnK4nM32ywYDlPoyVnwCRA3UhlfCEjIaIwLDirAAgJF67JQc1TipKWhbj@17HJB8MwZbKD6GfK5mkPv0@4Nw) using a global variable to save the current state) --- # [R](https://www.r-project.org/), 37 bytes (non-competing) ``` {x=F;function(f,g){x<<-(z=x|f)&!g;z}} ``` [Try it online!](https://tio.run/##bY3LCoJAFIbXzVNMijEHUkooIp1tT9FCmRw7EWfERhIvzz4htkho9V8W31e7LIiiIJOub@Ul0Q0pi4aE3pbQt2kaik62g4bNuky6cXQ@fzQvyw0VXD@xCg3xnG4/W2umTS2QI/H9Od5Bz1aohUApY5hUUzsBVDWSFQhsZEzlVnhX8oAxf4GdcNy@URW8yNX9P3lGD8OU@wPMktnyPY@w8LkP "R – Try It Online") Doesn't fit the written spec of the challenge (the function `%..%` returns truthy/falsy, rather than a function), but it seems to very well mimic the described behaviour of Ruby's `..`. Usage example (to mimic the Ruby example in the challenge): ``` for(i in 1:20){ if((i==2)%..%(i==8))print(i) } ``` [Answer] # [C (clang)](http://clang.llvm.org/), 43 bytes Reusable form as proposed by [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco) ``` #define f(x,a,b)static m;m|(m^=m?x b:x a)&& ``` [Try it online!](https://tio.run/##tY1RCsIwEET/e4olYtnQFCz@iDF4EyFNm7LQxNJGLGivbowFvYEDy8CbHcaUpte@i3HTtJZ8CxZnoUXNp6ADGXDSPdFdlDvPUB9n0DzPI/kATpNHDo8Mkux1xA8ktZNAJ1VVEoqCvvH6giSU2qc78B9MGsZUtMi2DTABxOUaLtlqwy1MyFiC/5pZ4svYXndTLO9v "C (clang) – Try It Online") # [C (clang)](http://clang.llvm.org/), ~~41~~ 40 bytes -1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)! ``` t;f(a(),b(),i,*r){*r=t|(t^=(t?b:a)(i));} ``` [Try it online!](https://tio.run/##dY/BCsIwDIbve4o4UNKtg4EHxVp8E6Wr6yjMKl2Hh7lXt3YU68kfAiH5kvyRleyF6bx3TKFAQpsQmhaWTIXl7oXuzNGdmoMgqAlhs9fGgRqNvAhcUk1gyiDItm60BjRwDluWzVmWyOY/uU/kTWiDX0TdbZzhNQN95DsGZZkWLFq6th3G3rFUUxiN0Xg1/LGJCPkxWgHGIqw41CQ1gh42bFWYr6@Q0@A3Ts3BoX9L1Ytu8NXzAw "C (clang) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~29~~ 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Ï{T|(T^=YgXgT ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=z3tUfChUXj1ZZ1hnVA&footer=W1h7WD09Mn1Ye1g9PTh9XWdVCjExb0BbWFhnVl0g&input=LVI) Defines a function which accepts an array of predicates as its input, and returns the flip-flop function. Theoretically should work on strings, numbers, or arrays as the input for the predicate, but I've only tested with numbers. ``` Ï{T|(T^=YgXgT # Initialize T = 0 Ï # Define a function with argument X (an array of predicates): { # Return a function with argument Y: T # Current value of T | # Bitwise OR (T^= # T XOR-equals the following: XgT # Get the function in X at index T Yg # Apply it to Y ``` A [16 byte](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=zz0wQXtZfChZXj1BZ1hnWQ&footer=W1h7WD09Mn1Ye1g9PTh9XWdVCjExb0BbWFhnVl0g&input=LVI) alternative doesn't use a global variable, so could be used to define multiple flip flops. [Answer] # [Python](https://www.python.org), 76 bytes *`-1 byte` thanks to `py3_and_c_programmer`* Takes as input an element `i`, two lambda functions `a` and `b` while using a global variable `t` to toggle between the `true` & `false` cycles. ``` def f(i,a,b): global t if~t&a(i):t=1 if t&b(i):t=0;return 1 return t t=0 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZBBCoMwFET3OcVsKgoWVCiIJTfoJRI0NmCjhC_ophfpxo29U2_TpLGLli66mxk-bz5zuw8znXuzLOtIal8-TnWjoGKdilQmFUPb9VJ0IAatrhSJWCcV8dxbUCSDzY62odEauHxTxFy8MVfVW2hoAytM28R57sme4Is6cZG1wFRNnBcfrnydAYPVhlwTY0E58ScROxzAObIfWfFFD8--h3gC) [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12~~ 10 bytes ``` %2ṁ§≠²o⁰←ḣ ``` [Try it online!](https://tio.run/##yygtzv6f9qip8VFT06Om5oc7FhsZ/Fc1eriz8dDyR50LDm3Kf9S44VHbBKDEf1sjLluL/wA "Husk – Try It Online") ``` %2ṁ§≠²o⁰←ḣ # 2-argument function, # which yields a partially-applied function # requiring 1 further argument: ḣ # 1..further argument ṁ # map over this and return sum §≠ # absolute differences between ² # function arg2 applied to each element, and o⁰ # function arg1 applied to ← # each element plus 1; %2 # modulo 2. ``` Example usage `f₁₂₃ḣ20` ``` f # filter ḣ20 # 1..20 # keeping only truthy results of ₁ # function returned by function on line 1 # called with arguments: ₂₃ # functions on line 2 and line 3 ``` [Answer] # [Rust](https://www.rust-lang.org/), 40 bytes ``` |f|{let mut t=0;move|x|t|{t^=f[t](x);t}} ``` [Try it online!](https://tio.run/##RY7daoQwEIXvfYrZu0xJZdf@idn4GL0RKyITCHVdaibLUuOz2yh0PTAwczh8Z0bveDEDXFo7CIQpgaieOBrf1BhTgBlEFcfn@Fx6Z39JQVbHvQG9BBOmLewZWB/V5XqjcA8cJv7SpuJa3FHxPC9q58aoMaD/C0QVbABhQWvIEFoHW4mE3c53u0aVbKjWORq5oZ@D2O5V4pimpxOmxvZMo1gBkf9kUWvBo6cHBTHtrn1PHRfF@ZO6c1OWAuUDdKPuUGUSXiS8SniT8C7hQ0Jeb4n1hTlZ/gA "Rust – Try It Online") An expression compatible with `fn([fn(T)->usize; 2])->impl Fn(T)->usize` for any `T`. (Yes I know `impl Trait` can't be used as a return type for `fn` pointers) [Answer] # [C++ (clang)](http://clang.llvm.org/), 64 bytes ``` [t=0](auto p){return[=](auto x)mutable{return t|(t^=p[t](x));};} ``` Port of [@Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/253208/112488). Instead of `t` being a default parameter, it's captured and initialized to 0. The function returns a mutable lambda which captures this `t` by value along with the predicates container. This other lambda (the closure) does the heavy lifting, it's declared mutable because it's member `t` will alternate between the values 0 and 1. We could save a byte by making the predicates take an `int x` but it would no longer be generic. [Try it online!](https://tio.run/##rZDBboMwDIbveQqr09Rk7SRWadJUEo59CcamFMIUDZIIzETFeHYWEGWreuhlPiSR/9/2F6fOPaaFNB@DbNBCKT/Ve15o5w/rQAwxiiChk@ZYVylsKhOLOdOyskF5LNQsAH5TfBMuxoS2jIV92A8hudMmLZpMAde2xkrJMvqTk1UlTxEhqEpXSFQcT04ZWSo4ROTL6swrNdIDLFSMdAR85Lai2iBoEBCE/uICnvxjs9FsMoyhc6BLJdXsVxmjxmy/T22DwPnYgMMKViHpCfGNSSm1oedpE8XleuhUPn2AH60t6AMbgdgWdlG3zImTibI9bw9aEAJ2Yb@9YXk5W3q/SkKueNevZj3n/xPuHp7H6cENwNm2u4Dshx8 "C++ (clang) – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform) ~~120~~ ~~117~~ 107 bytes Here is a C# version based of the Dart and Go examples. ``` Func<Func<int,bool>,Func<int,bool>,Func<int,bool>>f=(l,r)=>{var s=1<0;return v=>l(v)?s=!s:r(v)?!(s=!s):s;}; ``` * Shaved off 3 bytes by replacing `false` with `1<0` and a non needed space. Hat tip to [jdt](https://codegolf.stackexchange.com/users/41374/jdt) * Shaved off 10 bytes by not doing boolean wizardry Ungolfed main version: ``` var flipflop = new Func<Func<int,bool>, Func<int, bool>, Func<int,bool>> ( (condition1,condition2) => { var flipflop = false; return new Func<int,bool>(value => { if (condition1(value)) { flipflop = !flipflop; } else if (condition2(value)) { flipflop = !flipflop; return true; } return flipflop; }); }); ``` How you use it: ``` var flop = f(v => v == 2, v => v == 8); for(var x = 0; x< 11; x++) { if (flop(x)) { Console.WriteLine(x); } } ``` [Try it online!](https://tio.run/##fY1BS8QwEIXP9lfM3hK2ytaTbJp4EDwpCB48iIdY0xLIJjKThkrpb6@JF7cgvsPMe8x8Mx1ddgHNOpL1Azx/UTQnUXVOE8EThgH1CebqgqKOtoMU7Ac8ausZRczA6xtoHIjDvN6Pvmt/ivWxfg/BqfrfqHrJXI1cqjlpBJJNexBo4ogeklSOJX5LckdHLG7HiudHEotY4UyF7V34BAk9SyAV5CLhuobfcMNFdc70Id/M3JShg4CphabJbb/nsNmbN6nI9sDKNzZx/se46C54Cs5cvaCN5sF6k3e375dq65ZqWb8B "C# (.NET Core) – Try It Online") # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 91 bytes Using a delegate as proposed by [jdt](https://codegolf.stackexchange.com/users/41374/jdt) ``` delegate bool d(int i);Func<d,d,d>f=(l,r)=>{var s=1<0;return v=>l(v)?s=!s:r(v)?!(s=!s):s;}; ``` [Try it online!](https://tio.run/##bU7BSsQwEL3nK2ZvCVuXrSfZNPUgCIKCoOBBPMQ2LYFsIpm0rpR@e00K3bXgG5iZ5L2ZNxVeVc6rqUNtW3j5waCOnJDKSER49q718kiGqVZGtTIo@HTOQE21DaAZv@9sVdRZjLIR1GSeiXLopQcUebHnXoXOW@hFaWjPblFs8OBTt6GpZwfkI58IRGCQQVfQO13Dk9SWYvDxovcPkL5FNmuGOScki6AwgACrvpc7KeNnRWJ3rzE9hOV7JHOZLRbmn72NcV9xb0N7ECXEJOA6g8vj5o9L4zzQNHSKE3seSwF5Hut2y86iy/oE3QBNFvTE2IpYyxLunEVn1O7N66AetVVxhq9UI1l3IxmnXw "C# (.NET Core) – Try It Online") [Answer] # [Go](https://go.dev), 131 bytes, `int`s only ``` func m(l,r func(int)bool)func(int)bool{f:=1<0 return func(t int)bool{if!f&&l(t){f=!f;return f} if f&&r(t){f=!f;return!f} return f}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dY5NDoIwEIXX9BQDiaaNaDBuCNg7eAX8GdMIlDRlRbryDK7cEBMP4VG8jUNAjCauZjrv9b3vejvq9lFlu1N2PECRqZKpotLGLgIsbHCvLc7j5xnrcgcFz0MD3cpVacVW61x8vRpM5HIdMXOwtSl7p4VRVejjdJpzKxqUPqZvm2MKgRTzo_ikjB43oFx6FALlomEe5rqCRBJbT_JpG34qKVcuhP9q7ATFaAOqy4lSmmsJy26ZzYAqvI6OargS0MDGUAbyYLKHIKSLY55jA1zb9vMF) # [Go](https://go.dev), 132 bytes, generic ``` func m[T any](l,r func(T)bool)func(T)bool{f:=1<0 return func(t T)bool{if!f&&l(t){f=!f;return f} if f&&r(t){f=!f;return!f} return f}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dY5NasMwEIXX1inGhgSJuCGhm5BEd8giu9KF8zNhqCUZIS-C0a5X6KobE8ghepTeJuPYLaWQ1QzzvXnvfV5Orv2qiv1bcTqCKcgKMpXzYZqhCdm1Dvi0-H7H2u7BvGyhsOdXWeYeuovcqp1zpfqzN7jU8_VM-GOove1VAQZGmOJ4XMqgGtQprn5EURACE_-PpEx-NXHo8tF34aZSNSLB0lWw1GDkPYuAbOjThk_S-jnm8JguomIb54E6n9mK51rDvFsmE-CIpGvHMZIUNLDx7IEyGx0gy_kSRRLFUK5t-3kD) This solution is fully generic for any type `T`. ### Ungolfed ``` func makeFlipFlop[T any](l,r func(T)bool) func(T)bool { flipped := false return func(t T)bool { if !flipped && l(t) {flipped = true; return true} if flipped && r(t) {flipped = false; return true} return flipped } } ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dU87TgMxFKzXp3hZichWFgRUEYnb1BTpEIVJ7OgpXtsy3gKtfBKaFRKH4ChUXAV7P2IFonq_mXkzr28n2304cTiLk4RaoCFYO-vDVanqUL43QV2uP79UYw7pepY7jW6nrXvYgzAvj1RXHvKR7tmTtZrNB2hJoRLeySPccVBCP0tSeBkabwZcgB9kgQoWE3y5BE0Dg3ZacAi-kRsY2XmIA2dG8b8o_cc_nMnAACNFJHGM2Y0x0VDWe7cuG5_npr1vBDShd96Oasj5bazg_-s6sqRoPWCWvN6kuuVwk5vVasqfP1JMGeDeJw1Fy4sjlFXaxJnPrhvqNw) [Answer] # Dart, 42 bytes ``` f(f,s,[b=1<0])=>(i)=>b?b|(b=!s(i)):b=f(i); ``` You use it as: ``` void main() { var flipflop = f((i)=>i % 3 == 0, (i) => i % 7 == 0); for (var i = 1; i < 15; i++) { if (flipflop(i)) print(i); } } ``` Which prints 3,4,5,6,7,9,10,11,12,13,14. It even allows you to pass in an extra Boolean to make it the active state. In a less horribly mangled and more typed version, it would be: ``` bool Function(T) flipflop<T>(bool Function(T) from, bool Function(T) until) { bool b = false; return (T value) { if (b) { b = !until(value); return true; } b = from(value); return b; } } ``` [Answer] # [Nim](https://nim-lang.org/), 100 bytes ``` import sugar var s,t=off proc f(x,y:int->bool):proc=(z:int)=>(s=s or z.x;t=s;s=s and not z.y;s or t) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=nVBBDoIwELz3FRtONAGCJiYEsv0LgtUm0iVtMcBXvJAY_-E3_I0U5eTFeJrMTGZnd683rZppundOxtmzVk1LxoHtjqVhl9KAjRySlKw1VIEM-2jIlXax2BOdee5VDEcvcRShRQtkYEz6wqEtPC11DZrcrA3FYjr-6XrImSlQGtIk2aQ5A1DSV6DoEbfRgGKYkYeKew_gUJ0IFFsgCNhP8eyfODRUww4xXYas7GuT9x3r714) Works with `int`-typed inputs, uses a couple of globals to store the current and previous states. Unfortunately, Nim doesn't let us omit type annotations, unless we are supplying the lambda directly as an argument to a higher-order function (as in test cases in the footer), so this ends up rather verbose. Importing syntax sugar macros `->` and `=>` allows getting rid of some repetitive annotations and thus, pays off by a few bytes. As a bonus, Nim also allows defining operators, so that we can mimick Ruby's behavior precisely: [Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY3PcoSixSKdUps89PSuAqK8pMVEvT0EjQqdCqtkvLzczTBpK1GsW2xQn6RQoV1iW2xNYiTmJeikJdfolBpDZYo0YSatzoNyMtUyMxTMNDTMzSw4lJQyExT0Mi0tTXS1NOD0CBBBYXU5Ix8hUwuMKWkxEVQnwVJ-hRy81MUTG1tDcC6YTxUuyFOhgUFAA) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 11 bytes ``` L+Z=?Z!PbOb ``` [Try it online!](https://tio.run/##K6gsyfj/38U/JagwxcjaJQBEW1j7aEfZ2kcpBiT5J4UFVvr9/29oCAA) Pyth doesn't have any way to take functions as arguments, nor any way to return a function. So here we do the next best thing, which is to define a function which will implement the required behavior on the two functions `O` and `P`. That is to say that when we call `y` it will flip-flop on whatever `O` and `P` are defined as. The try it online link above links to a full working example which is the same as the first example in the question, I'll explain below. ``` DOdRqd2; define O(d): (d==2) DPdRqd8; define P(d): (d==8) L+Z=?Z!PbOb implement y as the flip-floperator VQyN loop N over range(0,input()) and print the output of y(N) ``` And the actual flip-floperator ``` L define y(b) +Z sum of previous output and ?Z ternary on previous output !Pb not P(b) if Z currently True Ob O(b) if Z currently False = assign result of ternary to Z ``` [Answer] # [C++ (clang)](http://clang.llvm.org/), ~~123~~ 101 bytes ``` struct F{int r=0;template<class A,class B>int operator()(A a,B b,int t){return r|(r^=r?b(t):a(t));}}; ``` [Try it online!](https://tio.run/##fY8xT8MwEIV3/4ojDLXVEIFYUJ0UtUPFwM5QiuQ6l9ZSYkfORS0q@e3BptAJWO6ke3fv3qfb9kbXyu7GsSPfa4LVyVgCX9xKwqatFWEeFroOFum5L@dxwbXoFTnPBV@ASpewTeOYxMkj9d6C/@D@rfCPW05ipkIRchjkeG2srvsSc@PCQ1TNnPWdsTuwqsGuVRqhoxIki26NMpaLE4MVVJJBFd7FsQnhwOR3oU6nJupgKuAVXxebr4XjJcWxKO7lkP4qPATBCKFdT3lu8jyBJDwZGGNwnqEtazi3oD4jTTog/w4qRPQhc5bxJ6xrBy/O1@UVOItABwe094hZJmCJdEC0MHGTVxvMg3NkcZJFFL1XHvQs@c8jiXSm4o6vN98HFwRdFME40v0t6R8@LVkgG9j4CQ "C++ (clang) – Try It Online") * actually we can go to 92 Bytes if we just implemented a class function [*h* for example](https://tio.run/##fY8xT8MwEIV3/4ojDHXUEIFYUO0UtUPFwM4ARXKdS2MpsSPnohaV/PZgU2ACljv53vnd@3TXXelG2f009eQHTbA5GUvgi2tB2HaNIpRhoe9hlZ37ehkXar4Cla1hl8UXpSePNHgL/p3718Lf7zilCxVKKsZRTJfG6mYoURoX7qBql2zojd2DVS32ndIIPZUgWHRrlbE8PTHYQCUYVM7zODYhExh5E@p8bqIOpgJe5TV/LrafK8efHMeiuBVj9qtwFwSTptoNJKWRMoEknBkZY3CeoS0bOLegPiLNeiD/BiqE9CF1nvMHbBoHT8435QU4i0AHB1R7xDxPYY10QLQwc7MXG8yDc6RxgkUYXSsPepH855FEPlNxF@m2X19@IHRRBOvI97ekvwm1YIFtZNMH "C++ (clang) – Try It Online") but it's no more exactly a closure. Assumes predicates take int type, generalize also predicates will cost a few Bytes. Due to implicit type conconversion can work with strings. Struct *F* is a closure with operator () defined to behave flipFlop. Saved 22 Bytes by templatizing operator () instead of the entire class. Approach stolen from @Arnauld [answer](https://codegolf.stackexchange.com/a/253208/84844) where *r* keeps the state of flipFlop. [Answer] # PHP 67 bytes ``` function f($i,$a,$b){static$k=0;$r=$k;return$r|$k^=($k?$b:$a)($i);} ``` $k must be copied to a temp variable because the `^=` is executed before the `|`, although both operators are LTR. Just define your two functions and give them to `f` as parameters within the loop. The functions may be anonymous or named, or even predefined. e.g. ``` # example 1 $a=function($i){return$i==2;} $b=function($i){return$i==8;} for($i=0;$i<=10;$i++) f($i,$a,$b) && print "$i "; ``` or ``` # example 2 function a($i){return$i%5==0;} function b($i){return$i%5==2;} for($i=0;$i<=10;$i++) f($i,'a','b') && print "$i "; # important: function names must be quoted to avoid "undefined constant" error (in PHP 8) ``` or ``` # other example for($i=0;$i<=10;$i++) f($i,'intval',function($i){return$i<5;) && print "$i "; # prints 1 2 3 4 5 6 7 8 9 10 # ('$i<5' is irrelevant because testing 'intval' immediately resumes the printing) ``` [Try it online](https://onlinephp.io/c/29cb0) ]
[Question] [ Given a non-empty rectangular array of integers from `0` to `9`, output the amount of cells that are `8` and do not have a neighbour that is `8`. Neighbouring is here understood in the [Moore sense](https://en.wikipedia.org/wiki/Moore_neighborhood), that is, including diagonals. So each cell has `8` neighbours, except for cells at the edges of the array. For example, given the input ``` 8 4 5 6 5 9 3 8 4 8 0 8 6 1 5 6 7 9 8 2 8 8 7 4 2 ``` the output should be `3`. The three qualifying cells would be the following, marked with an asterisk (but only the amount of such entries should be output): ``` * 4 5 6 5 9 3 8 4 * 0 8 6 1 5 6 7 9 * 2 8 8 7 4 2 ``` ## Additional rules * You can optionally take two numbers defining the size of the array as additional inputs. * Input can be taken by [any reasonable means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). The format is flexible as usual. For example, it can be a 2D character array, or a list of lists of numbers, or a flat list. * [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Shortest code in bytes wins. ## Test cases 1. Input: ``` 8 4 5 6 5 9 3 8 4 8 0 8 6 1 5 6 7 9 8 2 8 8 7 4 2 ``` Output: `3` 2. Input ``` 8 8 2 3 ``` Output: `0` 3. Input: ``` 5 3 4 2 5 2 ``` Output: `0` 4. Input: ``` 5 8 3 8 ``` Output: `2` 5. Input: ``` 8 0 8 ``` Output: `2`. 6. Input: ``` 4 2 8 5 2 6 1 8 8 5 5 8 ``` Output: `1` 7. Input: ``` 4 5 4 3 8 1 8 2 8 2 7 7 8 3 9 3 9 8 7 8 5 4 2 8 4 5 0 2 1 8 6 9 1 5 4 3 4 5 6 1 ``` Output `3`. 8. Input: ``` 8 ``` Output: `1` 9. Input: ``` 8 5 8 1 6 8 7 7 9 9 2 8 2 7 8 3 2 8 4 9 7 3 2 7 9 2 9 7 1 9 5 6 6 9 8 7 3 1 5 2 1 9 9 7 1 8 8 2 3 5 6 8 1 4 7 5 ``` Output: `4`. 10. Input: ``` 8 1 8 2 5 7 8 0 1 ``` Output: `3`. Inputs in MATLAB format: ``` [8 4 5 6 5; 9 3 8 4 8; 0 8 6 1 5; 6 7 9 8 2; 8 8 7 4 2] [8 8; 2 3] [5 3 4; 2 5 2] [5 8 3 8] [8; 0; 8] [4 2 8 5; 2 6 1 8; 8 5 5 8] [4 5 4 3 8 1 8 2; 8 2 7 7 8 3 9 3; 9 8 7 8 5 4 2 8; 4 5 0 2 1 8 6 9; 1 5 4 3 4 5 6 1] [8] [8 5 8 1 6 8 7 7; 9 9 2 8 2 7 8 3; 2 8 4 9 7 3 2 7; 9 2 9 7 1 9 5 6; 6 9 8 7 3 1 5 2; 1 9 9 7 1 8 8 2; 3 5 6 8 1 4 7 5] [8 1 8; 2 5 7; 8 0 1] ``` Inputs in Python format: ``` [[8, 4, 5, 6, 5], [9, 3, 8, 4, 8], [0, 8, 6, 1, 5], [6, 7, 9, 8, 2], [8, 8, 7, 4, 2]] [[8, 8], [2, 3]] [[5, 3, 4], [2, 5, 2]] [[5, 8, 3, 8]] [[8], [0], [8]] [[4, 2, 8, 5], [2, 6, 1, 8], [8, 5, 5, 8]] [[4, 5, 4, 3, 8, 1, 8, 2], [8, 2, 7, 7, 8, 3, 9, 3], [9, 8, 7, 8, 5, 4, 2, 8], [4, 5, 0, 2, 1, 8, 6, 9], [1, 5, 4, 3, 4, 5, 6, 1]] [[8]] [[8, 5, 8, 1, 6, 8, 7, 7], [9, 9, 2, 8, 2, 7, 8, 3], [2, 8, 4, 9, 7, 3, 2, 7], [9, 2, 9, 7, 1, 9, 5, 6], [6, 9, 8, 7, 3, 1, 5, 2], [1, 9, 9, 7, 1, 8, 8, 2], [3, 5, 6, 8, 1, 4, 7, 5]] [[8, 1, 8], [2, 5, 7], [8, 0, 1]] ``` Outputs: ``` 3, 0, 0, 2, 2, 1, 3, 1, 4, 3 ``` [Answer] # [R](https://www.r-project.org/), ~~117 63~~ 59 bytes ``` function(m)sum(colSums(as.matrix(dist(which(m==8,T)))<2)<2) ``` [Try it online!](https://tio.run/##hVJdb5wwEHznV6zoi1F9bew750DKPfa9StOny6lKKAdIfAkbhVPb335dr23SNkiVANm7ntmZMeP1HXy@mKrvNtpcmgLqbpgMmB7uoX0yYz1Hw5CXcoS7DZynLjd137E5gR8RwGyLpZ6eWQwxj2M@J1jtvo39i7atpuhKU2k2FiVy5VWh2cyhxG0xDyOLHx@PMYc5SRLYgCBo3jcEZf/D8oB8DyKBj36q5ZhaYtBmNH3Npq6ptWG400NTG@bk5j9xNr4nZImJiVsHyIcMzjezRNzzci@Nw/MF93CAh/uvn5LoVxSdD9cllzbRU8vw4BfEsif9wVN9txJeqjqvWHs4pPwBB91J@1zPzOXL4uMx5bDjoDjc4vfE4Zhx2HJw5dQWbmiHbeFP4HLPIaOytIWUlnuCyNMJLUX/jCAiicxvu4rm7fwBtcqgaICVtcJOGknG26YVRFjl@Z2N1KtW9KzjFNlxUYi/vEryug@abGA@uDSUHVj6SY7thgoipJnZjvhjznINYs3kWqoqiLsNo/deSBZ8y0WoD8BdbEblret7jAxlQQurxd/24mzrfgIfhTu3YNLXkLbBipO3oyNq1YN4/TmU15JSVi6F628 "R – Try It Online") `dist` computes distances (default is Euclidean) among rows of a matrix. `which` with second argument `TRUE` returns the coordinates where the predicate is true. Coordinates are neighbours if the distance between them is not more than the square root of 2, but the inner `<2` is good enough because the possible distance jumps from `sqrt(2)` ro `2`. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~29~~ ~~28~~ 25 bytes ``` ≢∘⍸16=2⊥¨3,⌿3,/8=(⍉0,⌽)⍣4 ``` [Try it online!](https://tio.run/##TVHBSsNAFLz3K/aWBFLM7mbTjdCPCZVKMVCxvYh4ESm2GtGD4FVF6A8IIojgp7wfiTMbS0Ng895kdmbeS3VaD4/Oq3p@PJzU1WIxm7Ry/zSby@oha6c4Zf0qN8/SfOpibGTz/ru1qdz92PTAj2Np1hm670Sat7xtl@BfSPMh65czlFNpvg6j@Ukkt9fRtJrVEQB8Prsc2KU0W1k9xl7lyqlCuSQulVVsfRJnKAqliRZqpEq0JgHXo8lRDrL9fdCNsj3IQScn6Mg0OziVzZWDAkz6KK6nWcL3QO9AWIDoqMEUntYODzh2z3GIwsR6l84g3Sg4YBTO40NLnqEIr2QodZiuTGL9r9GtQPcSMCwj5fs5XbAqguiI6mVIaTpLZuXySrSWIBkmtBon9LnKLpLlZhmZXzqG72awIQh9csAu6f8n3W3aUdpjDsQd/gE "APL (Dyalog Classic) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 15 bytes ``` 8=µ+Ż+ḊZµ⁺ỊṖḋµS ``` [Try it online!](https://tio.run/##VVG7bcMwEO09BXuzMCmdRRaewp0FlWkCL5AyaQI4faZIK8CfToYHkRdhyHd3VAIYBvV473d8fTke31IKu2lcP27r@Xw6TOPz/TrfTvPlez5/TeM@3T@fHz8p9X0frGmtIWu2@X@wpo/WNNYwHAqwwVe@djKRj501EbAvQMCxA8UPw8pCFmSf1Rgh6LYCUp0kkIulMOEJWQaKKGZIuBwliDPht8wSYnAF9y@jR8ZO/UpRKRwUZrIXdVbbAHC6hVhu3B@fuj6nBXQDpCG2atGJYdROvgaScrz4CLjhe@F4hR0OxVNeozZo@JGkMs9VTliW0WhkjtdihGputzweiX/AHnLD4Rc "Jelly – Try It Online") ### How it works ``` 8=µ+Ż+ḊZµ⁺ỊṖḋµS Main link (monad). Input: digit matrix 8= 1) Convert elements by `x == 8` µ 2) New chain: +Ż+Ḋ x + [0,*x] + x[1:] (missing elements are considered 0) Effectively, vertical convolution with [1,1,1] Z Transpose µ⁺ 3) Start new chain, apply 2) again ỊṖ Convert elements by `|x| <= 1` and remove last row ḋ Row-wise dot product with result of 1) µS 4) Sum ``` # Previous solution, 18 bytes ``` æc7B¤ZḊṖ 8=µÇÇỊḋµS ``` [Try it online!](https://tio.run/##VVE7TgMxEO1zCh/ARezdie2ChivQsdoK0aBcgJZmpdBzAkRFGyko3e5JNhcx9psZL0hR5H2e9xu/PB@PrzkvX0/hfv58XC@n9edjF@/m8zIt03o9rZf3@fyQl@n29p3zMAzRmt4asuZQ/kdrhmRNZw3DsQJ7fJVrJxPlGKxJgH0FIo4BFD@OOwtZkH1RY4Sg2wtIbZJArpbChCdkGaiimCHhcpQozoTfNkuIwRXcv4weGYP61aJSOCrMZC/qrLYH4HQLqd64Pz5tfU4L6AZIQxzUIohh0k6@BZJyvPgEuON74XiFHQ7VU16jNej4kaQyzzVO3JbRaWSO12OEWm63PR6Jf8QeSsPxFw "Jelly – Try It Online") Wanted to share another approach, though this is 1 byte longer than [Jonathan Allan's solution](https://codegolf.stackexchange.com/a/175727/78410). ### How it works ``` æc7B¤ZḊṖ Auxiliary link (monad). Input: integer matrix æc7B¤ Convolution with [1,1,1] on each row ZḊṖ Zip (transpose), remove first and last elements 8=µÇÇỊḋµS Main link (monad). Input: digit matrix 8= Convert 8 to 1, anything else to 0 (*A) µÇÇ Apply aux.link twice (effective convolution with [[1,1,1]]*3) Ịḋ Convert to |x|<=1, then row-wise dot product with A µS Sum the result ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` =8ŒṪµŒcZIỊȦƲƇẎ⁸ḟL ``` **[Try it online!](https://tio.run/##y0rNyan8/9/W4uikhztXHdp6dFJylOfD3V0nlh3bdKz94a6@R407Hu6Y7/P/4e4tD3dsetS0Juxw@///JgqmCiYKxgoWCoZAbMQFxArmQGgBFLNUMOayBLJAPJAqIwULLpB6AyALpNpMwZLLEKofJG6mYAgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##VVE7TgMxEO05hQ/gIvbuZO2CAyBxAlZboTRRLkAJTSQKilyAjgJRIUVKoCNKlGtsLmLsNzNekKLI@zzvN14uVquHlK7DcTPu33@2x8393c34/Xx@O32e1uPXy@VxN@5eb9NhfXn6SKnv@2BNaw1ZM8//gzV9tKaxhuFQgBm@8rWTiXzsrImAfQECjh0ofhiuLGRB9lmNEYJuKyDVSQK5WAoTnpBloIhihoTLUYI4E37TLCEGV3D/Mnpk7NSvFJXCQWEme1FntRkAp1uI5cb98anrc1pAN0AaYq4WnRhG7eRrICnHi4@AG74XjlfY4VA85TVqg4YfSSrzXOWEaRmNRuZ4LUao5nbT45H4B@whNxx@AQ "Jelly – Try It Online"). ### How? ``` =8ŒṪµŒcZIỊȦƲƇẎ⁸ḟL - Link: list of lists of integers (digits) =8 - equals 8? ŒṪ - multidimensional truthy indices (pairs of row & column indices of 8s) µ - start a new monadic chain Œc - all pairs (of the index-pairs) Ƈ - filter keep if: (keep those that represent adjacent positions) Ʋ - last four links as a monad: Z - transpose I - incremental differences Ị - insignificant? (abs(x) <= 1) Ȧ - all? Ẏ - tighten (to a list of all adjacent 8's index-pairs, at least once each) ⁸ - chain's left argument (all the index-pairs again) ḟ - filter discard (remove those found to be adjacent to another) L - length (of the remaining pairs of indices of single 8s) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~88~~ 85 bytes ``` a=>g=(x,y=0,c=0)=>a.map(p=>p.map((q,j)=>c+=q-8?0:1/x?(x-j)**2+y*y<3:g(j,-y)<2)&--y)|c ``` [Try it online!](https://tio.run/##dVHbboMwDH3fh0wJNR1JCISqoR@CeECsRUVdoes0gbR/Z7ZBe5kiJOL7Ocfum@/m2X5ex6/4Pryfl4tfGl92Xkww@wRan0hfNvuPZhSjL0c2xAN6jLY7/4jdKTmot@kkpriXUaR3czQfzaETPcSzPGr5GuP70y7tcH8Ot/P@NnTiIqrKQQoWMrA1VAUYIN@hnaCVgeJ4BjkU6Gu0Hb451ui6lkLKl//zqFuDCeQtYqRcYYMzLGIgkxACsSMmgTxyw37LGKTAMWuLX7jDoiLSrv5UalSZMw/cCu/GsU@VmmdSV4K24k0VGFHbnHWjKsg/tDnLDDJGyhmzYC16ZcKK6D4F@oaiXKPZV/hHVL7WytXQ9VgN5dYat@kzzJDQUozbICO1XdMylkO9m6rlFw "JavaScript (Node.js) – Try It Online") Thank Arnauld for 2 bytes [Answer] # [J](http://jsoftware.com/),43, 40 37 bytes -3 bytes thanks to Bubbler ``` 1#.1#.3 3(16=8#.@:=,);._3(0|:@,|.)^:4 ``` [Try it online!](https://tio.run/##RVDLasMwELz7K4ZGkBiM0NORVQz5kvZQakovOeSafrs7u7YjsKzd2d2ZWf2uy2O2cKhwqz9ZfhHx4se5nOytzkP/bj/jxT3rbXja/qOmte/eLM7LbM8Y8FexPLru@@vnjgUZ2RQk3iPPhAjJCukLEa/4lXhB4CmME8IxHBBM0VJsUDSZLOzi7KvTIxEuQn9AEd6oTgOSSSrDQRUvGufWwtCI16Q@/e4q0NVVySc9RbOMjUz6HSOvG026U1KHsptvDmnnSDhvhEE0RuWTN5heaqK1cU/MomJSlczzL8zj7iSqYlB8q@9Ppl2ikIjm9grRHKtllXLw6z8 "J – Try It Online") ## Explanation: The first part of the algorithm assures that we can apply a 3x3 sliding window to he input. This is achieved by prepending a row of zeroes and 90 degrees rotation, repeated 4 times. ``` 1#.1#.3 3(16=8#.@:=,);._3(0|:@,|.)^:4 ( )^:4 - repeat 4 times 0|:@,|. - reverse, prepend wit a row of 0 and transpose ;._3 - cut the input (already outlined with zeroes) 3 3 - into matrices with size 3x3 ( ) - and for each matrix do , - ravel (flatten) 8 = - check if each item equals 8 #.@: - and convert the list of 1s and 0s to a decimal 16= - is equal to 16? 1#. - add (the result has the shape of the input) 1#. - add again ``` [Answer] # Java 8, ~~181~~ ~~157~~ ~~156~~ ~~149~~ 147 bytes ``` (M,R,C)->{int z=0,c,f,t;for(;R-->0;)for(c=C;c-->0;z+=f%9/8)for(f=t=9;M[R][c]==8&t-->0;)try{f-=M[R+t/3-1][c+t%3-1]%9/8;}finally{continue;}return z;} ``` -24 bytes thanks to *@OlivierGrégoire* -2 bytes thanks to *@ceilingcat*. Takes the dimensions as additional parameters `R` (amount of rows) and `C` (amount of columns). The cells are checked pretty similar as I did in [my *Fryer simulator* answer](https://codegolf.stackexchange.com/a/154563/52210). [Try it online.](https://tio.run/##hVRNj5swEL3nV1grbQWKyfIRJxDEXnLqIVspe0QcWC9s2YITgUmVIH57OjakrbrLNJGM7XmeefPGnvf0lFrvrz@uvEybhuzSQnQzQgohszpPeUae1FJvEG7AGCdxQnZUb@yHz9YMAdPPYGhkKgtOnoggEbkaO7qnW9N67BTsEtmU05zKMD/URri3rEc7NNWcR9uQ6@VlHuX3wYOvt/NIRkG4i/dJzJMo8r/I4Yisz11uRWCYywfPcsA8l/dqoo6GfV6ItCzPHT8IWYg2C/s6k20tyCXsr6GieWxfSqA5sj0dildSQebGs6wL8QYJpuaQtswaaYjsJxkz7zqfLimjK8p6qhEffl1APapQ/iTCBvuKOoiPFV3TAFDuJMIH6xqiuH2v5f@c6zQHl3rISQY5LJGzDI3LgBtogDGb1mY6Y8Qf6AAxGcJY6e0jajL44xEYqK0q6/ynLi7UZa0VgJuA3BJfo5RXF2Gm4tqAcPSdCSZxzshvuJ0Oqj12Y5jOcKXZrRH2gVbcHTJFdFcvIQCUp7CIP1ejHBiBP/IuBt089XqQKig/gz8frZan1VIZLwHNUGUc9DUxJDsfKniryN9tUjceHerWWKux7zyfG5lVi0MrF0doSbIUxt1XcWzlhtyNFFWHPKU1qTe3Q3/2Tpva/M3lX1/GafTwaZjR1k/S@NbKgcdcLLhRUVItyky8ye8wi@1kXJijn6kI/ay//gI) **Explanation:** ``` (M,R,C)->{ // Method with integer-matrix as parameter & integer return int z=0, // Result-counter, starting at 0 c,f,t; // Temp-integers, starting uninitialized for(;R-->0;) // Loop over the rows: for(c=C;c-->0 // Inner loop over the columns: ; // After every iteration: z+=f%9/8) // If the digit in this cell is 8: // Increase the result-counter by 1 // Else: leave it the same for(f=t=9; // Reset the flag to 9 M[R][c]==8& // If the current cell contains an 8: t-->0;) // Inner loop `t` in the range (9, 0]: try{f-= // Decrease the flag by: M[R+t/3-1] // If `t` is 0, 1, or 2: Look at the previous row // Else-if `t` is 3, 4, or 5: Look at the current row // Else (`t` is 6, 7, or 8): Look at the next row [c+t%3-1] // If `t` is 0, 3, or 6: Look at the previous column // Else-if `t` is 1, 4, or 7: Look at the current column // Else (`t` is 2, 5, or 8): Look at the next column %9/8; // And if the digit in this cell is 8: // Decrease the flag-integer by 1 // Else: leave it the same }finally{continue;} // Catch and ignore ArrayIndexOutOfBoundsExceptions // (try-finally saves bytes in comparison to if-checks) return z;} // And finally return the counter ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~21~~ ~~17~~ 10 bytes ``` 8=t3Y6Z+>z ``` [Try it online!](https://tio.run/##y00syfn/38K2xDjSLErbrur//2gLBRMFUwUzBVNrBUsFYwUQ18JawQDIMFMwBImaKZgDZSwUjKyBhAWQY6JgFAsA "MATL – Try It Online") Thanks to Luis Mendo for help in chat, and for suggesting 2D convolution. Explanation: ``` #implicit input, m 8= #equal to 8? matrix of 1 where m is 8, 0 otherwise t #duplicate 3Y6 #push [1 1 1; 1 0 1; 1 1 1], "neighbor cells" for convolution Z+ #2D convolution; each element is replaced by the number of neighbors that are 8 > #elementwise greater than -- matrix of 1s where an 8 is single, 0s otherwise z #number of nonzero elements -- number of single eights #implicit output ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 84 bytes ``` .+ _$&_ m`(?<!(?(1).)^(?<-1>.)*.?.?8.*¶(.)*.|8)8(?!8|.(.)*¶.*8.?.?(?<-2>.)*$(?(2).)) ``` [Try it online!](https://tio.run/##FYsxDsIwEAR7/yJShOwgTrpz7NuTEP4JgYKCAgqUMu/KA/IxY3c7o9nfa31/n7XS2S3jaXGfhy/XwRfPgcK97QvfKExUqICmY/cdNgT4MmCjjsdOE3rQa@n12P7S/qFWJHCGqjMTiCI6wWwapRkxZUvZZYNGTuLYmgHExZTBs6Y/ "Retina 0.8.2 – Try It Online") Explanation: ``` .+ _$&_ ``` Wrap each line in non-`8` characters so that all `8`s have at least one character on each side. ``` m` ``` This is the last stage, so counting matches is implied. The `m` modifier makes the `^` and `$` characters match at the start or end of any line. ``` (?<!...|8) ``` Don't match a character directly after an 8, or... ``` (?(1).)^(?<-1>.)*.?.?8.*¶(.)*. ``` ... a character below an 8; the `(?(1).)^(?<-1>.)*` matches the same column as the `¶(.)*` on the next line, but the `.?.?` allows the `8` to be 1 left or right of the character after the `.` on the next line. ``` 8 ``` Match `8`s. ``` (?!8|...) ``` Don't match an 8 immediately before an 8, or... ``` .(.)*¶.*8.?.?(?<-2>.)*$(?(2).) ``` ... a character with an 8 in the line below; again, the `(?<-2>.)*$(?(2).)` matches the same column as the `(.)*¶` on the previous line, but the `.?.?` allows the `8` to be 1 left or right of the `8` before the `.` on the previous line. [Answer] # J, 42 bytes ``` [:+/@,8=]+[:+/(<:3 3#:4-.~i.9)|.!.0(_*8&=) ``` [Try it online!](https://tio.run/##VVFBTsQwDLzzigEkdst6Q5MmTRpRCQmJEyeuCHFArIALH0B8vYydIu0qamuP3Zmx87VcuM0Bc8UGgh6Vz97h/unxYXmuu5s7KfPLTqPtbR0wXNa4d7@fbup@3Lnrt6/X5Wrulu7s/e3jGwNmHFAQkTAiCSZCmhblLsS8oiMyKwUBUvkpTCNCo@hXiqK1gOEYTWSLUgODtTsYLjWxn0onoCPW/2PeMKoQpINgVopUZjzl2L6aj@bbq0cxo5lHJTiQmHdNUyMU@6Vn6G3GSapfOdoi/LEHjqVTNyiu0yZTG403q8BkTkNTFUsiwUzO0DqCpZ5vSuhOm6tBV6yuvbFk86RjVJaSSXhSZaTTK9NtQDeb7U56@OUP "J – Try It Online") # explanation The high-level approach here is similar to the one used in the classic APL solution to the game of life: <https://www.youtube.com/watch?v=a9xAKttWgP4>. In that solution, we shift our matrix in the 8 possible neighbor directions, creating 8 duplicates of the input, stack them up, and then add the "planes" together to get our neighbor counts. Here, we use a "multiply by infinity" trick to adapt the solution for this problem. ``` [: +/@, 8 = ] + [: +/ (neighbor deltas) (|.!.0) _ * 8&= NB. NB. [: +/@, NB. the sum after flattening 8 = NB. a 0 1 matrix created by NB. elmwise testing if 8 NB. equals the matrix (the matrix to test for equality with 8 ) NB. defined by... ] + NB. the original input plus [: +/ NB. the elmwise sum of 8 NB. matrices defined by _ * NB. the elmwise product of NB. infinity and 8&= NB. the matrix which is 1 NB. where the input is 8 NB. and 0 elsewhere, thus NB. creating an infinity-0 NB. matrix (|.!.0) NB. then 2d shifting that NB. matrix in the 8 possible NB. "neighbor" directions (neighbor deltas) NB. defined by the "neighbor NB. deltas" (see below) NB. QED. NB. *********************** NB. The rest of the NB. explanation merely NB. breaks down the neighbor NB. delta construction. (neighbor deltas ) NB. the neighbor deltas are NB. merely the cross product NB. of _1 0 1 with itself, NB. minus "0 0" (<: 3 3 #: 4 -.~ i.9) NB. to create that... <: NB. subtract one from 3 3 #: NB. the base 3 rep of i.9 NB. the numbers 0 - 8 4 -.~ NB. minus the number 4 NB. NB. All of which produces NB. the eight "neighbor" NB. deltas: NB. NB. _1 _1 NB. _1 0 NB. _1 1 NB. 0 _1 NB. 0 1 NB. 1 _1 NB. 1 0 NB. 1 1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` œẹ8ạṀ¥þ`’Ạ€S ``` [Try it online!](https://tio.run/##VVExjsIwEOx5hR/gAjtZYr/jKhRFuuaaEx@gQzT3ACo6KK7jA6SgAPGQ8BGfPbvrcFKUbMY7OzPr76/NZpvS8zCN1zCN5@m6u/8@bp@v3XEaT6/95SM9fvJnnVLf98Ga1hqyZpXfgzV9tKaxhuFQgCX@8rGTjlx21kTAvgABZQeKH4aFxViQfZ7GCGFuKyDVTgK5SAoTmhjLQBmKHhIuWwmiTHjmXoINjuD@efTw2KleCSqBg8JM9jKdpy0BON1CLCfuTaeuz2kA3QCpiZVKdCIYNZOvhiQcLz4CbvhcOF5hh6Joym3UBA1fkkTmvsoJ8zIatcz2WrRQ9e3myyPRD9hDTjj8AQ "Jelly – Try It Online") ### How it works ``` œẹ8ạṀ¥þ`’Ạ€S Main link. Argument: M (matrix) œẹ8 Find all multidimensional indices of 8, yielding an array A of pairs. þ` Table self; for all pairs [i, j] and [k, l] in A, call the link to the left. Return the results as a matrix. ạ Absolute difference; yield [|i - k|, |j - l|]. Ṁ Take the maximum. ’ Decrement all the maxmima, mapping 1 to 0. Ạ€ All each; yield 1 for each row that contains no zeroes. S Take the sum. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 8Q2Fø0δ.ø}2Fø€ü3}˜9ôʒÅs}OΘO ``` [Try it online](https://tio.run/##yy9OTMpM/f/fItDI7fAOg3Nb9A7vqAUxHzWtObzHuPb0HMvDW05NOtxaXOt/bob////R0RY6JjqmOmY6prE60ZY6xjogvgWQbQBkmekYgsXNdMx1LIF8IyDbAkibA9UYxcYCAA) or [verify all test cases](https://tio.run/##PVC7TsNAEOz5Csv1gnxnn31HE9HQGmrLRQAXlqIQJTaSCzdI/AAVBZ9AGaFIUMUdSPkIfsTMrh@K5Ozszs7M7eNueVcW/ZN/dV/Vy5VXrjd1den5i4bO/JttUVXN@WZbrqviYZ5Rc/zCNK2rCff2Vl93h@C0v@gOLZd/zx/dd9j@vrtu//Paveza9PSW9nT8XPRZllmKyFBMJqfMUUiMLeoAVUxK@jEl5IA1aov/BByd5@TxOpM1hQM0UIikYSaGwQJkRzors8oAIYOpkQU2s2Jg8JsJBl6cSs3@Gv6JiCKvpLaCmalFgrcC1Ere4NBRo87wVjWFGZ9gRD8WnUQUnQTTg4/E47s44JC7wtGCFb7QlCsNSUK@mmTl2cCxY/pQ/NktQt9MAdR4RSPSFuERMf8H). **Explanation:** ``` 8Q # Check for each inner value in the (implicit) input-matrix if it's an 8 # (1 if 8; 0 if not) 2Fø0δ.ø} # Add a border of 0s around the matrix: 2F } # Loop 2 times: ø # Zip/transpose; swapping rows/columns δ # Map over each inner list: 0 .ø # Surround it with a leading/trailing 0 2Fø€ü3} # Then get all overlapping 3x3 blocks of this modified matrix: 2F } # Loop 2 times again: ø # Zip/transpose again € # Map over each inner list again: ü3 # Split it into overlapping triplets ˜ # Flatten the entire list of lists of lists of lists of integers # (aka the list of lists of 3x3 blocks) 9ô # Split it into parts of size 9 # (so we now have a single list with flattened 3x3 blocks) ʒÅs} # Keep the (flattened) 3x3 blocks with a 1 in the center: ʒ } # Filter over the list of flattened 3x3 blocks: Ås # Pop the list and push its center value O # Sum the inner lists of any remaining flattened 3x3 block Θ # Check for each sum whether it's equal to 1 (1 if 1; 0 otherwise) O # Sum those together again # (after which this sum is output implicitly as result) ``` [Answer] # [Python 2](https://docs.python.org/2/), 130 bytes ``` lambda a:sum(sum(u[~-c*(c>0):c+2].count(8)for u in a[~-r*(r>0):r+2])*8==8==a[r][c]for r in range(len(a))for c in range(len(a[0]))) ``` [Try it online!](https://tio.run/##lVPNjtowED6vn2IkDrFpuoqdOHGQ6HFfwutDmoUWCQIKcOilr07HYzth/6StZMD@5vuZccLpz@X3cVC37fr5tu8OP1866Fbn64H7z9X@/d4vef@jEKv@m3KP/fE6XLgR2@MIV9gN0CFjXPLRM0ZkiKVZr3F1dnS2d543et7YDb82fL8ZeCdI3b9BbeGEELeXzRae@Fms2EMHa7CH7sR3wyUfH8@n/e7ChYDJ8xyx7HnIhGMPpxGZsMUExp54lmUGKtBQg2YtlOBPhhX4W4NErIYGWjwpZvC7wapCzaw1yJJMoVKCuat4z4r8ZFQrVDe4L9GvZC25GWIpTPT8AneSklsmoz70JoNz6D1bLBYZY37Czk9owVqTQ5WDzqHGb5eDbXMocwiw8UBBJyzLyMBtk0NLsPKAoW1DEuVczsiWxArdAqLJt4qgnpiaxD4yKimTbAPgTYmjoza0YmKypjVzNbURRpCvelTUY5Py/KBxYJPgIFbRPbgVBMh0C62vyLuc6fpkGiDdgE5N1CmiiYFtmklNDcXhwsW3BJehHjUqwZI2PjM@jWmCMjykOHLgTRozX0aZWg7tVUTRU99yfng65hu6B5wQ3Or@r3Cz/v2QVA3L751jhM8rvkhypgRgFpNG0tGvuV68YqfTHPk@7KO8d5afib/Q6eeM/2zpDptg@TbvwwQK@Qc "Python 2 – Try It Online") [Answer] # Powershell, 121 bytes ``` param($a)(($b='='*4*($l=($a|% Le*)[0]))+($a|%{"!$_!"})+$b|sls "(?<=[^8]{3}.{$l}[^8])8(?=[^8].{$l}[^8]{3})" -a|% m*).Count ``` Less golfed test script: ``` $f = { param($a) $length=($a|% Length)[0] $border='='*4*$length $pattern="(?<=[^8]{3}.{$length}[^8])8(?=[^8].{$length}[^8]{3})" $matches=$border+($a|%{"!$_!"})+$border |sls $pattern -a|% Matches $matches.count } @( ,(3,"84565","93848","08615","67982","88742") ,(0,"88","23") ,(0,"534","252") ,(2,"5838") ,(2,"8","0","8") ,(1,"4285","2618","8558") ,(3,"45438182","82778393","98785428","45021869","15434561") ,(1,"8") ,(4,"85816877","99282783","28497327","92971956","69873152","19971882","35681475") ,(3,"818","257","801") ,(0,"") ) | % { $expected,$a = $_ $result = &$f $a "$($result-eq$expected): $result : $a" } ``` Output: ``` True: 3 : 84565 93848 08615 67982 88742 True: 0 : 88 23 True: 0 : 534 252 True: 2 : 5838 True: 2 : 8 0 8 True: 1 : 4285 2618 8558 True: 3 : 45438182 82778393 98785428 45021869 15434561 True: 1 : 8 True: 4 : 85816877 99282783 28497327 92971956 69873152 19971882 35681475 True: 3 : 818 257 801 True: 0 : ``` Explanation: First, the script calculates a length of the first string. Second, it adds extra border to strings. Augmended ~~reality~~ string likes: ``` ....=========!84565! !93848! !08615! !67982! !88742!===========.... ``` represents the multiline string: ``` ...===== ======= !84565! !93848! !08615! !67982! !88742! ======= ========... ``` Note 1: the number of `=` is sufficient for a string of any length. Note 2: a large number of `=` does not affect the search for eights. Next, the regular expression `(?<=[^8]{3}.{$l}[^8])8(?=[^8].{$l}[^8]{3})` looks for the digit `8` with the preceding non-eights `(?<=[^8]{3}.{$l}[^8])` and the following non-eights `(?=[^8].{$l}[^8]{3})`: ``` ....... <<<.... <8>.... >>>.... ....... ``` Finally, the number of matches is returned as a result. [Answer] # JavaScript (ES6), 106 bytes ``` a=>a.map((r,y)=>r.map((v,x)=>k+=v==8&[...'12221000'].every((d,i,v)=>(a[y+~-d]||0)[x+~-v[i+2&7]]^8)),k=0)|k ``` [Try it online!](https://tio.run/##dVHbboMwDH3fh7SJcFESCISH9EeiTEItnbp2paITaiW0X2e2QXsZCCn4@HqO/Vn39ePQne/fu1t7bMaTH2u/r9Ov@i5EBy/p990EengiuCS@995tQpqmW22M0UqpbUybvuleQhzhDD2miTq8kp/dMQ6DkuGJZh/OidmUMb47KeHilRwu46G9Pdprk17bD3ESITjIwUIBNkKoIAPCDm2FVgGa/QWUUCE2aDv8l5hjYpTy7X83qjWQLUYt9s85blfqLXZHDsu9iRUxWIwiI6y13J14O@Zq8VvLt6iC9Oo/ZQaVlcwAN8H7cIwp03BHqlJoa95OhR4995m2qFeYL@/K8vSCp5Q8r2IVZmLBWugeFeKMvJxjGGt8cSJfZ@KZ0bVYCcWmHDdry5gdTcvRb1f46Pl6lic5VMp6xl8 "JavaScript (Node.js) – Try It Online") --- # Bitwise approach, 110 bytes ``` a=>a.map(r=>r.map(v=>x=x*2|v==8,x=k=0)|x).map((n,y,b)=>a[0].map((_,x)=>(n^1<<x|b[y-1]|b[y+1])*2>>x&7||k++))&&k ``` [Try it online!](https://tio.run/##dVHbboMwDH3fhyBS3IoEAkFq@BGUTbRrp40OKjqhVOLfmW3QXgZCIr4en2N/1UP9OPef9599271fpqudalvWh@/6Hva27NkYbOmt36lxsNaAt42NxegF58IWnnAS2FPFbo68gUc/bF/l8ejHU/XcS0dPJJ3YqbL0QT6OTRQJEQTNdO7aR3e7HG7dR3gNq8pAChoy0A6qAhIg36Ado5WB5HgGORToK7QNvjnWKOeEePmPRr0KktWsRvyU83qjXyM6cljHJlbEYDWLjLBXMzrxNsxV47dVr1EF6ZV/yhQqy5kBboL3YdinSsWI1BWjLXk7BUbkgjNvUW4wX9@V5ukZT8l5XsEq1MyCtdA9CvQTinKNYl/iHyfydWaeCV2LlVBurjGLtoTZ0bQU43qDj1yup3mSQaWsZ/oF "JavaScript (Node.js) – Try It Online") [Answer] # [Clojure](https://clojure.org/), ~~227~~ 198 bytes ``` (fn[t w h](let[c #(for[y(range %3 %4)x(range % %2)][x y])e #(= 8(get-in t(reverse %)0))m(fn[[o p]](count(filter e(c(dec o)(+ o 2)(dec p)(+ p 2)))))](count(filter #(= 1(m %))(filter e(c 0 w 0 h)))))) ``` Ouch. Definitely not the shortest here by any means. 54 bytes of parenthesis is killer. I'm still relatively happy with it though. **-29 bytes** by creating a helper function that generates a range since I was doing that twice, changing the `reduce` to a `(count (filter` setup, and getting rid of the threading macro after golfing. ``` (defn count-single-eights [td-array width height] ; Define three helper functions. One generates a list of coords for a given range of dimensions, another checks if an eight is ; at the given coord, and the other counts how many neighbors around a coord are an eight (letfn [(coords [x-min x-max y-min y-max] (for [y (range y-min y-max) x (range x-min x-max)] [x y])) (eight? [[x y]] (= 8 (get-in td-array [y x] 0))) (n-eights-around [[cx cy]] (count (filter eight? (coords (dec cx) (+ cx 2), (dec cy) (+ cy 2)))))] ; Gen a list of each coord of the matrix (->> (coords 0 width, 0 height) ; Remove any coords that don't contain an eight (filter eight?) ; Then count how many "neighborhoods" only contain 1 eight (filter #(= 1 (n-eights-around %))) (count)))) (mapv #(count-single-eights % (count (% 0)) (count %)) test-cases) => [3 0 0 2 2 1 3 1 4 3] ``` Where `test-cases` is an array holding all the "Python test cases" [Try it online!](https://tio.run/##XZDdSsQwFIRfZUAK52CEbrt1u4hPEnKx1NMfaZOSTXX36WsSFcRchPNNZiYh3ezeNy87rX6yYbagnXqrAz4xGpol6A4P1Duv7@QvdhAUNYoj334JRcVG33A3LNH5ipYGCU@TRSAvH@Kv0cQl85J6tcNqDHVus4H6aQ7iIdTRm3RwTI9wqDjTmmiNlNa/RLrmQEvs5T8lKOOjS4w5wbvWrcJRoVF4jrtR0GeFWuFbbpNQZorHhx9HHE8K5yxXSWjzeMqRyhg0aJjxghoXP2yL2HDFKPEDvwA "Clojure – Try It Online") ]
[Question] [ This is sequence [A054261](https://oeis.org/A054261) The \$n\$th prime containment number is the lowest number which contains the first \$n\$ prime numbers as substrings. For example, the number \$235\$ is the lowest number which contains the first 3 primes as substrings, making it the 3rd prime containment number. It is trivial to figure out that the first four prime containment numbers are \$2\$, \$23\$, \$235\$ and \$2357\$, but then it gets more interesting. Since the next prime is 11, the next prime containment number is not \$235711\$, but it is \$112357\$ since it's defined as the smallest number with the property. However, the real challenge comes when you go beyond 11. The next prime containment number is \$113257\$. Note that in this number, the substrings `11` and `13` are overlapping. The number `3` is also overlapping with the number `13`. It is easy to prove that this sequence is increasing, since the next number needs to fulfill all criteria of the number before it, and have one more substring. However, the sequence is not strictly increasing, as is shown by the results for `n=10` and `n=11`. ## Challenge Your goal is to find as many prime containment numbers as possible. Your program should output them in an ordered fashion, starting with 2 and going up. ## Rules 1. You are **allowed** to hard-code prime numbers. 2. You are not allowed to hard-code prime containment numbers (`2` is the only exception), or any magic numbers which makes the challenge trivial. Please be nice. 3. You may use any language you wish. Please include a list of commands to get the environment ready for executing the code. 4. You are free to use both CPU and GPU, and you may use multithreading. ## Scoring The official scoring will be from my laptop (dell XPS 9560). Your goal is to generate as many prime containment numbers as possible within 5 minutes. ## Specs * 2.8GHz Intel Core i7-7700HQ (3.8GHz boost) 4 cores, 8 threads. * 16GB 2400MHz DDR4 RAM * NVIDIA GTX 1050 * Linux Mint 18.3 64-bit The numbers found so far, along with the last prime added to the number: ``` 1 => 2 ( 2) 2 => 23 ( 3) 3 => 235 ( 5) 4 => 2357 ( 7) 5 => 112357 ( 11) 6 => 113257 ( 13) 7 => 1131725 ( 17) 8 => 113171925 ( 19) 9 => 1131719235 ( 23) 10 => 113171923295 ( 29) 11 => 113171923295 ( 31) 12 => 1131719237295 ( 37) 13 => 11317237294195 ( 41) 14 => 1131723294194375 ( 43) 15 => 113172329419437475 ( 47) 16 => 1131723294194347537 ( 53) 17 => 113172329419434753759 ( 59) 18 => 2311329417434753759619 ( 61) 19 => 231132941743475375961967 ( 67) 20 => 2311294134347175375961967 ( 71) 21 => 23112941343471735375961967 ( 73) 22 => 231129413434717353759619679 ( 79) 23 => 23112941343471735359619678379 ( 83) 24 => 2311294134347173535961967837989 ( 89) 25 => 23112941343471735359619678378979 ( 97) 26 => 2310112941343471735359619678378979 (101) 27 => 231010329411343471735359619678378979 (103) 28 => 101031071132329417343475359619678378979 (107) 29 => 101031071091132329417343475359619678378979 (109) 30 => 101031071091132329417343475359619678378979 (113) 31 => 101031071091131272329417343475359619678378979 (127) 32 => 101031071091131272329417343475359619678378979 (131) 33 => 10103107109113127137232941734347535961967838979 (137) 34 => 10103107109113127137139232941734347535961967838979 (139) 35 => 10103107109113127137139149232941734347535961967838979 (149) 36 => 1010310710911312713713914923294151734347535961967838979 (151) ``` Thanks to Ardnauld, Ourous, and japh for extending this list. Note that `n = 10` and `n = 11` are the same number, since \$113171923295\$ is the lowest number which contains all numbers \$[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\$, but it also contains \$31\$. For reference, you can use the fact that the original Python script I wrote to generate this list above calculates the first 12 terms in about 6 minutes. ## Additional rules After the first results have come in, I have realized that there's a good chance that top results can end up having the same score. In case if a tie, the winner will be the one with the shortest time to generate their result. If two or more answers produce their results equally fast, it will simply be a tied victory. ## Final note The 5 minute runtime is only put to ensure a fair scoring. I'd be very interested in seeing if we can push the OEIS sequence further (right now it contains 17 numbers). With Ourous' code, I have generated all numbers until `n = 26`, but I plan on letting the code run for a longer period of time. # Scoreboard 1. [Python 3 + Google OR-Tools](https://codegolf.stackexchange.com/a/177402/79994): 169 2. [Scala](https://codegolf.stackexchange.com/a/177332/79994): 137 (unofficial) 3. [Concorde TSP solver](https://codegolf.stackexchange.com/a/177257/79994): 84 (unofficial) 4. [C++ (GCC) + x86 assembly](https://codegolf.stackexchange.com/a/176984/79994): 62 5. [Clean](https://codegolf.stackexchange.com/a/176881/79994): 25 6. [JavaScript (Node.js)](https://codegolf.stackexchange.com/a/176854/79994): 24 [Answer] # [C++ (GCC)](https://gcc.gnu.org/) + x86 assembly, score ~~32~~ ~~36~~ 62 in 259 seconds (official) Results computed so far. My computer runs out of memory after `65`. ``` 1 2 2 23 3 235 4 2357 5 112357 6 113257 7 1131725 8 113171925 9 1131719235 10 113171923295 11 113171923295 12 1131719237295 13 11317237294195 14 1131723294194375 15 113172329419437475 16 1131723294194347537 17 113172329419434753759 18 2311329417434753759619 19 231132941743475375961967 20 2311294134347175375961967 21 23112941343471735375961967 22 231129413434717353759619679 23 23112941343471735359619678379 24 2311294134347173535961967837989 25 23112941343471735359619678378979 26 2310112941343471735359619678378979 27 231010329411343471735359619678378979 28 101031071132329417343475359619678378979 29 101031071091132329417343475359619678378979 30 101031071091132329417343475359619678378979 31 101031071091131272329417343475359619678378979 32 101031071091131272329417343475359619678378979 33 10103107109113127137232941734347535961967838979 34 10103107109113127137139232941734347535961967838979 35 10103107109113127137139149232941734347535961967838979 36 1010310710911312713713914923294151734347535961967838979 37 1010310710911312713713914915157232941734347535961967838979 38 1010310710911312713713914915157163232941734347535961967838979 39 10103107109113127137139149151571631672329417343475359619798389 40 10103107109113127137139149151571631672329417343475359619798389 41 1010310710911312713713914915157163167173232941794347535961978389 42 101031071091131271371391491515716316717323294179434753596181978389 43 101031071091131271371391491515716316723294173434753596181917978389 44 101031071091131271371391491515716316717323294179434753596181919383897 45 10103107109113127137139149151571631671731792329418191934347535961978389 46 10103107109113127137139149151571631671731791819193232941974347535961998389 47 101031071091271313714915157163167173179181919321139232941974347535961998389 48 1010310710912713137149151571631671731791819193211392232941974347535961998389 49 1010310710912713137149151571631671731791819193211392232272941974347535961998389 50 10103107109127131371491515716316717317918191932113922322722941974347535961998389 51 101031071091271313714915157163167173179181919321139223322722941974347535961998389 52 101031071091271313714915157163167173179181919321139223322722923941974347535961998389 53 1010310710912713137149151571631671731791819193211392233227229239241974347535961998389 54 101031071091271313714915157163167173179211392233227229239241819193251974347535961998389 55 101031071091271313714915157163167173179211392233227229239241819193251972574347535961998389 56 101031071091271313714915157163167173179211392233227229239241819193251972572634347535961998389 57 101031071091271313714915157163167173179211392233227229239241819193251972572632694347535961998389 58 101031071091271313714915157163167173179211392233227229239241819193251972572632694347535961998389 59 1010310710912713137149151571631671731792113922332277229239241819193251972572632694347535961998389 60 101031071091271313714915157163167173211392233227722923924179251819193257263269281974347535961998389 61 1010310710912713137149151571631671732113922332277229239241792518191932572632692819728343475359619989 62 10103107109127131371491515716316717321139223322772293239241792518191932572632692819728343475359619989 63 1010307107109127131371491515716316717321139223322772293239241792518191932572632692819728343475359619989 64 10103071071091271311371391491515716316721173223322772293239241792518191932572632692819728343475359619989 65 10103071071091271311371491515716313916721173223322772293239241792518191932572632692819728343475359619989 ``` These all agree with the output of the [Concorde-based solver](https://codegolf.stackexchange.com/a/177257/75067), so they stand a good chance of being correct. Changelog: * Wrong calculation for needed context length. The earlier version was 1 too large, and also had a bug. Score: ~~32~~ 34 * Added equal-context-group optimisation. Score: ~~34~~ 36 * Overhauled the algorithm to use context-free strings properly, plus some other optimizations. Score: ~~36~~ 62 * Added a proper write-up. * Added the prime numbers variant. # How it works *Warning: this is a brain dump. Scroll to the end if you just want the code.* Abbreviations: * **PCN**: prime containment number problem *i.e. this challenge* * **SCS**: [shortest common superstring](https://en.wikipedia.org/wiki/Shortest_common_superstring) * **TSP**: [travelling salesman problem](https://en.wikipedia.org/wiki/Travelling_salesman_problem) This program basically uses the textbook dynamic programming algorithm for the TSP. 1. Plus a reduction from PCN/SCS, the problem we're actually solving, to TSP. 2. Plus using item contexts instead of all digits in each item. 3. Plus subdividing the problem based on primes that cannot overlap with the ends of other primes. 4. Plus merging calculations for primes with the same start/end digits. 5. Plus precomputed lookup tables and a custom hash table. 6. Plus some low-level prefetching and bit-packing. That's a lot of potential bugs. After playing around with anselm's entry and failing to coax any wrong results from it, I should at least prove that my overall approach is correct. Although the Concorde-based solution is (much, much) faster, it is based on the same reduction, so this explanation applies to both. Additionally, this solution can be adapted for [OEIS A054260](https://oeis.org/A054260), the prime-containing primes sequence; I don't know how to solve that efficiently in the TSP framework. So it's still somewhat relevant. ## TSP reduction Let's start by actually proving that reducing to TSP is correct. We have a set of strings, say ``` A = 13, 31, 37, 113, 137, 211 ``` and we want to find the smallest superstring that contains these items. ### Knowing the length is enough For the PCN, if there are multiple shortest strings, we have to return the lexicographically smallest one. But we will look at a different (and easier) problem. * **SCS**: Given an initial prefix and a set of items, find any shortest string that contains all the items as substrings, and starts with that prefix. * **SCS-Length**: Just find the length of the SCS. If we can solve SCS-Length, we can reconstruct the smallest solution and obtain the PCN. If we know that the smallest solution starts with our prefix, we try to extend it by appending each item, in lexicographic order, and solving for the length again. When we find the smallest item for which the solution length is the same, we know that this must be the next item in the smallest solution (why?), so add it and recurse on the remaining items. This method of reaching the solution is called [self-reduction](https://en.wikipedia.org/wiki/Self-reducible). ### Touring the maximal-overlap graph Suppose we started solving SCS for the above example by hand. We would probably: * Get rid of `13` and `37`, because they're already substrings of the other items. Any solution that contains `137`, for example, must also contain `13` and `37`. * Start considering the combinations `113,137 → 1137`, `211,113 → 2113`, etc. This is in fact the right thing to do, but let's prove it for the sake of completeness. Take any SCS solution; for example, a shortest superstring for `A` is ``` 2113137 ``` and it can be decomposed into a concatenation of all items in `A`: ``` 211 113 31 137 ``` (We ignore the redundant items `13, 37`.) Observe that: 1. The start and end positions of each item increase by at least 1. 2. Each item is overlapped with the previous item to the greatest extent possible. We will show that every shortest superstring can be decomposed this way: 1. For every pair of adjacent items `x,y`, `y` starts and ends at later positions than `x`. If this is not true, then either `x` is a substring of `y` or vice versa. But we already removed all items which are substrings, so that cannot happen. 2. Suppose adjacent items in the sequence have less-than-maximal overlap, e.g. `21113` instead of `2113`. But that would make the extra `1` redundant. No later item needs the initial `1` (as in 2**1**113), because it occurs earlier than `113`, and all items that appear after `113` cannot start with a digit before `113` (see point 1). A similar argument prevents the last extra `1` (as in 211**1**3) being used by any item before `211`. But our *shortest* superstring, by definition, won't have redundant digits, so such non-maximal overlaps will not occur. With these properties, we can convert any SCS problem into a TSP: 1. Remove all items which are substrings of other items. 2. Create a directed graph which has one vertex for each item. 3. For each pair of items `x`, `y`, add an edge from `x` to `y` whose weight is the number of extra symbols added by appending `y` to `x` with maximal overlap. For example, we would add an edge from `211` to `113` with weight 1, because `2113` adds one more digit over `211`. Repeat for the edge from `y` to `x`. 4. Add a vertex for the initial prefix, and edges from it to all the other items. Any path on this graph, from the initial prefix, corresponds to a maximal-overlap concatenation of all items on that path, and the total weight of the path equals the concatenated string length. Therefore, every lowest-weight tour, that visits all the items at least once, corresponds to a shortest superstring. And that's the reduction from SCS (and SCS-Length) to TSP. ## Dynamic programming algorithm This is a classic algorithm, but we will modify it quite a bit, so here's a quick reminder. (I've written this as an algorithm for SCS-Length instead of TSP. They're essentially equivalent, but the SCS vocabulary helps when we get to the SCS-specific optimizations.) Call the set of input items `A` and the given prefix `P`. For every `k`-element subset `S` in `A`, and every element `e` of `S`, we calculate the length of the shortest string that starts with `P`, contains all of `S`, and ends with `e`. This involves storing a table from values of `(S, e)` to their SCS-Lengths. When we get to each subset `S`, the table needs to already contain the results for `S - {e}` for all `e` in `S`. As the table can get quite large, I calculate the results for all `k`-element subsets, then `k+1`, etc. For this, we only need to store the results for `k` and `k+1` at any one time. This reduces memory usage by a factor of roughly `sqrt(|A|)`. One more detail: instead of calculating the minimum SCS-Length, I actually calculate the maximum total overlap between the items. (To get the SCS-Length, just subtract the total overlap from the sum of the items' lengths.) Using overlaps helps some of the following optimizations. ### [2.] Item contexts A *context* is the longest suffix of an item that can overlap with following items. If our items are `113,211,311`, then `11` is the context for `211` and `311`. (It's also the prefix context for `113`, which we'll look at in part [4.]) In the DP algorithm above, we kept track of SCS solutions that end with each item, but we don't actually care which item an SCS ends in. All we need to know is the context. Thus, for example, if two SCSs for the same set end in `23` and `43`, any SCS that continues from one will also work for the other. This is a significant optimization, because non-trivial primes end in only the digits `1 3 7 9`. The four single-digit contexts `1,3,7,9` (plus the empty context) are in fact sufficient to compute the PCNs for primes up to `131`. ### [3.] Context-free items Others have already pointed out that many primes begin with the digits `2,4,5,6,8`, such as `23,29,41,43...`. None of these can overlap with a previous prime (aside from `2` and `5`, primes cannot end in these digits; `2` and `5` will already have been removed as redundant). In the code, these are referred to as *context-free strings*. If our input has context-free items, every SCS solution can be split into blocks ``` <prefix>... 23... 29... 41... 43... ``` and the overlaps in each block are independent of the other blocks. We can shuffle the blocks or swap items between blocks that have the same context, without changing the SCS length. Thus, we only need to keep track of the possible *multisets* of contexts, one for each block. Full example: for the primes less than 100, we have 11 context-free items and their contexts: ``` 23 29 41 43 47 53 59 61 67 83 89 3 9 1 3 7 3 9 1 7 3 9 ``` Our initial multiset context: ``` 1 1 3 3 3 3 7 7 9 9 9 ``` The code refers to these as *combined contexts*, or *ccontexts*. Then, we only need to consider subsets of the remaining items: ``` 11 13 17 19 31 37 71 73 79 97 ``` ### [4.] Context merging Once we get to primes with 3 digits or more, there are more redundancies: ``` 101 151 181 191 ... 107 127 157 167 197 ... 109 149 1009 ... ``` These groups share the same starting and ending contexts (usually—it depends on which other primes are in the input), so they are indistinguishable when overlapping other items. We only care about overlaps, so we can treat primes in these *equal-context groups* as indistinguishable. Now our DP subsets are condensed into multisubsets ``` 4 × 1_1 5 × 1_7 3 × 1_9 ``` (This is also why the solver maximizes overlap length instead of minimizing SCS length: this optimization preserves overlap length.) ### Summary: the high-level optimizations Running with `INFO` debug output will print statistics like ``` solve: N=43, N_search=26, ccontext_size=18, #contexts=7, #eq_context_groups=16 ``` This particular line is for the SCS-Length of the first 62 primes, `2` to `293`. * After removing redundant items, we're left with 43 primes that are not substrings of each other. * There are 7 unique *contexts*: `1,3,7,11,13,27` plus the empty string. * 17 of the 43 primes are *context-free*: `43,47,53,59,61,89,211,223,227,229,241,251,257,263,269,281,283`. These and the given prefix (in this case, empty string) form the basis of the initial *combined context*. * In the remaining 26 items (`N_search`), there are 16 nontrivial *equal-context groups*. By exploiting these structures, the SCS-Length calculation only needs to check 8498336 `(multiset, ccontext)` combinations. Straightforward dynamic programming would take `43×2^43 > 3×10^14` steps, and brute forcing the permutations would take `6×10^52` steps. The program still needs to run SCS-Length several more times to reconstruct the PCN solution, but that doesn't take much longer. ### [5., 6.] The low-level optimizations Instead of doing string operations, the SCS-Length solver works with indices of items and contexts. I also precompute the overlap amount between each context and item pair. The code initially used GCC's `unordered_map`, which seems to be a hash table with linked list buckets and prime hash sizes (i.e. expensive divisions). So I wrote my own hash table with linear probing and power-of-two sizes. This nets a 3× speedup and 3× reduction in memory. Each table state consists of a multiset of items, a combined context and an overlap count. These are packed into 128-bit entries: 8 for the overlap count, 56 for the multiset (as a bitset with run-length encoding), and 64 for the ccontext (1-delimited RLE). Encoding and decoding the ccontext was the trickiest part and I ended up using the new [`PDEP`](https://stackoverflow.com/questions/45482787/how-to-efficiently-find-the-n-th-set-bit) instruction (it's so new, GCC doesn't have an intrinsic for it yet). Finally, accessing a hash table is really slow when `N` gets large, because the table doesn't fit in cache any more. But the only reason we write to the hash table, is to update the best known overlap count for each state. The program splits this step off into a prefetch queue, and the inner loop prefetches each table lookup a few iterations before actually updating that slot. Another 2× speedup on my computer. ## Bonus: further improvements ***AKA* How is Concorde so fast?** I don't know much about TSP algorithms, so here is a rough guess. Concorde uses the [branch-and-cut](https://en.wikipedia.org/wiki/Branch_and_cut) method to solve TSPs. * It encodes the TSP as an integer linear program * It uses linear programming methods, as well as initial heuristics, to obtain lower and upper bounds on the optimal tour distance * These bounds are then fed into a *branch and bound* recursive algorithm that searches for the optimal solution. Large parts of the search tree can be pruned, if the computed lower bound for a subtree exceeds a known upper bound * It also searches for *cutting planes* to tighten the LP relaxation and obtain better bounds. Typically, these cuts encode knowledge of the fact that the decision variables must be integers Obvious ideas we could try: * Pruning in the SCS-Length solver, especially when reconstructing the PCN solution (at that point, we already know what the solution length is) * Deriving some easy-to-calculate lower bounds for SCS, that can be used to help pruning * Finding more symmetries or redundancies in the prime number distribution to exploit However, the branch-and-cut combination is very powerful, so we might not be able to beat a state-of-the-art solver like Concorde, for large values of `N`. ## Bonus bonus: the prime containment primes Unlike the Concorde-based solution, this program can be modified to find the smallest containing *primes* ([OEIS A054260](https://oeis.org/A054260)). This involves three changes: 1. When reconstructing the solution from SCS-Length, test whether the solution is also a prime number. If not, backtrack and try some other ordering. There are reasonably many prime numbers (\$1/\ln(n)\$ density), so this usually succeeds quickly. However, if the PCN happens to have a digit sum divisible by 3, then the PCN (and many of its sibling permutations) will be divisible by 3. To avoid getting stuck in this situation, we also… 2. Modify the SCS-Length solver code to categorize solutions based on whether their digit sums are divisible by 3. This involves adding another entry, the digit sum mod 3, to each DP state. This greatly reduces the odds of the main solver getting stuck with non-prime permutations. This is the change that I couldn't work out how to translate to TSP. It can be encoded with ILP, but then I'd have to learn about this thing called “subtour inequality” and how to generate those. 3. It may be that *all* of the shortest PCNs are divisible by 3. In that case, the smallest prime containment prime must be at least one digit longer than the PCN. If our SCS-Length solver detects this, the solution reconstruction code has the option to add *one* extra digit at any point in the process. It tries adding each possible digit `0..9` and each remaining item to the current solution prefix, in lexicographic order as before. With these changes, I can obtain the solutions up to `N=62`. Except for `47`, where the reconstruction code gets stuck and gives up after 1 million steps (I don't know why, yet). The prime containment primes are: ``` 1 2 2 23 3 523 4 2357 5 112573 6 511327 7 1135217 8 1113251719 9 11171323519 10 113171952923 11 113171952923 12 11131951723729 13 11317237419529 14 1131723294375419 15 113172329541947437 16 1131723294195343747 17 1113172329419434753759 18 11231329417437475361959 19 231132941743475375967619 20 2311294134347175967619537 21 23112941343471735967619537 22 231129413434717359537679619 23 23112941343471735375961983679 24 11231294134347173535961967983789 25 23112941343471735359679837619789 26 2310112941343471735359619783789679 27 231010329411343471735359619678379897 28 101031071132329417343475359619798376789 29 101031071091132329417343475359619767898379 30 101031071091132329417343475359619767898379 31 1010310710911131272329417343475359619678979837 32 1010310710911131272329417343475359619678979837 33 10103107109113127137232941734347535978961967983 34 10103107109113127137139232941734347535961967838979 35 10103107109113127137139149232941734347535961976798389 36 1010310710911312713713914923294151734347535976198389679 37 1010310710911312713713914915157232941734347535967619798389 38 10103107109111312713713914915157163232941734347535967897961983 39 10103107109113127137139149151571631672329417343475961979838953 40 10103107109113127137139149151571631672329417343475961979838953 41 10103107109111312713713914915157163167173232941794347535976198983 42 1010310710911131271371391491515716316717323294179434761819535989783 43 1010310710911131271371391491515716316723294173434753596181917989783 44 101031071091131271371391491515716316717323294179434753836181919389597 45 10103107109113127137139149151571631671731792329418191934347538961975983 46 101031071091113127137139149151571631671731791819193232941974347535989836199 47 (failed) 48 1010310710912713137149151571631671731791819193211392232941974347895359836199 49 10103107109112713137149151571631671731791819193211392232272941974347619983535989 50 10103107109127131371491515716316717317918191932113922322722941974347595389836199 51 101031071091271313714915157163167173179181919321139223322722941974347595389619983 52 101031071091271313714915157163167173179181919321139223322722923941974347538361995989 53 10103107109112713137149151571631671731791819193211392233227229239241974347619983538959 54 101031071091271313714915157163167173179211392233227229239241819193251974347619953835989 55 1010310710911271313714915157163167173179211392233227229239241819193251974325747596199538983 56 101031071091271313714915157163167173179211392233227229239241819193251972572634347619959895383 57 101031071091271313714915157163167173179211392233227229239241819193251972572632694359538983619947 58 101031071091271313714915157163167173179211392233227229239241819193251972572632694359538983619947 59 1010310710912713137149151571631671731792113922332277229239241819193251972572632694347535983896199 60 1010310710911271313714915157163167173211392233227722923924179251819193257263269281974347535961998389 61 1010310710912713137149151571631671732113922332277229239241792518191932572632692819728343538947619959 62 10103107109127131371491515716316717321139223322772293239241792518191932572632692819728343534759896199 ``` # Code Compile with ``` g++ -std=c++14 -O3 -march=native pcn.cpp -o pcn ``` For the prime number version, also link with GMPlib, e.g. ``` g++ -std=c++14 -O3 -march=native pcn-prime.cpp -o pcn-prime -lgmp -lgmpxx ``` This program uses the PDEP instruction, which is only available on recent (Haswell+) x86 processors. Both my computer and maxb's support it. If yours doesn't, the program will compile in a slow software version. A compile warning will be printed when this happens. ``` #include <cassert> #include <cstdlib> #include <cstring> #include <iostream> #include <vector> #include <unordered_map> #include <string> #include <algorithm> #include <array> using namespace std; void debug_dummy(...) { } #ifndef INFO //# define INFO(...) fprintf(stderr, __VA_ARGS__) # define INFO debug_dummy #endif #ifndef DEBUG //# define DEBUG(...) fprintf(stderr, __VA_ARGS__) # define DEBUG debug_dummy #endif bool is_prime(size_t n) { for (size_t d = 2; d * d <= n; ++d) { if (n % d == 0) { return false; } } return true; } // bitset, works for up to 64 strings using bitset_t = uint64_t; const size_t bitset_bits = 64; // Find position of n-th set bit of x uint64_t bit_select(uint64_t x, size_t n) { #ifdef __BMI2__ // Bug: GCC doesn't seem to provide the _pdep_u64 intrinsic, // despite what its manual claims. Neither does Clang! //size_t r = _pdep_u64(ccontext_t(1) << new_context, ccontext1); size_t r; // NB: actual operand order is %2, %1 despite the intrinsic taking %1, %2 asm ("pdep %2, %1, %0" : "=r" (r) : "r" (uint64_t(1) << n), "r" (x) ); return __builtin_ctzll(r); #else # warning "bit_select: no x86 BMI2 instruction set, falling back to slow code" size_t k = 0, m = 0; for (; m < 64; ++m) { if (x & (uint64_t(1) << m)) { if (k == n) { break; } ++k; } } return m; #endif } #ifndef likely # define likely(x) __builtin_expect(x, 1) #endif #ifndef unlikely # define unlikely(x) __builtin_expect(x, 0) #endif // Return the shortest string that begins with a and ends with b string join_strings(string a, string b) { for (size_t overlap = min(a.size(), b.size()); overlap > 0; --overlap) { if (a.substr(a.size() - overlap) == b.substr(0, overlap)) { return a + b.substr(overlap); } } return a + b; } vector <string> dedup_items(string context0, vector <string> items) { vector <string> items2; for (size_t i = 0; i < items.size(); ++i) { bool dup = false; if (context0.find(items[i]) != string::npos) { dup = true; } else { for (size_t j = 0; j < items.size(); ++j) { if (items[i] == items[j]? i > j : items[j].find(items[i]) != string::npos) { dup = true; break; } } } if (!dup) { items2.push_back(items[i]); } } return items2; } // Table entry used in main solver const size_t solver_max_item_set = bitset_bits - 8; struct Solver_entry { uint8_t score : 8; bitset_t items : solver_max_item_set; bitset_t context; Solver_entry() { score = 0xff; items = 0; context = 0; } bool is_empty() const { return score == 0xff; } }; // Simple hash table to avoid stdlib overhead struct Solver_table { vector <Solver_entry> t; size_t t_bits; size_t size_; size_t num_probes_; Solver_table() { // 256 slots initially -- this needs to be not too small // so that the load factor formula in update_score works t_bits = 8; size_ = 0; num_probes_ = 0; resize(t_bits); } static size_t entry_hash(bitset_t items, bitset_t context) { uint64_t h = 0x3141592627182818ULL; // Add context first, since its bits are generally // less well distributed than items h += context; h ^= h >> 23; h *= 0x2127599bf4325c37ULL; h ^= h >> 47; h += items; h ^= h >> 23; h *= 0x2127599bf4325c37ULL; h ^= h >> 47; return h; } size_t probe_index(size_t hash) const { return hash & ((size_t(1) << t_bits) - 1); } void resize(size_t t2_bits) { assert (size_ < size_t(1) << t2_bits); vector <Solver_entry> t2(size_t(1) << t2_bits); for (auto entry: t) { if (!entry.is_empty()) { size_t h = entry_hash(entry.items, entry.context); size_t mask = (size_t(1) << t2_bits) - 1; size_t idx = h & mask; while (!t2[idx].is_empty()) { idx = (idx + 1) & mask; ++num_probes_; } t2[idx] = entry; } } t.swap(t2); t_bits = t2_bits; } uint8_t update_score(bitset_t items, bitset_t context, uint8_t score) { // Ensure we can insert a new item without resizing assert (size_ < t.size()); size_t index = probe_index(entry_hash(items, context)); size_t mask = (size_t(1) << t_bits) - 1; for (size_t p = 0; p < t.size(); ++p, index = (index + 1) & mask) { ++num_probes_; if (likely(t[index].items == items && t[index].context == context)) { t[index].score = max(t[index].score, score); return t[index].score; } if (t[index].is_empty()) { // add entry t[index].score = score; t[index].items = items; t[index].context = context; ++size_; // load factor 4/5 -- ideally 2-3 average probes per lookup if (5*size_ > 4*t.size()) { resize(t_bits + 1); } return score; } } assert (false && "bug: hash table probe loop"); } size_t size() const { return size_; } void swap(Solver_table table) { t.swap(table.t); ::swap(size_, table.size_); ::swap(t_bits, table.t_bits); ::swap(num_probes_, table.num_probes_); } }; /* * Main solver code. */ struct Solver { // Inputs vector <string> items; string context0; size_t context0_index; // Mapping between strings and indices vector <string> context_to_string; unordered_map <string, size_t> string_to_context; // Items that have context-free prefixes, i.e. prefixes that // never overlap with the end of other items nor context0 vector <bool> contextfree; // Precomputed contexts (suffixes) for each item vector <size_t> item_context; // Precomputed updates: (context, string) to overlap amount vector <vector <size_t>> join_overlap; Solver(vector <string> items, string context0) :items(items), context0(context0) { items = dedup_items(context0, items); init_context_(); } void init_context_() { /* * Generate all relevant item-item contexts. * * At this point, we know that no item is a substring of * another, nor of context0. This means that the only contexts * we need to care about, are those generated from maximal join * overlaps between any two items. * * Proof: * Suppose that the shortest containing string needs some other * kind of context. Maybe it depends on a context spanning * three or more items, say X,Y,Z. But if Z ends after Y and * interacts with X, then Y must be a substring of Z. * This cannot happen, because we removed all substrings. * * Alternatively, it depends on a non-maximal join overlap * between two strings, say X,Y. But if this overlap does not * interact with any other string, then we could maximise it * and get a shorter solution. If it does, then call this * other string Z. We would get the same contradiction as in * the previous case with X,Y,Z. */ size_t N = items.size(); vector <size_t> max_prefix_overlap(N), max_suffix_overlap(N); size_t context0_suffix_overlap = 0; for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { if (i == j) continue; string joined = join_strings(items[j], items[i]); size_t overlap = items[j].size() + items[i].size() - joined.size(); string context = items[i].substr(0, overlap); max_prefix_overlap[i] = max(max_prefix_overlap[i], overlap); max_suffix_overlap[j] = max(max_suffix_overlap[j], overlap); if (string_to_context.find(context) == string_to_context.end()) { string_to_context[context] = context_to_string.size(); context_to_string.push_back(context); } } // Context for initial join with context0 { string joined = join_strings(context0, items[i]); size_t overlap = context0.size() + items[i].size() - joined.size(); string context = items[i].substr(0, overlap); max_prefix_overlap[i] = max(max_prefix_overlap[i], overlap); context0_suffix_overlap = max(context0_suffix_overlap, overlap); if (string_to_context.find(context) == string_to_context.end()) { string_to_context[context] = context_to_string.size(); context_to_string.push_back(context); } } } // Now compute all canonical trailing contexts context0_index = string_to_context[ context0.substr(context0.size() - context0_suffix_overlap)]; item_context.resize(N); for (size_t i = 0; i < N; ++i) { item_context[i] = string_to_context[ items[i].substr(items[i].size() - max_suffix_overlap[i])]; } // Now detect context-free items contextfree.resize(N); for (size_t i = 0; i < N; ++i) { contextfree[i] = (max_prefix_overlap[i] == 0); if (contextfree[i]) { DEBUG(" contextfree: %s\n", items[i].c_str()); } } // Now compute all possible overlap amounts join_overlap.resize(context_to_string.size(), vector <size_t> (N)); for (size_t c_index = 0; c_index < context_to_string.size(); ++c_index) { const string& context = context_to_string[c_index]; for (size_t i = 0; i < N; ++i) { string joined = join_strings(context, items[i]); size_t overlap = context.size() + items[i].size() - joined.size(); join_overlap[c_index][i] = overlap; } } } // Main solver. // Returns length of shortest string containing all items starting // from context0 (context0's length not included). size_t solve() const { size_t N = items.size(); // Length, if joined without overlaps. We try to improve this by // finding overlaps in the main iteration size_t base_length = 0; for (auto s: items) { base_length += s.size(); } // Now take non-context-free items. We will only need to search // over these items. vector <size_t> search_items; for (size_t i = 0; i < N; ++i) { if (!contextfree[i]) { search_items.push_back(i); } } size_t N_search = search_items.size(); /* * Some groups of strings have the same context transitions. * For example "17", "107", "127", "167" all have an initial * context of "1" and a trailing context of "7", no other * overlaps are possible with other primes. * * We group these strings and treat them as indistinguishable * during the main algorithm. */ auto eq_context = [&](size_t i, size_t j) { if (item_context[i] != item_context[j]) { return false; } for (size_t ci = 0; ci < context_to_string.size(); ++ci) { if (join_overlap[ci][i] != join_overlap[ci][j]) { return false; } } return true; }; vector <size_t> eq_context_group(N_search, size_t(-1)); for (size_t si = 0; si < N_search; ++si) { for (size_t sj = si-1; sj+1 > 0; --sj) { size_t i = search_items[si], j = search_items[sj]; if (!contextfree[j] && eq_context(i, j)) { DEBUG(" eq context: %s =c= %s\n", items[i].c_str(), items[j].c_str()); eq_context_group[si] = sj; break; } } } // Figure out the combined context size. A combined context has // one entry for each context-free item plus one for context0. size_t ccontext_size = N - N_search + 1; // Assert that various parameters all fit into our data types using ccontext_t = bitset_t; assert (context_to_string.size() + ccontext_size <= bitset_bits); assert (N_search <= solver_max_item_set); assert (base_length < 0xff); // Initial combined context. unordered_map <size_t, size_t> cc0_full; ++cc0_full[context0_index]; for (size_t i = 0; i < N; ++i) { if (contextfree[i]) { ++cc0_full[item_context[i]]; } } // Now pack into unary-encoded bitset. The bitset stores the // count for each context as <count> number of 0 bits, // followed by a 1 bit. ccontext_t cc0 = 0; for (size_t ci = 0, b = 0; ci < context_to_string.size(); ++ci, ++b) { b += cc0_full[ci]; cc0 |= ccontext_t(1) << b; } // Map from (item set, context) to maximum achievable overlap Solver_table k_solns; // Base case: cc0 with empty set k_solns.update_score(0, cc0, 0); // Now start dynamic programming. k is current subset size size_t eq_context_groups = 0; for (size_t g: eq_context_group) eq_context_groups += (g != size_t(-1)); if (context0.empty()) { INFO("solve: N=%zu, N_search=%zu, ccontext_size=%zu, #contexts=%zu, #eq_context_groups=%zu\n", N, N_search, ccontext_size, context_to_string.size(), eq_context_groups); } else { DEBUG("solve: context=%s, N=%zu, N_search=%zu, ccontext_size=%zu, #contexts=%zu, #eq_context_groups=%zu\n", context0.c_str(), N, N_search, ccontext_size, context_to_string.size(), eq_context_groups); } for (size_t k = 0; k < N_search; ++k) { decltype(k_solns) k1_solns; // The main bottleneck of this program is updating k1_solns, // which (for larger N) becomes a huge table. // We use a prefetch queue to reduce memory latency. const size_t prefetch = 8; array <Solver_entry, prefetch> entry_queue; size_t update_i = 0; // Iterate every k-subset for (Solver_entry entry: k_solns.t) { if (entry.is_empty()) continue; bitset_t s = entry.items; ccontext_t ccontext = entry.context; size_t overlap = entry.score; // Try adding a new item for (size_t si = 0; si < N_search; ++si) { bitset_t s1 = s | bitset_t(1) << si; if (s == s1) { continue; } // Add items in each eq_context_group sequentially if (eq_context_group[si] != size_t(-1) && !(s & bitset_t(1) << eq_context_group[si])) { continue; } size_t i = search_items[si]; // actual item index size_t new_context = item_context[i]; // Increment ccontext's count for new_context. // We need to find its delimiter 1 bit size_t bit_n = bit_select(ccontext, new_context); ccontext_t ccontext_n = ((ccontext & ((ccontext_t(1) << bit_n) - 1)) | ((ccontext >> bit_n << (bit_n + 1)))); // Select non-empty sub-contexts to substitute for new_context for (size_t ci = 0, bit1 = 0, count; ci < context_to_string.size(); ++ci, bit1 += count + 1) { assert (ccontext_n >> bit1); count = __builtin_ctzll(ccontext_n >> bit1); if (!count // We just added new_context; we can only remove an existing // context entry there i.e. there must be at least two now || (ci == new_context && count < 2)) { continue; } // Decrement ci in ccontext_n bitset_t ccontext1 = ((ccontext_n & ((ccontext_t(1) << bit1) - 1)) | ((ccontext_n >> (bit1 + 1)) << bit1)); size_t overlap1 = overlap + join_overlap[ci][i]; // do previous prefetched update if (update_i >= prefetch) { Solver_entry entry = entry_queue[update_i % prefetch]; k1_solns.update_score(entry.items, entry.context, entry.score); } // queue the current update and prefetch Solver_entry entry1; size_t probe_index = k1_solns.probe_index(Solver_table::entry_hash(s1, ccontext1)); __builtin_prefetch(&k1_solns.t[probe_index]); entry1.items = s1; entry1.context = ccontext1; entry1.score = overlap1; entry_queue[update_i % prefetch] = entry1; ++update_i; } } } // do remaining queued updates for (size_t j = 0; j < min(update_i, prefetch); ++j) { Solver_entry entry = entry_queue[j]; k1_solns.update_score(entry.items, entry.context, entry.score); } if (context0.empty()) { INFO(" hash stats: |solns[%zu]| = %zu, %zu lookups, %zu probes\n", k+1, k1_solns.size(), update_i, k1_solns.num_probes_); } else { DEBUG(" hash stats: |solns[%zu]| = %zu, %zu lookups, %zu probes\n", k+1, k1_solns.size(), update_i, k1_solns.num_probes_); } k_solns.swap(k1_solns); } // Overall solution size_t max_overlap = 0; for (Solver_entry entry: k_solns.t) { if (entry.is_empty()) continue; max_overlap = max(max_overlap, size_t(entry.score)); } return base_length - max_overlap; } }; // Wrapper for Solver that also finds the smallest solution string string smallest_containing_string(vector <string> items) { items = dedup_items("", items); size_t soln_length; { Solver solver(items, ""); soln_length = solver.solve(); } DEBUG("Found solution length: %zu\n", soln_length); string soln; vector <string> remaining_items = items; while (remaining_items.size() > 1) { // Add all possible next items, in lexicographic order vector <pair <string, size_t>> next_solns; for (size_t i = 0; i < remaining_items.size(); ++i) { const string& item = remaining_items[i]; next_solns.push_back(make_pair(join_strings(soln, item), i)); } assert (next_solns.size() == remaining_items.size()); sort(next_solns.begin(), next_solns.end()); // Now try every item in order bool found_next = false; for (auto ns: next_solns) { size_t i; string next_soln; tie(next_soln, i) = ns; DEBUG("Trying: %s + %s -> %s\n", soln.c_str(), remaining_items[i].c_str(), next_soln.c_str()); vector <string> next_remaining; for (size_t j = 0; j < remaining_items.size(); ++j) { if (next_soln.find(remaining_items[j]) == string::npos) { next_remaining.push_back(remaining_items[j]); } } Solver solver(next_remaining, next_soln); size_t next_size = solver.solve(); DEBUG(" ... next_size: %zu + %zu =?= %zu\n", next_size, next_soln.size(), soln_length); if (next_size + next_soln.size() == soln_length) { INFO(" found next item: %s\n", remaining_items[i].c_str()); soln = next_soln; remaining_items = next_remaining; // found lexicographically smallest solution, break now found_next = true; break; } } assert (found_next); } soln = join_strings(soln, remaining_items[0]); return soln; } int main() { string prev_soln; vector <string> items; size_t p = 1; for (size_t N = 1;; ++N) { for (++p; items.size() < N; ++p) { if (is_prime(p)) { char buf[99]; snprintf(buf, sizeof buf, "%zu", p); items.push_back(buf); break; } } // Try to reuse previous solution (this works for N=11,30,32...) string soln; if (prev_soln.find(items.back()) != string::npos) { soln = prev_soln; } else { soln = smallest_containing_string(items); } printf("%s\n", soln.c_str()); prev_soln = soln; } } ``` [Try it online!](https://tio.run/##7Txrc9s4kt/1KxBNxUPFsmIpb8vyVjK7mUrVjGdrk93ZHa@PRZGQRVt8DB@xPZP89ct1Nx4EQFJyMtn7cHWuSiSBQAPodzcaDPP84CIMP336Jk7DTR1xdhwGZcmL6mRgNJVVtImXTlMRpxdmU5xBGw8Ss@09D6usMFvqNCsiXvDIT4LcfNAGGGwusiKu1hbEoCiC25PBoC6hN0uDhJd5EHIGS5wPBu@zOGIRX9YXflQnya03mUxG7PfBxwGAWKURX7E3p69/Gjx8@A2Dfqs45dQg@q1yWEK18gAWL4ox8/1/vPRf/u37t74/GtgDzEkG3/A0ilfNFH/@y6u/fy/m0IOo7bOmoRGd8yyzbMPi0gc4CffK@DfuVywdDX4f4ISrrGCqMWILNpvDxwP4d7xg6Zzt70eIESb/4hXzUnYfey7YofkE/wpe1UXKVsGm5HP95OOg@V/2qIoaOgCaHz5ky7gqeTVm11lxVdJy6pxVGXv6mAkil5J6oiMsc8FqwMjTx341H4RZWlZMrl/2wA/o9PTxnCZ4HacRy7MyruIsZdmKpQfVmkFH7I@/bwYKHrb4Jd8AH3q67WbMNNJgw0A2pJrvv/rxzcz3aVswy6v64oh9/913LMp4mX4La@I8wX3kRfY@Bl6s1pz5ecRzv4atAXDYWxmHYwUgAtaMK86u10HFcAdJkNbBhoWbIE7KCTvlwNy8IPjsu02QXtyTQ@XqCtiznsALATMVvwF8edMROz5mKb/2ZduYqafTkaCTAjFXqzl9dcSCsMIFZDkvAkAhSSIwErs/G7P7U71g3JjeDquCKyTW/Sn0mRG0oEyYN8SFyZHw73DYMM4RGy6KIfOKkdWGTYoGagujsWi/MbrKHUjO8v1lHW@qOPXD6rfNBoDOQRCAH1FUroMixcUNGzIfsTRjN8@fMqQmbANYrg6JUYgpgZU3xHtBeIXELDfZNQuziA9NtF0B5g/HLMGPeSNVc2g5RjYEKUpcKbphe639JSNXorDnFcpa6j7BvyUo0Ku51fzR@rW/f7VVDpO50hKGytvEV3xza6gW0QBIN7DLb3IUEpCN6UjBUADqtAVCNfUBOdRAUGL/JrUEMFa5zoqKo4iTLoA2kI4lvwBKsWsQCBYw5E0YK38vB7LnZQYzSA3iybZgrOAsFT5N/Ze958UmyIGMSZx6wQSbPeC5pfw2musuJ0BpdnAgf7rEhaH1EmbSMNgB012Bmkv1HLhGtfco04DtN91V361EpRGkXYU91cYSiBHVuQ8ym2iMSD0A63A7UzdlJTofzuYtDMYkAvBxLLrI7aMExOYGySbBYqC7Yy0QfWpRE@CdyCNAZ/H5iN1bSPIdHaWg0LtEQsAU9kXjiKECcDqbq74Uq77sWPVl1yS4RrUqJKf4fnn@p1ZP6g3Mctn5RGg6NfoLdtu34x1Koq0oPg7a33CX9wB6SycR7Sd5Xa591IvNkreypWIZYfXfBcsNB7GtiltWlzwC1QsGD/4rsw0wuW3XRRu4gDfEvD7a7oVl7Q/Y8/lA6G72VvQm2JJ9Uc8@R0BhVnBA@XOxUu1R0NqgvWMip6dkTfAssNmcyhM2qcGVmAw462a1MvibptKGAv8kzKZR4E35bTzJK4DOBEoa@BKvchpzno@Dj8L1eRsnOaB5HZRrMMyIcbBhAbm9wkkn7bPmQeQgjzo7sm9u9oRVluMgyGA10YfVktYJOKHZkpe@jT@arYU/WP/syVM0uUDgOAX3DYzxLShdMALghaScg86H/Sw52HBYQgbmOYEuJoAyExYDTckmCyLQNrQZkP6k3gTIdXUeBRX3BRrJCdUAtCv5vCEW7cWmn7Ev@0HBSZEIMCOTtmUVVOAsScQQSn2kkmez5LjFeC6StJe6Jk57NH08ffJi9nT2bPp89nz6/O8//DA38fEyijS7reKirNC3TSEgwn3SZgPAwgVPweUDZJtDN7wEE8s3oLdj1EvLugKxBexK0dZ912x/0chJ0/pfC/jv5ITNHpmtD3DZs@ns2ZMXL5arx49mT8JHz6xlNyMfP5vbs9DE/7k5pIStLcoJkhG9fVDY/EZZEaRfr5SSCILHJztLh09yBqivqcUeJKGSe5SEzURfh/4i/JaWDOyXDX5mct4WWZ55O8aRtQxqkDYacsSqLk/1Hj2cNDqry2YpbAG/GnwvRwqmFz8Ux8/7QCRBiZ5399oRp70j4@iGIb33CEa72/U6Bl3p3atmZ9D1fMeOaPsE0cOPfSBmL2ThlVuacLtlJj0klqEwNt9puqtJeR3kXjUzkKeVmcSQyW/KPpq6cKcqGttmtUN9/yUta1SqnIWoJVJi1QAjUYJJDntWV4LTwdHp5epKO@CDgUtKFEHYlSmQBl/JtSteGs0Hd2KiLh4yPcZceIy5sTb0FvOxXo8nvhjM4LLOFjZAYZIBU3VGgM4n0nGQSo/t7TH9SDsQi2ajHXyq@yvPBPwcz24cS1q2uVJlbqzu22JP3EOz@K0CBKwSRJFg7t2r7pjZ6qc8LMc4tPo1blfLWDUkMrwYZ8WmO/H44RP0S@KIk4syO3gEXhaY0Asu@LJkOS9gRHZV553RxJMHgtXB/jzQzN6jaiyvghjsLjrE9BZ3KxAlgBScIa8Nl5jfMhxJ2hduKR@OOuyjDHv7fNYGq4bBI51luoRiKlexKOWGzyameTg6ogcEfCzGEir9dh@BPNWpcs2d7GXIp@pqNI0sZ/vBgD1gPzYRDGWJJtD40HatpVMNDPQmzeuq7A@vpe9sx@mWQ60ahdqTuhEg/xjkOSU5eHXNearyqJQpga5xyLun1SnDTCZOxGxWEl71VknREwkdB9nBEW6RRJE88DUIhJrgYFVw5CC@im84UCGe8In@Sd0VgJQjKlXShRI86MpzTEeuWEYJUSHvsEaND2tzGEbpreHEzfL@WvAwS3JyZGWHElR8vaKFjEjj8yBc0xQ2xuTeKUq01IcDVljU8kgnNVQGaoShi9pYkGR1WlkzODOdiHyWHGCFT14n94xdzmlSpkciAyQSPNo2Hnp2z99bIauZPmryRgKMEeBCpKZQ4ntaSBoxdzq4bsODRjk9YN9TJFJxBnoVlMeGvw9S4ZAckAehqDYxBpnjX1YiWMwBeXjGwNlVml0Ljkwz4YXA44CJBBviK1uZAIKUmGxM/AUsp1NT7B3CTXiQlk2ImaWg/dWaTDAwMcarSPMQI6xgCX7PmIItcIFKFXIhx6yKLEHLHEMsS0Q34Uj6l1q0g/SWVdeZzFv1YOGvRZatjsyWt3We47R65TrPiqsHLYaYkAgRgXaZJVwInAnnKhaSKPc8AdVzu8RoEpglp6RshglJZWrLPEhT09EDENUalQFgN0Hzrng3uGX/HP9r/MuEvQIHEUzkLyLHG6wqEPl/oSozgQB1AX1hJZPA/xzjplLol9Ql5osdCrNfTFQJUoKLimmENehOnoK3y8OgLsl5LXgCeI@IBzWUfpbbwFJSCO/fg/s2bqEizdIDk7qKpCYIRVwkrJxNo0QjhPhaKRA6FILld@FE5smBUYS@VPqbMIS@eVZvIsFxcYkUsPk/At5Er11wSIHmrcYDkgl7s6LdZajCCViIGMJ1WSxrTAp4Zz9jlgVnRLDEekEiLEMRgGmis5cAEz42k5C9eB9nNVIK6SLojCxidHzouvenyhFUXnorFFaqHJN@wgYpLeudgnbEZmERjOZWFKEtsd3VTgf1JMpPW9nxLfnp0@1JaQwBLsntquK0KyNsHI5wPO61TklUJloqdTul6@y42aHOX0ufb1@Pbg4/xHwtGjirajzyBkLrnKQ9uk05ystTeNP5bBcwm4iwNQNY65kJrJMoLf9IJPpVpIYka3cBhdEfAbS6n8nP8yaYaZy4XqwbuWejd5PX70/AuIcHAyc2@k6lGIGJZeZWKDuSWstNU3@/fx6rOv7HHVlVW@//E6zar3QQXM/T/2fXrngXKx7oZJ/cdrL04A9kaQwmjYFhijcG0ctBiwIq69Peau/BnzFcsY7Lngd9JB6d2wdKmg4yN3A6@kKrYwITnPl5O2riBUMi2jLWoUhBgM/N80OXNBGvwGDbEaR97mCEeH8YDwYsgQavR3KxCqqdu7OHd8mFKPAaWjMdsfvlv9Nho9ImIXK5Nxr1J2y2cTB4@GWMaRQ7zGwwZoaUCmV98jhuOUyA3R70hloeAMnqx3G/qAMFZK8OOujajz3Wytg1oM4kgPN5rxe1k@h3NTpfZHP@gMkxyaT3KdhS5wO2KbiPRmJI56cmqk0U25Rsw9MLMM4QHLk1N0ZIiGwl0gFlFRSVCuUADIWtSl01JRzfasAYXMm6zGg0sXKFuCCVLHQP0fvceJPxf6AZxih6knDqZEHFyxR2YK0BBOBxgiV5XARQS@uMEy0dRYgqzI5FFRJVJsQYTmF44i5uCfGIL3fZdvjp1KyUZR4uy5lD90HZtnigLeFVcMUpimyrQhFcxUAjSkSojEPJgyJcm3Bwf7ixkruJA1fIxVjfyaV/nk3Bk8HdGtGcySwuGe3OVism8QUMtFomsDbLWAH7W8xsXBRZDfRG7pfJUkpYWvEpqh7wBVJRSWolANhrTBXeBFRuMZw@AyU@nB6Kj5n4ePpsSOJDcOk4jPxiE4iaBFYxnA4p9g5a3gc9RZBp1s7HaMbFzJLW/@R1izicioB7cxc/S0RI3jDzxlisTfF6IqJzLAKAh3VcrqlWxIAS1bJUTwqOrszujtTFsfKvfqPdz/bONXfp4tvLLr5y/ZV7C9uFuexkte465banaNk0yedhvMuSxX3Rua3H43O54FZz96K3L3ybm9sqvNZd@rMhDT184ghPCZeih3cw7TP/pURVSTpBjpvTYdq2LEeJaY4yPpjCyMv9qSqxLC@3VBHEjqyflRgyXbZaL8/nnSSx9BLE@Xt7xs49YL7L3qhGe3D8V8UP6MCxRbjo8@PGTa6k27NTfy72cVu4p8uvVOJn2oLX8QUe0qO1RIkFB3JJJlTnbAHTE/ay/WAdlJZNSVU9nz42aVkolm/qknqujOOaSSubpjaPv2Hfp@AjaeW@j2fyVk2TOKukVPb7oKAUYR4UoLXBYJekc1cx@h544FIXLAoq0Kq3OW@WLy4YNCXzTXWhcSiszkT7hB9WZi/82KpRHLUh6T1Bz47Sw44Rpr9wTBV/jiv0RmZbXGo1OHZP8wjlzWleGB76q3qzaeYGlSbbzux49/wPOAS7/QFjWkfLn8/vGs/nWLZPhK/ToLg94CmeykaSLHiGw@V3sHVZQYeP3AQSYsDUYmi0gMf06ASL/5acjoYOCdTY8iezzSa7xglvwZJPsUNDCIPdYKf9qWJhecZseWcDNIb/ly1Xk8ryNCVjB4u4hA8L1ro2suzzRX8E7iGnn4ywuC6hk0SAcTpQqMFbCNcxfx8YcaiGYp31X/kgAmlplSu@wkw/pvuPaH3kx1AdCU6nO8qRE6t66RAvuRyOKTx32YJiFxbdpkESh1jJcAHaIkEssis8DgzrogBVRoc9XGhAV0W5Grrsp9/FUav3qGM8UMe7oKLvLvtqlcX3lNLQ1bQhKZIjdrq4/1s91mpT/LL0k2j6RiW15M/WwrAdrVnb8pw24B3QY9afRmhNMNpRqS8NrdyXHLu4X47/N/bYGCltw/8D2@7kmysh71eOE9WqI4t4uEFz5kk5GLGrqZIlNzH/Tvnky6yqwI5w0I@ZPEuUcoACQJKEJlFBGruArtcx6EMP17sJigvQgKcjPDOFWAqP09f1hazembgjIcbAc9WACj54BVB@rXlNlelglOoQFsiTDNyIDQhzGt5OuhJCqghXQrAqtMle4r1Pu8x1rLufyMJTmtceJwFLTSIsWQuJbypRk4C1Kbfs6kCoibZfa86u6maVrqr6goR2CW1zmNe@AKZKMktVGzrpqXqzjI0OtKxC2zvkskR/WUPWVRT3DnYaRJRDaeo8Wx2/MFho73qKTjH7oFukzSrjbj@ZjjfoAGPaB1uJfPfpaXdpnVFbL3JjIF/kLrgyD1YLeC4VFxl6V9jp/Ft2AcKU3sXfgx3uuQjpAjn62ijYEpLNqcRTXCcVNTfoPw62gTGuq7KFey4x76PBmzQseIK2W3H5t6XhxBlAJ30gfm5KdTAdSDcjIr6JE8z/CR9u27rxamkq4gd1kzjUeWNj/r4DrracIrheQnkaOt0uaLtvuBxxwWDUf3DzwYRzciI3AcM98Q2LTEejrhNDibS3tFNKS0r/rF4e6JI6zEHiUVBc4dGEQ4hOkJ3@b1xNxTci6Lx/O9td5P5xwnemeegKC7INbr1zRL/w6ECxIaDA6XTL5GK2ResC82cBkSkNVUvY9ye4/BJLo0BZA68b5Jircn1KIYvSJ0xX8huR8NsFWHGRsHqYc@SivlN81fVYFdvwAL5jjVOaXW8F@wH4M6TaFlMr7O1JpB2z2VZltluhdVQxONv6M9eKJUb93pCld1RzX0Jdtt8ix7YsA7H7pHm6U5hdgRac4wm2xqEaUp9At23/tDlrAhgdicz5VuxFWVO9pbwwXRy7lZu1J3ay0CN30brtd@m7RuTynWmg9zXM8/lWkMoPtmPM/ktLY9NVGn0p00nHGLNyMiIV01NCXq18cHc0TOe7yG3cogGc6V2bl2vMoP3oyLhqU07N90ps2XSj4tQevD09VXVmTHa@BYrYkb7tUU53djWOj9Uyd45Rl06UHOwYsIXBFA9Ot4jK/r4aeVfHa1clVoRRVSJPb2lxuib9LuWG@B4EtaQmgOq/Gb9T9LoS8V9TuBwM3CVt0qROmLjggpdzyyP2gRZ1dv@3@vwD7IJSB/CfvMZTih/iLkhP7gD3tg9SoTeokgENSvWj9sWSrUkR6wTiq6/6qyzb@qXiXrpXo0b3nnP/9J7uH@ta4/alvW0ltp8Vd@@Kud3qPbvIzmjRB2Mmc3YmeeRZnJnLPzBhO5f4fy6wJJ3urEv5EmcdwaYUIUopjqnx7jtVbUikyeNb9T4U9dxvyjmkY@xtffVH1@2P4bC59@FUcqRyS3OnkEOuXBxzqGuZw6FZSt0MZuo8ZCJrQ8y7YpLtX4PvFzWbFQOPmMzkmdD0IiUi4Mm88/6T1pR@xx1CeSfY6aPOfk6YlVKQ6QCrCitF2yM3HuOCb@IQM275Og7Fy5Vap7F5EBetC1cnBMnNlvecwHQvt6/mzai1ojB94Y5vxd7NUoyajSS44j6u3bNfwgPdBN/gSWi3bKjYyYArMbxY9GzGYqGiMofSi4JQcxltolS1fShAyoIyejJD4dCEXsexQqbzU@FFOMfwTbVPCnq4mdHFsyKSk3lUl23kMPtpFfNmX4g8mD510nxSLt4Vt/jOGDyK3sf/Dk7kcXSHqkdoTWK7TevmmZ685@TaFSXqrwHO7@Jr9LNq732HZlVUo@xuAAspFnd7i469XoOXO2B@Zj28rfnsiQzEjjoz0alxDN6lElu@wGQyaQaROkQ2gP8Xf1po5Zg2JxYNCpWVtzVnN8pxQfutsYRsY/QWR4sEqVGJuvS1nwe7ai1hLhSEbpkRptbV6NsYU5/a4tos/UzXulsWdiwqLzrzF5am6H4709bXt3XcxdYQ7QvXAgkdmtbF5eG5UnvqGjbhDNg1Tis6FvKU0ZfaCIN2v99emteUm/ciTNuvBTulZvg4XrBHMxTpU5M5qOv@fj63ajxV/UDeWfil3meZd/rz4Too2LJenb140RFwlKl8pyb0EGY1WzH6PgQJAS7sum3hFiZC/9Fn03TgnJXQoRceh@n0iHZoPDqUa96KebqYTsePDsePZvha0IFjN2z2Rwxp2hnvFZvQykc73y0mecohf28wIrtv8TDdS8INTiQlhlL@e0yMXolQg6l2kQefPv13uNoEF@Wng59mnw4SOggW1y//Bw "C++ (gcc) – Try It Online") And the [prime-only version on TIO](https://tio.run/##7T1rcxu5kd/5K2BuySYtkitSlm2JolL2Jt64LqtNZZ3bJIpuasgBqZE4j8zDkrzWXz9fd@MxwGCGpJzd@3B1qrIpzgANoNHvbkCLNB2uFosvX74J48W6DDg7Xfh5zrPirGM8yotgHc5rj7IwXpmPwgSecT8yn7mt/Czz780HH/miSDKrE7dGj/zUArBeJVlYXFnjlEW4DgsL7ipK7@5GV2edTpnDHFjsRzxP/QVnsJppp/MxCQMW8Hm58oIyiu57o9Goz37pPHQAyDIO@JK9P3/3Y@fbb79h0G4ZxpweiHbLFBZWLHsAi2fZgHnef77x3vzl@588r9@xO5iDdL7hcRAuqyF@/4e3f/3eGoOePGoQ6tE4yjxJ1izMPYAT8V4efuJeweJ@55cOg59lkjH1MGAzNpnCx3P4dzpj8ZTt7weIDyZ/wiXrxWwPW87YgfkGfzJelFnMlv4651P95qFT/S9bFFkJDR701ObhSk2PaIUF4SoscjXHKP3kLdZAkizuyTdTExy@T7Nk7s8FFC/txaMVLzx8UfT6AzY@OOjjgIBkNof@vBiw2yS7yWn9ZcqKhL18wcTouSQW0RDwMmMlbMHLF14x7SySOC@YRJhsgR/Q6OWLKQ3wLowDliZ5WIRJzJIli4fFFYOG2B6/33UUPHzi5XwN5N/Tz@4GTO8SYBioBInE897@8H7iebRwGOVtuTph33/3HQsSnsfPYE6cR7gOwMTHEIi/uOLMSwOeeiUsDYDD2vJwMVAAAuCEsODs9sovGK4g8uPSXzPAdBjlI3bOgcF4RvDZd2s/Xj2RXeXsMlizHqC3AMwU/A7w1Rv32ekpi/mtJ58NmHo7ljunQEzVbM7fnjB/UeAEkpRnPqAwyYDigTzY3mTA9sZ6wrgwvRxW@De4WXtjaDMhaH4esV4XJyZ7wr@DbkWpJ6w7y7qsl/WtZ/hI7YFaApAOPb8zmtq053nzMlwXYewtik/rNQCdAucBAyBv3vpZjJPrVtt8wuKE3b1@yXA3YRlAcuWCCIWIEnhnTbTnL25wM/N1cssWScC7JtpuAPMHAxbhx7Ri4yk8OUUyBLaN6mx7x54664v6dRbGljfI3HH9Df7MQbTfTK3HD9a3/f2bjYwfTZVYMiTsOrzh63tDlokHgHQDu/wuRSYB3hj3FQwFoIwdEOpRG5ADDQQ59i9SLAFh5VdJVnBkcSGJCuSOOV/BTrFbYAjmM6RN6Cu/zzuy5XUCI0gJouSYP1Bw5gqfpsBNPvJs7aewjVEY9/wRPkZxNZe/9ae6yRnsNBsO5df65kLXcg4jaRhsyHRT2M25eg9Uo563SG@f7VfNVduNm0o9SLoKNa41PmxGUKYe8GykMSLlAMyj3piaKZHf@HIydTAYEgvAx6loIpePHBCaCyRNA5OB5jX1hOhTkxoB7QQ9AnQRXvbZk5ncvpOTGAR6E0sImEKhaRwxFAC1xuasr8Wsrxtmfd00CM5RzQq3U/x@ffk7pyW1BmK5bnwjJJ3q/RWrbVvxFiHhCoqHjvsbrvIJQHdkEu39KC3zKw/lYjXljWSpSEZo/Q/@fM2BbYvsnpU5D0D0gsKD//JkDURu63XxzIv8OyJeD3X3zNL2Q/Ya/007Qn6zn0QPgi9JGGXtawS2SDIOaH89tR5HSXBYPdW2Bs0anjdModZSEi3YHPjYnEBPaKsKi2IKQHN3y2WFM5qB1iAa0/YjOUr1UOBYWW48SgsYjwn0VSPKPZADmyM/dB6EmfRTGKWwJVd@fgVKHHcH9J1PFrlwNUhSXXE/qCGZGtfkhLn8M1ZYRobYMusRfVhP4jIiG5Lnno1RGs3BKMx/cvQS1TMQQxiDqQeK@x4ENCgMsFhizkE/wHrmHPQ9TCEBVR5BExNAngjtgmpnnfgBSCZaDEiKqFz7SKFlGvgF9wQayWDVALTZ@braLFqLvX/GuuwXGSehI8D0zb3NC78Aw0oihlDq4S71bCIdOKQ4sIi7jjJt314RJU4Oj16Nx@PD8avx8eRwcvzXP/1p6rb9dHEIEq8mEA7uDscvxkfHk5dHh0evj18dH0LnQa3J5NX49eQ1/ntxdHzw4qihCQB5MRkfHr2cHL46PDi2mzxMzb16EwSaFZZhlhdoo8fgR@Ie0Eb4sEMrHoPpCoRgdl1zcFxu@Rr0T4jydV4WIH5g56WI0m2v2P6s4urq6X/N4L@zMzY5NJ8@JySOJ6@Ojo/nyxeHk6PF4SsLiVXPF6@m9iifLnCHLn/jUWh5v90YUsZcWbQriJYo3gP1xu@UzkUKbpVTJITAPpaNpXkseQME/dhiEJJRkn@UjJmItjWaF2EUqfdB29vgJybvbZBmk96WfmRb@CXIG@pywoomu/4JvRxVUrtJwytsAdMZnC97CrYXXzTPi6/E8dM2cJGfo8/SvA7Eb2vPMLhjuPdPCYbb7PYqBM3Re1JMLqDp5ZbVESoIYg8/9mFjWyELf8bSC5ttGpLKYhoKe9OtRk8xym/9tFdMDORp0S4xZNKekrCmZnikYB7YpkmDavtDnJeocDhboJSKiYh99OhpBHJ8krIQPAAGYyu9F9qR6XTqG4vMCWs0WdWgOLkSvQCir/60sxNhNdGVaX@nwv5OjRmi7Z0O9Kx64heDQOrktIE0kNmk@1lcEKDLkTStZjWZX/t5@pTpHtry0kphl17CqJtJfDWwgG6pjEIwMXv2w4EkDJfgVfzOar4pIICoqHCwkTeB7vwgEHyzfdYNI1vtpHGLHxtaKYO3pqmcdpUV7Ojnih4Mo7K2LtO6e/HtEZqJYcDJYpwMD8HoBathxQUr5CzlGfRIbsq00RE8ei64C5Thc81fLbLOMvKImncRYqbxvl2CKZ4nvxppsTvH0KRh19O6cElpt9@grGXEos2FqLBqaF8SmqaFLoaqyzIlXfHdqDDFRxGcnNA7gj8Q3QmbXmMzgULVrqhr4KqhIRVUa@NR33KCnnfYc/ZD5YVSpG8ED7@1XR7p7AAlvY/TssjbQyTSp7FjLZajox4KkSvlMkD@wU9TClTx4pbzWMXCKdoFTcMFbx5Wh30TGfwSo0V@qtqocPaZhIlNbecVF0acSP7QFfCDAjtcZhwJiC/DOw7oD0d8pL9ScwUg5ohAFS6j0Bw6VhwDyUuWUChbsHucZBoL1pLQqdULwoGr6f0544skSsl0lw1yUCflkibSJ@3C/cUVDWHjSa6dvHhLetTACo2en@hwlIod9tGRVAvzo6SMC2uE2khnIhIpO3zFUHkZUdYCtL3ItqAUZYeNY0pLQg0qxK3hPvcaqXRQp9AqvH4iooUiGKj1/0HPbvmLE7IwQ41VjFGAMQIc4KmrTfB6mhkruVJrUDeNnlfS8Dn7nry9gjMQ5CCt1vyjHwsTbEhWkqKTkdHJ7P@mEMGCFDCH@SjObuLkVvBAnAhLC177TARjEV/J0gTgx0TWA6Jo2DEdxmQfEG7E/TivQgxJDOpGzckEAwNjvAK3foFerD8H225ADi2Yeblya5FwllkSocEQRv6adtyEIyku1yLEj@9ZcZvIGGcLFv6cJcnyxHzyU5mmOKyeuY7J4@xBWiImJEJEoCVPIi5Y3IRzEwrel2segYi7n6PHDsSSUgA/weC10u156sexacwCiOIKxQ9gN0KrQ9Guf8/@Nvj74B8j9haMYNDJ/xD5AH9ZgJD5O4pMEwjsLqBvUciEwd8GuKgY2kVljrmF2g6zf5ioElsJZjiGka5ARvMY7Hu@8MucDPSMR4D3gGhQQ2knuTVMJfaL8CMYpwMHFXESD83dVVtqglCbixsrR9Mo0QghulYiixKIMP0mnMicChCKkNBKYxCG0P9IynUgKC7McQds@g@ANtEzERSSoRotMZk2Yu@XtLoElQYBWyCGcF4WyRqDAt7ZzxhlwxERLJGeHwldlPmgAilP52PAzyYS0lAfw6TEncJ9EfuMJNKyER9@/P2PJ5JuEV0855VeicLVVSEVGpAHhqtrJMEBX4tFmd5TSllUNIQigWUEtZ/lrMrKYrjxlptgAGm41DQrY0qqRswvxJRIIplDflv3u86V0azcJyeGofQeRrCFwlYqqXcOgh0fC/VpPHbcO22s2E3tSGZLPujcSQJtSMOcb869oEd1TSZqEcZNiQ8jB8ixjMJKBqqEi9RHduaituJqhTpNI@3jfd27yvGJ8Zw9qM2q8l4qCE460O3t7hyln8hhbHy3DZi9ibA0A5jzzgTWuCmOMSnyWfILpT3dJiDr2r0lp/mF/LysHL/Kzm3FupE2MVpX6Ss1w@05sk7Nj/xORaCBiGXSQchpEjiWTat@fnkcqdZMpx1JVRse/ydItV3oILiWt/9Prk2xASzsoQIWcjzISAFTJolD0MYMdGq4NjY97zg7oMJx7lJb89tGd0U6dfIctm1x/9LOhep9kHGU8/5Xah0TmKDMx62ocnUMjnB5rEGQAgNfmmny@tYEvACFbbvbdojS8If/bTwYsAQaei2ci9WFblDV7t7EF6JwsmuNdML28n/G3UqkjRZI5b1@vz24tYmCwTnJQww52T55hTHT/1Yoa@PHgWMwAXaNiWm3endAyievQTI3aqE5C7ZLfTltFxqwl7JVw47qYqmnzImTVqAuJIDLaas9tpV8dlVfX6W9/h3lJZMRTkGFtcrFlZ@JiMqJw8ttRVm1Wo0efe4LKDCvZwfP@myPHe4S1TWpUm@G4EIrVuT0wTFrHdyw@oNTilMFFrVDMlLPRMFdztY8XoHlAi5Qve7OcPWR50SYJy/8rFAuOoChcISS5VUZ1zMNGJ1mWQwe9PXo4D@JJL5qBs5qGQN/wdCLggdT4fpxgBdgHFuiG@NiT2B7jXBY6oeac40wJy5WRbTrpTht/pMpcf5E0xqgzJN0rjJuKsZCrirWMhUJCyMs@eXC6Z5btQdoYlBUQYVmTCcxRBccXdr65Obgw3oSNa6nRXnmXJJwnV7Nrvug5RyWcUVr4d9wijy4Okg45CHsPwWvVJQq5362uDLh4PqkF10LNtWlq@jr1RI@j1PmmEvfrorMkczitf72lIoiEk/AQHPBBOaSjBVb@Ald@FWWlLDfyFkykE9hdSumgZIajLBYVKpbQSP2DgPadz6VaHXHr0B7dscH4mMiPl6@6hJrElxKE5NDYgJRg8AsuuMuxWt8x@yjtwgyTtwYniZcjEZqxUvujojdUMF/a7zrZ4kISRtmTgOPqRQy7JFThiNH0VKG@RXVlxlQglKWAkvG0adPmkMkohDjX16lDC@eXmrq0sX91010VTcUn8xs2/G6kdSaD164asAyASSdL8Jtij9sC4vYGiW8lBN2Hl9fNuq0z59N/WJ318@aF7x50Zt8E@cUSkO9V11mVHvpETX1FGOqvewNx22WVi7RnJM8kf2mlC3eFJrKMTaVh8Mx9LzeH6vy7/x6Q81OWJMTFzn6udfO0@vLaeN2WjLt@hJTudXKe0C4163miTa7@b8ULaHVzWaLWZvxPagCXM3muPqpYx@XhWu6/pXKj0098i5cYeELalrkdrD656R@dY4AMD1ib9wXYCVY@ihWtcY6MehoN5auy5xaLo2E5MgJgarF43dY9zmYfVox7GOFi1WnKJLxlDr56GcUkk79DCQ@KPuc5PUyRJsIU4olmKN@ARL5PuXV9MXhJyNwrCufjaoHlfRvExwwM3vip1b9dN@FpNcELRuKnxt6mLbGKVUY18yo9zJEVt@tCsciS10z3xaLA29ZrtfViCAE5bMLOzRx@W@YENstCGPYml643N1zTfEkEe13GfvZ/ZDHWGQQyN0YkTEsfgf1mGSUVecmkAU6tw4do9I8pVdnWGM855SBPCBQA8sETdbr5BYHvAflP8YGFf4NKoOltof1hbIasPnOOmsA/88d65QqbPVWhjU04hQ@z5hzkm3eZr4qAqv8A0o31mQDuQsjs9@fyWgBoX5YZfbQiLIBSUdjIArFwbYPLRmDJleUgteEWedliJk9Zd6j8qWEIHGUI1JQuXpN2CYPdXFSpeVr@NMde/I34PJGL/Tht2QLa6rV8ZV2x3mnKT9OUfwAgoO8T7LYxNk9u1YRHRXKW8JmAt@E/KNvxIw0LKuG6cYDyRfnVuX5W0woYlbxhOiTTF@qosNBdUPZc2SVhR7gucuDgcTBgEJqdfFALjUL7mM/ChdYqbUCZREhN7Eb9IsXZZaBJqPcMhcKsE5OdQWdt/Px6sRp3W/oD1zaW9F5pCbzyjqx1VJQSIe0u6RHTtj5bO9TOdBaU3yz1JN49I0KRMuvzsTwORozLqWdV@BroAesPWLnDNDfcohM2llyXbLvbC8f/G@ssbJRtAn3Gyy7kW5uhOS4qdnQTlFuwBdrtGZ6kh/67GaseKqeTPug3Ll5UhRgRnDQk4ksXZB8QIEh5Ci0iBSkQR3Q7VUIerGH81372QrE8HkfSzQSlPE@uypXsjpxVO/5MyX3oQ1GwHkBUP5V8pIOQmU8KBcwQR4lYEWuganjxf2oKfSqTjxICDM2fmlLNbptwT5UMNDtz2SZPw1s95OQpUgRwtvB4vtC1EBhscI9uxkKOeH6Nebo6pSCElpFm4PpHlioMvDu4WRV9J6r6vtRS1mvZXVoJ9061rBD2Fi0b6lDtiPC1RGJhnkjKQJO/IAidVWVfbPee7xb6eJnjO4T@6yfSDMnD5s9KspeUn5y3AZbSYfm4ojmeLRxskpEd4EVycKsiwdQdECdsThi1zrDRjfRUiHg0LZO/gms8GkdIU0g@782CjY471My88SlCKIaEH2OziYwxqULbFZPO07b9uB9vMh4hGpe8QOWDmm73wA6agPxc1VEiEFnOhcX8HUYYZRZmP2b5o0XJMTC01T3YSy0PWWM35a/djkawbVuVE9Dp1NfrsWP0xEHv/rtednPJpyzM7kI6N4Tv2G9fb/fVBAgkfYTrZSC39KkK@dDXQZGpbjzvAgLzDzWNqIRZKPLFBZj8Rtt6LR9OZu9qvZ@wt2icegAI5INLr2xRzvz6JBCtYECp@MNg4vRZs41HI8CIoNfqq667UdQ@TUWbYKwBlo3tmOqDktRokIUZaKHxu9EWHkbYEVFQj9iZJuLWnfxq64UxZSVD79j9WWc3G4E@xnoc0Gla6ZUePpUIu2UTTYKs@0CraFIqbas33MtWEKU79W2tPaqzq6pK2M28LHNy7DZbdw83srMdYYWlNMTZI1dNaQ2hnathHGVWwUYDeHy6TZA5LqNZcZVwTAC5tNN2BeH6fHSkzgPgR6h30YekIOdzRi4r/LLcMYOpxv3OEiq6ldlVeozBhvH05bl2Uz33EaRrh2pT6qSCXuhge5pmBuwRL7zuMl53u3I68A0A/tfyybS6seIs3S3xVQoUaVW0dkdJeOtdGWcugT8aQyYhzHNyMTJiXE0Mx8b9znJ6MK4v2HxlXBWa@k91UMWF8aglxugiJXpI3v5eGtToxpFTXdrH@PcoLe9tTqNqPh9S4cNJKqoeLyB2fb3Vc9dDcxtBaUBOpqRrLOgyenDQbtUTeOtRWpKlUvZfo/NVuZtSk39VuxZw8YuUaUqssTE@Ua8KiM/YZ9pghd7n8rLz7AiiqzAf/IUZy6@iBOALaEVXOc@MJNerIqVVOjVr9zjhBtjRlZ@7lef9a8ybeubigrQaUrVu7WC5EcV6pYnP9wD4i2nBtz3Xpx4QfjxsCF8@ajoxbbIRb1w2a4vNp7o9LJJxA1lkRW9U31SE9U2L7M2nnqzy7gt1b7vxT2E8tgZ4o4KNIaynAtNwYEopFCzdXcOwOCxt/Wtfy@OTIHhOJbHZFgZY1UWFaz41a5b2ZUPIleCR/JCkGdJjKknun2H5@JwnxB44rJIGb5Du90EAr4Pz2FYEAeZysvAiuhIG/QaWdHoJuyCzYh2jfGq5cK1yL/hHhaSWQnNodlzsNlsbe2nJrMtrAzr1aeA6tVVTTN1c6a9Y/oZMPHZcDOXvPXp5wzPsNElR1IdCFLx17mIHORiEnK79A7L2p1RByR@iuFQdiquBH1Hma8BE99@LIszca1o64b33DoP@2yqiKsKuE8F/Xpg0i5u1CsY5CnWCAzaKkaeqgw2eVpGxFjMLPUz7gmSEhep6fOwohIanna7A@MystioxlM35EmRzmM69@YtPJDo/@zu5f/sUrmFgFQrrWg6LNvtVsdkO3ZeE/P2BUa0VaFkRxG8midO1CRruaNi9eoOj27XPdi1lhWO4lPRqXEFSsh7zW36TNUHjGSdpZmnt/A@8oueWTFXyyEpnM6cERzuEF441qBVdaqSMOloIwiIj6GoTQNZczgcSi8@EnWmdljd2k/xSy3wbhFI/TrdFgauphgnMR8OfUy766hybAkyPOR3i@23TszdGVPc2z3adkVS6jvYk6DiZ9HthMl0kzm6fS5b5kAxBdoxy@TUruIGWoFpzURWabh4qqqODi6tmygcmKc1mILotSSQ0BwDEYSCejXdoeSsaSs3X6JcFVCDpwgI6RhRdOtsQoyOj2TAELF9Fy4wp5WCthM367rXNNiinW5DOCNAnrpxQUzoq2/htGBdbNgePLVC9olSjVg2WXGFs3fmO/sqoz@@@e4/Ttgb1C6@zjSI@lGs0SKmoMPIEQ9CVCsExDEnxPXS63uwK/CuZR4n5epK5OlEUQwWyhY85jmdN8a3tgUJYzDF0YAq8StQ2THdsV2fuHHQQSBmzGaKrvcZ1j70nh08UwcB@m5a7m25Wt0PRDLzNsEp4@2BYD0V4VpK6ZF51wEiJ68Dwbj0KuM8uDfLhO2qe7vP8zqId@KuPGIafTBcLB5tPMptAFZRZthVt23KRKKjwQq2xQ@lfgyR0mATN1vkD50mb4/MExDq@nJyEFwByS2TII1i4F0OuWzkFTPqjFvnZyQ/TaYB8REGqjJZX9fRdmJGYq6ipHHrbWoNnDkeG7xJx6E3cm9bGE9PAjMFLhlvj2jouuMN01NC/KxxCpsnXtUvtiY7aUfw5LwM8@PlnlGJPoRy2wLiODQWQ7rCvOg8LrjuLnur5LQQ4MhO0ib9XU/s0KkMdHQppy8zj4bSqI6BxGB0WlMzcaav6NDvYVrgMJNJ5FiEoXgpTt3U2wi7GWTX2rONo6qH@HCsjg/Es1SMvI//Dc9kQXKniTDrxclmubKxjoaK5bovocNqm46aPOYeaPrTC8YUjMubry@N48PtlzfXpuRcqHx9ucuBSFsq12BaWHKt/tioY7bFtbN9DaZ8ff6OUa@jXKPRqBqLTEzcfPh/9ruZNjjjqlTJxKuKYLn2qLULtIr9hp60E@2KR8/RtdR2PadKym67d7tl@we2Z2u5s44GafZmXUVTY1ALszZKW1SddBLq3v8AE6lFY8az0bLeJt8qN2SJA3Zcwxtao8mGKOspl7tSpB8p9jfdeg9bdd3k2L27/pwewweYgYcHyPTnJlao6f5@OmW2ZyJqZ9PG00Pqr7w0HySlmtl5ubw4Pm6Is@ex/Esz0EIEH5Ilo9@7wDIYUmhQ0HVJAu0bWm38uxF2PPeDONOYcSyM03lFvV09adGqP91yPgPFd3gwOJzgH8upq55qk4zAhdg7Q36OaOb9rRfgYzdhPJnb3@rIyV32C4xY0XWuB@LaG@PJ@IB@bNQ4RxZN7us1x25Ms8WGRqqTqByF7iPFhpAUze/oUJtU8RuztvQHKvSaWwLUTUlKkiEeVsM3HqpuLwqPt45AxaIaPBqjoih8yygPm1/jSiuoe@xwt@XS/Gt/5qlLBb0nxokA1F/1MJPmi8i/pzgU1ZtsyNY0/JwPKkz0v379GzLcDgWYXLAVO60CfteZ7e@rsTb0V380wvxjVHEbOh52YAl@S0Ji4/KkRFFtHzmaJRcabIQngus/f2aPwX0bIS59cA2r@j7jfD4h6wnrfcgw3YJkijV/eX8jGQLV6Vk06CKBmG53u2@ubk4FwZZToodMvm5/p2smbBtziydOGrb1VnG6JmwPJPpWnpcxBdiXbguBSX2iYB7tDHIbxK0QWvvv4KMKEMJWsBDr3sPRtJFALo3nAIiUSWW3ZOUlweLIyoI@F8ZmiwGtNbhwQ@KGZFXny5f/XizX/ir/MgROmC3298cvvgx/PPwyjOh8hbhE8ctwvYpS8f/d3f8A "C++ (gcc) – Try It Online"). Sorry, but I didn't golf these programs and there's a post length limit. [Answer] # [JavaScript (Node.js)](https://nodejs.org), score 24 in 241 seconds ### Results * \$a(1)\$ to \$a(21)\$ are solved in ~15 seconds [on TIO](https://tio.run/##lVTtctowEPyfp7jMtEGeGLeh/@LQV@gDMMxEsWUQNhKRZLAncV89XckGTNJ2WoYv351Oe3t7t@F7bjMjd26qdC7eJrUVZJ2RmZukb5VwVNCcFM2/08sVkTfspZVO5DC/dDFs/sVjymMqY3oS1sVkBTfZOr2C98sXeqpllZNbC6qkdaQL2hm5FTYmbsNdamURWWjDOLIuaDKb0DImNZ0iJyzfUlIplbe3UQDRh3oAJaz0mfB/OqdZlMLfhQA453RHNzc@if/hya62a1bSLU0mUYqgzqPzcJGHJxstFQueHrMRWW2s3IuhFipqlTmpFdxsMM2JoW5wQ19jMh75MjoS1VPVxNTGJGPaBHJsyD7k32ok51VFQoECYUkqMosleOKOMq6ADXXWKvcOrjT4MyG2DTn8fSYpZOWEYWyHW8Ld1yaxeisYe8alwSLpek4bz8HP50SqXDQ/CraLougMhj9p4whFVS3JAgikJa8GOqBBvDKC5@2x7eGMLNjwuDDLY1OASbjaqDQ8dafsAflBWhHTlpuSpPN9H6c750JRd2dcB16VQGN0vVoHqnLoR6IPtOPSWGKe32gg7iQM6RuSou4HEFQJtXJrPJ3F00dtECWhhrsU5IwjN@NIosbzvJDL9GRpg2WzHHAOWNEXcpq2wqwEDnH0zZN5P465i8IUFMDuINxcrqSzfh4aEs81r/oZ4e@c7SmFx10GiqhJbCUzwaC8MvJibwfDtIwuRmXoDCrAwRYFH0@WUToK6CUd9Awtj1zdRZXaXBQ0@1NB7d8Kan5XUPu@oOZfCmpQUPu/Bb3PcfR1Y@FC4r71fKFGAvd9hpgxt/j0E9mvMt/6ndGZsNhqVtNKk1Z0kG4dKFCiwd5T4uoDNq/AmBZJkpiYmmV0HB7/LSrs4ourMZd4c@wWXoQJvUcu4Wf2ICZYJ3ILEHvsZl0bwgIz2BdkM21ON4etcbHshmLtMAD0MA9bcXgcs94fttgVLPqY412WcRJ6fcXh3nTZxmH/2o/t6U5EdBHj/TX9fgmH0qvuzavHb1nVK0h56DP/5yiWTCurK5FUesUeOfv0ojpIix5BesGU34Dd2y8 "JavaScript (Node.js) – Try It Online") * \$a(22)=231129413434717353759619679\$ was found in ~70 seconds on my laptop * \$a(23)=23112941343471735359619678379\$ was found in approximately 2 minutes and 40 seconds on my laptop * **\$a(1)\$ to \$a(24)\$ was found in 241 seconds for the official scoring** (edited by maxb) ### Algorithm This is a recursive search which tries all possible ways of merging numbers together, and eventually sort the resulting lists in lexicographical order when a leaf node is reached. A merge is attempted on \$x\$ and \$y\$ if the first \$k\$ digits of \$x\$ equal the last \$k\$ digits of \$y\$, or the first \$k\$ digits of \$y\$ equal the last \$k\$ digits of \$x\$. At the beginning of each iteration, any entry that can be found in another entry is removed from the list. A significant speed-up was achieved by keeping track of visited nodes, so that we can abort early when different operations lead to the same list. A small speed-up was achieved by updating and restoring the list when possible rather than generating a copy, as suggested by ~~an anonymous user~~ Neil. ### Example Below are the steps that are executed for \$n=7\$, with the primes \$[2,3,5,7,11,13,17]\$. ``` [] // start with an empty list [ 2 ] // append 2 [ 2, 3 ] // append 3 [ 2, 3, 5 ] // append 5 [ 2, 3, 5, 7 ] // append 7 [ 2, 3, 5, 7, 11 ] // append 11 [ 2, 3, 5, 7, 11, 13 ] // append 13 [ 2, 5, 7, 11, 13 ] // remove 3, which appears in 13 [ 2, 5, 7, 113, 13 ] // try to merge 11 and 13 into 113 [ 2, 5, 7, 113 ] // remove 13, which now appears in 113 [ 2, 5, 7, 113, 17 ] // append 17 [ 2, 5, 113, 17 ] // remove 7, which appears in 17 --> leaf node: 1131725 // new best result [ 2, 5, 7, 11, 13, 17 ] // append 17 [ 2, 5, 11, 13, 17 ] // remove 7, which appears in 17 [ 2, 5, 113, 13, 17 ] // try to merge 11 and 13 into 113 [ 2, 5, 113, 17 ] // remove 13, which now appears in 113 // abort because this node was already visited // (it was a leaf node anyway, so we don't save much here) [ 2, 5, 117, 13, 17 ] // try to merge 11 and 17 into 117 [ 2, 5, 117, 13 ] // remove 17, which now appears in 117 --> leaf node: 1171325 // not better than the previous one --> leaf node: 11131725 // not better than the previous one ``` ### Code [Try it online!](https://tio.run/##lVTtctowEPyfp7jMtEGeGLeh/@LQV@gDMMxEsWUQNhKRZLAncV89XckGTNJ2WoYv351Oe3t7t@F7bjMjd26qdC7eJrUVZJ2RmZukb5VwVNCcFM2/08sVkTfspZVO5DC/dDFs/sVjymMqY3oS1sVkBTfZOr2C98sXeqpllZNbC6qkdaQL2hm5FTYmbsNdamURWWjDOLIuaDKb0DImNZ0iJyzfUlIplbe3UQDRh3oAJaz0mfB/OqdZlMLfhQA453RHNzc@if/hya62a1bSLU0mUYqgzqPzcJGHJxstFQueHrMRWW2s3IuhFipqlTmpFdxsMM2JoW5wQ19jMh75MjoS1VPVxNTGJGPaBHJsyD7k32ok51VFQoECYUkqMosleOKOMq6ADXXWKvcOrjT4MyG2DTn8fSYpZOWEYWyHW8Ld1yaxeisYe8alwSLpek4bz8HP50SqXDQ/CraLougMhj9p4whFVS3JAgikJa8GOqBBvDKC5@2x7eGMLNjwuDDLY1OASbjaqDQ8dafsAflBWhHTlpuSpPN9H6c750JRd2dcB16VQGN0vVoHqnLoR6IPtOPSWGKe32gg7iQM6RuSou4HEFQJtXJrPJ3F00dtECWhhrsU5IwjN@NIosbzvJDL9GRpg2WzHHAOWNEXcpq2wqwEDnH0zZN5P465i8IUFMDuINxcrqSzfh4aEs81r/oZ4e@c7SmFx10GiqhJbCUzwaC8MvJibwfDtIwuRmXoDCrAwRYFH0@WUToK6CUd9Awtj1zdRZXaXBQ0@1NB7d8Kan5XUPu@oOZfCmpQUPu/Bb3PcfR1Y@FC4r71fKFGAvd9hpgxt/j0E9mvMt/6ndGZsNhqVtNKk1Z0kG4dKFCiwd5T4uoDNq/AmBZJkpiYmmV0HB7/LSrs4ourMZd4c@wWXoQJvUcu4Wf2ICZYJ3ILEHvsZl0bwgIz2BdkM21ON4etcbHshmLtMAD0MA9bcXgcs94fttgVLPqY412WcRJ6fcXh3nTZxmH/2o/t6U5EdBHj/TX9fgmH0qvuzavHb1nVK0h56DP/5yiWTCurK5FUesUeOfv0ojpIix5BesGU34Dd2y8 "JavaScript (Node.js) – Try It Online") ``` let f = n => { let visited = {}, a, d, k, best, search; // build the list of primes, as strings for(a = [ '2' ], n--, k = 3; n; k++) { for(d = k; k % (d -= 2);) {} d == 1 && n-- && a.push(k + ''); } best = a.join(''); // recursive search function (search = (a, n = 0, r = []) => { let x, y, i, j, k, s; // remove all entries in r[] that can be found in another entry r = r.filter((p, i) => !r.some((q, j) => i != j && ~q.indexOf(p))); // abort early if this node was already visited if(visited[r]) { return; } // otherwise, mark it as visited visited[r] = 1; // walk through all distinct pairs (x, y) in r[] for(i = 0; i < r.length; i++) { for(j = i + 1; j < r.length; j++) { x = r[i]; y = r[j]; // try to merge x and y if: // 1) the first k digits of x equal the last k digits of y for(k = 1; x.slice(0, k) == y.slice(-k); k++) { r[i] = y + x.slice(k); search(a, n, r); } // or: // 2) the first k digits of y equal the last k digits of x for(k = 1; y.slice(0, k) == x.slice(-k); k++) { r[i] = x + y.slice(k); search(a, n, r); } r[i] = x; } } if(x = a[n]) { // there are other primes to process, so go on with the next one search(a, n + 1, [...r, x]); } else { // this is a leaf node: see if we've improved our current score s = r.join(''); if(s.length <= best.length) { s = r.sort().join(''); if(s.length < best.length || s < best) { best = s; } } } })(a); return best; } ``` [Answer] # [Concorde TSP solver](http://www.math.uwaterloo.ca/tsp/concorde/), score 84 in 299 seconds Well… I feel silly for only realising this now. This whole thing is essentially a [travelling salesman problem](https://en.wikipedia.org/wiki/Travelling_salesman_problem). For each pair of primes `p` and `q`, add an edge whose weight is the number of digits added by `q` (removing overlapping digits). Also, add an initial edge to every prime `p`, whose weight is the length of `p`. The shortest travelling salesman path matches the length of the smallest prime containment number. Then an industrial grade TSP solver, such as [Concorde](http://www.math.uwaterloo.ca/tsp/concorde/), will make short work of this problem. This entry should probably be considered non-competing. ## Results The solver gets to `N=350` in about 20 CPU hours. The full results are too long for one SE post, and the OEIS doesn't want that many terms anyway. Here are the first 200: ``` 1 2 2 23 3 235 4 2357 5 112357 6 113257 7 1131725 8 113171925 9 1131719235 10 113171923295 11 113171923295 12 1131719237295 13 11317237294195 14 1131723294194375 15 113172329419437475 16 1131723294194347537 17 113172329419434753759 18 2311329417434753759619 19 231132941743475375961967 20 2311294134347175375961967 21 23112941343471735375961967 22 231129413434717353759619679 23 23112941343471735359619678379 24 2311294134347173535961967837989 25 23112941343471735359619678378979 26 2310112941343471735359619678378979 27 231010329411343471735359619678378979 28 101031071132329417343475359619678378979 29 101031071091132329417343475359619678378979 30 101031071091132329417343475359619678378979 31 101031071091131272329417343475359619678378979 32 101031071091131272329417343475359619678378979 33 10103107109113127137232941734347535961967838979 34 10103107109113127137139232941734347535961967838979 35 10103107109113127137139149232941734347535961967838979 36 1010310710911312713713914923294151734347535961967838979 37 1010310710911312713713914915157232941734347535961967838979 38 1010310710911312713713914915157163232941734347535961967838979 39 10103107109113127137139149151571631672329417343475359619798389 40 10103107109113127137139149151571631672329417343475359619798389 41 1010310710911312713713914915157163167173232941794347535961978389 42 101031071091131271371391491515716316717323294179434753596181978389 43 101031071091131271371391491515716316723294173434753596181917978389 44 101031071091131271371391491515716316717323294179434753596181919383897 45 10103107109113127137139149151571631671731792329418191934347535961978389 46 10103107109113127137139149151571631671731791819193232941974347535961998389 47 101031071091271313714915157163167173179181919321139232941974347535961998389 48 1010310710912713137149151571631671731791819193211392232941974347535961998389 49 1010310710912713137149151571631671731791819193211392232272941974347535961998389 50 10103107109127131371491515716316717317918191932113922322722941974347535961998389 51 101031071091271313714915157163167173179181919321139223322722941974347535961998389 52 101031071091271313714915157163167173179181919321139223322722923941974347535961998389 53 1010310710912713137149151571631671731791819193211392233227229239241974347535961998389 54 101031071091271313714915157163167173179211392233227229239241819193251974347535961998389 55 101031071091271313714915157163167173179211392233227229239241819193251972574347535961998389 56 101031071091271313714915157163167173179211392233227229239241819193251972572634347535961998389 57 101031071091271313714915157163167173179211392233227229239241819193251972572632694347535961998389 58 101031071091271313714915157163167173179211392233227229239241819193251972572632694347535961998389 59 1010310710912713137149151571631671731792113922332277229239241819193251972572632694347535961998389 60 101031071091271313714915157163167173211392233227722923924179251819193257263269281974347535961998389 61 1010310710912713137149151571631671732113922332277229239241792518191932572632692819728343475359619989 62 10103107109127131371491515716316717321139223322772293239241792518191932572632692819728343475359619989 63 1010307107109127131371491515716316717321139223322772293239241792518191932572632692819728343475359619989 64 10103071071091271311371391491515716316721173223322772293239241792518191932572632692819728343475359619989 65 10103071071091271311371491515716313916721173223322772293239241792518191932572632692819728343475359619989 66 10103071071091271311371491515716313921167223317322772293239241792518191932572632692819728343475359619989 67 10103071071091271311371491515716313921167223317322772293239241792518191932572632692819728343475359619989 68 1010307107109127131137149151571631392116722331732277229323924179251819193257263269281972833743475359619989 69 1010307107109127131137149151571631392116722331732277229323924179251819193257263269281972833743475359619989 70 101030710710912713113714915157163139211672233173227722932392417925181919325726326928197283374347534959619989 71 101030710710912713113714915157163139211672233173227722932392417925181919325726337269281972834743534959619989 72 101030710710912713113714915157163139211672233173227722932392417925181919337257263472692819728349435359619989 73 10103071071091271311371491515716313921167223317322772293372392417925181919347257263492692819728353594367619989 74 101030710710912713113714915157163139211672233173227722932392417925181919337347257263492692819728353594367619989 75 1010307107109127131137313914915157163211672233173227722933792392417925181919347257263492692819728353594367619989 76 101030710710912713113731391491515716321167223317322772293379239241792518191934725726349269281972835359438367619989 77 101030710710912713113731391491515716321167223317337922772293472392417925181919349257263535926928197283674383896199 78 1010307107109127131137313914915157163211672233173379227722934723972417925181919349257263535926928197283674383896199 79 101030710710912713113731391491515721163223317337922772293472397241672517925726349269281819193535928367401974383896199 80 101030710710912713113731391491515721163223317337922772293472397241672517925726349269281819193535928367401974094383896199 81 101030710710912713113731391491515721163223317337922772293472397241916725179257263492692818193535928367401974094383896199 82 1010307107109127131137313914915157223317322772293379239724191634725167257263492692817928353594018193674094211974383896199 83 1010307107109127131137313914922331515722772293379239724191634725167257263492692817353592836740181938389409421197431796199 84 101030710710912713113731391492233151572277229323972419163472516725726349269281735359283674018193838940942119743179433796199 85 101030710710912713113731391492233151572277229323924191634725167257263492692817353592836740181938389409421197431794337943976199 86 1010307107109127131137313914922331515722772293239241916347251672572634926928173535928367401819383894094211974317943379443976199 87 1010307107109127131137313914922331515722772293239241916347251672572634926928173535928367401819383894094211974317943379443974496199 88 1010307107109127131137313914922331515722772293239241916347251672572634926928173535928367401819383894094211974317943379443974494576199 89 10103071071091271311373139149223315157227722932392419163472516725726349269281735359283674018193838940942119743179433794439744945746199 90 10103071071091271311373139149223315157227722932392419163251672572634726928173492835359401819367409421197431794337944397449457461994638389 91 10103071071091271311373139149223315157227722932392419163251672572634726928173492835359401819367409421197431794337944397449457461994638389467 92 101030710710912713113731391492233151572277229323924191632516725726347926928173492835359401819367409421197431794337944397449457461994638389467 93 101030710710912713113731391492233151572277229323924191632516725726347926928173492835359401819367409421197431794337944397449457461994638389467487 94 101030710710912713113731392233149151572277229323924191632516725726347926928173492835359401819367409421197431794337944397449457461994638389467487 95 1010307107109127131137313922331491515722772293239241916325167257263479269281734928353594018193674094211974317943379443974499457461994638389467487 96 1010307107109127131137313922331491515722772293239241916325167257263269281734792834940181935359409421197431794337944397449945746199463674674875038389 97 1010307107109127131137313922331491515722772293239241916325167257263269281734792834940181935359409421197431794337944397449945746199463674674875038389509 98 101030710710912713113732233139227722932392419149151572516325726326928167283479401734940942118193535943179433794439744994574619746367467487503838950952199 99 1010307107109127131137322331392277229324191491515725163257263269281672834794017349409421181935359431794337944394499457461974636746748750383895095219952397 100 101030710710922331127131373227722932414915157251632572632692816728347940173494094211394317943379443944994574618191935359463674674875038389509521975239754199 101 101030710710922331127131373227722932414915157251632572632692816728347401734940942113943179433794439449945746181919353594636746748750383895095219752397541995479 102 101030710710922331127131373227722932414915157251632572632692816728347401734940942113943179433794439449945746181919353594636746748750383895095219752397541995479557 103 101030710710922331127131373227722932414915157251632572632692816728340173474094211394317943379443944945746181919349946353594674875036750952197523975419954795575638389 104 101030710710922331127131373227722932414915157251632572632692816728340173474094211394317943379443944945746181919349946353594674875036750952197523975419954795575638389569 105 101030710722331109227127722932413137325149151571632572632692816728340173474094211394317943379443944945746181919349946353594674875036750952197523975419954795575638389569 106 1010307107223311092271277229324131373251491515716325726326928167283401734740942113943179433794439449457461819193499463535946748750367509521975239754199547955775638389569 107 1010307107223311092271277229324131373251491515716325726326928167283401734740942113943179433794439449457461819193499463535946748750367509521975239754199547955775638389569587 108 10103071072233110922712772293241313732514915157163257263269281672834017340942113943179433794439449457461819193474634994674875035359367509521975239754199547955775638389569587 109 10103071072233110922712772293241313732514915157163257263269281672834017340942113943179433794439449457461819193474634994674875035359367509521975239754199547955775638389569587599 110 1010307223311072271092293241277251313732571491515726326928163283401674094211394317343379443944945746179463474674875034995095218191935359367523975419754795577563838956958759960199 111 1010307223311072271092293241277251313732571491515726326928163283401674094211394317343379443944945746179463474674875034995095218191935359367523975419754795577563838956958759960199607 112 1010307223311072271092293241277251491515716325726326928167283401734094211313734317943379443944945746139463474674875034995095218191935359367523975419754795577563838956958759960199607 113 22331101030722710722932410925127725714915157263269281632834016740942113137343173433794439449457461394634746748750349950952181919353593675239754197547955775638389569587599601996076179 114 2233110103072271072293241092512571277263269281491515728340163409421131373431734337944394494574613946347467487503499509521675239754191819353593675479557756383895695875996019760761796199 115 22331010307227107229324109251257126311277269281491515728340163409421131373431734337944394494574613946347467487503499509521675239754191819353593675479557756383895695875996019760761796199 116 22331010307227107229324109251257126311269281277283401491515740942113137343173433794439449457461394634674875034750952163499523975416754795577563535936756958759960181919383896076179619764199 117 223310103072271072293241092512571263112692812772834014915157409421131373431734433794494574613946346748750347509521634995239541675479557756353593675695875996018191938389607617961976419964397 118 223310103072271072293241092512571263112692812772834014915157409421131373431734433794494574613946346748750347509521634995239541675475577563535936756958759960181919383896076179619764199643976479 119 223310103072271072293241092512571263112692812772834014915157409421131373431734433794494574613946346748750347509521634995239541675475577563535695875935996018191936760761796197641996439764796538389 120 2233101030722710722932410925125712631126928127728340149151574094211313734317344337944945746139463467487503475095216349952395416754755775635356958760181919359367607617961976419964397647965383896599 121 22331010307227107229324109251257126311269281277283401491515740942113137343173443379449457461394634674875034750952163499523954167547557756353569587601819193593676076179641976439764796538389659966199 122 223310103072271072293241092512571263112692812772834014915157409421131373431734433794494574613946346734748750349950952163523954167547557756353569587601819193593676076179641976439764796538389659966199 123 2233101030722710722932410925125712631126928127728340149151574094211313734317344337944945746139463467347487503499509521635239541675475577563535695876018191935936776076179641976439764796538389659966199 124 2233101030722710722932410925125712631126928127728340149151574094211313734317344337944945746139463467347487503499509521635239541675475577563535695876018191935936076179641976439764796536776599661996838389 125 22331010307227107229324109251257126311269127728128340149151574094211313734317344337944945746139463467347487503499509521635239541675475577563535695876018191935936076179641976439764796536776599661996838389 126 2233101030701072271092293241251257126311269127728128340149151574094211313734317344337944945746139463467347487503499509521635239541675475577563535695876018191935936076179641976439764796536776599661996838389 127 223310103070107092271092293241251257126311269127728128340149151574094211313734317344337944945746139463467347487503499509521635239541675475577563535695876018191935936076179641976439764796536776599661996838389 128 223310103070107092271092293241251257191263112691277281283401491515740942113137343173443379449457461394634673474875034995095216352395416754755775635356958760181935936076179641976439764796536776599661996838389 129 22331010307010709227109229324125125719126311269127277281283401491515740942113137343173443379449457461394634673474875034995095216352395416754755775635356958760181935936076179641976439764796536776599661996838389 130 223307010103227092293241072510925712631126912719128128340140942113137331491515727743173443379449457461394634673474875034995095216352395416754755775635356958760181935936076179641976439764796536776599661996838389 131 2233070101032270922932410725109257126311269127191281283401409421131373314915157277431734433794494574613946346739487503475095216349952395416754755775635356958760181935936076179641976439764796536776599661996838389 132 2233070101032270922932410725109257126311269127191281283401409421131373314915157277431734433794494574613946346739487503475095216349952395416754755775635356958760181935936076179641976439764796536776599661996838389 133 223307010103227092293241072510925712631126912719128128340140942113137331443173449149457277433794613946346739487503475095215157516349952395416754755775635356958760181935936076179641976439764796536776599661996838389 134 22330701010322709229324107251092571263112691271912812834014094211313733144317344914945727743379461394634673948750347509521515751634995239541675475575635356958757760181935936076179641976439764796536776599661996838389 135 22330701010322709229324107251092571263112691271912812834014094211313733144317344914945727743379461394634673948750347509521515751634995239541675475575635356958757760181935936076179641976439764796536776599661996838389 136 2233070101032270922932410725109257126311269127191281283401409421131373314431734491494572774337946139463467394875034750952151575163499523954167547557563535695875776018193593607617964197643976479653677696599661996838389 137 22330701010322709229324107251092571263112691271912812834014094211313733144317344914945727734613946346739487433795034750952151575163499523954167547557563535695875776018193593607617964197643976479653677696599661996838389 138 2233070101032270922932410725109257126311269127191281283401409421131373314431734491494572773461394634673948743379503475095215157516349952395416754755756353569587577601819359360761796419764397647965367787696599661996838389 139 22330701010322709229324107251092571263112691271912812834014094211313733144317344914945727734613946346739487433795034750952151575163499523954167547557563535695875776018193593607617964197643976479765367787696599661996838389 140 22330701010322709229324107251092571263112691271912812834014094211313733144317344914945727734613946346739487433795034750952151575163499523954167547557563535695875776018193593607617964197643976479765367787696599661996838389809 141 223307010103227092293241072510925712631126912719128112834014094211313733144317344914945727734613946346739487433795034750952151575163499523954167547557563535695875776018193593607617964197643976479765367787696599661996838389809 142 223307010103227092293241072510925712631126912719128112834014094211313733144317344914572773461394634673948743379503475095214952395415157516349954755756353569587577601676076179641935936439764797653677659966197876968383898098218199 143 223070101032270922932410725109257126311269127191281128340140942113137331443173449145727734613946346739487433475034950952149952337954151575163535475575635695875776016760761796419359364396479765367765996619768383898098218199823978769 144 223070101032270922932410725109257126311269127191281128340140942113137331443173449145727433461394634673474875034950952149952337954151575163535475575635695875773960167607617964193593643964797653677659966197683838980982181998239769827787 145 223070101032270922924107251092571263112691271912811283401409421131373314431734491457274334613946346734748750349509521499523379541515751635354755756356958757739601676076179641935936439647976536599661976836776980982181998239782778782938389 146 2230701010322709229241072510925712631126912719128112834014094211313733144317344914572743346139463467347487503495095214995233795415157516353547557563569587577396016760761796419359364396479765367765996619768383976980982181998239827787829389 147 2230701010322709229241072510925712631126912719128112834014094211313733144317344914572743346139463467347487503495095214995233795415157516353547557563569587577396016760761796419359364396479765365996619768367769809821819982397827787829383985389 148 2230701010322709229241072510925712631126912719128112834014094211313733144317344914572743346139463467347487503495095214995233795415157516353547557563569587576016760761796419359364396479765365996619768367739769809821819982398277829383985389857787 149 2230701010322709229241072510925712631126912719128112834014094211313733144317344914572743346139463467347487503495095214995233795415157516353547557563569587576016760761796419359364396479765365966197683677397698098218199823982778293839853898577878599 150 2230701010322709229241072510925712631126912719128112834014094211313733144317344914572743346139463467347487503495095214995233795415157516353547557563569587576016760761796419359364396479765365966197683677397698098218199823982778293839853857787859986389 151 22307010103227092292410725109257126311269127191281128340140942113137331443173449145727433461394634673474875034950952149952337954151575163535475575635695875760167607617964193593643964797653659661976836773976980982181998239827782938398538577877859986389 152 22307010103227092292410725109257126311269127191281128340140942113137331443173449145727433461394634673474875034950952149952337954151547515755756353569587576016359360761796419364396479765365966197683676980982167739782398277829383985385778778599863898818199 153 22307010103227092292410725109257126311269127191281128340140942113137331443173449145727433461394634673474875034950952149952337954151547515755756353569587576016359360761796419364396479765365966197683676980982167739782398277829383853857787785998638988181998839 154 22307010103227092292410725109257126311269127191281128340140942113137331443173449145727433461394634673474875034950952149952337954151547515755756353569587576016359360761796419364396479765365966197683676980982167739782398277829383853857785998638988181998839887787 155 2230701010322709072292410725109257126311269127191281128340140942113137331443173449145727433461394634673474875034950952149952337954151547515755756353569587576016359360761796419364396479765365966197683676980982167739782398277829383853857785998638988181998839887787 156 22307010103227090722924107251092571263112691127191281128340140942113137331443173449145727433461394634673474875034950952149952337954151547515755756353569587576016359360761796419364396479765365966197683676980982167739782398277829383853857785998638988181998839887787 157 22307010103227090722924107251092571263112691127191281128340140942113137331443173449193457274334613946346734748750349509521499523379541515475155756353569587576015760761796419764396479765359365966199683676980982163823978277398293838538577859986389881816778778839887 158 2230701010322709072292410725109257126311269112719128112834014092934211313733144317344919345727433461394634673474875034950952149952337954151547515575635356958757601576076179641976439647976535936596619968367698098216382397827739829853838577859986389881816778778839887 159 22307010103227090722924107251092571263112691127191281128340140929342113137274314433173344919345746139463467347487503495095214995233735354151547515575635695875760157607617964197643964796535937976596619968367698098216382397827739829853838577859986389881816778778839887 160 2230701010322709072292410725109257126311269112719128112834014092934211313727431443317334491934574613941463467347487503495095214995233735354151547515575635695875760157607617964197643964796535937976596619968367698098216382397827739829853838577859986389881816778778839887 161 223070101032270907229241072510925712631126911271912811283401409293421131372743144331733449193457461394146346734748750349475095214995233735354151547515575635695875760157607617964197643964796535937976596619968367698098216382397827739829853838577859986389881816778778839887 162 22307010103227090722924107251092571263112691127191281128340140929342113137274314433173344919345746139414634673474875034947509521499523373535415154751557563569535875760157607617964197643964796535937976596619968367698098216382397827739829853838577859986389881816778778839887 163 2230701010322709072292410725109257126311269112719128112834014092934211313727431443317334491934574613941463467347487503494750952149952337353541515475155756356953587576015760761796419764396479653593797659661996768367698098216382397827739829853838577859986389881816778778839887 164 22307010103227090722924107251092571263112691127128112834014092934211313727431443317334491457461394146346734748750349475095214995233735354151547515575635695358757601576076179641919359379643964797197653659661996768367698098216382397827739829853838577859986389881816778778839887 165 223070101032270907229241072510925712631126911271281128340140929342113137274314433173344914574613941463467347487503494750952149952337353541515475155756356953587576015760761796419193593796439647971976536596619967683676980982163823977398277829853838577859986389881816778778839887 166 22307010103227090722924107251092571263112691127128112834014092934211313727431443317334491457461394146346734748750349475095214995233735354151547515575635695358757601576076179641919359379643964797197653659661996768367698098216382397739827782983838538577859986389881816778778839887 167 223070101032270907229241072510925712631126911271281128340140929342113137274314433173344914574613941463467347487503494750952149915152337353541547515575635695358757601576076179641919359379643964797197653659661996768367698098216382397739827782983838538577859986389881816778778839887 168 2230701010322709072292410725109257126311269112712811283401409293421131372743144331733449145746139414634673474875034947509521499151523373535415475155756356953587576015760761796419193593796439647971976536596619967683676980982163823977398277829838385385778599786389881816778778839887 169 2230701009070922710103229241072510925712631126911272728112834014092934211313733144317344914574334613941463467347487503494750952149915152337515415475575635356953587576015760761796419193593796439647971976536596619967683676980982163823977398277829838385385778599786389881816778778839887 170 22307010090709227101310322924107251092571263112691127272811283401409293421134431373317344914574334613941463467347487503494750952149915152337515415475575635356953587576015760761796419193593796439647971976536596619967683676980982163823977398277829838385385778599786389881816778778839887 171 22307010090709227101310191032292410725109257126311269112727281128340140929342113443137331734491457433461394146346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 172 22307010090709227101310191021032292410725109257126311269112727281128340140929342113443137331734491457433461394146346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 173 223070100907092271013101910210310722924109251257126311269112727281128340140929342113443137331734491457433461394146346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 174 223070100907092271013101910210310331107229241092512571263132691127272811283401409293421137334431734491457433461394146346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 175 223070100907092271013101910210310331103922924107251092571263132691127272811283401409293421137334431734491457433461394146346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 176 223070100907092271013101910210310331103922924104910725109257126313269112727281128340140929342113733443173449414574334613946346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 177 223070100907092271013101910210310331103922924104910510725109257126313269112727281128340140929342113733443173449414574334613946346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 178 223070100907092271013101910210310331103922924104910510610725109257126313269112727281128340140929342113733443173449414574334613946346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 179 223070100907092271013101910210310331103922924104910510610631325107257109263269112727281128340140929342113733443173449414574334613946346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 180 223070100907092271013101910210310331103922924104910510610631325106911072571092632692811272728340140929342113733443173449414574334613946346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 181 223070100907092271013101910210310331103922924104910510610631325106911072571087263269281092834012727409293421137334431734494145743346139463467347487503494750952149919352337515154154755756353569535875760157607617964196439647965359379719765966199676836769809821638239773982778298383853857785997863898811816778778839887 182 2230701009070922710131019102103103311039229241049105106106313251069107257108726326928109112727283401409293421137334431734494145743346139463467347487503494750952149919352337515154154755756353569535875760157607617964196439647965359379719765966199676836769809821638239773982778298383853857785997863898811816778778839887 183 2230701009070922710131019102103103311039229241049105106106313251069107257108726326928109110932834012727409293421137334431734494145743346139463467347487503494750952149919352337515154154755756353569535875760157607617964196439647965359379719765966199676836769809821638239773982778298383853857785997863898811816778778839887 184 2230701009070922710131019102103103311039229241049105106106313251069107257108726326928109110932834010971929340941272742113733443173449457433461394634673474875034947509521499193523375151541547557563535695358757601576076179641976439647965359379765966199676836769809821638239773982778298383853857785997863898811816778778839887 185 2230701009070922710131019102103103311039229241049105106106313251069107257108726326928109110932834010971929340941272742113733443173449457433461394634673474875034947509521499193523375151541547557563535695358757601576076179641976439647965359379765966199676836769809821638239773982778298383853857785997863898811816778778839887 186 2230701009070922710131019102103103311039229241049105106106313251069107257108726326928109110932834010971929340941272742113733443173449457433461394634673474875034947509521499193523375151541547557563535695358757601576076179641976439647965359379765966199676836769809821638239773982778298383853857785997863898811816778778839887 187 223070100907092271013101910210310331103922924104910510610631325106910725710872632692810911093283401097192934094127274211173344317433449457461373463467347487503494750952149919352337515154157547557563535695358757601635937960761796419764396479765365966199676836769809821677397782398277829838385385778599786389881811398839887787 188 223070100907092271013101910210310331103922924104910510610631325106910725710872632692810911093283401097192934094111727421123344317334494574337346137463467347487503494750952127514991935235354151575475575635695358757601635937960761796419764396479765365966199676836769809821677397782398277829838385385778599786389881811398839887787 189 1009070101307092232271019102103103310491051061063110392292410691072510872571091109326326928109719283401117274092934211233443131733449411294574337346137463467347487503494750952127514991935235354151575475575635695358757601635937960761796419764396479765365966199676836769809821677397782398277829838385385778599786389881811398839887787 190 10090701013070922322710191021031033104910510610631103922924106910725108725710911093263269281097192834011172740929342112334431317334494112945743373461374634673474875034947509521139523535412751499193547557563569535875760157607617964197643964796535937976596619967683676980982163823977398277829838385385778599786389881151816778778839887 191 100907010130709101910210310331049105106106311039223227106910722924108725109110932571097192632692811172728340112334092934211294113137334431734494574337461394634673474875034947509521151153523535412751499193547557563569535875760157607617964197643964796535937976596619967683676980982163823977398277829838385385778599786389881816778778839887 192 1009070101307091019102103103310491051061063110392232271069107229241087251091109325710971926326928111727283401123340929342112941131373344317344945743374613946346734748750349475095211511535235354116354751275575635695358757601499193593796076179641976439647976536596619967683676980982157739778239827782983838538578599786389881816778778839887 193 1009070101307092232271019102103103310491051061063110392292410691072510872571091109326326928109711171928340112334092934211294113137274317334433734494574613946346734748750349475095211511535235354127514991935475575635695358757601576076179641976439647965359379765966199676836769809821677397782398277829838385385778599786388181163898839887787 194 10090701013070922322710191021031033104910510610631103922924106910725108725710911093263269281097111719283401123340929342112941131372743173344337344945746139463467347487503494750952115115352353541163547512755756356953587576014991935937960761796419764396479765365966199676836769809821577397782398277829838385385785997863898811816778778839887 195 100907010130709101910210310331049105106106311039223227106910722924108725109110932571097111719263269281123283401129293409411313727421151153443173344945743346139463467347487503494750952116352337353541181187512754755756356953587576014991935937960761796419764396479765365966199676836769809821577397782398277829838385385785997863898816778778839887 196 100907010130709101910210310331049105106106310691072231103922710872292410911093251097111711232571926326928112928340113137274092934211511534431733449411634574334613946346734748750349475095211811875119352337353541275475575635695358757601499196076179641976439647965359379765966199676836769809821577397782398277829838385385785997863898816778778839887 197 100907010130709101910210310331049105106106310691072231103922710872292410911093251097111711232571926326928112928340113137274092934211511534431733449411634574334613946346734748750349475095211811875119352337353541201275475575635695358757601499196076179641976439647965359379765966199676836769809821577397782398277829838385385785997863898816778778839887 198 1009070101307091019102103103310491051061063106910710872231103922710911093229241097111711232511292571926326928113132834011511534092934211634431733449411811872743345746137346346734748750349475095211935233751201213953535412754755756356958757601499196076179641976439647965359379765966199676836769809821577397782398277829838385385785997863898816778778839887 199 10090701013070910191021031033104910510610631069107108710911039223110932271097111711232292411292511313257192632692811511532834011634092934211811872743173344334494119345746137346346734748750349475095212012139523375121754127547557563535695358757601499196076179641976439647965359379765966199676836769809821577397782398277829838385385785997863898816778778839887 200 100907010130709101910210310331049105106106310691071087109109311039110971117112322711292292411313251151153257192632692811632834011811872740929342119344317334494120121373457433461394634673474875034947509521217512233752353541275475575635695358757601499196076179641976439647965359379765966199676836769809821577397782398277829838385385785997863898816778778839887 ``` ## Code Here's a Python 3 script to call the Concorde solver over and over until it constructs the solutions. Concorde is free for academic use. You can download an [executable binary of Concorde](http://www.math.uwaterloo.ca/tsp/concorde/downloads/downloads.htm) built with their own linear programming package QSopt, or if you somehow have a license for IBM CPLEX, you could [build Concorde from source](http://www.math.uwaterloo.ca/tsp/concorde/DOC/README.html) to use CPLEX. ``` #!/usr/bin/env python3 ''' Find prime containment numbers (OEIS A054261) using the Concorde TSP solver. The n-th prime containment number is the smallest natural number which, when written in decimal, contains the first n primes. ''' import argparse import itertools import os import sys import subprocess import tempfile def join_strings(a, b): '''Shortest string that starts with a and ends with b.''' for overlap in range(min(len(a), len(b)), 0, - 1): if a[-overlap:] == b[:overlap]: return a + b[overlap:] return a + b def is_prime(n): if n < 2: return False d = 2 while d*d <= n: if n % d == 0: return False d += 1 return True def prime_list_reduced(n): '''First n primes, with primes that are substrings of other primes removed.''' primes = [] p = 2 while len(primes) < n: if is_prime(p): primes.append(p) p += 1 reduced = [] for p in primes: if all(p == q or str(p) not in str(q) for q in primes): reduced.append(p) return reduced # w_med is an offset for actual weights # (we use zero as a dummy weight when splitting nodes) w_med = 10**4 # w_big blocks edges from being taken w_big = 10**8 def gen_tsplib(prefix, strs, start_candidates): '''Generate TSP formulation in TSPLIB format. Returns a TSPLIB format string that encodes the length of the shortest string starting with 'prefix' and containing all 'strs'. start_candidates is the set of strings that solution paths are allowed to start with. ''' N = len(strs) # Concorde only supports symmetric TSPs. Therefore we encode the # asymmetric TSP instances by doubling each node. node_in = lambda i: 2*i node_out = lambda i: node_in(i) + 1 # 2*(N+1) nodes because we add an artificial node with index N # for the start/end of the tour. This node is also doubled. num_nodes = 2*(N+1) # Ensure special offsets are big enough assert w_med > len(prefix) + sum(map(len, strs)) assert w_big > w_med * num_nodes weight = [[w_big] * num_nodes for _ in range(num_nodes)] def edge(src, dest, w): weight[node_out(src)][node_in(dest)] = w weight[node_in(dest)][node_out(src)] = w # link every incoming node with the matching outgoing node for i in range(N+1): weight[node_in(i)][node_out(i)] = 0 weight[node_out(i)][node_in(i)] = 0 for i, p in enumerate(strs): if p in start_candidates: prefix_w = len(join_strings(prefix, p)) # Initial length edge(N, i, w_med + prefix_w) else: edge(N, i, w_big) # Link every str to the end to allow closed tours edge(i, N, w_med) for i, p in enumerate(strs): for j, q in enumerate(strs): if i != j: w = len(join_strings(p, q)) - len(p) edge(i, j, w_med + w) out = '''NAME: prime-containment-number TYPE: TSP DIMENSION: %d EDGE_WEIGHT_TYPE: EXPLICIT EDGE_WEIGHT_FORMAT: FULL_MATRIX EDGE_WEIGHT_SECTION ''' % num_nodes out += '\n'.join( ' '.join(str(w) for w in row) for row in weight ) + '\n' out += 'EOF\n' return out def parse_tour_soln(prefix, strs, text): '''This constructs the solution from Concorde's 'tour' output format. The format simply consists of a permutation of the graph nodes.''' N = len(strs) node_in = lambda i: 2*i node_out = lambda i: node_in(i) + 1 nums = list(map(int, text.split())) # The file starts with the number of nodes assert nums[0] == 2*(N+1) nums = nums[1:] # Then it should list a permutation of all nodes assert len(nums) == 2*(N+1) # Find and remove the artificial starting point start = nums.index(node_out(N)) nums = nums[start+1:] + nums[:start] # Also find and remove the end point if nums[-1] == node_in(N): nums = nums[:-1] elif nums[0] == node_in(N): # Tour printed in reverse order nums = reversed(nums[1:]) else: assert False, 'bad TSP tour' soln = prefix for i in nums: # each prime appears in two adjacent nodes, pick one arbitrarily if i % 2 == 0: soln = join_strings(soln, strs[i // 2]) return soln def scs_length(prefix, strs, start_candidates, concorde_path, concorde_verbose): '''Find length of shortest containing string using one call to Concorde.''' # Concorde's small-input solver CCHeldKarp, tends to fail with the # cryptic error message 'edge too long'. Brute force instead if len(strs) <= 5: best = len(prefix) + sum(map(len, strs)) for perm in itertools.permutations(range(len(strs))): if perm and strs[perm[0]] not in start_candidates: continue soln = prefix for i in perm: soln = join_strings(soln, strs[i]) best = min(best, len(soln)) return best with tempfile.TemporaryDirectory() as tempdir: concorde_path = os.path.join(os.getcwd(), concorde_path) with open(os.path.join(tempdir, 'prime.tsplib'), 'w') as f: f.write(gen_tsplib(prefix, strs, start_candidates)) if concorde_verbose: subprocess.check_call([concorde_path, os.path.join(tempdir, 'prime.tsplib')], cwd=tempdir) else: try: subprocess.check_output([concorde_path, os.path.join(tempdir, 'prime.tsplib')], cwd=tempdir, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: print('Concorde exited with error code %d\nOutput log:\n%s' % (e.returncode, e.stdout.decode('utf-8', errors='ignore')), file=sys.stderr) raise with open(os.path.join(tempdir, 'prime.sol'), 'r') as f: soln = parse_tour_soln(prefix, strs, f.read()) return len(soln) # Cache results from previous N's pcn_solve_cache = {} # (prefix fragment, strs) -> soln def pcn(n, concorde_path, concorde_verbose): '''Find smallest prime containment number for first n primes.''' strs = list(map(str, prime_list_reduced(n))) target_length = scs_length('', strs, strs, concorde_path, concorde_verbose) def solve(prefix, strs, target_length): if not strs: return prefix # Extract part of prefix that is relevant to cache prefix_fragment = '' for s in strs: next_prefix = join_strings(prefix, s) overlap = len(prefix) + len(s) - len(next_prefix) fragment = prefix[len(prefix) - overlap:] if len(fragment) > len(prefix_fragment): prefix_fragment = fragment fixed_prefix = prefix[:len(prefix) - len(prefix_fragment)] assert fixed_prefix + prefix_fragment == prefix cache_key = (prefix_fragment, tuple(strs)) if cache_key in pcn_solve_cache: return fixed_prefix + pcn_solve_cache[cache_key] # Not in cache, we need to calculate it. soln = None # Try strings in ascending order until scs_length reports a # solution with equal length. That string will be the # lexicographically smallest extension of our solution. next_prefixes = sorted((join_strings(prefix, s), s) for s in strs) # Try first string -- often works next_prefix, _ = next_prefixes[0] next_prefixes = next_prefixes[1:] next_strs = [s for s in strs if s not in next_prefix] next_length = scs_length(next_prefix, next_strs, next_strs, concorde_path, concorde_verbose) if next_length == target_length: soln = solve(next_prefix, next_strs, next_length) else: # If not, do a weighted binary search on remaining strings while len(next_prefixes) > 1: split = (len(next_prefixes) + 2) // 3 group = next_prefixes[:split] group_length = scs_length(prefix, strs, [s for _, s in group], concorde_path, concorde_verbose) if group_length == target_length: next_prefixes = group else: next_prefixes = next_prefixes[split:] if next_prefixes: next_prefix, _ = next_prefixes[0] next_strs = [s for s in strs if s not in next_prefix] check = True # Uncomment if paranoid #next_length = scs_length(next_prefix, next_strs, next_strs, # concorde_path, concorde_verbose) #check = (next_length == target_length) if check: soln = solve(next_prefix, next_strs, target_length) assert soln is not None, ( 'solve failed! prefix=%r, strs=%r, target_length=%d' % (prefix, strs, target_length)) pcn_solve_cache[cache_key] = soln[len(fixed_prefix):] return soln return solve('', strs, target_length) parser = argparse.ArgumentParser() parser.add_argument('--concorde', type=str, default='concorde', help='path to Concorde binary') parser.add_argument('--verbose', action='store_true', help='dump all Concorde output') parser.add_argument('--start', type=int, metavar='N', default=1, help='start at this N') parser.add_argument('--end', type=int, metavar='N', default=1000000, help='stop after this N') parser.add_argument('--one', type=int, metavar='N', help='solve for a single N and exit') def main(): opts = parser.parse_args(sys.argv[1:]) if opts.one is not None: opts.start = opts.one opts.end = opts.one prev_soln = '' for n in range(opts.start, opts.end+1): primes = map(str, prime_list_reduced(n)) if all(p in prev_soln for p in primes): soln = prev_soln else: soln = pcn(n, opts.concorde, opts.verbose) print('%d %s' % (n, soln)) sys.stdout.flush() prev_soln = soln if __name__ == '__main__': main() ``` [Answer] # Python 3 + [Google OR-Tools](https://developers.google.com/optimization/), score 169 in 295 seconds (official score) ### How it works After discarding redundant primes contained in other primes, draw a directed graph with an edge from each prime to each of its suffixes, with distance zero, and an edge to each prime from each of its prefixes, with distance defined by the number of added digits. We seek the lexicographically first shortest path through the graph starting at the empty prefix, passing through each prime (but not necessarily through each prefix or suffix), and ending at the empty suffix. For example, here are the edges of the optimal path ε → 11 → 1 → 13 → 3 → 31 → 1 → 17 → ε → 19 → ε → 23 → ε → 29 → ε → 5 → ε for *n* = 11, corresponding to the output string 113171923295. [![graph](https://i.stack.imgur.com/KgGlp.png)](https://i.stack.imgur.com/KgGlp.png) Compared to the straightforward [reduction to the travelling salesman problem](https://codegolf.stackexchange.com/a/177257/39242), note that by connecting the primes indirectly through these extra suffix/prefix nodes, instead of directly to each other, we have dramatically reduced the number of edges we need to consider. But since the extra nodes need not be traversed exactly once, this is no longer an instance of TSP. We use the incremental CP-SAT constraint solver of Google OR-Tools, first to minimize the total length of the path, then to minimize each group of added digits in order. We initialize the model with only local constraints: each prime precedes one suffix and succeeds one prefix, while each suffix/prefix precedes and succeeds the same number of primes. The resulting model could contain disconnected cycles; if so, we add additional connectivity constraints dynamically and rerun the solver. ### Code ``` import multiprocessing from ortools.sat.python import cp_model def superstring(strings): def gen_prefixes(s): for i in range(len(s)): a = s[:i] if a in affixes: yield a def gen_suffixes(s): for i in range(1, len(s) + 1): a = s[i:] if a in affixes: yield a def solve(): def find_string(s): found_strings.add(s) for i in range(1, len(s) + 1): a = s[i:] if ( a in affixes and a not in found_affixes and solver.Value(suffix[s, a]) ): found_affixes.add(a) q.append(a) break def cut(skip): model.AddBoolOr( skip + [ suffix[s, a] for s in found_strings for a in gen_suffixes(s) if a not in found_affixes ] + [ prefix[a, s] for s in unused_strings if s not in found_strings for a in gen_prefixes(s) if a in found_affixes ] ) model.AddBoolOr( skip + [ suffix[s, a] for s in unused_strings if s not in found_strings for a in gen_suffixes(s) if a in found_affixes ] + [ prefix[a, s] for s in found_strings for a in gen_prefixes(s) if a not in found_affixes ] ) def search(): while q: a = q.pop() for s in prefixed[a]: if ( s in unused_strings and s not in found_strings and solver.Value(prefix[a, s]) ): find_string(s) return not (unused_strings - found_strings) while True: if solver.Solve(model) != cp_model.OPTIMAL: raise RuntimeError("Solve failed") found_strings = set() found_affixes = set() if part is None: found_affixes.add("") q = [""] else: part_ix = solver.Value(part) p, next_affix, next_string = parts[part_ix] q = [] find_string(next_string) if search(): break if part is not None: if part_ix not in partb: partb[part_ix] = model.NewBoolVar("partb%s_%s" % (step, part_ix)) model.Add(part == part_ix).OnlyEnforceIf(partb[part_ix]) model.Add(part != part_ix).OnlyEnforceIf(partb[part_ix].Not()) cut([partb[part_ix].Not()]) if last_string is None: found_affixes.add(next_affix) else: find_string(last_string) q.append(next_affix) if search(): continue cut([]) solver = cp_model.CpSolver() solver.parameters.num_search_workers = 4 affixes = {s[:i] for s in strings for i in range(len(s))} & { s[i:] for s in strings for i in range(1, len(s) + 1) } prefixed = {} for s in strings: for a in gen_prefixes(s): prefixed.setdefault(a, []).append(s) suffixed = {} for s in strings: for a in gen_suffixes(s): suffixed.setdefault(a, []).append(s) unused_strings = set(strings) last_string = None part = None model = cp_model.CpModel() prefix = { (a, s): model.NewBoolVar("prefix_%s_%s" % (a, s)) for a in affixes for s in prefixed[a] } suffix = { (s, a): model.NewBoolVar("suffix_%s_%s" % (s, a)) for a in affixes for s in suffixed[a] } for s in strings: model.Add(sum(prefix[a, s] for a in gen_prefixes(s)) == 1) model.Add(sum(suffix[s, a] for a in gen_suffixes(s)) == 1) for a in affixes: model.Add( sum(suffix[s, a] for s in suffixed[a]) == sum(prefix[a, s] for s in prefixed[a]) ) length = sum(prefix[a, s] * (len(s) - len(a)) for a in affixes for s in prefixed[a]) model.Minimize(length) solve() model.Add(length == solver.Value(length)) out = "" for step in range(len(strings)): in_parts = set() parts = [] for a in [""] if last_string is None else gen_suffixes(last_string): for s in prefixed[a]: if s in unused_strings and s not in in_parts: in_parts.add(s) parts.append((s[len(a) :], a, s)) parts.sort() part = model.NewIntVar(0, len(parts) - 1, "part%s" % step) partb = {} for part_ix, (p, a, s) in enumerate(parts): if last_string is not None: model.Add(part != part_ix).OnlyEnforceIf(suffix[last_string, a].Not()) model.Add(part != part_ix).OnlyEnforceIf(prefix[a, s].Not()) model.Minimize(part) solve() part_ix = solver.Value(part) model.Add(part == part_ix) p, a, last_string = parts[part_ix] unused_strings.remove(last_string) out += p return out def gen_primes(): yield 2 n = 3 d = {} for p in gen_primes(): p2 = p * p d[p2] = 2 * p while n <= p2: if n in d: q = d.pop(n) m = n + q while m in d: m += q d[m] = q else: yield n n += 2 def gen_inputs(): num_primes = 0 strings = [] for new_prime in gen_primes(): num_primes += 1 new_string = str(new_prime) strings = [s for s in strings if s not in new_string] + [new_string] yield strings with multiprocessing.Pool() as pool: for i, out in enumerate(pool.imap(superstring, gen_inputs())): print(i + 1, out, flush=True) ``` ### Results Here are the [first 1000 prime containment numbers](https://glot.io/snippets/f7ktb0wlni/raw/prime-containment.txt), computed in 1½ days on an 8-core/16-thread system. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), score 25 in 231 seconds (official score) ## Results * `1 < n <= 23` in ~~42~~ 36 seconds on TIO * `n = 24 (2311294134347173535961967837989)` in ~~32~~ 24 seconds locally * `n = 25 (23112941343471735359619678378979)` in ~~210~~ 160 seconds locally * **`n = 1` to `n = 25` was found in 231 seconds for the official scoring** (edited by maxb) This uses a similar approach to Arnauld's JS solution based on recursive permutation rejection, using a specialized tree-set to gain a lot of speed. For every prime that needs to fit in the number: 1. check if the prime is a sub-string of another prime, and if so, remove it 2. sort the current list of prime sub-strings, join it, and add it to the balanced tree set 3. check if any primes fit on the front of any other ones, and if so, join them - ignoring adjacent already-ordered elements that are tested by the rejection step anyway Then, for each pair of sub-strings that we joined, remove any sub-strings of that joined pair from the list of sub-strings and recurse on it. Once no more sub-strings can be joined to any other sub-strings on any arm of our recursion, we use the already-ordered tree set to quickly find the lowest number containing the sub-strings. Things to be improved / added: * Move away from permuting the entire search space, generate candidates instead * Prefix / Suffix -based candidate generation to enable memoization * Multithreading, split work over prefixes evenly to the number of threads There were large performance drops between `19 -> 20` and `24 -> 25` due to duplicate handling by the merge trial step and the candidate rejection step, but these have been fixed. **Optimizations:** * `removeOverlap` is designed to always give a set of sub-strings already in the optimal order * `uInsertMSpec` reduces check-if-is-member and insert-new-member to one set traversal * `containmentNumbersSt` checks if the previous solution works for a new number ``` module main import StdEnv,StdOverloadedList,_SystemEnumStrict import Data.List,Data.Func,Data.Maybe,Data.Array import Text,Text.GenJSON // adapted from Data.Set to work with a single specific type, and persist uniqueness :: Set a = Tip | Bin !Int a !.(Set a) !.(Set a) derive JSONEncode Set derive JSONDecode Set delta :== 4 ratio :== 2 :: NumberType :== String :: SetType :== NumberType //uSingleton :: SetType -> Set uSingleton x :== (Bin 1 x Tip Tip) // adapted from Data.Set to work with a single specific type, and persist uniqueness uFindMin :: !.(Set .a) -> .a uFindMin (Bin _ x Tip _) = x uFindMin (Bin _ _ l _) = uFindMin l uSize set :== case set of Tip = (0, Tip) s=:(Bin sz _ _ _) = (sz, s) uMemberSpec :: String !u:(Set String) -> .(.Bool, v:(Set String)), [u <= v] uMemberSpec x Tip = (False, Tip) uMemberSpec x set=:(Bin s y l r) | sx < sy || sx == sy && x < y # (t, l) = uMemberSpec x l = (t, Bin s y l r) //= (t, if(t)(\y` l` r` = Bin sz y` l` r`) uBalanceL y l r) | sx > sy || sx == sy && x > y # (t, r) = uMemberSpec x r = (t, Bin s y l r) //= (t, if(t)(\y` l` r` = Bin sz y` l` r`) uBalanceR y l r) | otherwise = (True, set) where sx = size x sy = size y uInsertM :: !(a a -> .Bool) -> (a u:(Set a) -> v:(.Bool, w:(Set a))), [v u <= w] uInsertM cmp = uInsertM` where //uInsertM` :: a (Set a) -> (Bool, Set a) uInsertM` x Tip = (False, uSingleton x) uInsertM` x set=:(Bin _ y l r) | cmp x y//sx < sy || sx == sy && x < y # (t, l) = uInsertM` x l = (t, uBalanceL y l r) //= (t, if(t)(\y` l` r` = Bin sz y` l` r`) uBalanceL y l r) | cmp y x//sx > sy || sx == sy && x > y # (t, r) = uInsertM` x r = (t, uBalanceR y l r) //= (t, if(t)(\y` l` r` = Bin sz y` l` r`) uBalanceR y l r) | otherwise = (True, set) uInsertMCmp :: a !u:(Set a) -> .(.Bool, v:(Set a)) | Enum a, [u <= v] uInsertMCmp x Tip = (False, uSingleton x) uInsertMCmp x set=:(Bin _ y l r) | x < y # (t, l) = uInsertMCmp x l = (t, uBalanceL y l r) //= (t, if(t)(\y` l` r` = Bin sz y` l` r`) uBalanceL y l r) | x > y # (t, r) = uInsertMCmp x r = (t, uBalanceR y l r) //= (t, if(t)(\y` l` r` = Bin sz y` l` r`) uBalanceR y l r) | otherwise = (True, set) uInsertMSpec :: NumberType !u:(Set NumberType) -> .(.Bool, v:(Set NumberType)), [u <= v] uInsertMSpec x Tip = (False, uSingleton x) uInsertMSpec x set=:(Bin sz y l r) | sx < sy || sx == sy && x < y #! (t, l) = uInsertMSpec x l = (t, uBalanceL y l r) //= (t, if(t)(\y` l` r` = Bin sz y` l` r`) uBalanceL y l r) | sx > sy || sx == sy && x > y #! (t, r) = uInsertMSpec x r = (t, uBalanceR y l r) //= (t, Bin sz y l r) //= (t, if(t)(\y` l` r` = Bin sz y` l` r`) uBalanceR y l r) | otherwise = (True, set) where sx = size x sy = size y // adapted from Data.Set to work with a single specific type, and persist uniqueness uBalanceL :: .a !u:(Set .a) !v:(Set .a) -> w:(Set .a), [v u <= w] //a .(Set a) .(Set a) -> .(Set a) uBalanceL x Tip Tip = Bin 1 x Tip Tip uBalanceL x l=:(Bin _ _ Tip Tip) Tip = Bin 2 x l Tip uBalanceL x l=:(Bin _ lx Tip (Bin _ lrx _ _)) Tip = Bin 3 lrx (Bin 1 lx Tip Tip) (Bin 1 x Tip Tip) uBalanceL x l=:(Bin _ lx ll=:(Bin _ _ _ _) Tip) Tip = Bin 3 lx ll (Bin 1 x Tip Tip) uBalanceL x l=:(Bin ls lx ll=:(Bin lls _ _ _) lr=:(Bin lrs lrx lrl lrr)) Tip | lrs < ratio*lls = Bin (1+ls) lx ll (Bin (1+lrs) x lr Tip) # (lrls, lrl) = uSize lrl # (lrrs, lrr) = uSize lrr | otherwise = Bin (1+ls) lrx (Bin (1+lls+lrls) lx ll lrl) (Bin (1+lrrs) x lrr Tip) uBalanceL x Tip r=:(Bin rs _ _ _) = Bin (1+rs) x Tip r uBalanceL x l=:(Bin ls lx ll=:(Bin lls _ _ _) lr=:(Bin lrs lrx lrl lrr)) r=:(Bin rs _ _ _) | ls > delta*rs | lrs < ratio*lls = Bin (1+ls+rs) lx ll (Bin (1+rs+lrs) x lr r) # (lrls, lrl) = uSize lrl # (lrrs, lrr) = uSize lrr | otherwise = Bin (1+ls+rs) lrx (Bin (1+lls+lrls) lx ll lrl) (Bin (1+rs+lrrs) x lrr r) | otherwise = Bin (1+ls+rs) x l r uBalanceL x l=:(Bin ls _ _ _) r=:(Bin rs _ _ _) = Bin (1+ls+rs) x l r // adapted from Data.Set to work with a single specific type, and persist uniqueness uBalanceR :: .a !u:(Set .a) !v:(Set .a) -> w:(Set .a), [v u <= w] uBalanceR x Tip Tip = Bin 1 x Tip Tip uBalanceR x Tip r=:(Bin _ _ Tip Tip) = Bin 2 x Tip r uBalanceR x Tip r=:(Bin _ rx Tip rr=:(Bin _ _ _ _)) = Bin 3 rx (Bin 1 x Tip Tip) rr uBalanceR x Tip r=:(Bin _ rx (Bin _ rlx _ _) Tip) = Bin 3 rlx (Bin 1 x Tip Tip) (Bin 1 rx Tip Tip) uBalanceR x Tip r=:(Bin rs rx rl=:(Bin rls rlx rll rlr) rr=:(Bin rrs _ _ _)) | rls < ratio*rrs = Bin (1+rs) rx (Bin (1+rls) x Tip rl) rr # (rlls, rll) = uSize rll # (rlrs, rlr) = uSize rlr | otherwise = Bin (1+rs) rlx (Bin (1+rlls) x Tip rll) (Bin (1+rrs+rlrs) rx rlr rr) uBalanceR x l=:(Bin ls _ _ _) Tip = Bin (1+ls) x l Tip uBalanceR x l=:(Bin ls _ _ _) r=:(Bin rs rx rl=:(Bin rls rlx rll rlr) rr=:(Bin rrs _ _ _)) | rs > delta*ls | rls < ratio*rrs = Bin (1+ls+rs) rx (Bin (1+ls+rls) x l rl) rr # (rlls, rll) = uSize rll # (rlrs, rlr) = uSize rlr | otherwise = Bin (1+ls+rs) rlx (Bin (1+ls+rlls) x l rll) (Bin (1+rrs+rlrs) rx rlr rr) | otherwise = Bin (1+ls+rs) x l r uBalanceR x l=:(Bin ls _ _ _) r=:(Bin rs _ _ _) = Bin (1+ls+rs) x l r primes :: [Int] primes =: [2: [i \\ i <- [3, 5..] | let checks :: [Int] checks = TakeWhile (\n . i >= n*n) primes in All (\n . i rem n <> 0) checks]] primePrefixes :: [[NumberType]] primePrefixes =: (Scan removeOverlap [|] [toString p \\ p <- primes]) removeOverlap :: !u:[NumberType] NumberType -> v:[NumberType], [u <= v] removeOverlap [|] nsub = [|nsub] removeOverlap [|h: t] nsub | indexOf h nsub <> -1 = removeOverlap t nsub | nsub > h = [|h: removeOverlap t nsub] | otherwise = [|nsub, h: Filter (\s = indexOf s nsub == -1) t] tryMerge :: !NumberType !NumberType -> .Maybe .NumberType tryMerge a b = first_prefix (max (size a - size b) 0) where sa = size a - 1 max_len = min sa (size b - 1) first_prefix :: !Int -> .Maybe .NumberType first_prefix n | n > max_len = Nothing | b%(0,sa-n) == a%(n,sa) = Just (a%(0,n-1) +++. b) | otherwise = first_prefix (inc n) mergeString :: !NumberType !NumberType -> .NumberType mergeString a b = first_prefix (max (size a - size b) 0) where sa = size a - 1 first_prefix :: !Int -> .NumberType first_prefix n | b%(0,sa-n) == a%(n,sa) = a%(0,n-1) +++. b | n == sa = a +++. b | otherwise = first_prefix (inc n) // todo: keep track of merges that we make independent of the resulting whole number mapCandidatePermsSt :: ![[NumberType]] !u:(Set .NumberType) -> v:(Set NumberType), [u <= v] mapCandidatePermsSt [|] returnSet = returnSet mapCandidatePermsSt [h:t] returnSet #! (mem, returnSet) = uInsertMSpec (foldl mergeString "" h) returnSet = let merges = [removeOverlap h y \\ [x:u=:[_:v]] <- tails h, (Just y) <- Map (tryMerge x) v ++| Map (flip tryMerge x) u] in (mapCandidatePermsSt t o if(mem) id (mapCandidatePermsSt merges)) returnSet containmentNumbersSt =: Tl (containmentNumbersSt` primePrefixes "") where containmentNumbersSt` [p:pref] prev | all (\e = indexOf e prev <> -1) p = [prev: containmentNumbersSt` pref prev] | otherwise #! next = uFindMin (mapCandidatePermsSt [p] Tip) = [next: containmentNumbersSt` pref next] minFinder :== (\a b = let sa = size a; sb = size b in if(sa == sb) (a < b) (sa < sb)) Start = [(i, ' ', n, "\n") \\ i <- [1..] & n <- containmentNumbersSt] ``` [Try it online!](https://tio.run/##xVlbc9u2En4Wf8XanaZkLMu59DxEtTzTNEknnTjJWJ7pg6yRIQmKOAZBFQB1yei3H51d8AaKtJw0yZwH2wR2sfjw7eIDSE8EZ3K3i@JpIjhELJReGC1iZaBvpq/lso1/Piy5EjGb8um7UJv2qL/RhkevZRL1jQonJh/xihnWsS726U0iJ@nTJduMefr4u1Jskw@45mvTpl@dP7n8q//hveednQGbsoXhU5ipOEpj9rkBE8MqVnewCs0cGOhQfkLAesEn4SycgNkseBuYnMKCK40YIJHhPwmXXGuv2wUKwaAH1@ECtvAylHD0VlLXUce3tqB88qZchUsOhOi1nMRTTsPd3le86MVuYRh0ez341VPMhLF9fubRrO@TaMzVNWKznUSX/ORleIru0ovWn/Tt0kwswfE7vbCzOca1HevTUp5igxaGP8EPojB5E8rpZWgxZUR1kDOE1WGl0aIZZWhGAfK9rhlHIMgEaCxMwqOVfUYwGJeWNWE6bcQzr0XBcKVP2ukCW7rXtbH0ZxvOzuPrz23QaPSSS0509nFZlkDLORwlXQs6babA/c7LOBZtWFZMQRsGCZz3YDmsxEoXhTO9YULzDEvVAQHn0GCDy1SIZwt6DeegN7C1j7g4fH70CKh347VaP4Fv2iBoEdVoAo09a6xGbJ2dpd3hzDeBf7O5BXEL6hYDZKzkPQEkL5lgcsLfVfFcNOK5cPCoOh71HfFcOXhiM@dqFWLCMcy1SpBbJDLwVtjNMduIEWsVi2ONjU3e2GDJvJWaK3Npa9JnWNKUVcqpzS/2ZElPCxXTnCV8lXfbZC/Bpns1LANOIsp03rzNoeDmzLtoTgZOdD8NnSlIq3Tcrxt3C@85lvUzKtndWjRr2JydPVBJlVJywlIhZZmr18M3llMGbwNrC@9QYVUqy4Gn6vCuvg3elQvvvvJqtYp8/4ErsPk8qhTMvkBgveDZQeceMFcknCiHk131bMr2tlEWKsNKWWjIxjdKQ5MGVCZX3oFU/SAdKGjLJd05VfOElV2NmXPMQUPmGvW9OXV1pf/8FVJ/VE9qTey/f1YfEvyjerZrkn8g3Xss/N@Ogx9z7yn4xMLrlApBl5@jZde9CK2KVuVQOTtjUNwxOxV5yQ6Lco7iGue1Uracm13FTRTKMSpufu64Z@RzYJRIw@Yttbb3qEqI57Y7u1@K8oLZcOW8dw7h4rQ3tX2gz1O3LwwqdCWqwHYWV6i8T2kLXCiBPypf09YazsHe0B/jQFvZNMB/eiJ04MKgHoVdFCS7cqIgYkDdprB2n9jbKjYyk7Im5ZpUpZhr0@XcUlvoE4qeg7BzlEhyKKrOC5GVL1zlXHjlTOlQ6/X9@GyYcEuRLsC@Cj1W2p67db5dBiy0KudKO7RbJTnA@iHa93ivT/ul3FtEJf17@uTVI9Omu5fpjNlD@aqE@bGCdvWvBa2M8EVydbVXp65kuXJVrdL6KJV1qD1JCUopKfXKkSv1QND8SaxLhXJCiqaYWY9qkKur@rZEN5XXAZaajamw1pRQQbkeVRSELTNyzLePUhW5ohJxSthWbzapsOulzYET4ObA3@XmwEZmUtakXNP9cmWnE@587oTudsH9okSGTtEmVlVe6pvBqZ1MGPfPrauHNtG/Y7eUK5HKVZ3v2rZ0ZUPntIuC9EOsH6L9IblyubfzlhM/QH7r6/Tq6tv0Cl@oFiqMuCZlGbyVZpi3e9h@hj8h3NxACOenMHjehv90OkN8n8IrNg6dzPnkzhlZ9PTgmt3xv@chKpx/I6GDAS56IB/LANLwXgvB/E4HSWZWPAIJ5xfwJIA0ynDopVg@Kj4L1xnEQflaMBzu2RGy358wScHiJbefQNkCBtshDEycfVRa0HoWtJ4UyRBfVqr@9GUi6boTuW8v9qOEa3TeTerzSp2MkY7Blh7qDvMumNSJsh7KKV9/mME8HYZknD61BVAdZooB1u0C5tbJRmvyHNYrKsXTBhzxJhSGK8wDpS1HoDPgPUQQIETPM2pzydUnbtlxX@aq1KSfjaHjfB4tRjIgKmah0ma0sDkDP2L4y74MMDhN3wrGAdZA8ebA8pcFsiMbOGAkuMTeiF5MWDZ6TFas8kp0gkofjJtxVX2l3dMS2cxmSHf1e@SNPv@Scfyz/6St2SkWMRLDfvYltoLU768ET2yfkYckyk5OTjq4kiahqBIQyglILMGIKMpK9AGKnTW4o76GXriX33sJfIC5Q@Ts05JRTS@1LPNwLV/CV4suWiaexl244xwrXbHJHcQzsIxoMHNmYEX/HLnjtqoXHH9J@jaNNhRxrhNhiLbVPEaVknZ1XsQWf@AdLJwywz9yFem@sSRUZae8f@19wqh/uXDEoSk2SYTiJlGSxvXK52bvedc4/p79ChDxqF321b4H@LNYTAW4hXJ8DPPADdMjPc@ZQ3Goisgc3/NRMgfrbtLrDkbdJRKA6mlYiOfNvA2@rf1NQJ2X6O8XG34dwBITu027ZyKkPJW2ZGhPAb9pqZgo@haBiwsgnDb7pIADdyneJJYITEaY6jQL5IjnwjWeNE22W6geIcfHhfQ0uw8WXSrFIY7jS1uuzJ5i3FFPbo2pfuOBl5bxgPq6cB8IPrODhvUdgEmWfG3cf7000jFYDLN7sJ2OxhycjhxQ2FFGKSweAfZfUzepjFBBONrwG@hx3hjjOik3ZMYu1BOf4S2M/mp6wB7Us75hijAb2oDPnsPAD9vwC/zSBtmG4xt5HJT3iqd0qXhEx/9pI@DhbvffyUywT3p3@vbd7tVGsiicpI2PgplZrKLd6Xh3Ot@9ePECH2eJDmP5Pw "Clean – Try It Online") Save to `main.icl` and compile with: `clm -fusion -b -IL Dynamics -IL StdEnv -IL Platform main` This produces a file `a.out` which should be run as `a.out -h <heap_size>M -s <stack_size>M`, where `<heap_size> + <stack_size>` is the memory that will be used by the program in megabytes. (I generally set the stack to 50MB, but I rarely have programs use even that much) [Answer] # ~~[Scala](https://www.scala-lang.org/), score 137~~ # Edit: The code here oversimplifies the problem. Thus, the solution works for *many* inputs, but not for all. --- # Original Post: ## Basic Idea ### Simpler problem Let's simplify the problem first: We seek for a string containing all \$n\$ first primes, as *short* as possible. (not necessarily the lowest number) First, we generate the set of primes, and remove all, that are already substrings of others. Then, we can apply multiple rules, i.e. if there is only one string ending in a sequence and only one starting with that same sequence, we can merge them. Another one would be that if a string starts and ends with the same sequence (as 101 does), we can append/prepend it to another string without changing that's ends. (Those rules only yield under certain conditions, so be careful when to apply them) If we have no remaining equal ends/starts of strings, we can just concatenate them and have a minimal-length string containing all \$n\$ first primes. Those rules are not trivial to figure out, but most of the time, they are sufficient to solve this problem in (I think..) \$O(n^4)\$ or less. There are cases (i.e. in the generation for \$n=128\$), where those rules are not sufficient. There, we have to fall back to an algorithm taking NP time. ### The real problem With the algorithm from above, we can calculate the length \$k\$ of the result. Imagine we had a god-given start of the sequence: ``` 10103.............. ^ we want to know this digit ``` Then we can just take our algorithm from the simplified problem to test *if* there is a sequence starting with `10103`**`0`**, containing all \$n\$ primes and having length \$k\$. If there is, we can continue with the next digit, because the smallest number seeked cannot be bigger than that. If not, we increase the last digit, so we get `10103`**`1`** and test with that. Starting with the empty string, we can generate the wanted number in \$O(n\cdot\log(n))\times\text{the time for the simpler algorithm}\$. Thus, if the rules in the algorithm above were always sufficient, the problem would have been shown not to be NP-hard. The "TSP-solving" part in my program is done only by simplification, if possible (that is possible for the first 127 numbers). (When it is possible, we could translate the tail-recursive `findSeq` to a loop, so we could prove it not to be NP-hard). It only gets tricky, if simplification is not sufficient, what happens the first time for \$n=128\$. # Try online Scastie timeouts after 30s, so it stops at \$n\approx75\$ <https://scastie.scala-lang.org/Y9aPRusTRY2ve4avaKAsrA> # Code ``` import scala.annotation.tailrec object Better { var primeLength: Int = 3 var knownLengths: Map[(String,List[String]), Int] = Map() def main(args: Array[String]): Unit = { val start = System.currentTimeMillis() var last = "" Stream.from(1).foreach { i => primeLength = primeList(i-1).toString.length val pcn = if (last.contains(primeList(i-1).toString)) last else calcPrimeContainingNumber(i) last = pcn if (System.currentTimeMillis() - start > 300 * 1000) // reached the time limit while calculating the last number, so, discard it and exit return println(i + ": " + pcn) } } def calcPrimeContainingNumber(n: Int): String = { val numbers = relevantNumbers(n) generateIntegerContainingSeq(numbers, numOfDigitsRequired(numbers, "X"), "X").tail } def relevantNumbers(n: Int): List[String] = { val primesRaw = primeList.take(n) val primes = primesRaw.map(_.toString).foldRight(List[String]())((i, l) => if (l.exists(_.contains(i))) l else i +: l) primes.sorted } @tailrec def generateIntegerContainingSeq(numbers: List[String], maxDigits: Int, soFar: String): String = { if (numbers.isEmpty) return soFar val nextDigit = (0 to 9).find(i => numOfDigitsRequired(numbers.filterNot((soFar + i).contains), soFar + i) == maxDigits).get generateIntegerContainingSeq(numbers.filterNot((soFar + nextDigit).contains), maxDigits, soFar + nextDigit) } def numOfDigitsRequired(numbers: List[String], soFar: String): Int = { soFar.length + knownLengths.getOrElse((soFar.takeRight(primeLength - 1), numbers), { val len = findAnySeq(soFar :: numbers).length - soFar.length knownLengths += (soFar.takeRight(primeLength - 1), numbers) -> len len }) } def findAnySeq(numbers: List[String]): String = { val tails = numbers.flatMap(_.tails.drop(1).toSeq.dropRight(1)).distinct .filter(t => numbers.exists(n1 => n1.startsWith(t) && numbers.exists(n2 => n1 != n2 && n2.endsWith(t)))) // require different strings for start & end .sorted.sortBy(-_.length) val safeTails = tails.filterNot(t1 => tails.exists(t2 => t1 != t2 && t2.contains(t1))) // all those which are not substring of another tail @inline def merge(e: String, s: String, i: Int): String = findAnySeq((numbers diff List(e, s)) :+ (e + s.drop(i))) safeTails.foreach { overlap => val ending = numbers.filter(_.endsWith(overlap)) val starting = numbers.filter(_.startsWith(overlap)) if (ending.nonEmpty && starting.nonEmpty) { if (ending.size == 1 && starting.size == 1 && ending != starting) { // there is really only one way return merge(ending.head, starting.head, overlap.length) } val startingAndEnding = ending.filter(_.startsWith(overlap)) if (startingAndEnding.nonEmpty && ending.size > 1) { return merge(ending.filter(_ != startingAndEnding.head).head, startingAndEnding.head, overlap.length) } else if (startingAndEnding.nonEmpty && starting.size > 1) { return merge(startingAndEnding.head, starting.filter(_ != startingAndEnding.head).head, overlap.length) } } } @inline def startsRelevant(n: String): Boolean = tails.exists(n.startsWith) @inline def endsRelevant(n: String): Boolean = tails.exists(n.endsWith) safeTails.foreach { overlap => val ending = numbers.filter(_.endsWith(overlap)) val starting = numbers.filter(_.startsWith(overlap)) ending.find(!startsRelevant(_)).foreach { e => starting.find(endsRelevant) .orElse(starting.headOption) // if there is no relevant starting, take head (ending is already shown to be irrelevant) .foreach { s => return merge(e, s, overlap.length) } } ending.find(startsRelevant).foreach { e => starting.find(!endsRelevant(_)).foreach { s => return merge(e, s, overlap.length) } } } safeTails.foreach { overlap => val ending = numbers.filter(_.endsWith(overlap)) val starting = numbers.filter(_.startsWith(overlap)) return ending .flatMap(e => starting.filter(_ != e).map(s => merge(e, s, overlap.length))) .minBy(_.length) } if (tails.nonEmpty) throw new Error("that was unexpected :( " + numbers) numbers.mkString("") } // 1k primes val primeList = Seq(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71 , 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173 , 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281 , 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409 , 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541 , 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659 , 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809 , 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941 , 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069 , 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223 , 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373 , 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511 , 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657 , 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811 , 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987 , 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129 , 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287 , 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423 , 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617 , 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741 , 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903 , 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079 , 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257 , 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413 , 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571 , 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727 , 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907 , 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057 , 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231 , 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409 , 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583 , 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751 , 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937 , 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087 , 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279 , 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443 , 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639 , 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791 , 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939 , 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133 , 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301 , 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473 , 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673 , 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833 , 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997 , 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207 , 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411 , 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561 , 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723 , 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919) } ``` As Anders Kaseorg pointed out in the comments, this code may return suboptimal (thus, wrong) results. # Results The results for \$n\in[1,200]\$ match those from japh except for `187`, `188`, `189`, `193`. ``` 1: 2 2: 23 3: 235 4: 2357 5: 112357 6: 113257 7: 1131725 8: 113171925 9: 1131719235 10: 113171923295 11: 113171923295 12: 1131719237295 13: 11317237294195 14: 1131723294194375 15: 113172329419437475 16: 1131723294194347537 17: 113172329419434753759 18: 2311329417434753759619 19: 231132941743475375961967 20: 2311294134347175375961967 21: 23112941343471735375961967 22: 231129413434717353759619679 23: 23112941343471735359619678379 24: 2311294134347173535961967837989 25: 23112941343471735359619678378979 26: 2310112941343471735359619678378979 27: 231010329411343471735359619678378979 28: 101031071132329417343475359619678378979 29: 101031071091132329417343475359619678378979 30: 101031071091132329417343475359619678378979 31: 101031071091131272329417343475359619678378979 32: 101031071091131272329417343475359619678378979 33: 10103107109113127137232941734347535961967838979 34: 10103107109113127137139232941734347535961967838979 35: 10103107109113127137139149232941734347535961967838979 36: 1010310710911312713713914923294151734347535961967838979 37: 1010310710911312713713914915157232941734347535961967838979 38: 1010310710911312713713914915157163232941734347535961967838979 39: 10103107109113127137139149151571631672329417343475359619798389 40: 10103107109113127137139149151571631672329417343475359619798389 41: 1010310710911312713713914915157163167173232941794347535961978389 42: 101031071091131271371391491515716316717323294179434753596181978389 43: 101031071091131271371391491515716316723294173434753596181917978389 44: 101031071091131271371391491515716316717323294179434753596181919383897 45: 10103107109113127137139149151571631671731792329418191934347535961978389 46: 10103107109113127137139149151571631671731791819193232941974347535961998389 47: 101031071091271313714915157163167173179181919321139232941974347535961998389 48: 1010310710912713137149151571631671731791819193211392232941974347535961998389 49: 1010310710912713137149151571631671731791819193211392232272941974347535961998389 50: 10103107109127131371491515716316717317918191932113922322722941974347535961998389 51: 101031071091271313714915157163167173179181919321139223322722941974347535961998389 52: 101031071091271313714915157163167173179181919321139223322722923941974347535961998389 53: 1010310710912713137149151571631671731791819193211392233227229239241974347535961998389 54: 101031071091271313714915157163167173179211392233227229239241819193251974347535961998389 55: 101031071091271313714915157163167173179211392233227229239241819193251972574347535961998389 56: 101031071091271313714915157163167173179211392233227229239241819193251972572634347535961998389 57: 101031071091271313714915157163167173179211392233227229239241819193251972572632694347535961998389 58: 101031071091271313714915157163167173179211392233227229239241819193251972572632694347535961998389 59: 1010310710912713137149151571631671731792113922332277229239241819193251972572632694347535961998389 60: 101031071091271313714915157163167173211392233227722923924179251819193257263269281974347535961998389 61: 1010310710912713137149151571631671732113922332277229239241792518191932572632692819728343475359619989 62: 10103107109127131371491515716316717321139223322772293239241792518191932572632692819728343475359619989 63: 1010307107109127131371491515716316717321139223322772293239241792518191932572632692819728343475359619989 64: 10103071071091271311371391491515716316721173223322772293239241792518191932572632692819728343475359619989 65: 10103071071091271311371491515716313916721173223322772293239241792518191932572632692819728343475359619989 66: 10103071071091271311371491515716313921167223317322772293239241792518191932572632692819728343475359619989 67: 10103071071091271311371491515716313921167223317322772293239241792518191932572632692819728343475359619989 68: 1010307107109127131137149151571631392116722331732277229323924179251819193257263269281972833743475359619989 69: 1010307107109127131137149151571631392116722331732277229323924179251819193257263269281972833743475359619989 70: 101030710710912713113714915157163139211672233173227722932392417925181919325726326928197283374347534959619989 71: 101030710710912713113714915157163139211672233173227722932392417925181919325726337269281972834743534959619989 72: 101030710710912713113714915157163139211672233173227722932392417925181919337257263472692819728349435359619989 73: 10103071071091271311371491515716313921167223317322772293372392417925181919347257263492692819728353594367619989 74: 101030710710912713113714915157163139211672233173227722932392417925181919337347257263492692819728353594367619989 75: 1010307107109127131137313914915157163211672233173227722933792392417925181919347257263492692819728353594367619989 76: 101030710710912713113731391491515716321167223317322772293379239241792518191934725726349269281972835359438367619989 77: 101030710710912713113731391491515716321167223317337922772293472392417925181919349257263535926928197283674383896199 78: 1010307107109127131137313914915157163211672233173379227722934723972417925181919349257263535926928197283674383896199 79: 101030710710912713113731391491515721163223317337922772293472397241672517925726349269281819193535928367401974383896199 80: 101030710710912713113731391491515721163223317337922772293472397241672517925726349269281819193535928367401974094383896199 81: 101030710710912713113731391491515721163223317337922772293472397241916725179257263492692818193535928367401974094383896199 82: 1010307107109127131137313914915157223317322772293379239724191634725167257263492692817928353594018193674094211974383896199 83: 1010307107109127131137313914922331515722772293379239724191634725167257263492692817353592836740181938389409421197431796199 84: 101030710710912713113731391492233151572277229323972419163472516725726349269281735359283674018193838940942119743179433796199 85: 101030710710912713113731391492233151572277229323924191634725167257263492692817353592836740181938389409421197431794337943976199 86: 1010307107109127131137313914922331515722772293239241916347251672572634926928173535928367401819383894094211974317943379443976199 87: 1010307107109127131137313914922331515722772293239241916347251672572634926928173535928367401819383894094211974317943379443974496199 88: 1010307107109127131137313914922331515722772293239241916347251672572634926928173535928367401819383894094211974317943379443974494576199 89: 10103071071091271311373139149223315157227722932392419163472516725726349269281735359283674018193838940942119743179433794439744945746199 90: 10103071071091271311373139149223315157227722932392419163251672572634726928173492835359401819367409421197431794337944397449457461994638389 91: 10103071071091271311373139149223315157227722932392419163251672572634726928173492835359401819367409421197431794337944397449457461994638389467 92: 101030710710912713113731391492233151572277229323924191632516725726347926928173492835359401819367409421197431794337944397449457461994638389467 93: 101030710710912713113731391492233151572277229323924191632516725726347926928173492835359401819367409421197431794337944397449457461994638389467487 94: 101030710710912713113731392233149151572277229323924191632516725726347926928173492835359401819367409421197431794337944397449457461994638389467487 95: 1010307107109127131137313922331491515722772293239241916325167257263479269281734928353594018193674094211974317943379443974499457461994638389467487 96: 1010307107109127131137313922331491515722772293239241916325167257263269281734792834940181935359409421197431794337944397449945746199463674674875038389 97: 1010307107109127131137313922331491515722772293239241916325167257263269281734792834940181935359409421197431794337944397449945746199463674674875038389509 98: 101030710710912713113732233139227722932392419149151572516325726326928167283479401734940942118193535943179433794439744994574619746367467487503838950952199 99: 1010307107109127131137322331392277229324191491515725163257263269281672834794017349409421181935359431794337944394499457461974636746748750383895095219952397 100: 101030710710922331127131373227722932414915157251632572632692816728347940173494094211394317943379443944994574618191935359463674674875038389509521975239754199 101: 101030710710922331127131373227722932414915157251632572632692816728347401734940942113943179433794439449945746181919353594636746748750383895095219752397541995479 102: 101030710710922331127131373227722932414915157251632572632692816728347401734940942113943179433794439449945746181919353594636746748750383895095219752397541995479557 103: 101030710710922331127131373227722932414915157251632572632692816728340173474094211394317943379443944945746181919349946353594674875036750952197523975419954795575638389 104: 101030710710922331127131373227722932414915157251632572632692816728340173474094211394317943379443944945746181919349946353594674875036750952197523975419954795575638389569 105: 101030710722331109227127722932413137325149151571632572632692816728340173474094211394317943379443944945746181919349946353594674875036750952197523975419954795575638389569 106: 1010307107223311092271277229324131373251491515716325726326928167283401734740942113943179433794439449457461819193499463535946748750367509521975239754199547955775638389569 107: 1010307107223311092271277229324131373251491515716325726326928167283401734740942113943179433794439449457461819193499463535946748750367509521975239754199547955775638389569587 108: 10103071072233110922712772293241313732514915157163257263269281672834017340942113943179433794439449457461819193474634994674875035359367509521975239754199547955775638389569587 109: 10103071072233110922712772293241313732514915157163257263269281672834017340942113943179433794439449457461819193474634994674875035359367509521975239754199547955775638389569587599 110: 1010307223311072271092293241277251313732571491515726326928163283401674094211394317343379443944945746179463474674875034995095218191935359367523975419754795577563838956958759960199 111: 1010307223311072271092293241277251313732571491515726326928163283401674094211394317343379443944945746179463474674875034995095218191935359367523975419754795577563838956958759960199607 112: 1010307223311072271092293241277251491515716325726326928167283401734094211313734317943379443944945746139463474674875034995095218191935359367523975419754795577563838956958759960199607 113: 22331101030722710722932410925127725714915157263269281632834016740942113137343173433794439449457461394634746748750349950952181919353593675239754197547955775638389569587599601996076179 114: 2233110103072271072293241092512571277263269281491515728340163409421131373431734337944394494574613946347467487503499509521675239754191819353593675479557756383895695875996019760761796199 115: 22331010307227107229324109251257126311277269281491515728340163409421131373431734337944394494574613946347467487503499509521675239754191819353593675479557756383895695875996019760761796199 116: 22331010307227107229324109251257126311269281277283401491515740942113137343173433794439449457461394634674875034750952163499523975416754795577563535936756958759960181919383896076179619764199 117: 223310103072271072293241092512571263112692812772834014915157409421131373431734433794494574613946346748750347509521634995239541675479557756353593675695875996018191938389607617961976419964397 118: 223310103072271072293241092512571263112692812772834014915157409421131373431734433794494574613946346748750347509521634995239541675475577563535936756958759960181919383896076179619764199643976479 119: 223310103072271072293241092512571263112692812772834014915157409421131373431734433794494574613946346748750347509521634995239541675475577563535695875935996018191936760761796197641996439764796538389 120: 2233101030722710722932410925125712631126928127728340149151574094211313734317344337944945746139463467487503475095216349952395416754755775635356958760181919359367607617961976419964397647965383896599 121: 22331010307227107229324109251257126311269281277283401491515740942113137343173443379449457461394634674875034750952163499523954167547557756353569587601819193593676076179641976439764796538389659966199 122: 223310103072271072293241092512571263112692812772834014915157409421131373431734433794494574613946346734748750349950952163523954167547557756353569587601819193593676076179641976439764796538389659966199 123: 2233101030722710722932410925125712631126928127728340149151574094211313734317344337944945746139463467347487503499509521635239541675475577563535695876018191935936776076179641976439764796538389659966199 124: 2233101030722710722932410925125712631126928127728340149151574094211313734317344337944945746139463467347487503499509521635239541675475577563535695876018191935936076179641976439764796536776599661996838389 125: 22331010307227107229324109251257126311269127728128340149151574094211313734317344337944945746139463467347487503499509521635239541675475577563535695876018191935936076179641976439764796536776599661996838389 126: 2233101030701072271092293241251257126311269127728128340149151574094211313734317344337944945746139463467347487503499509521635239541675475577563535695876018191935936076179641976439764796536776599661996838389 127: 223310103070107092271092293241251257126311269127728128340149151574094211313734317344337944945746139463467347487503499509521635239541675475577563535695876018191935936076179641976439764796536776599661996838389 128: 223310103070107092271092293241251257191263112691277281283401491515740942113137343173443379449457461394634673474875034995095216352395416754755775635356958760181935936076179641976439764796536776599661996838389 129: 22331010307010709227109229324125125719126311269127277281283401491515740942113137343173443379449457461394634673474875034995095216352395416754755775635356958760181935936076179641976439764796536776599661996838389 130: 223307010103227092293241072510925712631126912719128128340140942113137331491515727743173443379449457461394634673474875034995095216352395416754755775635356958760181935936076179641976439764796536776599661996838389 131: 2233070101032270922932410725109257126311269127191281283401409421131373314915157277431734433794494574613946346739487503475095216349952395416754755775635356958760181935936076179641976439764796536776599661996838389 132: 2233070101032270922932410725109257126311269127191281283401409421131373314915157277431734433794494574613946346739487503475095216349952395416754755775635356958760181935936076179641976439764796536776599661996838389 133: 223307010103227092293241072510925712631126912719128128340140942113137331443173449149457277433794613946346739487503475095215157516349952395416754755775635356958760181935936076179641976439764796536776599661996838389 134: 22330701010322709229324107251092571263112691271912812834014094211313733144317344914945727743379461394634673948750347509521515751634995239541675475575635356958757760181935936076179641976439764796536776599661996838389 135: 22330701010322709229324107251092571263112691271912812834014094211313733144317344914945727743379461394634673948750347509521515751634995239541675475575635356958757760181935936076179641976439764796536776599661996838389 136: 2233070101032270922932410725109257126311269127191281283401409421131373314431734491494572774337946139463467394875034750952151575163499523954167547557563535695875776018193593607617964197643976479653677696599661996838389 137: 22330701010322709229324107251092571263112691271912812834014094211313733144317344914945727734613946346739487433795034750952151575163499523954167547557563535695875776018193593607617964197643976479653677696599661996838389 138: 2233070101032270922932410725109257126311269127191281283401409421131373314431734491494572773461394634673948743379503475095215157516349952395416754755756353569587577601819359360761796419764397647965367787696599661996838389 139: 22330701010322709229324107251092571263112691271912812834014094211313733144317344914945727734613946346739487433795034750952151575163499523954167547557563535695875776018193593607617964197643976479765367787696599661996838389 140: 22330701010322709229324107251092571263112691271912812834014094211313733144317344914945727734613946346739487433795034750952151575163499523954167547557563535695875776018193593607617964197643976479765367787696599661996838389809 141: 223307010103227092293241072510925712631126912719128112834014094211313733144317344914945727734613946346739487433795034750952151575163499523954167547557563535695875776018193593607617964197643976479765367787696599661996838389809 142: 223307010103227092293241072510925712631126912719128112834014094211313733144317344914572773461394634673948743379503475095214952395415157516349954755756353569587577601676076179641935936439764797653677659966197876968383898098218199 143: 223070101032270922932410725109257126311269127191281128340140942113137331443173449145727734613946346739487433475034950952149952337954151575163535475575635695875776016760761796419359364396479765367765996619768383898098218199823978769 144: 223070101032270922932410725109257126311269127191281128340140942113137331443173449145727433461394634673474875034950952149952337954151575163535475575635695875773960167607617964193593643964797653677659966197683838980982181998239769827787 145: 223070101032270922924107251092571263112691271912811283401409421131373314431734491457274334613946346734748750349509521499523379541515751635354755756356958757739601676076179641935936439647976536599661976836776980982181998239782778782938389 146: 2230701010322709229241072510925712631126912719128112834014094211313733144317344914572743346139463467347487503495095214995233795415157516353547557563569587577396016760761796419359364396479765367765996619768383976980982181998239827787829389 147: 2230701010322709229241072510925712631126912719128112834014094211313733144317344914572743346139463467347487503495095214995233795415157516353547557563569587577396016760761796419359364396479765365996619768367769809821819982397827787829383985389 148: 2230701010322709229241072510925712631126912719128112834014094211313733144317344914572743346139463467347487503495095214995233795415157516353547557563569587576016760761796419359364396479765365996619768367739769809821819982398277829383985389857787 149: 2230701010322709229241072510925712631126912719128112834014094211313733144317344914572743346139463467347487503495095214995233795415157516353547557563569587576016760761796419359364396479765365966197683677397698098218199823982778293839853898577878599 150: 2230701010322709229241072510925712631126912719128112834014094211313733144317344914572743346139463467347487503495095214995233795415157516353547557563569587576016760761796419359364396479765365966197683677397698098218199823982778293839853857787859986389 151: 22307010103227092292410725109257126311269127191281128340140942113137331443173449145727433461394634673474875034950952149952337954151575163535475575635695875760167607617964193593643964797653659661976836773976980982181998239827782938398538577877859986389 152: 22307010103227092292410725109257126311269127191281128340140942113137331443173449145727433461394634673474875034950952149952337954151547515755756353569587576016359360761796419364396479765365966197683676980982167739782398277829383985385778778599863898818199 153: 22307010103227092292410725109257126311269127191281128340140942113137331443173449145727433461394634673474875034950952149952337954151547515755756353569587576016359360761796419364396479765365966197683676980982167739782398277829383853857787785998638988181998839 154: 22307010103227092292410725109257126311269127191281128340140942113137331443173449145727433461394634673474875034950952149952337954151547515755756353569587576016359360761796419364396479765365966197683676980982167739782398277829383853857785998638988181998839887787 155: 2230701010322709072292410725109257126311269127191281128340140942113137331443173449145727433461394634673474875034950952149952337954151547515755756353569587576016359360761796419364396479765365966197683676980982167739782398277829383853857785998638988181998839887787 156: 22307010103227090722924107251092571263112691127191281128340140942113137331443173449145727433461394634673474875034950952149952337954151547515755756353569587576016359360761796419364396479765365966197683676980982167739782398277829383853857785998638988181998839887787 157: 22307010103227090722924107251092571263112691127191281128340140942113137331443173449193457274334613946346734748750349509521499523379541515475155756353569587576015760761796419764396479765359365966199683676980982163823978277398293838538577859986389881816778778839887 158: 2230701010322709072292410725109257126311269112719128112834014092934211313733144317344919345727433461394634673474875034950952149952337954151547515575635356958757601576076179641976439647976535936596619968367698098216382397827739829853838577859986389881816778778839887 159: 22307010103227090722924107251092571263112691127191281128340140929342113137274314433173344919345746139463467347487503495095214995233735354151547515575635695875760157607617964197643964796535937976596619968367698098216382397827739829853838577859986389881816778778839887 160: 2230701010322709072292410725109257126311269112719128112834014092934211313727431443317334491934574613941463467347487503495095214995233735354151547515575635695875760157607617964197643964796535937976596619968367698098216382397827739829853838577859986389881816778778839887 161: 223070101032270907229241072510925712631126911271912811283401409293421131372743144331733449193457461394146346734748750349475095214995233735354151547515575635695875760157607617964197643964796535937976596619968367698098216382397827739829853838577859986389881816778778839887 162: 22307010103227090722924107251092571263112691127191281128340140929342113137274314433173344919345746139414634673474875034947509521499523373535415154751557563569535875760157607617964197643964796535937976596619968367698098216382397827739829853838577859986389881816778778839887 163: 2230701010322709072292410725109257126311269112719128112834014092934211313727431443317334491934574613941463467347487503494750952149952337353541515475155756356953587576015760761796419764396479653593797659661996768367698098216382397827739829853838577859986389881816778778839887 164: 22307010103227090722924107251092571263112691127128112834014092934211313727431443317334491457461394146346734748750349475095214995233735354151547515575635695358757601576076179641919359379643964797197653659661996768367698098216382397827739829853838577859986389881816778778839887 165: 223070101032270907229241072510925712631126911271281128340140929342113137274314433173344914574613941463467347487503494750952149952337353541515475155756356953587576015760761796419193593796439647971976536596619967683676980982163823977398277829853838577859986389881816778778839887 166: 22307010103227090722924107251092571263112691127128112834014092934211313727431443317334491457461394146346734748750349475095214995233735354151547515575635695358757601576076179641919359379643964797197653659661996768367698098216382397739827782983838538577859986389881816778778839887 167: 223070101032270907229241072510925712631126911271281128340140929342113137274314433173344914574613941463467347487503494750952149915152337353541547515575635695358757601576076179641919359379643964797197653659661996768367698098216382397739827782983838538577859986389881816778778839887 168: 2230701010322709072292410725109257126311269112712811283401409293421131372743144331733449145746139414634673474875034947509521499151523373535415475155756356953587576015760761796419193593796439647971976536596619967683676980982163823977398277829838385385778599786389881816778778839887 169: 2230701009070922710103229241072510925712631126911272728112834014092934211313733144317344914574334613941463467347487503494750952149915152337515415475575635356953587576015760761796419193593796439647971976536596619967683676980982163823977398277829838385385778599786389881816778778839887 170: 22307010090709227101310322924107251092571263112691127272811283401409293421134431373317344914574334613941463467347487503494750952149915152337515415475575635356953587576015760761796419193593796439647971976536596619967683676980982163823977398277829838385385778599786389881816778778839887 171: 22307010090709227101310191032292410725109257126311269112727281128340140929342113443137331734491457433461394146346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 172: 22307010090709227101310191021032292410725109257126311269112727281128340140929342113443137331734491457433461394146346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 173: 223070100907092271013101910210310722924109251257126311269112727281128340140929342113443137331734491457433461394146346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 174: 223070100907092271013101910210310331107229241092512571263132691127272811283401409293421137334431734491457433461394146346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 175: 223070100907092271013101910210310331103922924107251092571263132691127272811283401409293421137334431734491457433461394146346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 176: 223070100907092271013101910210310331103922924104910725109257126313269112727281128340140929342113733443173449414574334613946346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 177: 223070100907092271013101910210310331103922924104910510725109257126313269112727281128340140929342113733443173449414574334613946346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 178: 223070100907092271013101910210310331103922924104910510610725109257126313269112727281128340140929342113733443173449414574334613946346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 179: 223070100907092271013101910210310331103922924104910510610631325107257109263269112727281128340140929342113733443173449414574334613946346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 180: 223070100907092271013101910210310331103922924104910510610631325106911072571092632692811272728340140929342113733443173449414574334613946346734748750349475095214991935233751515415475575635356953587576015760761796419643964796535937971976596619967683676980982163823977398277829838385385778599786389881816778778839887 181: 223070100907092271013101910210310331103922924104910510610631325106911072571087263269281092834012727409293421137334431734494145743346139463467347487503494750952149919352337515154154755756353569535875760157607617964196439647965359379719765966199676836769809821638239773982778298383853857785997863898811816778778839887 182: 2230701009070922710131019102103103311039229241049105106106313251069107257108726326928109112727283401409293421137334431734494145743346139463467347487503494750952149919352337515154154755756353569535875760157607617964196439647965359379719765966199676836769809821638239773982778298383853857785997863898811816778778839887 183: 2230701009070922710131019102103103311039229241049105106106313251069107257108726326928109110932834012727409293421137334431734494145743346139463467347487503494750952149919352337515154154755756353569535875760157607617964196439647965359379719765966199676836769809821638239773982778298383853857785997863898811816778778839887 184: 2230701009070922710131019102103103311039229241049105106106313251069107257108726326928109110932834010971929340941272742113733443173449457433461394634673474875034947509521499193523375151541547557563535695358757601576076179641976439647965359379765966199676836769809821638239773982778298383853857785997863898811816778778839887 185: 2230701009070922710131019102103103311039229241049105106106313251069107257108726326928109110932834010971929340941272742113733443173449457433461394634673474875034947509521499193523375151541547557563535695358757601576076179641976439647965359379765966199676836769809821638239773982778298383853857785997863898811816778778839887 186: 2230701009070922710131019102103103311039229241049105106106313251069107257108726326928109110932834010971929340941272742113733443173449457433461394634673474875034947509521499193523375151541547557563535695358757601576076179641976439647965359379765966199676836769809821638239773982778298383853857785997863898811816778778839887 187: 223070100907092271013101910210310331103922924104910510610631325106910725710872632692810911093283401097192934094127274211173344317433449457461373463467347487503494750952149919352337515154157547557563535695358757601635937960761796419764396479765365966199676836769809821811397739823982778298383853857785997863898816778778839887 188: 223070100907092271013101910210310331103922924104910510610631325106910725710872632692810911093283401097192934094111727421123344317334494574337346137463467347487503494750952127514991935235354151575475575635695358757601635937960761796419764396479765365966199676836769809821811397739823982778298383853857785997863898816778778839887 189: 1009070101307092232271019102103103310491051061063110392292410691072510872571091109326326928109719283401117274092934211233443131733449411294574337346137463467347487503494750952127514991935235354151575475575635695358757601635937960761796419764396479765365966199676836769809821811397739823982778298383853857785997863898816778778839887 190: 10090701013070922322710191021031033104910510610631103922924106910725108725710911093263269281097192834011172740929342112334431317334494112945743373461374634673474875034947509521139523535412751499193547557563569535875760157607617964197643964796535937976596619967683676980982163823977398277829838385385778599786389881151816778778839887 191: 100907010130709101910210310331049105106106311039223227106910722924108725109110932571097192632692811172728340112334092934211294113137334431734494574337461394634673474875034947509521151153523535412751499193547557563569535875760157607617964197643964796535937976596619967683676980982163823977398277829838385385778599786389881816778778839887 192: 1009070101307091019102103103310491051061063110392232271069107229241087251091109325710971926326928111727283401123340929342112941131373344317344945743374613946346734748750349475095211511535235354116354751275575635695358757601499193593796076179641976439647976536596619967683676980982157739778239827782983838538578599786389881816778778839887 193: 1009070101307092232271019102103103310491051061063110392292410691072510872571091109326326928109711171928340112334092934211294113137274317334433734494574613946346734748750349475095211511535235354127514991935475575635695358757601576076179641976439647965359379765966199676836769809821811638239773982778298383853857785997863898816778778839887 194: 10090701013070922322710191021031033104910510610631103922924106910725108725710911093263269281097111719283401123340929342112941131372743173344337344945746139463467347487503494750952115115352353541163547512755756356953587576014991935937960761796419764396479765365966199676836769809821577397782398277829838385385785997863898811816778778839887 195: 100907010130709101910210310331049105106106311039223227106910722924108725109110932571097111719263269281123283401129293409411313727421151153443173344945743346139463467347487503494750952116352337353541181187512754755756356953587576014991935937960761796419764396479765365966199676836769809821577397782398277829838385385785997863898816778778839887 196: 100907010130709101910210310331049105106106310691072231103922710872292410911093251097111711232571926326928112928340113137274092934211511534431733449411634574334613946346734748750349475095211811875119352337353541275475575635695358757601499196076179641976439647965359379765966199676836769809821577397782398277829838385385785997863898816778778839887 197: 100907010130709101910210310331049105106106310691072231103922710872292410911093251097111711232571926326928112928340113137274092934211511534431733449411634574334613946346734748750349475095211811875119352337353541201275475575635695358757601499196076179641976439647965359379765966199676836769809821577397782398277829838385385785997863898816778778839887 198: 1009070101307091019102103103310491051061063106910710872231103922710911093229241097111711232511292571926326928113132834011511534092934211634431733449411811872743345746137346346734748750349475095211935233751201213953535412754755756356958757601499196076179641976439647965359379765966199676836769809821577397782398277829838385385785997863898816778778839887 199: 10090701013070910191021031033104910510610631069107108710911039223110932271097111711232292411292511313257192632692811511532834011634092934211811872743173344334494119345746137346346734748750349475095212012139523375121754127547557563535695358757601499196076179641976439647965359379765966199676836769809821577397782398277829838385385785997863898816778778839887 200: 100907010130709101910210310331049105106106310691071087109109311039110971117112322711292292411313251151153257192632692811632834011811872740929342119344317334494120121373457433461394634673474875034947509521217512233752353541275475575635695358757601499196076179641976439647965359379765966199676836769809821577397782398277829838385385785997863898816778778839887 201: 1009070101307091019102103103310491051061063106910710871091093110391109711171123112922711313241151153251163257192632692811811872728340120121373340929342119344317344941217433457461394634673474875034947509521223375122952353541275475575635695358757601499196076179641976439647965359379765966199676836769809821577397782398277829838385385785997863898816778778839887 202: 1009070101307091019102103103310491051061063106910710871091093110391109711171123112922711313241151153251163257192632692811811872728340120121373340929342119344317344941217433457461394634673474875034947509521223375122952353541275475575635695358757601499196076179641976439647965359379765966199676836769809821577397782398277829838385385785997863898816778778839887 203: 10090701013070910191021031033104910510610631069107108710910931103911097111711231129113132271151153241163251181187257192632692812012137272834012173340929342119344317433449412233734574613946346734748750349475095212295235354123751275475575635695358757601499196076179641976439647965359379765966199676836769809821577397782398277829838385385785997863898816778778839887 204: 100907010130709101910210310331049105106106310691071087109109311039110971117112311291131151153132271163241181187251201213725719263269281217272834012233409293421193443173344941229457433734613946346734748750349475095212375124952353541275475575635695358757601499196076179641976439647965359379765966199676836769809821577397782398277829838385385785997863898816778778839887 205: 1009070101307091019102103103310491051061063106910710871091093110391109711171123112911311511531163132271181187241201213725121725719263269281223283401229293409412372742119344317334494574334613946346734748750349475095212495233735354125937953547512755756356958757601499196076179641976439647976535965966199676836769809821577397782398277829838385385785997863898816778778839887 206: 1009070101307091019102103103310491051061063106910710871091093110391109711171123112911311511531163132271181187241201213725121725719263269281223283401229293409412372742119344317334494574334613946346734748750349475095212495233735354125937953547512773955756356958757601499196076179641976439647976535965966199676836769809821577823977827829838385385785997863898816778778839887 207: 10090701013070910191021031033104910510610631069107108710910931103911097111711231129113115115311631181187227120121313724121725122325719263269281229283401237274092934211934431733449412494574334613946346734748750349475095212593735233795353541277395475127955756356958757601499196076179641976439647976535965966199676836769809821577823977827829838385385785997863898816778778839887 208: 100907010130709101910210310331049105106106310691071087109109311039110971117112311291131151153116311811871201213137227121724122325122925719263269281237274012492934094125934211937334431734494574334613946346734748750349475095212773952337953535412795475128355756356958757601499196076179641976439647976535965966199676836769809821577823977827829838385385785997863898816778778839887 209: 1009070101307091019102103103310491051061063106910710871091093110391109711171123112911311511531163118118712012131217227122313724122925123725719263269281249293401259340941277274211937334431734494574334613946346734748750349475095212795233795353541283547512895575635695875760149919607617964197643964797653596596619967683676980982157739778239827829838385385785997863898816778778839887 210: 1009070101307091019102103103310491051061063106910710871091093110391109711171123112911311511531163118118712012131217227122313724122925123725719263269281249293401259340941277274211937334431734494574334613946346734748750349475095212795233795353541283547512895575635695875760149919607617964197643964797653596596619967683676980982157739778239827829838385385785997863898816778778839887 211: 10090701013070910191021031033104910510610631069107108710910931103911097111711231129113115115311631181187120121312171223137227122924123725124925719263269281259293401277274094127942119344317334494574334613946346734748750349475095212835233735354128953547512975575635695875760149919607617964197643964796535937976596619967683676980982157739778239827829838385385785997863898816778778839887 212: 100907010130101910210310330709104910510610631069107108710910931103911097111711231129113115115311631181187120121312171223227122924123725124925719263269281259293401277274094127942119344313733173449457433461394634673474875034947509521283523375128953535412975475575635695875760149919607617964197643964796535937976596619967683676980982157739778239827829838385385785997863898816778778839887 213: 10090701013010191021031033070910491051061063106910710871091093110391109711171123112911303115115311631181187120121312171223227122924123725124925719263269281259293401277274094127942119344313733173449457433461394634673474875034947509521283523375128953535412975475575635695875760149919607617964197643964796535937976596619967683676980982157739778239827829838385385785997863898816778778839887 214: 1009070101301019102103103310491051061063106910709108710910931103911097111711231129113031151153116311811871201213071217122312292271237241249251259257192632692812772740127929340941283421193443131733449457433461373463467347487503494750952128952337512975413953535475575635695875760149919607617964197643964796535937976596619967683676980982157739778239827829838385385785997863898816778778839887 215: 100907010130101910210310331049105106106310691070910871091093110391109711171123112911303115115311631181187120121307121712231229227123724124925125925719263131926928127727401279293409412834211934431733449457433461373463467347487503494750952128952337512975413953535475575635695875760149919607617964197643964796535937976596619967683676980982157739778239827829838385385785997863898816778778839887 216: 100907010130101910210310331049105106106310691070910871091093110391109711171123112911303115115311631181187120121307121712231229227123724124925125925719263131926928127727401279293409412834211934431733449457433461321289463467347487503494750952129751373523375413953535475575635695875760149919607617964197643964796535937976596619967683676980982157739778239827829838385385785997863898816778778839887 217: 1009070101301019102103103310491051061063106910709108710910931103911097111711231129113031151153116311811871201213071217122312291237227124924125925127725719263131926928127929340128340941289421193443173344945727433461321297463467347487503494750952132751373523375413953535475575635695875760149919607617964197643964796535937976596619967683676980982157739778239827829838385385785997863898816778778839887 218: 1009070101301019102103103310491051061063106910709108710910931103911097111711231129113031151153116311811871201213071217122312291237227124924125925127725719263131926928127929340128340941289421193443173344945727433461297463467347487503494750952132132751361373523375413953535475575635695875760149919607617964197643964796535937976596619967683676980982157739778239827829838385385785997863898816778778839887 219: 100907010130101910210310331049105106106310691070910871091093110391109711171123112911303115115311631181187120121307121712231229123712492271259241277251279257192631319269281283401289293409412972742119344317334494574334613213274634673474875034947509521361367513735233754139535354755756356958757601499196076179641976439647965359379765966199676838098215769823977398278298383853857785997863898816778778839887 220: 100907010130101910210310331049105106106310691070910871091093110391109711171123112911303115115311631181187120121307121712231229123712492271259241277251279257192631319269281283401289293409412972742119344317334494574334613213274634673474875034947509521361367513735233754139535354755756356958757601499196076179641976439647965359379765966199676838098215769823977398278298383853857785997863898816778778839887 221: 100907010130101910210310331049105106106310691070910871091093110391109711171123112911303115115311631181187120121307121712231229123712492271259241277251279257192631319269281283401289293409412972742119344317334494574334613213274634673474875034947509521361367513735233754138139535354755756356958757601499196076179641976439647965359379765966199676838098215769823977398278298383853857785997863898816778778839887 222: 1009070101301019102103103310491051061063106910709108710910931103911097111711231129113031151153116311811871201213071217122312291237124922712592412772512792571926313192692812834012892934094129727421193443173344945743346132132746346734748750349475095213613675137352337541381399195353547557563569587576014996076179641976439647965359379765966199676838098215769823977398278298383853857785997863898816778778839887 ``` ]
[Question] [ Let's start by defining a **reflection** of a character in a string: > > Given a string with distinct lowercase alphabetical letters with no spaces such > as `abcdefg`, define a reflection of a letter in the string `c` as > moving it (without changing the order of any other letter) to a new > place in the string such that the number of letters originally to the > right of it is now the number of letters to the left of it. > > > Thus, a reflection of the letter `c` in `abcdefg` would be `abdecfg`. *Explanation: there were 4 letters to the right of `c` and now, there are 4 letters to the left of `c`.* Some more examples: > > Reflecting the character `e` in `myfriend` would form the string `myefrind` > > > Reflecting the character `a` in `axyz` would form the string `xyza`. > > > Reflecting the character `b` in `abc` would form the string `abc`. > > > Reflecting the character `d` in `d` would form the string `d`. > > > Reflecting the character `e` in `ef` would form the string `fe`. > > > For more information or to try out some test cases, [here](http://cpp.sh/7b7bx) is a (somewhat long) program I wrote in C++. ## The Challenge Given a string with distinct lowercase letters, go through each character alphabetically and "reflect" it in the string. *Clarifications: The letters in the string are from `a-z`, there are no spaces, the letters are unique, and the string is at least 1 letter long and at most 26 letters long.* ## Examples > > Input: `dcba`. Output: `dcba`. > > > *Reason: First, reflect the `a` as it is the character in the string that comes earliest in the alphabet. You will get `adcb`. Then, reflect the `b` as it comes next in the alphabet, to get `badc`. Then, reflect the `c` to get `cbad`, and then the `d` to get `dcba`.* --- > > Input: `myface`. Output: `fyecma`. > > > *Hint: Go through the letters in the order `a, c, e, f, m, y`.* --- > > Input: `a`. Output: `a`. > > > --- > > Input: `acb`. Output: `bac`. > > > --- > > Input: `cwmfjordbankglyphsvextquiz`. Output: `ieabhqzugdltkfnvpjxsormycw`. > > > ## Scoring * The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. * Accepting ~100 hours after posting. ## Current Winner ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution 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> <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> <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><script>var QUESTION_ID = 162891; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 188 bytes ``` <>((((()()()){}){}()){}){(({}[()])<({}[(((((()()()()()){}){}){})()){}{}])<>{<>(({})<({}<>({}<>))((){[()](<{}>)}{}){{}(<({}<([]<<>{({}<>)<>}<>>){({}[()]<({}<>)<>>)}{}>)>)}{}>)<>}<>{}<>>)}<> ``` [Try it online!](https://tio.run/##RY1LCgNBCESvYy3mBuJFhll0hgyEfBbZBfHspjQdplvKQl7p5T1ur@V4jHummtRDfXiwZhfxWAUbtM1JnWRVew9i5rWLowrQlgAMea0R9TBEhXiiEVk3ZeoHqlENPq/qf9oZw2xNeZOUzOfnGPs1l/0L "Brain-Flak – Try It Online") In addition to the reflections described in the challenge specification, this code also reverses the string exactly 26 times. This has no effect on the final output. ``` # Push 26 <>((((()()()){}){}()){}) # Do 26 times: {(({}[()])< # Subtract 122 from counter to get negative lowercase letter ({}[(((((()()()()()){}){}){})()){}{}]) # For each character in string: <>{ # Keep a copy of pivot letter on the third stack <>(({})< # Move next letter to other stack and compare to pivot ({}<>({}<>)) # If letters are equal: ((){[()](<{}>)}{}){ # Keep current letter separate from this transformation {}(<({}< # While keeping a copy of current stack height: ([]< # Move all letters to one stack <>{({}<>)<>}<> >) # Move a number of letters equal to old stack height back {({}[()]<({}<>)<>>)}{} >)>) }{}>)<> } # Destroy pivot letter <>{}<> >)} # Switch stack for output <> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ 17 bytes ``` {vð.øy¡€á€gsJ£yý ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/uuzwBr3DOyoPLXzUtObwwsNNQCq92OvQ4srDe///Ty7PTcvKL0pJSszLTs@pLMgoLkutKCkszawCAA "05AB1E – Try It Online") **Explanation** With example for the first iteration of `myface` ``` {v # for each char y in sorted input ð.ø # surround current string with spaces # STACK: ' myface ' y¡ # split at current letter # STACK: [' myf', 'ce '] €á # remove non-letters # STACK: ['myf','ce'] €g # get the length of each string in the pair, reversed # STACK: ['myf','ce'], [2,3] sJ # join the pair back to a string £ # split into 2 pieces of the calculated sizes # STACK: ['my','fce'] yý # join on the current char y # STACK: 'myafce' ``` The string is surrounded with spaces each iteration as splitting on the first or last letter of the string would result in a length-1 list otherwise and the merge wouldn't include that letter. [Answer] # Pyth, ~~18~~ ~~16~~ ~~19~~ 16 bytes ``` VSQ=QXx_QN-QNN)Q ``` [Try it here](https://pyth.herokuapp.com/?code=VSQ%3DQXx_QN-QNN%29Q&input=%22ofxckieuqht%22&debug=0) ### Explanation ``` VSQ=QXx_QN-QNN)Q VSQ ) For each character (N) in the sorted input (Q)... -QN ... remove the character from Q... x_QN ... get the reflected position... X N ... insert N... =Q ... and save the result into Q. Q Output the final result. ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~80~~ 73 bytes Thanks to Esolanging Fruit for reminding me that functions can return by modifying their argument. ``` lambda x:[x.insert(len(x)+~x.index(i),x.remove(i)or i)for i in sorted(x)] ``` [Try it online!](https://tio.run/##NYwxDoMwDEV3TpHNiUpZuiHRiwCDIY6aCpwqWFVYevU0UdXl@/np679OeQS@ZTdMecN9sahSP6bO80FR9Eask7l8qrCUtDdt6iLt4U2FQ1TeuJrKszpCFLKlPufqpLgREFoFuC717KfDlSrZdUGY@0a9omfR0hLbASa53icB0ygZNn8Ub/4NVxjZAnTP4Lk8Jv/Wvg "Python 3 – Try It Online") Takes input as a list of characters. [Answer] # [Python 2](https://docs.python.org/2/), 70 bytes ``` def f(t): for c in sorted(t):i=t.index(c);l=len(t)+~i;t[l:l]=t.pop(i) ``` [Try it online!](https://tio.run/##JY7NEoIwDITvPEVuhVE5eITBF3E8QH8kWNpaooIHX72mekky@81mN2w0endMSWkDpqSqKcD4CBLQweIjaZVF7KhGp/Rayqq1ndWO1d0HWzrbxl6YBh9KrFL2UvaKXux5yCGveTO91PlScmAg5Gs2k49q6N3tarcwLk@90v2Bb8EFQkRHQAVQZ3Ehjip@3do/EHA48Q9RTx5zj/QF "Python 2 – Try It Online") Modifies the input list [Answer] # [Ruby](https://www.ruby-lang.org/), 51 bytes ``` ->s{s.sort.map{|c|s.insert~s.index(c),s.delete(c)}} ``` [Try it online!](https://tio.run/##PZBbbsMgEEX/vQo@ItFWLhuo6EaqqoJhiF9gh0di8ujWXQhJv@6co6sZaVyUadtpvr1/@otnfnaBGbFcrnD1rLceXfgtg8L1BV5bzxROGDDPt9umUBMXLentEkNL5hhyNqQy4TUZdML5bEdeeZYDQvjpVXY7/XWX3x9kqfU3Sgnnz11oVdOUE1SBFLR9ZFUmaQFYpE4I5qnvtX8AWVAKeAg4GT3MTklhx/2Uls4fcQ2H2J9Lr0chu8M57tUURm2Py7Dml5gEJ7r9AQ "Ruby – Try It Online") Takes an array of chars Returns by modifying the input [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 61 bytes ``` $ a {`(.)(.*)\1$ $2$.`$*_$1$1 +`(.)_(_*.) $2$1 }T`_l`l!`.$ ! ``` [Try it online!](https://tio.run/##FcxLCsIwEADQ/dyiMEISYSBewgu4FDKTNK3VtPbnp4pnj@36wRvj3HSSd@rIGUHgy4q0IqPPFgEPSIzGoUUL@02ccob0BhZ@J3aJU8GEUEDOZfAC7VJJiGskwUN4tdX1PpZeuludlv4yPeN7Hh7N5w8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` $ a ``` Start the loop at `a`. ``` {`(.)(.*)\1$ $2$.`$*_$1$1 ``` If the input contains the current letter, move it to the end, with a string of `_`s representing its original position. ``` +`(.)_(_*.) $2$1 ``` For each `_` move the letter back one character. ``` }T`_l`l!`.$ ``` Increment the letter. After `z` change it to a `!` so it doesn't match anything and the loop ends. ``` ! ``` Delete the `!`. [Answer] # Java 8, ~~140~~ ~~96~~ ~~92~~ ~~88~~ ~~87~~ 85 bytes ``` s->{for(char c=9;++c>0;){int i=s.indexOf(c);if(i>=0)s.add(s.size()+~i,s.remove(i));}} ``` -44 bytes creating a port of [*@TFeld*'s Python 2 answer](https://codegolf.stackexchange.com/a/162907/52210). -6 bytes thanks to *@OlivierGrégoire*. Modifies the input List instead of creating a new one. **Explanation:** [Try it online.](https://tio.run/##jZE9b4MwEIb3/gqLyRbBylpRkKqsbTKkW9XBHCYxAUx9hnwp/evUfERtqkqtBIOP13fPPeSiFUGe7jooBCJ5Fqo63xGiKitNJkCSZX8kpNUqJUBzF@eNVQV/NEYcnxTah8VWGAEuHxNkoUtf3OsetMIqIEtSkYh0GMTnTBsKLk0gug99H@J5yM5uFFERclWl8rDKKLBQZVTF0ZwhF2lKkaM6Scr8DzVDbmSpW0kVY@Hl0oXjqLpJCjdqmjiwlm4TurZGVZvXN8HGLaxES70UEuENpNdKeex3va39iAhIbguwL7NcmzQR1W5THOsttvJg3xt18iYLXw4GouHaSOREjUB/@OyvOHmV3P@WdGZ6m0gZL0X9oldJTiGIB8UMGAddFBLst5@G1khR8sX4QRvkVg@dGJt2qzjQfup0XB/RypLrxvLagdvi6pTn2vn1vNnAODUeQagMYul73v8A@j6uX08wabt0nw) ``` s->{ // Method with ArrayList<Character> parameter and no return-type for(char c=9;++c>0;){ // Loop over all characters known // (except for the first 9 unprintables) int i=s.indexOf(c); // Index of the character, or -1 of it isn't present if(i>=0) // If the current character is present in the List s.add(s.size()+~i,s.remove(i));}} // Change the position of this character to index `l-i-1`, // (where `l` is the size of the input-List) ``` [Answer] # JavaScript, ~~85~~ ~~80~~ 79 bytes -6 bytes thanks to @DanielIndie ``` a=>[...a].sort().map(i=>a.splice(s=a.indexOf(i),1)&&a.splice(a.length-s,0,i))&&a ``` [Try it online!](https://tio.run/##PY9dboMwEISfyzF4iGzVsdoDmCv0AFGkLPYalvgv2CGQqmenULV9GumbGY1mgAmyHimVY4gGV6tWUM1JSglnmeNYGJceEiPVgMzJkUaWFUgKBucPy4iLd/76b4F0GLrSH7N4E8T54QBrwVwUo5AEzomr5rN60THk6FC62DHL9rXNPnM5RAqXi1J7sPqq9iar/WJBYy1qu6D2UPNfbnQLG/2RP6Yf3g5xNC2Ea@eW1OcJ53K703NLEkLb3573zrhytWFKw7w99It@1Hz9Bg "JavaScript (Node.js) – Try It Online") [Answer] # [Red](http://www.red-lang.org), 96 94 bytes 2 bytes saved thanks to Kevin Cruijssen ``` func[x][foreach c sort copy x[i:(length? x)+ 1 - index? find x c insert at replace x c""i c]x] ``` [Try it online!](https://tio.run/##TYuxEsIgEET7fMUNlY5jYZsm/2DLUJDjSNAEkJB48ecRGyfVztvdl8iUOxmpGtsWu3qUrKQNiTSOgLCElAFD3IGla08T@SGPHfD5Aje4gvOGuANbE7jenV@oCjpDojhppF8rhANUrEpMzmewIDT2ovmTwV4fcN5tFQ/FccT3bB8hmV775zDtcVw24vxa3UeULw "Red – Try It Online") More readable: ``` f: func[x][ foreach c sort copy x[ ; for each symbol in the sorted input i: (length? x) + 1 - index? find x c ; find its index and reflect it insert at replace x c "" i c ; remove it by replacing it with an empty char ; and insert the symbol at its new index ] x ; return the transformed string ] ``` [Answer] # [R](https://www.r-project.org/), ~~73~~ ~~72~~ 69 bytes ``` function(s){for(x in sort(s))s=append(s[x!=s],x,match(x,rev(s))-1);s} ``` [Try it online!](https://tio.run/##FY7BDsIgEETP@hW1l7IJHjybfol62G7BohSQpZVq/PZKL5OZybxk4qrbVU@OkvFOMHy1jyJXxlXsYyoFcIshKNcLvuRDyzeZ5YiJBpFlVPO2OJ7gzL91I3kjSdRYyxqpK9pTt4Vx0UiqGHqP@uFj36F73u0SBp5VTq/JfGqAar8jTCIgJyW0mJw1XE6kyMGaYmTTAIAkby0GVm2Jsrm6BtY/ "R – Try It Online") Inputs and outputs a vector of characters. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` W;ṢḟṁUṣ¥jʋ/ ``` A monadic link accepting a list of characters and returning a list of characters. **[Try it online!](https://tio.run/##ATkAxv9qZWxsef//VzvhuaLhuJ/huYFV4bmjwqVqyosv////Y3dtZmpvcmRiYW5rZ2x5cGhzdmV4dHF1aXo "Jelly – Try It Online")** ### How? ``` W;ṢḟṁUṣ¥jʋ/ - Link: list of characters V e.g. "myface" ...i.e. ['m','y','f','a','c','e'] W - wrap V in a list ["myface"] Ṣ - sort V ['a','c','e','f','m','y'] ; - concatenate ["myface",'a','c','e','f','m','y'] / - reduce with: ʋ - last four links as a dyad: - (i.e. start with "myface" on the left and 'a' on the right - 2nd iteration has that result on the left and 'c' on the right - and so-forth) e.g. left = myface, right = 'a' ḟ - filter out (right from left) "myfce" ¥ - last two links as a dyad: U - upend left "ecafym" ṣ - split at occurrences of right ["ec","fym"] ṁ - mould (ḟ(x,y)) like (Uṣ¥(x,y)) ["my","fce"] j - join with right "myafce" ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 37 bytes ``` #!/usr/bin/perl -p for$a(a..z){s/$a//&&s/.{@{-}}$/$a$&/} ``` [Try it online!](https://tio.run/##Dcg5EoQgEADAnHdQ1BrIRJvvVwYEj1VB8EKKrzvaYXsTxi@RdYHjB6W8qhyBI4AQEWT@5boU/gYXUIgarZBNyaI2DLVi@pjs4EKjcP63Y/Jd3M25Llt/sdv5tXdzpNo/ "Perl 5 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~23~~ 22 bytes ``` ¬n rÈ+S kY iYJ-XbY)x}U ¬n // Split the input into chars and sort it. r }U // Then reduce the result with initial value of the input. È+S // Append a space for replacing edge cases and kY // remove the current char from the string. iY // Insert it back J-XbY // at the calculated index, )x // and remove the unnecessary space once we're done. ``` Saved one byte thanks to [Oliver](https://codegolf.stackexchange.com/users/61613/oliver). [Try it online!](https://tio.run/##y0osKPn//9CaPIWiwx3awQrZkQqZkV66EUmRmhW1of//K@VWpiUmpyoBAA) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~15~~ ~~12~~ 10 bytes ``` s(n/₌ṅtLnṀ ``` Thanks to @AndrovT and @TheThonnu! [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJ+IiwiIiwicyhuL+KCjOG5hXRMbuG5gCIsIiIsIiFJbnB1dDogKFteXFwuXSspXFwuIE91dHB1dDogKFteXFwuXSspXFwuXG5JbnB1dDogbXlmYWNlLiBPdXRwdXQ6IGZ5ZWNtYS5cbklucHV0OiBhLiBPdXRwdXQ6IGEuXG5JbnB1dDogYWNiLiBPdXRwdXQ6IGJhYy5cbklucHV0OiBjd21mam9yZGJhbmtnbHlwaHN2ZXh0cXVpei4gT3V0cHV0OiBpZWFiaHF6dWdkbHRrZm52cGp4c29ybXljdy4iXQ==) [Answer] ## Haskell, 87 bytes ``` s#c|(h,_:t)<-span(/=c)s,(v,w)<-splitAt(length t)$h++t=v++c:w|1<2=s f s=foldl(#)s['a'..] ``` [Try it online!](https://tio.run/##Hci7DoIwGEDh3adoigltQIyOhA7uOjkSQkqhFCkF6Q@I4d3rZTjfcBS3baW1c9YTG1FhHgNNDnbghhyZoDYkc7j8j27gAkRXpgaFgO5VEACbg0DEy3ZKzszuJLJM9rrUxKM29bkfRZnreGMQQx0fbjkiwwR3GK8GRZKiFHer5KLCIea/RPFVLJ189GNZcNPWeh2UnasXPKfmjTP3AQ "Haskell – Try It Online") ``` f s=foldl(#)s['a'..] -- fold the function '#' into all characters from 'a' -- with the starting value of the input string s s#c= -- in each step (s: result so far, c: next char) (h,_:t)<-span(/=c)s -- let 'h' be the substring before 'c' and -- 't' the substring after 'c'. the pattern match -- fails if there's no 'c' in 's' (v,w)<-splitAt(length t)$h++t -- split the string 'h++t' at index length of t =v++c:w -- return 'v' followed by 'c' followed by 'w' |1<2=s -- if there's no 'c' in 's', return 's' unchanged ``` [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~132~~ 128 bytes ``` DEFINE('I(I)') I U =&LCASE N U LEN(1) . K REM . U :F(RETURN) I ARB @S K :F(N) I K = I ARB . L RPOS(S) REM . R I =L K R :(N) ``` [Try it online!](https://tio.run/##XU7JCsIwFDynX/FONrkUBE@FgNWkEBrTkjQf4L7VVq37z8cU9eJphtmYtm5mTTVwKMaMOMR4KhTHocCChCQQyALtyXFieKA8l1zhPoEIMtB84tGiOMWal1YrEiABiR7B0EDWyR8lA/ozIpCgi9xgQ7513VlUdnP@gCKO/T9AuS0LWwIVOJzfD6tdc17MpvV@XT2Pm/a2fFxO1@3LB7li7g0 "SNOBOL4 (CSNOBOL4) – Try It Online") Straightforward implementation of the required algorithm. Saved a few bytes by switching to a function rather than a full program; the explanation remains the same, more or less. ``` I =INPUT ;* read input U =&LCASE ;* alias for lowercase letters (it started out as uppercase) N U LEN(1) . K REM . U :F(O) ;* set K to the next lowercase letter, and when empty, goto O I ARB @S K :F(N) ;* set S to the number of letters before K, or goto N I K = ;* remove K I ARB . L RPOS(S) REM . R ;* set R to the last S characters of I and L to the others I =L K R :(N) ;* recombine the string and goto N O OUTPUT =I ;* print new string END ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~164~~ 162 bytes ``` y,n,a,b,c,p,i;f(char*s,l){for(i=0;p=0,++i<123;p<l&&(y=s[p],n=l+~p,a=p+1,b=p,n<p&&(a=n,b=n+1),c=l+~(2*(n<p?n:p)),memmove(s+b,s+a,c),s[n]=y))while(s[p]^i&&p<l)p++;} ``` [Try it online!](https://tio.run/##dZBNktsgEIX3OgXlVFxCIjP2ZDeyknVWOYDjVAECCRsQBiRZnppc3UHWj2czu9ffe003Tb9RiXV5@yI0lU3BwM75QtRP1Y/oI7JCl4HdeqQRRgRRZJDIeEwrbBOHJHzjtY1FvslMvkFpKnbbl@@Z2cn1Ou5ztzcHpHOZ/jMI5ybdIpIbpHcmuDjXodLpFiI6JOKXJA7OT/1qIESKKVW3LHYpQS7FiELk9vqQ9xB2lZDBCE//Fet1GAVNmmbvN4qlHBcDiYPgLQImbO95vPqlTeNfwf6rO4Dfjb8XKwQczCLAYxeUt5Lp2MGBzF1D/I@ecu9RFChQWOh4ePs@Bu8PIAerghK8ykZERqR6jimbIR3hEiqmmpKZsJHQTvFjbQuC9amUvalcyy7@3IjrHORTK6EF42UljiepdG3O1vmm7S79EizH4LW/dG3jnT2bWit5Ooqq5GzaOBpPhsP/RkUWRRdVLIotii@qDCqyzDdWg81wpuckms49DHla7n2vZms8z8PkPaMKz@6Hrgej5EEJpjP//GKPuGCYVOdrUxbSn7huzfHiaqt62kXJ8@0/ "C (clang) – Try It Online") `f()` takes char-array containing input string and length of this array as parameters and performs required reflections in place. `callf()` does pretty-printing. # Credits -2 bytes. @Kevin. Thanks [Answer] # APL+WIN, 63 bytes Prompts for input string ``` l←s[⍋⎕av⍳s←,⎕]⋄⍎∊(⍴s)⍴⊂'s←(n←⌽~s=↑l)\s~↑l⋄((~n)/s)←↑l⋄l←1↓l⋄'⋄s ``` Explanation: ``` l←s[⍋⎕av⍳s←,⎕] sort characters into alphabetical order ⍎∊(⍴s)⍴⊂'....' create an implicit loop for each character s←(n←⌽~s=↑l)\s~↑l⋄((~n)/s)←↑l do the relection for first character in l l←1↓l drop the first character in l s display the result ⋄ statement separator ``` [Answer] # [Perl](https://www.perl.org/), ~~74~~ 70 bytes ~~84~~ 80 bytes including invocation as unix filter ``` for$c(a..z){if($p=1+index$_,$c){substr$_,$p-1,1,"";substr$_,-$p,0,$c}} ``` ``` $ echo -e 'dcba\nmyface\na\nacb\ncwmfjordbankglyphsvextquiz' | > perl -pE'for$c(a..z){if($p=1+index$_,$c){substr$_,$p-1,1,"";substr$_,-$p,0,$c}}' dcba fyecma a bac ieabhqzugdltkfnvpjxsormycw ``` ]
[Question] [ Your task is to given two integer numbers, `a` and `b` calculate the modular multiplicative inverse of a modulo b, if it exists. The modular inverse of `a` modulo `b` is a number `c` such that `ac ≡ 1 (mod b)`. This number is unique modulo `b` for any pair of `a` and `b`. It exists only if the greatest common divisor of `a` and `b` is `1`. The [Wikipedia page](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse) for modular multiplicative inverse can be consulted if you require more information about the topic. ## Input and Output Input is given as either two integers or a list of two integers. Your program should output either a single number, the modular multiplicative inverse that is in the interval `0 < c < b`, or a value indicating there is no inverse. The value can be anything, except a number in the range `(0,b)`, and may also be an exception. The value should however be the same for cases in which there is no inverse. `0 < a < b` can be assumed ## Rules * The program should finish at some point, and should solve each test case in less than 60 seconds * Standard loopholes apply ## Test cases Test cases below are given in the format, `a, b -> output` ``` 1, 2 -> 1 3, 6 -> Does not exist 7, 87 -> 25 25, 87 -> 7 2, 91 -> 46 13, 91 -> Does not exist 19, 1212393831 -> 701912218 31, 73714876143 -> 45180085378 3, 73714876143 -> Does not exist ``` # Scoring This is code golf, so the shortest code for each language wins. [This](https://codegolf.stackexchange.com/questions/129716/compute-the-inverse-of-an-integer-modulo-100000000003) and [this](https://codegolf.stackexchange.com/questions/215/compute-modular-inverse?rq=1) are similar questions, but both ask for specific situations. [Answer] # Mathematica, 14 bytes Obligatory Mathematica [builtin](https://reference.wolfram.com/language/ref/ModularInverse.html): ``` ModularInverse ``` It's a function that takes two arguments (`a` and `b`), and returns the inverse of a mod b if it exists. If not, it returns the error `ModularInverse: a is not invertible modulo b.`. [Answer] # JavaScript (ES6), ~~79~~ ~~73~~ ~~62~~ 61 bytes Returns `false` if the inverse does not exist. It uses the extended Euclidean algorithm and solves all test cases almost instantly. ``` f=(a,b,c=!(n=b),d=1)=>a?f(b%a,a,d,c-(b-b%a)/a*d):b<2&&(c+n)%n ``` ### Test cases ``` f=(a,b,c=!(n=b),d=1)=>a?f(b%a,a,d,c-(b-b%a)/a*d):b<2&&(c+n)%n console.log(f(1, 2)) // -> 1 console.log(f(3, 6)) // -> Does not exist console.log(f(7, 87)) // -> 25 console.log(f(25, 87)) // -> 7 console.log(f(2, 91)) // -> 46 console.log(f(13, 91)) // -> Does not exist console.log(f(19, 1212393831)) // -> 701912218 console.log(f(31, 73714876143)) // -> 45180085378 console.log(f(3, 73714876143)) // -> Does not exist ``` [Answer] # [Python 2](https://docs.python.org/2/), 34 bytes ``` f=lambda a,b:a==1or-~b*f(-b%a,a)/a ``` [Try it online!](https://tio.run/##XY7BCsJADETvfkVAhFZSJEltdoX9mCyyKGhbSi9e/PW1Bytrj@8NzMz4mm9Dzzmn8LBnvBoYxouFQMPUvOMxVU08GFp9sjxO936GVBECQ73brywI3cIrKoLTgvm8FQieygKSr/kJj0BMLF6clIEs2ypKrdOOWtm8@EvyBw "Python 2 – Try It Online") Recursive function that gives `True` for `print f(1,2)`, which I believe to be acceptable, and errors for invalid inputs. We are trying to find \$x\$ in \$a\cdot x\equiv 1\pmod{b}\$. This can be written as \$a\cdot x-1=k\cdot b\$ where \$k\$ is an integer. Taking \$\mod{a}\$ of this gives \$-1\equiv k\cdot b\pmod{a}\$. Moving the minus gives \$-k\cdot b\equiv1\pmod{a}\$, where we have to solve for \$k\$. Seeing how it resembles the initial scenario, allow us to recurse to solve for \$k\$ by calling the function with \$f(-b\%a,a)\$ (works because Python gives positive values for modulo with a negative argument). The program recurses for until \$a\$ becomes 1, which only happens if the original \$a\$ and \$b\$ are coprime to each other (ie there exists a multiplicative inverse), or ends in an error caused by division by 0. This value of \$k\$ can be substituted in the equation \$a\cdot x-1=k\cdot b\$ to give \$x\$ as \$\frac{k\cdot b+1}{a}\$. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` æi ``` [Try it online!](https://tio.run/##y0rNyan8///wssz/h5frP2paE/n/f7S5joV5rE60sY4ZkIRyjEyhtI6lIZAyNAbRAA "Jelly – Try It Online") This uses a builtin for modular inverse, and returns 0 for no modular inverse. # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` R×%⁸’¬T ``` [Try it online!](https://tio.run/##y0rNyan8/z/o8HTVR407HjXMPLQm5P/h5Q76j5rWRP7/H22uY2EeqxNtrGMGJKEcI1MorWNpCKQMjUE0AA "Jelly – Try It Online") Outputs empty set (represented as empty string) on no modular inverse. Runs out of memory on TIO for the largest test-cases, but should work given enough memory. **How it Works** ``` R×%⁸’¬T R Generate range of b × Multiply each by a %⁸ Mod each by b ’ Decrement (Map 1 to 0 and all else to truthy) ¬ Logical NOT T Get the index of the truthy element. ``` If you want to work for larger test-cases, try this (relatively ungolfed) version, which requires much time rather than memory: ## Jelly, 9 bytes ``` ×⁴%³’¬ø1# ``` [Try it online!](https://tio.run/##AR8A4P9qZWxsef//w5figbQlwrPigJnCrMO4MSP///84N/83 "Jelly – Try It Online") **How it Works** ``` ×⁴%³’¬ø1# # Get the first ø1 one integer which meets: ×⁴ When multiplied by a %³ And modulo-d by b ’ Decrement ¬ Is falsy ``` [Answer] # Mathematica, 18 bytes ``` PowerMod[#,-1,#2]& ``` **input** > > [31, 73714876143] > > > [Answer] # [R](https://www.r-project.org/) + [numbers](https://cran.r-project.org/web/packages/numbers/numbers.pdf), 15 bytes ``` numbers::modinv ``` returns `NA` for those `a` without inverses mod `b`. [R-Fiddle to try it!](http://www.r-fiddle.org/#/fiddle?id=l01inC73&version=1) # [R](https://www.r-project.org/), 33 bytes (non-competing) This will fail on very large `b` since it actually creates a vector of size `32*b` bits. ``` function(a,b)which((1:b*a)%%b==1) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jUSdJszwjMzlDQ8PQKkkrUVNVNcnW1lDzf5qGuY6FueZ/AA "R – Try It Online") Returns `integer(0)` (an empty list) for those `a` without inverses mod `b`. [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~9~~ 8 bytes Takes the inputs in reverse order. Outputs `-1` for no match. Craps out as the bigger integer gets larger. ``` Ç*V%UÃb1 ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=xypWJVXDYjE=&input=ODcsNw==) * Saved 1 byte thanks to ETH pointing out an errant, and very obvious, space. [Answer] # [Python 3](https://docs.python.org/3/) + [gmpy](https://pypi.python.org/pypi/gmpy/1.17), 23 bytes I don't think it can get any shorter in Python. ``` gmpy.invert import gmpy ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPz23oFIvM68staiEKzO3IL@oRAEk9L@gKDOvRCNNw1zHwlxT8z8A "Python 3 – Try It Online") (won't work if you do not have gmpy installed) [Answer] # [Python 3](https://docs.python.org/3/), 49 bytes ``` lambda a,b:[c for c in range(b)if-~c*a%b==1][0]+1 ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRJ8kqOlkhLb9IIVkhM0@hKDEvPVUjSTMzTbcuWStRNcnW1jA22iBW2/B/QVFmXolGmoa5joW5piYXjGukY2mIxDXWMdPU/A8A "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), 50 bytes ``` lambda a,b:[c for c in range(1,b+1)if c*a%b==1][0] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRJ8kqOlkhLb9IIVkhM0@hKDEvPVXDUCdJ21AzM00hWStRNcnW1jA22iD2f0FRZl6JRpqGuY6FuaYmF4xrpGNpiMQ11jHT1PwPAA "Python 3 – Try It Online") This throws `IndexError: list index out of range` in case there is no modular multiplicative inverse, as it is allowed by the rules. [Answer] # [Python 2](https://docs.python.org/2/), ~~51~~ ~~49~~ ~~54~~ ~~53~~ ~~51~~ 49 bytes -1 byte thanks to officialaimm -1 byte thanks to Shaggy ``` a,b=input() i=a<2 while(a*i%b-1)*b%a:i+=1 print+i ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P1EnyTYzr6C0REOTK9M20caIqzwjMydVI1ErUzVJ11BTK0k10SpT29aQq6AoM69EO/P/f3MdC3MA "Python 2 – Try It Online") Prints `0` when there is no solution. [Answer] # [8th](http://8th-dev.com/), 6 bytes **Code** ``` invmod ``` **Explanation** `invmod` is a 8th word that calculates the value of the inverse of `a`, modulo `b`. It returns `null` on overflow or other errors. **Usage and test cases** ``` ok> 1 2 invmod . 1 ok> 3 6 invmod . null ok> 7 87 invmod . 25 ok> 25 87 invmod . 7 ok> 2 91 invmod . 46 ok> 13 91 invmod . null ok> 19 1212393831 invmod . 701912218 ok> 31 73714876143 invmod . 45180085378 ok> 3 73714876143 invmod . null ``` [Answer] # [J](http://jsoftware.com/), 28 bytes ``` 4 :'(1=x+.y)*x y&|@^<:5 p:y' ``` [Try it online!](https://tio.run/##TYsxCoNAFAV7T/GqqBEi7//Vv7sqeJCQFCES0sTShdx9I1aBYWCKeee8YIpwiGXFaWsuqT5vSKfvfBtjhzWmsiiej9cHd0E1LG19BSFQ9DB4g3SHEQjq4QAKRYN6JXZMjc5bT6f79lc5/wA "J – Try It Online") Uses [Euler's theorem](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse#Using_Euler.27s_theorem). Returns 0 if the inverse does not exist. ## Explanation ``` 4 :'(1=x+.y)*x y&|@^<:5 p:y' Input: a (LHS), b (RHS) 4 :' ' Define an explicit dyad - this is to use the special form `m&|@^` to perform modular exponentiation y Get b 5 p: Euler totient <: Decrement x Get a ^ Exponentiate y&|@ Modulo b x+.y GCD of a and b 1= Equals 1 * Multiply ``` [Answer] # [Pyth](https://pyth.readthedocs.io), 10 bytes *3 bytes saved thanks to [@Jakube](https://codegolf.stackexchange.com/users/29577/jakube)*. ``` xm%*szdQQ1 ``` **[Try it here!](https://pyth.herokuapp.com/?code=xm%25%2aszdQQ1&input=3%0A6&test_suite=1&test_suite_input=87%0A7%0A%0A6%0A3%0A%0A87%0A25%0A&debug=0&input_size=3)** Returns `-1` for no multiplicative inverse. ### Code Breakdown ``` xm%*szdQQ1 Let Q be the first input. m Q This maps over [0 ... Q) with a variable d. *szd Now d is multiplied by the evaluated second input. % Q Now the remained modulo Q is retrieved. x 1 Then, the first index of 1 is retrieved from that mapping. ``` # [Pyth](https://pyth.readthedocs.io), ~~15~~ 13 bytes ``` KEhfq1%*QTKSK ``` Throws an exception in case no multiplicative inverse exists. **[Try it here!](https://pyth.herokuapp.com/?code=KEhfq1%25%2aQTKSK&input=3%0A6&test_suite=1&test_suite_input=7%0A87%0A%0A3%0A6%0A%0A25%0A87%0A&debug=0&input_size=3)** # [Pyth](https://pyth.readthedocs.io), 15 bytes ``` Iq1iQKEfq1%*QTK ``` This adds lots of bytes for handling the case where no such number exists. The program can be shortened significantly if that case would not need to be handled: ``` fq1%*QTK ``` **[Try it here!](https://pyth.herokuapp.com/?code=Iq1iQKEfq1%25%2aQTK&input=7%0A87&test_suite=1&test_suite_input=7%0A87%0A%0A3%0A6%0A%0A25%0A87%0A&debug=0&input_size=3)** [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 11 bytes ``` a->b->1/a%b ``` Throws an error when there is no inverse. [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9R1y5J185QP1E16X9BUWZeiUaahrGhpoa5sbmhiYW5maGJsabmfwA "Pari/GP – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 115 bytes ``` #define L long long L g(L a,L b,L c,L d){return a?g(b%a,a,d-b/a*c,c):b-1?0:d;}L f(L a,L b){return(g(a,b,1,0)+b)%b;} ``` [Try it online!](https://tio.run/##bVHLbsIwEDzHX7ECIdllQ@OYEsAt/ECkHntoOdjOo5bSUIVwivzrTU1E2iL1sI9Z73pmbROWxvT9NMsLW@eQQnWsy8GRFEqagsIUtDfjLWNdk7fnpga1L6meKVSYhfpe3Rk0bKtDvo@2mXQpFOPkOEFLqlAjx4jNNZtp6fqprU11znJ4PLWZPS7ed4TYuoUPZWvKoCPBqW3OpoXuV5S/FLQEB@3rAZ4uPUEHHCEGh0MuEFZjniCskxHEDzcIYcNHwMUN2iDwmMdiI9bipyo8SSISvlwnK74Uf@j@qUYIETgSOEmC4tgAvaxlvd5IeuH2sFAS7Hw@7Bh8Nv60oJNZVWUIFw/hbohv9QSv/deo0b/sbYUxT@K5rh8TSeL6L1NUqjz14XPchy@qqr4B "C (gcc) – Try It Online") Extended Euclidean algorithm, recursive version # [C (gcc)](https://gcc.gnu.org/), 119 bytes ``` long long f(a,b,c,d,t,n)long long a,b,c,d,t,n;{for(c=1,d=0,n=b;a;a=t)t=d-b/a*c,d=c,c=t,t=b%a,b=a;return b-1?0:(d+n)%n;} ``` [Try it online!](https://tio.run/##bVFNb8IwDD23v8JiQmpXlzUNo2VZ2E/YkcPGIR@URcrCVMKp6l9fFyrYQNrF9nux9Z4dle@UGga7dzsYQ5MIlKhQo0eX/vFXLOuafZsoTlDzAh2XTDDBfeq5zuWDuA9tXKHiHj2X0zDIBWu3/tg6kDl5KZ4Snbl06lg/3Bmn7FFv4fngtdnPPlZxbJyHT2FckkIXRwffHpWHDq6tgGTQg3/bAD/1RB0QhBJ6HGuKsLjUFUJdXUD5eIMQluQCCL1BSwRSkpIuaU1/WRpEKlqReV0tyJxeyf3DFggF9HHUszgK54LktJYJfgsWjJvNTDAwWTbuGH214bVJJlNrNcIpQr4a87ub4Ln/nCWGP7pl0jSIBK3zkQsW98O3aqzYHYb8tRzytbD2Bw "C (gcc) – Try It Online") Extended Euclidean algorithm, iterative version [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~48 110~~ 104 bytes ``` #define f(a,b)g(a,b,!b,1,b) long g(a,b,c,d,n)long a,b,c,d,n;{a=a?g(b%a,a,d,c-(b-b%a)/a*d):!--b*(c+n)%n;} ``` [Try it online!](https://tio.run/##fY1NDoIwEIX3nKJgSFqcRociBYnxAhzBTVt@QoLVGHeEsyNo4ooyi0ne@2beM7w1Zpp2Vd10tiYNVaBZu2zwNeAsvP5hW/KzDFRg2df4y2JQF3VtqQ4VqNkwnGo@C3ZQUcXOPuc6omZvWWiLcbqrzlI2eM9XZ98NDcK@r242gLkZIWaEFWtIQOpCEjLpYvFpC0KOLoZiAwrA4zLu7xwIxhiLXGTCHYNApJCYZDLFRJSlu2/lbpw@ "C (gcc) – Try It Online") This should work with all inputs (that fit within a long) within 60 seconds. Edit. I'm already abusing the `n` variable so I might as well assume that gcc puts the first assignment in `%rax`. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 36 38 bytes ``` {⌈/i×1=⍵|(i←⍳⍵)×⍵|⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRT4d@5uHphraPerfWaGQ@apvwqHczkK15eDpI5FHvrtr/aWDRvkd9Uz39H3U1H1pv/KhtIpAXHOQMJEM8PIMV/hsqpCkYcRkDSTMucyBpYc5lZAqlgZSlIZehMYQGAA "APL (Dyalog Unicode) – Try It Online") Explanation: ``` ⍵|⍺} ⍝ Get ⍺ mod ⍵ (i←⍳⍵)× ⍝ Multiply the result by all numbers up to ⍵ ⍵| ⍝ Take result mod ⍵ i×1= ⍝ Find all numbers (1,⍵) where the mod is 1 {⌈/ ⍝ And take the largest ``` Much thanks to Adam in the APL Orchard chatroom for the help with this one! Formula obtained from [this site](https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/) First iteration: ``` {((⍵|⍺),⍵){+/⌈/⍵×1=(¯1↑⍺)|⍵×⊃⍺}⍳⍵} ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 22 bytes ``` lambda a,b:pow(a,-1,b) ``` Obligatory Python 3.8+ builtin. Outputs the result, or gives the error `ValueError: base is not invertible for the given modulus` if there is no result. [Try it online.](https://tio.run/##TY1BCsIwFET3niJ0ZeC7@Pm1SQruvEXtItEWC5qENKA9fUyli27mMTMwE5b09I5UiHm83PLLvO3DMAO2Df5zNHBCsDyPPq4ZmxzrOgTRQ0fQFJWgZIE4bwSNBUgbNaBAQZoUrZ4QJEmslWywpv/I3vftgbEUlzbEyaVybmFclfOSD9/7ENKuqq5@mJnzqVTTnCqefw) **Explanation:** To quote the [Python 3.8 release notes](https://docs.python.org/3.8/whatsnew/3.8.html#other-language-changes): > > For integers, the three-argument form of the [pow()](https://docs.python.org/3.8/library/functions.html#pow) function now > permits the exponent to be negative in the case where the base is > relatively prime to the modulus. It then computes a modular inverse to > the base when the exponent is -1, and a suitable power of that inverse > for other negative exponents. For example, to compute the [modular > multiplicative inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse) of 38 modulo 137, write: > > > > ``` > >>> pow(38, -1, 137) > 119 > >>> 119 * 38 % 137 > 1 > > ``` > > Modular inverses arise in the solution of [linear Diophantine equations](https://en.wikipedia.org/wiki/Diophantine_equation). For example, to find integer solutions for `4258𝑥 + 147𝑦 = 369`, first rewrite as `4258𝑥 ≡ 369 (mod 147)` then solve: > > > > ``` > >>> x = 369 * pow(4258, -1, 147) % 147 > y = (4258 * x - 369) // -147 > 4258 * x + 147 * y > 369 > > ``` > > (Contributed by Mark Dickinson in [bpo-36027](https://bugs.python.org/issue36027).) > > > [Answer] # [Pyt], 1 byte ``` ɯ ``` [Try it online!](https://tio.run/##K6gs@f//5Pr//y0NuQyNAQ "Pyt – Try It Online") Takes inputs in the order `b a` (on separate lines). Outputs `None` if there is no such multiplicate inverse. Gotta love built-ins. [Answer] # [Python 2](https://docs.python.org/2/) + sympy, 74 bytes ``` from sympy import* def f(a,m):i,_,g=numbers.igcdex(a,m);return g==1and i%m ``` [Try it online!](https://tio.run/##TY/BCoMwGIPvPkUuA5WfQVtn1eGTjDHcrK6HtlIrzKd3KkN2ykcCCRnm8HaWL0vnncE4m2GGNoPzIY1a1aGLGzJJpelBfW0n81R@POv@1arPnly9CpO36OuaNbaFPpklqDGMqHGLGYEnhFgQ8k0loZAb8MtBhJJtwMRBJYFxxkUpCrE7Yi2SQrKskDnLxK/y37lHUec8NLTFvl9h8NqG9UCqk@UL "Python 2 – Try It Online") [Taken from Jelly source code.](https://github.com/DennisMitchell/jelly/blob/master/jelly.py#L467-L469) [Answer] # Axiom, 45 bytes ``` f(x:PI,y:PI):NNI==(gcd(x,y)=1=>invmod(x,y);0) ``` 0 for error else return z with x\*z Mod y =1 [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes *-3 bytes thanks to Mr. Xcoder.* ``` f=lambda a,b,i=1:i*a%b==1and i or i<b and f(a,b,i+1) ``` [Try it online!](https://tio.run/##PY3BCsIwEETv/Yq5CEndy6ZotbhfIh4SanBB09Lm4tdHU8HTvIHhzfzOjym5UqI8/SuMHp4CqfCgrd8FEfZphGJaoJeAWqLZJnu2Jd/XvEJwNUxwlmA6wrFmTzj1FdzhT4QzV@DuR7emidULTdhMA@ZFU/4@tGrLBw "Python 2 – Try It Online") Outputs `False` on no solution and errors out as `b` gets larger. ## Embedded TIO I'm just testing out iframes in Stack Snippets and they work absolutely fantastic. ``` html,body{height:100%;}iframe{height:100%;width:100%;border:none;} ``` ``` <iframe src="https://tio.run/##PY3BCsIwEETv/Yq5CEndy6ZotbhfIh4SanBB09Lm4tdHU8HTvIHhzfzOjym5UqI8/SuMHp4CqfCgrd8FEfZphGJaoJeAWqLZJnu2Jd/XvEJwNUxwlmA6wrFmTzj1FdzhT4QzV@DuR7emidULTdhMA@ZFU/4@tGrLBw"></iframe> ``` [Answer] # JavaScript (ES6), ~~42~~ ~~41~~ ~~39~~ 38 bytes Outputs `false` for no match. Will throw a overflow error as the second number gets to be too large. ``` x=>y=>(g=z=>x*z%y==1?z:z<y&&g(++z))(1) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` ²%³ ⁴Ç⁹Сx⁸ ÆṪ’BṚçL$P%³×gỊ¥ ``` [Try it online!](https://tio.run/##AUsAtP9qZWxsef//wrIlwrMK4oG0w4figbnDkMKheOKBuArDhuG5quKAmULhuZrDp0wkUCXCs8OXZ@G7isKl////NzM3MTQ4NzYxNDP/MzE "Jelly – Try It Online") Uses Euler's theorem with modular exponentiation. Since Jelly doesn't have a builtin to perform modular exponentiation, it had to be implemented, and it took most of the bytes. [Answer] # Axiom, 99 bytes ``` w(a,b,x,u)==(a=0=>(b*b=1=>b*x;0);w(b rem a,a,u,x-u*(b quo a)));h(a,b)==(b=0=>0;(b+w(a,b,0,1))rem b) ``` it use the function h(); h(a,b) return 0 if error [not exist inverse] otherwise it return the z such that a\*z mod b = 1 This would be ok even if arguments are negative... this would be the general egcd() function that retunr a list of int (so they can be negative too) ``` egcd(aa:INT,bb:INT):List INT== x:=u:=-1 -- because the type is INT (a,b,x,u):=(aa,bb,0,1) repeat a=0=>break (q,r):=(b quo a, b rem a) (b,a,x,u):=(a,r,u,x-u*q) [b,x, (b-x*aa)quo bb] ``` this is how use it ``` (7) -> h(31,73714876143) (7) 45180085378 Type: PositiveInteger ``` i find the base algo in internet from <https://pastebin.com/A13ybryc> ]
[Question] [ A straight-chain alk\*ne is defined as a sequence of carbon atoms connected by single (alkane), double (alkene), or triple bonds (alkyne), (implicit hydrogens are used.) Carbon atoms can only form 4 bonds, so no carbon atom may be forced to have more than four bonds. A straight-chain alk\*ne can be represented as a list of its carbon-carbon bonds. These are some examples of valid straight-chain alk\*nes: ``` [] CH4 Methane [1] CH3-CH3 Ethane [2] CH2=CH2 Ethene [3] CH≡CH Ethyne [1,1] CH3-CH2-CH3 Propane [1,2] CH3-CH=CH2 Propene [1,3] CH3-C≡CH Propyne [2,1] CH2=CH-CH3 Propene [2,2] CH2=C=CH2 Allene (Propadiene) [3,1] CH≡C-CH3 Propyne [1,1,1] CH3-CH2-CH2-CH3 Butane ... ``` While these are not, as at least one carbon atom would have more than 4 bonds: ``` [2,3] [3,2] [3,3] ... ``` Your task is to create a program/function that, given a positive integer `n`, outputs/returns the **number** of valid straight-chain alk\*nes of exactly `n` carbon atoms in length. This is [OEIS A077998](//oeis.org/A077998). # Specifications/Clarifications * You must handle `1` correctly by returning `1`. * Alk\*nes like `[1,2]` and `[2,1]` are considered distinct. * Output is the *length* of a list of all the possible alk\*nes of a given length. * You do *not* have to handle 0 correctly. # Test Cases: ``` 1 => 1 2 => 3 3 => 6 4 => 14 ``` This is code golf, so lowest *byte* count wins! [Answer] # [MATL](http://github.com/lmendo/MATL), 10 bytes ``` 7K5vBiY^1) ``` [Try it online!](http://matl.tryitonline.net/#code=N0s1dkJpWV4xKQ&input=NA) ### Explanation This uses the characterization found in [OEIS](http://oeis.org/A006356) > > a(n) is the top left entry of the n-th power of the 3 X 3 matrix [1, 1, 1; 1, 0, 0; 1, 0, 1] > > > ``` 7 % Push 7 K % Push 4 5 % Push 5 v % Concatenate all numbers into a column vector: [7; 4; 5] B % Convert to binary: gives 3×3 matrix [1, 1, 1; 1, 0, 0; 1, 0, 1] i % Input n Y^ % Matrix power 1) % Take the first element of the resulting matrix, i.e. its upper-left corner. % Implicitly display ``` [Answer] # [Oasis](http://github.com/Adriandmen/Oasis), ~~9~~ 7 bytes ``` xcd-+3V ``` [Try it online!](http://oasis.tryitonline.net/#code=eGNkLSszVg&input=&args=NA) ### Explanation This uses the recurrence relationship in [OEIS](http://oeis.org/A006356): > > a(n) = 2\*a(n-1) + a(n-2) - a(n-3) > > > ``` x Multiply a(n-1) by 2: gives 2*a(n-1) c Push a(n-2) d Push a(n-3) - Subtract: gives a(n-2) - a(n-3) + Add: gives 2*a(n-1) + a(n-2) - a(n-3) 3 Push 3: initial value for a(n-1) V Push 1, 1: initial values for a(n-2), a(n-3) ``` [Answer] # [Oasis](http://github.com/Adriandmen/Oasis), ~~9~~ 8 bytes Saved a byte thanks to *Adnan* ``` xc+d-63T ``` [Try it online!](http://oasis.tryitonline.net/#code=eGMrZC02M1Q&input=&args=NA) **Explanation** ``` a(0) = 0 a(1) = 1 a(2) = 3 a(3) = 6 a(n) = xc+d- x # calculate 2*a(n-1) c # calculate a(n-2) + # add: 2*a(n-1) + a(n-2) d # calculate a(n-3) - # subtract: 2*a(n-1) + a(n-2) - a(n-3) ``` [Answer] # Jelly, 10 bytes ``` 745DBæ*µḢḢ ``` [Try it online!](https://tio.run/nexus/jelly#@29uYuridHiZ1qGtD3csAqL///@bAAA) Uses [Luis Mendo's algorithm](https://codegolf.stackexchange.com/a/103112/30164). ### Explanation ``` 745DBæ*µḢḢ Main link. Argument: n 745D Get the digits of 745 B Convert each to binary æ* Matrix power ḢḢ First element of first row ``` ## Jelly, 15 bytes ``` 3Rṗ’µ+2\<5PµÐfL ``` [Try it online!](https://tio.run/nexus/jelly#ARsA5P//M1LhuZfigJnCtSsyXDw1UMK1w5BmTP///zQ) Uses brute force. ### Explanation ``` 3Rṗ’µ+2\<5PµÐfL Main link. Argument: n 3R Start with [1, 2, 3] ’ Take the (n-1)'th ṗ Cartesian power Ðf Filter on: +2\ Sums of overlapping pairs <5 1 for sums < 5, 0 otherwise P Product: 1 if all pairs < 5 L Length ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 14 bytes ``` q3:Z^TTZ+!5<As ``` [Try it online!](http://matl.tryitonline.net/#code=cTM6Wl5UVForNTwhQXM&input=NA) ### Explanation This generates the Cartesian power of `[1 2 3]` "raised" to the number of atoms minus 1, and then uses convolution to check that no two contiguous numbers in each Cartesian tuple sum more than `4`. ``` q % Take number of atoms n implicitly 3: % Push [1 2 3] Z^ % Cartesian power. Gives a matrix with each (n-1)-tuple on a row TT % Push [1 1] Z+ % 2D convolution. For each tuple this gives the sum of contiguous numbers 5< % For each entry, gives true if less than 5 ! % Transpose A % True if all elements of each column are true. Gives a row vector s % Sum of true results. Implicitly display ``` [Answer] ## Mathematica, 48 bytes ``` MatrixPower[{{1,1,1},{1,0,0},{1,0,1}},#][[1,1]]& ``` As [Luis Mendo pointed out](https://codegolf.stackexchange.com/a/103112/61980), this is [A006356](http://oeis.org/A006356) in the OEIS. Here are my original attempts: ``` Count[Length@Split[#,+##<5&]&/@Tuples[{1,2,3},#-1],0|1]& ``` For an input `n`, `Tuples[{1,2,3},n-1]` is the list of all `(n-1)`-tuples of elements in `{1,2,3}` representing all possible sequences of single, double, or triple bonds for `n` carbon atoms. `+##<5&` is a pure function which returns whether the sum of its arguments is less than `5`, so `Split[#,+##<5&]&` splits a list into sublists consisting of consecutive elements whose pairwise sums are less than `5`. Describing a valid alk\*ne is equivalent to this list having length `0` (in the case where `n=1`) or `1`, so I just `Count` the number of `(n-1)`-tuples where the length of that list matches `0|1`. ``` Count[Fold[If[+##>4,4,#2]&]/@Tuples[{1,2,3},#-1],Except@4]& ``` `If[+##>4,4,#2]&` returns `4` if the sum of its arguments is greater than `4` and returns the second argument otherwise. `Fold[If[+##>4,4,#2]&]` does a left [`Fold`](http://reference.wolfram.com/language/ref/Fold.html) of its input with this function. So here I `Count` the number of `(n-1)`-tuples to which applying this operator doesn't give `4`. The case where `n=1` is covered since `Fold` remains unevaluated when its second argument is the empty list `{}`. [Answer] # Python, 51 bytes ``` f=lambda n:n<4and(n*n+n)/2or 2*f(n-1)+f(n-2)-f(n-3) ``` This is a straightforward implementation of the recurrence relation. Thanks to Tim Pederick for 3 bytes. The output is a float in Python 3 and an integer in Python 2. [Try it online!](https://tio.run/nexus/python3#FYtLDoMwDET3PYXFyuZTRFo2UXsYVxAUCaYooivE2VNn9UYzb3J4r7p9JiV4vJ6KiVGjgfTum8jVgdEN0hQ46QoekoNNkSIoKZaZh9bywRH772AR8TeiPZWqOi9P51Xd7bGpKS0Fjqbk8Q8 "Python 3 – TIO Nexus") [Answer] # Pyth - 16 bytes Uses brute force. ``` lf.AgL4+VTtT^S3t ``` [Test Suite](http://pyth.herokuapp.com/?code=lf.AgL4%2BVTtT%5ES3t&test_suite=1&test_suite_input=1%0A2%0A3%0A4&debug=0). [Answer] # Ruby, 62 bytes ``` ->n{c=0 (10**n/10).times{|i|"#{i}#{i*11}"=~/[3-9]/||c+=1} c} ``` Horribly inefficient base 10 brute force approach. Could be improved to base 5 for additional bytes. Numbers are generated where each digit represents a bond (n-1 digits.) `0` represents a bond order of 1, `2` represents a bond order of 3. Digits over 2 are invalid. We multiply this by 11 to sum adjacent pair of digits. Again digits over 3 are invalid. We combine the two numbers in a string and perform a regex to search for invalid digits. If none are found, we increment the counter. **in test program** ``` f=->n{c=0 (10**n/10).times{|i|"#{i}#{i*11}"=~/[3-9]/||c+=1} c} p f[gets.to_i] ``` [Answer] # Ruby, 51 bytes ``` ->n{a=[1,1,3] n.times{a<<2*a[-1]+a[-2]-a[-3]} a[n]} ``` Based on the recurrence relation per OEIS A006356. Starts with an array for elements 0,1 and 2 of the sequence which are 1 (as calculated by me, to make it work), 1 and 3 respectively. Iteratively adds `n` more elements to the sequence, then returns element `n`. It always calculates 2 elements more than it actually needs to, but it's still linear time, which is way more efficient than my previous answer. **in test program** ``` f=->n{a=[1,1,3] n.times{a<<2*a[-1]+a[-2]-a[-3]} a[n]} p f[gets.to_i] ``` [Answer] ## Mathematica, ~~42~~ 40 bytes Byte count assumes a compatible single-byte encoding like CP-1252 (the default on Windows installations). ``` ±0=±1=1;±2=3;±n_:=±(n-1)2+±(n-2)-±(n-3); ``` This simply implements the recurrence given on OEIS as a unary operator. [Answer] ## CJam (19 bytes) ``` {2,{__-2=+1b+}@*W=} ``` [Online test suite](http://cjam.aditsu.net/#code=10%2C%0A%0A%7B2%2C%7B__-2%3D%2B1b%2B%7D%40*W%3D%7D%0A%0A%25p). This is an anonymous block (function) which takes one item on the stack and leaves one on the stack. Note that the test suite includes `a(0) = 1`. The recurrence used is based on the observation for the related OEIS sequence [A006356](//oeis.org/A006356): > > Equals the INVERT transform of (1, 2, 1, 1, 1,...) equivalent to a(n) = a(n-1) + 2\*a(n-2) + a(n-3) + a(n-4) + ... + 1. a(6) = 70 = (31 + 2\*14 + 6 + 3 + 1 + 1). - Gary W. Adamson, Apr 27 2009 > > > but with the appropriate offset, which removes the need for the final `+ 1` as now covered by `a(0)`. ### Dissection ``` { e# Define a block 2, e# Take starting sequence [0 1] (beginning at index -1 for golfiness) { e# Loop... _ e# Copy sequence so far _-2=+ e# Append an extra copy of a(n-2) 1b e# Sum + e# Append }@* e# ...n times W= e# Take the final value from the sequence } ``` [Answer] # Brain-Flak, 56 bytes Uses the algorithm detailed in the first comment on the OEIS page. [Try it online!](http://brain-flak.tryitonline.net/#code=KHt9WygpXTwoKCgoKSkpKT4peyh7fVsoKV08eyh7fTw-KHt9KSk8Pn08Pj4pfXt9KHt9PD57fSk&input=NQ) ``` ({}[()]<(((())))>){({}[()]<{({}<>({}))<>}<>>)}{}({}<>{}) ``` ## Explanation The sequence can be defined as such: ``` For u(k), v(k), and w(k) such that u(1) = v(1) = w(1) = 1 u(k+1) = u(k) + v(k) + w(k) v(k+1) = u(k) + v(k) w(k+1) = u(k) u(k) is the number of straight-chain alk*nes with length k ``` The program starts at `1` and repeatedly applies this recurrence to calculate `u(k)` ### Annotated Code (actual annotation to come) ``` # Setup: decrement the input by one and push three 1's to the stack under it ({}[()]<(((())))>) # Calculation: { } # While the input is not zero (main loop) ({}[()] ) # Pop the counter decrement it by one and push it < > # Before the counter gets pushed back to the stack... { } # Loop while the top of the stack is not zero (subloop) ( ) # Push... {} # The top of the stack (popped)... <> # to the other stack... ({}) # plus the top of the other stack (peeked) <> # Switch back to the first stack. <> # Switch to the other stack {} # Pop the input (now zero) ( ) # Push... {} # The top of the stack (u(k))... <> # to the other stack... {} # plus the top of the other stack (zero). ``` ### Visualization of the stacks In one iteration of the main loop this is what happens (note that the zeros may or may not be present but it does not matter either way): ``` Start of main loop iteration/subloop first iteration: A B u v w 0 0 ^ After first subloop iteration: A B v w u 0 0 ^ After second subloop iteration: A B u+v w u 0 0 ^ After third subloop iteration (top of stack is zero so subloop terminates): A B u+v+w u+v u 0 0 ^ End of main loop iteration: A B u+v+w u+v u 0 0 ^ ``` The state of the stacks is now the same as it was at the start of the loop except that the current stack now has the next values for `u`, `v`, and `w` on it. [Answer] ## Perl 6, 48 ``` {my @a=1,0,0;@a=reverse [\+] @a for 1..$_;@a[0]} ``` Originally ``` sub f {$_>2??2*f($_-1)+f($_-2)-f($_-3)!!(1,1,3)[$_]} ``` but I forgot I needed the `sub f` so the iterative solution wins out. [Answer] # Dyalog APL, 30 bytes ``` {⍵<3:⍵⌷1 3⋄+/∧/¨4≥2+/¨,⍳1↓⍵/3} ``` Uses brute force. Explanation (my best attempt at one, at least): ``` ⍵<3:⍵⌷1 3 - if ⍵ (function arg) is 1 (case 1) or 2 (case 2), return 1 (case 1) or 3 (case 2) ⋄ - separate statements ⍵/3 - otherwise, 3 repeated ⍵ times 1↓ - without the first element ⍳ - the matrix of possible indices of a matrix of that size , - ravel, return a list of all the elements of the matrix 2+/¨ - sum of each contiguous pair on each element 4≥ - tests whether each element is less than or equal to 4 ∧/¨ - all elements are true, applied to each item. +/ - Sum. ``` [Answer] # Dyalog APL, 29 bytes ``` {⍵<4:⍵⌷1 3 6⋄+/2 1 ¯1×∇¨⍵-⍳3} ``` Works by using the recursive definition of the integer sequence OEIS A006356. [Answer] # Python with Numpy, 62 bytes I had to try it, but it seems [pure Python and recursion](https://codegolf.stackexchange.com/a/103149/13959) is shorter than numpy and the explicit, matrix-based calculation on the OEIS page. ``` from numpy import* lambda n:(mat('1 1 1;1 0 0;1 0 1')**n)[0,0] ``` [Answer] # R, ~~61~~ ~~58~~ ~~55~~ ~~51~~ 50 bytes Takes input from stdin, uses matrix exponentiation to determine exact result. ``` el(expm::`%^%`(matrix(!-3:5%in%2^(0:2),3),scan())) ``` If you prefer a recursive solution, here's a straightforward implementation of the recurrence relation listed in OEIS, for **55 bytes**. ``` f=function(n)`if`(n<4,(n*n+n)/2,2*f(n-1)+f(n-2)-f(n-3)) ``` [Answer] # Excel, 123 bytes Implements the formula from OEIS: ``` =4*(SIN(4*PI()/7)^2*(1+2*COS(2*PI()/7))^A1+SIN(8*PI()/7)^2*(1+2*COS(4*PI()/7))^A1+SIN(2*PI()/7)^2*(1+2*COS(8*PI()/7))^A1)/7 ``` As always, input in `A1`, formula in any other cell. Dug up old Trig identities to see if could be helpful. Now my head hurts. [Answer] ## [Lithp](https://github.com/andrakis/node-lithp), 79 bytes ``` #N:(((if(< N 4)((/(+ N(* N N))2))((-(+(* 2(f(- N 1)))(f(- N 2)))(f(- N 3))))))) ``` Implements recursive integer sequence listed in OEIS. Readable implementation and test suite. ``` % alkaline.lithp % run with: ./run.js alkaline.lithp ( (def f #N : (( (if (< N 4) ( (/ (+ N (* N N)) 2) ) (else ( (- (+ (* 2 (f (- N 1))) (f (- N 2))) (f (- N 3))) ))) ))) % Test cases 1 to 4 (import lists) (each (seq 1 4) #I :: ((print (f I)))) ) ``` [Answer] # MMIX, 44 bytes (11 instrs) If passed 0, returns \$A077998(2^{64})\$ (if the computer doesn't break down). Works mod \$2^{64}\$. (jxd) ``` 00000000: e3010001 e3020001 e3030003 27000001 ẉ¢¡¢ẉ£¡¢ẉ¤¡¤'¡¡¢ 00000010: 28ff0302 26ffff01 c1010200 c1020300 (”¤£&””¢Ḋ¢£¡Ḋ£¤¡ 00000020: c103ff00 5b00ffb5 f8020000 Ḋ¤”¡[¡”Ọẏ£¡¡ ``` Disassembly and explanation: ``` alkns SET $1,1 // a(0) SET $2,1 // a(1) SET $3,3 // a(2) 0H SUBU $0,$0,1 // loop: n-- 2ADDU $255,$3,$2 // a' = 2a + a` SUBU $255,$255,$1 // - a`` SET $1,$2 // a`` = a` SET $2,$3 // a` = a SET $3,$255 // a = a' PBNZ $0,0B // if(n) goto loop POP 2,0 // return a ``` ]
[Question] [ Your challenge, should you choose to accept it, is, given an integer `K >= 1`, find non-negative integers `A` and `B` such that at least one of the two conditions following hold: 1. `K = 2^A + 2^B` 2. `K = 2^A - 2^B` If there does not exist such `A` and `B`, your program may behave in any fashion. (To clarify, `A` and `B` can be equal.) ## Test cases There are often multiple solutions to a number, but here are a few: ``` K => A, B 1 => 1, 0 15 => 4, 0 ; 16 - 1 = 15 16 => 5, 4 ; 32 - 16 = 16; also 3, 3: 8 + 8 = 16 40 => 5, 3 ; 2^5 + 2^3 = 40 264 => 8, 3 17179867136 => 34, 11 ; 17179869184 - 2048 = 17179867136 ``` The last test case, `17179867136`, **must run in under 10 seconds** on any relatively modern machine. This is a code golf, so the shortest program in bytes wins. You may use a full program or a function. [Answer] ## Python 2, 43 bytes ``` lambda n:[len(bin((n&-n)+k))-3for k in n,0] ``` Say that `n==2^a ± 2^b` with `a>b`. Then, the greatest power-of-2 factor of `n` is `2^b`, and we can find it using the bit-trick `2^b = n&-n`. That lets us compute `2^b + n`, which equals either `2^a + 2 * 2^b` or just `2^a`. Either one has the same-length bit-length as `a`\*. So, we output the bit-lengths of `n&-n` and `(n&-n)+n`, computed from the lengths of their binary representations. Python 3 is one byte longer for parens in `for k in(n,0)]`. \*Except that `2^a + 2^b` with `a==b+1` has one longer bit-length, but that's fine because we can interpret that as `2^(a+1)-2^b`. [Answer] ## JavaScript (ES6), 73 bytes ``` (n,[s,f,z]=/^1+(.*1)?(0*)$/.exec(n.toString(2)))=>[s.length-!!f,z.length] ``` For the subtraction case, the first number is the number of digits in the binary representation and the second number is the number of trailing zeroes. For the addition case, we subtract 1 from the first number. If the binary representation is all 1s followed by some 0s then the addition case is assumed otherwise the subtraction case is assumed. 36-byte port of @xnor's version that only works for B≤30 in JavaScript: ``` n=>[(l=Math.log2)(n+(n&=-n))|0,l(n)] ``` [Answer] # Perl, ~~52~~ ~~49~~ 32 bytes Old solution (49 bytes) Includes +1 for `-p` Give input on STDIN: ``` pow2.pl <<< 17179867136 ``` `pow2.pl` ``` #!/usr/bin/perl -p $_=reverse sprintf"%b",$_;/()1(?:1+|0*)/;$_="@+" ``` However, using xnor's algorithm and adding a twist gives 32 bytes: ``` perl -nE 'say 13/9*log|0for$;=$_&-$_,$_+$' ``` Just the code: ``` say 13/9*log|0for$;=$_&-$_,$_+$ ``` This suffers from severe rounding error because `13/9 = 1.444...` is quite a bit above `1/log 2 = 1.44269...` (`log` itself also has a rounding error but that is so much smaller that we can wrap it up in the analysis of 13/9). But since any `2**big - 2** small` gets corrected to `2** big` before the log this doesn't mater and the calculation for `2**big + 2 * 2**small` gets truncated down so is also safe.. And at the other side of the range `2**n+2**(n-1)` doesn't get increased enough in the range `[0,64]` (I can't properly support more than the integer range anyways due to the use of `&`) to lead to a wrong result (multiplicator `1.5` however would be too far off for large numbers). [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 23 bytes ``` ,A:B#+.:2rz:^a{+|-}?,.= ``` [Try it online!](http://brachylog.tryitonline.net/#code=LEE6QiMrLjoycno6XmF7K3wtfT8sLj0&input=MTcxNzk4NjcxMzY&args=Wg) This is much faster than required, e.g. [this is still under 10 seconds on TIO](http://brachylog.tryitonline.net/#code=LEE6QiMrLjoycno6XmF7K3wtfT8sLj0&input=NDQ4NDg4NTUyODQxNTA1NjczNTI4NDUwNDY5MjEwMDMyMDI1MDA4NzE3ODUyMzc4Mzk2NTYyNjg2NTc5MTk0MDcyNTY0OTQ1ODU2Mzk0NjUzODUwMjU3NjExODQyMzg1MjYxNjg2ODkyOTU0OTM3MTA0NDc3NjQ1ODc3NzgwODQ0MDg3MTMwOTg4ODM4MjU0NDM2MDAyNTk4OTAwNTQzNDc2NTIwMDk4ODc2MDkzNzUyNjkwNTQzNTQ3ODEyNjc1Mjc5MDE5MjQ2MDU0OTM1NDkzMTQzNjc4MTg1NDA0ODY4NzA0NTQ2NjY5MjA3MTMyOTcwNTcxNjk1MTk4ODQ3NjQyODA1MzIxODcwMzQ3NDM5OTU5Mzk2OTY2MDYxMTMxMDAwNjQxNDkyMDcxNjEyMDM2NTAwNjU5ODAwNzIwNTQxMDM3NTA5Mjk0ODYyNTMwOTE0MjkyNTgxNzc2NDcwNzA0ODAwNzkxODYyMTM1MjU3MTUwNDc2NTk0MjY2NTQ3OTczNzk1OTQyNDUyNjY5MjA3ODM4Mjc3MzI1NzY3MjU4MzA4Njc4ODI3NTcxODkwNzg5Njg2OTI2NDk3MDc2MzMxNTk5MzUxMTgwMDQ2NTY0NjY3ODAzODQyMTQ3MTU2NDAyOTY5MDcwMTQ1Mzc3NDYzMjEzODg4MjA0Nzg3NDM2NDI5NzQ4MTU3MzgwODYyNzcyNDMxODMwNTM0NjAzMTU0MDYwNzc0MTI4Nzc1ODM4NDk0NDA4ODgyOTQ4NDQ1NDI4NzYyMzg1NzQyNzA4MzE1NTIxMDI0&args=Wg&debug=on). ### Explanation This is basically a direct transcription of the formula with no optimization: ``` ,A:B The list [A, B] #+ Both A and B are greater than or equal to 0 . Output = [A, B] :2rz The list [[2, A], [2, B]] :^a The list [2^A, 2^B] {+|-}? 2^A + 2^B = Input OR 2^A - 2^B = Input ,.= Assign a value to A and B which satisfy those constraints ``` [Answer] # Python, 69 bytes ``` def f(k):b=bin(k)[::-1];return len(b)-2-(b.count('1')==2),b.find('1') ``` Tests are on [**ideone**](http://ideone.com/LZAsgu) Since non-valid input can do anything, we know that if the input has exactly 2 bits set it is the sum of those 2 powers of 2, and otherwise (if valid) it will be be a run of some number of bits (including the possibility of just 1 bit) and will be the difference between the next highest power of 2 than the MSB and the LSB set. [Answer] ## JAVA 7 ,~~142~~ ,~~140~~, 134 BYTES This is my first post on PPCG!I would really appreciate for feedback on golfing tips *Thanks to **frozen** for saving 2 bytes* ``` void f(long n){for(int i=-1,j;i++<31;)for(j=0;j++<34;){long a=1,x=a<<i,y=a<<j;if(x+y==n|y-x==n){System.out.println(j+" "+i);return;}}} ``` ## UNGOLF ``` void f(long n){ for(int i=-1,j;i++<31;) for(j=0;j++<34;){ long a=1,x=a<<i,y=a<<j; if(x+y==n|y-x==n){ System.out.println(j+" "+i); return; } } } ``` [ideone](https://ideone.com/1kge2K) [Answer] # Mathematica, ~~57~~ 54 bytes *Saved 3 bytes thanks to LegionMammal978!* ``` Do[Abs[2^a-#]==2^b&&Print@{a,b},{a,2Log@#+1},{b,0,a}]& ``` Actually prints out all1 appropriate pairs {a,b}. `2Log@#+1` is an upper bound for the largest `a` that can possibly appear when representing the input `#` (the tight upper bound is Log[2#]/Log[2] = 1.44... Log[#] + 1). Runs almost instantaneously on the test input, and in less than a quarter second (on my new but off-the-shelf computer) on 100-digit inputs. 1 Letting `a` start at the default value of 1 instead of 0 saves two bytes; it causes the output {0,0} to be missed when the input is 2, but finds the output {2,1} in that case, which is good enough. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ;0+N&$BL€’ ``` Applying the bit twiddling trick from [the Python answer by @xnor](https://codegolf.stackexchange.com/a/92864/53748) Test it at [**TryItOnline**](http://jelly.tryitonline.net/#code=OzArTiYkQkzigqzigJk&input=&args=MTU) All test cases are also at [**TryItOnline**](http://jelly.tryitonline.net/#code=OzArTiYkQkzigqzigJkKxbzDh-KCrOG5hOKCrOG4ozA&input=&args=MTUsMTYsNDAsMjY0LDE3MTc5ODY3MTM2) How? ``` ;0+N&$BL€’ - main link takes an argument, k, e.g 15 ;0 - concatenate k with 0, e.g. [15, 0] $ - last two links as a monad N - negate, e.g. -15 & - bitwise and, e.g. -15&15=1 since these two are called as a monad (one input) + - add, vectorises, e.g. [16,1] B - convert to binary, vectorises, e.g. [[1,0,0,0,0],[1]] L€ - length for each, e.g. [5,1] ’ - decrement, vectorises, e.g. [4,0] ``` [Answer] # [MATL](http://github.com/lmendo/MATL), ~~23~~ 22 bytes ``` BnQ:qWtG-|ym)1)tG-|hZl ``` [Try it online!](http://matl.tryitonline.net/#code=Qm5ROnFXdEctfHltKTEpdEctfGhabA&input=MTcxNzk4NjcxMzY) Or [verify all test cases](http://matl.tryitonline.net/#code=IkAKQm5ROnFXdEAtfHltKTEpdEAtfGhabA&input=WzE1IDE2IDQwIDI2NCAxNzE3OTg2NzEzNl0). ### Explanation ``` B % Implicit input. Convert to binary. Gives n digits nQ:q % Range [1 ... n+1] W % 2 raised to that, element-wise: gives [1 2 4 ... 2^(n+1)] (*) tG-| % Duplicate. Absolute difference with input, element-wise (**) y % Push a copy of (*) m % True for elements of (**) that are members of (*) ) % Use as logical index to select elements from (*) 1) % Take the first element. Gives power of the first result tG-| % Duplicate. Absolute difference with input. Gives power of the second result hZl % Concatenate. Take binary logarithm. Implicit display ``` [Answer] # [Perl 6](http://perl6.org), 41 bytes ``` {.base(2).flip~~/1[1+|0*]/;$/.to,$/.from} ``` ( Algorithm shamelessly copied from [the Perl 5 answer](https://codegolf.stackexchange.com/questions/92850/a/92858#92858) ) ## Explanation: ``` # bare block lambda with implicit parameter 「$_」 { # turn into binary # ( implicit method call on 「$_」 ) .base(2) # flip the binary representation .flip ~~ # smartmatch that against: / 1 # a 「1」 [ | 1+ # at least one 「1」 | 0* # or any number of 「0」 ] /; # returns a list comprised of # the position of the end of the match (larger of the two) $/.to, # the position of the beginning of the match $/.from } ``` ## Usage: ``` # give it a lexical name for clarity my &bin-sum-diff = {.base(2).flip~~/1[1+|0*]/;$/.to,$/.from} say bin-sum-diff 15; # (4 0) say bin-sum-diff 16; # (5 4) say bin-sum-diff 20; # (4 2) # 2**4==16, 2**2==4; 16+4 == 20 say bin-sum-diff 40; # (5 3) say bin-sum-diff 264; # (8 3) say bin-sum-diff 17179867136; # (34 11) ``` [Answer] # PHP, 73 bytes I could have copied Jonathan´s Pyhton 2 solution for 54 bytes (+13 overhead), but wanted to come up with something different. save to file, then execute with `php` or `php-cgi`. ``` <?=strlen($n=decbin($argv[1]))-!!strpos($n,'01')._.strpos(strrev($n),49); ``` prints `a` and `b` separated by an underscore, anything for no solution. **distinctive solution, 96 bytes** ``` <?=preg_match('#^(10*1|(1+))(0*)$#',decbin($argv[1]),$m)?strlen($m[0])-!$m[2]._.strlen($m[3]):_; ``` prints `a` and `b` separated by an underscore; a sole underscore for no solution. It even tells you the operation for 11 more bytes: Just replace the first underscore in the code with `'-+'[!$m[2]]`. [Answer] # PHP ,117 Bytes ``` if(preg_match("#^(1+|(10*1))0*$#",$b=decbin($k=$argv[1]),$t))echo($l=strlen($b))-($t[2]?1:0).",",$l+~strrpos($b,"1"); ``` Extended version 4 Cases ``` $l=strlen($b=decbin($k=$argv[1])); // Case 1: n=2(n-1)=n+n or n=n*(2-1)=2n-n if(preg_match('#^100*$#',$b))echo($l-2).'a+'.($l-2).':'.$l.'a-'.($l-1); // Case 2: n-m elseif(preg_match('#^1+0*$#',$b)){echo $l.'b-',strpos($b,"0")?$l-strpos($b,"0"):0;} // Case 3: n+m elseif(preg_match('#^10*10*$#',$b))echo ($l-1).'c+',$l-strrpos($b,"1")-1; else echo "Nothing"; ``` the short version union Case 1 and 3 and makes a Difference to Case 3 and in both versions Case 4 gives no output. ]
[Question] [ Create a function or program that takes a number as input, and outputs a string where ASCII-code points for the lower and upper case alphabet are substituted by their character equivalents. * The upper case alphabet use the code points: `65-90` * The lower case alphabet use the code points: `97-122` If any adjacent digits in the input equals the code point of a letter, then that letter shall replace the digits in the output string. **Rules:** * The input will be a positive integer with between 1 and 99 digits * You can assume only valid input is given * You start substituting at the beginning of the integer (`976` -> `a6`, not `9L`) * The input can be on any suitable format (string representation is OK) * The output can be on any suitable format * Standard rules apply **Examples:** ``` 1234567 12345C 3456789 345CY 9865432 bA432 6566676869707172737475767778798081828384858687888990 ABCDEFGHIJKLMNOPQRSTUVWXYZ 6711110010100071111108102 Code000Golf ``` **Shortest code in bytes win!** --- ## Leaderboard The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. 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 ``` ``` var QUESTION_ID=71735,OVERRIDE_USER=31516;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] ## Perl, ~~39~~ 38 bytes (1 byte added for the `-p` flag.) ``` $"="|";s/@{[65..90,97..122]}/chr$&/ge ``` ``` s/ / replace... @{[ ]} this string, treated as a regex: join"|",65..90,97..122 65|66|67|68|...|121|122 /ge ...with this string, eval()'d: $& the entirety of the last match chr convert to char from ASCII code ``` Right Tool for the Job™. The explanation is outdated after one small optimization (thanks [dev-null](https://codegolf.stackexchange.com/users/48657/dev-null)!) that makes it a single byte shorter (but a bit less elegant): the `$"` variable represents what to `join` on when interpolating an arrray into a string, so setting `$"="|"` removes the need for `join`. Demo: ``` llama@llama:~$ perl -pe '$"="|";s/@{[65..90,97..122]}/chr$&/ge' 1234567 12345C 3456789 345CY 9865432 bA432 6566676869707172737475767778798081828384858687888990 ABCDEFGHIJKLMNOPQRSTUVWXYZ 6711110010100071111108102 Code000Golf ``` [Answer] # Javascript, 80 bytes ``` s=>s.replace(/6[5-9]|[78]\d|9[0789]|1[01]\d|12[012]/g,x=>String.fromCharCode(x)) ``` See regex in action here: <https://regex101.com/r/iX8bJ2/1> ``` f= s=>s.replace(/6[5-9]|[78]\d|9[0789]|1[01]\d|12[012]/g,x=>String.fromCharCode(x)) document.body.innerHTML = '<pre>' + "f('1234567')\n" + f('1234567') + '\n\n' + "f('3456789')\n" + f('3456789') + '\n\n' + "f('9865432')\n" + f('9865432') + '\n\n' + "f('6566676869707172737475767778798081828384858687888990')\n" + f('6566676869707172737475767778798081828384858687888990') + '\n\n' + "f('6711110010100071111108102')\n" + f('6711110010100071111108102') + '</pre>' ``` Just for curiosity, one thing I learned here: I can't change `x=>String.fromCharCode(x)` to `String.fromCharCode` [because ...](https://stackoverflow.com/a/35340883/4227915) [Answer] # CJam, 22 bytes ``` q{+'[,_el^{_is@\/*}/}* ``` [Try it online!](http://cjam.tryitonline.net/#code=cXsrJ1ssX2VsXntfaXNAXC8qfS99Kg&input=NjcxMTExMDAxMDEwMDA3MTExMTEwODEwMg) ### Background Simply replacing all occurrences of digit groups with the corresponding letters (in whatever order we may choose) will fail to comply with the left-to-right rule. Instead, we can generate all prefixes of the input string, and attempt to make all possible substitutions while we're generating them. Since no code point is contained in another code point, the order of these attempts is not important. For example: ``` 67466 6 -> 6 67 -> C C4 -> C4 C46 -> C46 C467 -> C4B C4B ``` ### How it works ``` q Read all input from STDIN. { }* Fold; push the first character, and for each subsequent character, push it and do the following: + Append the character to the string on the stack. '[,_el^ Push the string of all ASCII letters. See: http://codegolf.stackexchange.com/a/54348 { }/ For each ASCII letter: _ Push a copy of the letter. i Convert to integer, i.e., compute its code point. s Cast to string. @\ Rotate and swap. / Split the modified input characters at occurrences (at most one) of the string repr. of the code point. * Join, separating by the corresponding letter. ``` [Answer] # PHP, ~~110~~ ~~102~~ ~~101~~ ~~68~~ 67 bytes Pretty hard challenge. ~~This is the best I could come up with.~~ This is a completely new version. ``` for($i=64;123>$i+=$i-90?1:7;)$t[$i]=chr($i)?><?=strtr($argv[1],$t); ``` Run like this: ``` php -r 'for($i=64;123>$i+=$i-90?1:7;)$t[$i]=chr($i)?><?=strtr($argv[1],$t);' 6711110010100071111108102;echo > Code000Golf ``` * Saved 8 bytes by using `ctype_alpha` instead of `preg_match`, thx to manatwork * Saved 1 byte by prepending `0` to the string instead of checking non-empty string: when the last character of the input is a 0, the substring I'm taking would be "0", which is falsy, whereas "00" is truthy, so it won't skip printing the last 0. * Saved a massive 33 bytes by using `strtr` after building an array with conversion pairs * Saved a byte by using short print tag [Answer] # Jolf, ~~18~~ 16 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=z4FpTGHOnEdwd3B1RWTOokhkcEFI) I knew that upperLower function would be useful someday! Replace `ó` with `΢`, or just use the interpreter link. This is encoded in ISO 8859-7. ``` ρiLaΜGpwpuEdóH΅A pw upper and lower pu of the uppercase alphabet G E split by nothing (E = "") Μ dóH map each char to its numeric counterpart La regex alternate array (e.g. La[1,2,3] => "1|2|3") ρi ΅A replace input with the character code of the match (΅ is string lambda) ``` [Answer] ## Python 3, ~~211~~ ~~189~~ 188 bytes ``` def f(c,i=0,n=""): while i<len(c):a=1;x=int(c[i:i+2]);a=2 if 64<x<91 or 96<x<100 else a;x=int(c[i:i+3]) if a<2 else x;a=3 if 99<x<123 else a;x=chr(x) if a>1 else c[i];n+=x;i+=a return n ``` * ### Saved 23 bytes by replacing \n with ; thanks to Dennis ## Test [![enter image description here](https://i.stack.imgur.com/LgBYL.png)](https://i.stack.imgur.com/LgBYL.png) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~10~~ 9 bytes ``` JkBC:CV)R ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJ+IiwiIiwiSmtCQzpDVilSIiwiIiwiXCIxMjM0NTY3XCIgPT4gMTIzNDVDXG5cIjM0NTY3ODlcIiA9PiAzNDVDWVxuXCI5ODY1NDMyXCIgPT4gYkE0MzJcblwiNjU2NjY3Njg2OTcwNzE3MjczNzQ3NTc2Nzc3ODc5ODA4MTgyODM4NDg1ODY4Nzg4ODk5MFwiID0+IEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaXG5cIjY3MTExMTAwMTAxMDAwNzExMTExMDgxMDJcIiA9PiBDb2RlMDAwR29sZiJd) Link includes test cases. Port of @KevinCruijssen's 05AB1E answer. *-1 thanks to @KevinCruijssen* #### Explanation ``` JkBC:CV)R # Implicit input )R # Reduce by: J # Append to the string kB # Push constant [A-Za-z] C # Convert to codepoints :C # Duplicate and convert back V # Replace codepoints with characters # Implicit output ``` [Answer] ## Pyth, ~~20~~ 18 bytes ``` .Uu:G`CHHsrBG1+bZz ``` Same algorithm as @Dennis. It's a lot easier to code in Pyth on my phone than in Jelly. ``` implicit: z=input .U Reduce the following lambda b, Z over z b is the string being built; z is the next char u Reduce the following lambda G,H over +bZ G is the string, H is the next letter to match : Replace G in G ` C H the char code of H H with H s rB where H takes on values: G the lowercase alphabet (that's the global value of G) 1 concatenated to its uppercased self. + b Z z ``` *Thanks @isaacg* Try it [here](http://pyth.herokuapp.com/?code=.Uu%3AG%60CHHsrBG1%2BbZz&input=6711110010100071111108102&debug=1). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Å»«žnÇDç:}θ ``` [Try it online](https://tio.run/##yy9OTMpM/f//cOuh3YdWH92Xd7jd5fByq9pzO/7/NzM3BAIDA0MgNDAAcwwNLAwNjAA) or [verify all test cases](https://tio.run/##HYo7CgJBEETzOcWysUHPr6vaZBMvomBgooEgLGio5l7CwAsIgsEOph7Ci4zL1oMHD2q3X64263o89F3b/C63pu36Ws7Da3h83ttyXZT7/PR91ln1IaascJNpzqg5xeA0qyqUahB4BEQkZCgAwij0DIxMzFSCpJk4hR8n4kdEpvDjU4Iz6B8) or [see a step-by-step reduction with just the first 9 bytes](https://tio.run/##yy9OTMpM/f//cOuh3YdWH92Xd7jd5fByq///zcwNgcDAwBAIDQzAHEMDC0MDIwA). **Explanation:** ``` Å» # Cumulative left reduce the (implicit) input-string by: « # Append the current character to the string žn # Push the builtin "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Ç # Convert it to a list of integer codepoints D # Duplicate this list ç # Convert each integer to its character again # (so it's a list of the characters, instead of a string) : # Replace all integers with these characters (at the same indices) # (would only replace 0 or 1 time) } # After the cumulative reduce-by is done: θ # Pop the list, and only leave the last string # (after which it is output implicitly as result) ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, ~~50~~ 45 bytes -5 bytes thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) ``` gsub(/#{[*65..90,*97..122]*?|}/){$&.to_i.chr} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6BUuyCpaUlaboWN3XTi0uTNPSVq6O1zEz19CwNdLQszfX0DI2MYrXsa2r1NatV1PRK8uMz9ZIzimohmqB6F-w0MzcEAgMDQyA0MABzDA0sDA2MIAoA) [Answer] # [Java (JDK)](http://jdk.java.net/), 164 ~~169~~ bytes > > -5 bytes thanks to @KevinCruijssen ! > > > I tried without regexp, and it was surprisingly tricky to handle all the possibilities :') I'm seven years late to the party, but nice challenge anyway! ``` s->{var r="";for(int i=0,j,a,m=s.length();i<m;r+=a>64&a<91|a>96&a<123?(char)(a+0*(i=j)):s.charAt(i++))for(j=i,a=0;j<m&&(a=a*10+s.charAt(j++)-48)>0&a<13;);return r;} ``` [Try it online!](https://tio.run/##fVPLctowFN3nKzQsGCkGR8a2HhGmQ0maNiVt2vSVdrpQjE3k@sHIgkkn4duJTGhXYGkj3XvOuS8pkyvZz2Z/NovlXa5iEOeyrsGVVCV4PDoCQJUm0amMEzC1BmDXjdGqnIMU7g41Eta@bsC1kcZqTEEOok3dHz2upAY66nREWmlopYCKcC/ryV4R1W6elHNzD5FQw0JoJ5IjEnTlkHtPcsSJPXkD/xWM76VGUDr4GKooQ@i0dhvT2EDlOAg1wlmkejLCIhsW3S6UkTz2sPMflllYP2BohBtJXyChE7PUJdBivRFN2rvSd9mvKjUDhW3ArsBfv4HU8xr9K/9vbZLCrZbGXVi3yUuYuyns2GSDkNAOQsKiTk5A8rBIYpPMwCnY@iat9C2Z8b30hnzbyuaMhIE/2Mu@G1tPK5uEhBBKGOEUU48OqE8DGlJCKWWUM8w8NmA@C1jICKOMMc7x3lDj15Oz8zcXb99dvp9effh4/enzzZev377/uP3ZHp96dmHs2Y3x9uLZoHh/PZNqlljYRZWnh1S3L7JtVJwfmFPc3mZygMjP@csfWG@eAQ "Java (JDK) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 95 bytes ``` lambda x:re.sub("6[5-9]|[7-8]\d|90|9[7-9]|1[01]\d|12[0-2]",lambda r:chr(int(r[0])),x) import re ``` Assuming we can take in strings, otherwise this would be 100 bytes. [Try it online!](https://tio.run/##LU7RioMwEHy/r1jyZEDLJjG7G6Ffoj60V6WBViV60AP/3UvL7cAwM8zALr/bfZ7cMZ6743F5Xm8XeDVpOK0/10JR66vQ7y1X0ne3PeAess6JadG8E2NbrGyvyv9par7vqYjTVqQWe63Ll/6Kz2VOG6ThGOcEEeIEylhXe2L4sAQIQr52FsgTEZNQYGTDlh3X7JmYWTgIihErTmrxQsIiEgICscmHaDIQP8bkJlp1WpdH3ArdLOn9UyxhLKIuQakS1mE5q25S@vgD "Python 3 – Try It Online") [Answer] # [Io](http://iolanguage.org/), 228 bytes As for these warnings... let's just ignore them. ``` s :=method(H,r(H slice(0,1),H slice(1))) r :=method(H,T,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"foreach(i,H=H asMutable replaceSeq(i asString,i asCharacter))if(T=="",return H)r(list(H,T slice(0,1))join,T slice(1))) ``` [Try it online!](https://tio.run/##TY5JT8MwFITv/ArLJ1vyweYACCkHKItZytKE9ea6L42La6fPDtufDwkSqG8ub0Yjzedi3ydyWKwhN3HBtECmSfLOApNCcfFnFOd8B7eLlaBHx5OT07NzfXF5dT29ub27n5XVw@PT88urmdsF1MvGrd78OsR2gyl37x@fX9@0jgjGNswJXWhi0rTLZu6BILTeWChhw9wQlxldWIrxnTQGjc2AnLuaVUVBqUDIHQaiOTLvUh55trD5Krrwn4zsfWJ0b18NJ6UaJOWvUfJAyV3KSTusZR/6Hw "Io – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 51 bytes ``` $args-replace(65..90+97..122-join'|'),{[char]+"$_"} ``` [Try it online!](https://tio.run/##TZDZTsMwEEXf8xVWZEiiJpGdxTNGQqIUKPu@FYSq0LoLipqSFIHU9tuDmy4wfrDnHt@r0Yyzb5UXA5WmJe2RXTItaZL3Cy9X4zTpKFvEvi9ZTYLv8yDwPrLhyJpZjjt97QyS/K1m0rY5L@eGsWcbRJdrWzwIo1iA5S5fDctZk0pHqclCb/0BiSKOwkCD9/ri3gARCyFAoJDAgEMAIUQQgwAABIkMOQYYYoQxCgRElJLplPp@4@DwqHl8cnp2fnF5dX1ze3f/8Pj03Hr5Fw1cF2NcH8aqhus8tpiikXWVFptZ2tMGh8zIFplWRlpM8uGo7xKqfsaqM1FdvTTaXrJcFV/pRAvbepernxUxqb2CnvrcOJ2dtcU05uUv "PowerShell – Try It Online") Explanation: * replace by RegExp `65|66|67|68|...|121|122` * replace to result of `{[char]+"$_"}`: ``` $_ object with matched string "$_" matched string +"$_" convert the string to int ``` [char]+"$\_" convert the int to char ]
[Question] [ Time for another easy challenge in which all can participate! The multinomial theorem states: $$(x\_1 + x\_2 + \cdots + x\_m)^n = \sum\_{k\_1 + k\_2 + \cdots + k\_m = n} \binom n {k\_1, k\_2, \dots, k\_m} \prod\_{1 \le t \le m} x\_t^{k\_t}.$$ The expression in parentheses is the multinomial coefficient, defined as: $$\binom n {k\_1, k\_2, \dots, k\_m} = \frac {n!} {k\_1!k\_2!\cdots k\_m!}$$ Allowing the terms \$k\_i\$ to range over all integer partitions of \$n\$ gives the \$n\$-th level of Pascal's \$m\$-simplex. Your task is to compute this coefficient. ## Task Write a program or function which takes \$m\$ numbers, \$n, k\_{1}, k\_{2}, \dots, k\_{m-1}\$, and outputs or returns the corresponding multinomial coefficient. Your program may optionally take \$m\$ as an additional argument if need be. Note that **\$k\_m\$ is not in the input.** * These numbers may be input in any format one likes, for instance grouped into lists or encoded in unary, or anything else, as long as the actual computation of the multinomial coefficient is performed by your code, and not the encoding process. * Output format is similarly flexible. * All code should run in less than one minute for \$n\$ and \$m\$ up to 1000. * Do not worry about integer overflow. * Built-ins designed to compute the multinomial coefficient are not allowed. * Standard loopholes apply. ## Scoring This is code golf: Shortest solution in bytes wins. ## Test cases ``` Input: 3, [2, 0] Output: 3 Input: 3, [1, 1] Output: 6 Input: 11, [1, 4, 4] Output: 34650 Input: 4, [1,2] Output: 12 Input: 15, [5,4,3,2] Output: 37837800 Input: 95, [65,4,4] Output: 1934550571913396675776550070308250 Input: 32, [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] Output: 4015057936610313875842560000000 Input: 15, [3,3,3,3] Output: 168168000 Input: 1000, [10,10,10,10,10,10,10,10,10,10,100,100,100,100,100,100,100,100] Output: 1892260836114766064839886173072628322819837473493540916521650371620708316292211493005889278395285403318471457333959691477413845818795311980925098433545057962732816261282589926581281484274178579110373517415585990780259179555579119249444675675971136703240347768185200859583936041679096016595989605569764359198616300820217344233610087468418992008471158382363562679752612394898708988062100932765563185864346460326847538659268068471585720069159997090290904151003744735224635733011050421493330583941651019570222984959183118891461330718594645532241449810403071583062752945668937388999711726969103987467123014208575736645381474142475995771446030088717454857668814925642941036383273459178373839445456712918381796599882439216894107889251444932486362309407245949950539480089149687317762667940531452670088934094510294534762190299611806466111882595667632800995865129329156425174586491525505695534290243513946995156554997365435062121633281021210807821617604582625046557789259061566742237246102255343862644466345335421894369143319723958653232683916869615649006682399919540931573841920000000000000 Input: 33, [17] Output: 1166803110 Input: 55, [28] Output: 3824345300380220 ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes ``` ;_/!:/ ``` Look ma, no Unicode! This program takes a single list as input, with **n** at its first index. [Try it online!](http://jelly.tryitonline.net/#code=O18vITov&input=&args=MTAwMCwgMTAsIDEwLCAxMCwgMTAsIDEwLCAxMCwgMTAsIDEwLCAxMCwgMTAsIDEwMCwgMTAwLCAxMDAsIDEwMCwgMTAwLCAxMDAsIDEwMCwgMTAw) or [verify all test cases at once](http://jelly.tryitonline.net/#code=O18vITovCsOH4oKsauKBtw&input=&args=WzMsIDIsIDBdLCBbMywgMSwgMV0sIFsxMSwgMSwgNCwgNF0sIFs0LCAxLCAyXSwgWzE1LCA1LCA0LCAzLCAyXSwgWzk1LCA2NSwgNCwgNF0sIFszMiwgMiwgMiwgMiwgMiwgMiwgMiwgMiwgMiwgMiwgMiwgMiwgMiwgMiwgMiwgMl0sIFsxNSwgMywgMywgMywgM10sIFsxMDAwLCAxMCwgMTAsIDEwLCAxMCwgMTAsIDEwLCAxMCwgMTAsIDEwLCAxMCwgMTAwLCAxMDAsIDEwMCwgMTAwLCAxMDAsIDEwMCwgMTAwLCAxMDBdLCBbMzMsIDE3XSwgWzU1LCAyOF0). ### How it works ``` ;_/!:/ Input: A (list) _/ Reduce A by subtraction. This subtracts all other elements from the first. ; Concatenate A with the result to the right. ! Apply factorial to all numbers in the resulting list. :/ Reduce the result by division. This divides the first element by the others. ``` [Answer] ## CJam, 11 bytes ``` l~_:-+:m!:/ ``` Input as a single list with `n` first: ``` [95 65 4 4] ``` This handles inputs up to `n` and `m` 1000 pretty much instantly. [Test it here.](http://cjam.aditsu.net/#code=l~_%3A-%2B%3Am!%3A%2F&input=%5B95%2065%204%204%5D) ### Explanation ``` l~ e# Read a line of input and evaluate it. _ e# Duplicate. :- e# Fold subtraction over the list. A fold is essentially a foreach loop that starts e# from the second element. Hence, this subtracts all the k_i from n, giving k_m. + e# Append k_m to the list. :m! e# Compute the factorial of each element in the list. :/ e# Fold division over the list. Again, this divides n! by each of the k_i!. ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 21 ~~15~~ bytes Let's put the [log-gamma function](http://mathworld.wolfram.com/LogGammaFunction.html) to good use. This avoids internal overflowing by working with logarithms of factorials, not with factorials themselves. ``` 1+ZgiO$Gs-h1+Zgs-ZeYo ``` This works in [current version (9.2.2)](https://github.com/lmendo/MATL/releases/tag/9.2.2) of the language/compiler, which is earlier than this challenge. Inputs are: first a number, then a numeric vector. The result is produced as a `double`, which limits maximum output to somewhere around `2^52`. ### Example ``` >> matl 1+ZgiO$Gs-h1+Zgs-ZeYo > 15 > [5 4 3 2] 37837800 ``` ### Explanation ``` 1+ % implicit input (number). Add 1 Zg % log-gamma function i % input (numeric vector). 0$G % push both inputs s- % sum the second input (vector) and subtract from first h1+ % append to vector. Add 1 Zg % log-gamma function, element-wise on extended vector s % sum of results - % subtract from previous result of log-gamma Ze % exponential Yo % round. Implicit display ``` [Answer] ## PowerShell, ~~91~~ 74 bytes Woo! My 100th answer on PPCG! ``` param($n,$k)(1..$n-join'*'|iex)/(($k|%{$n-=$_;1..$_})+(1..$n)-join'*'|iex) ``` Whew. Not going to win shortest-code, that's for sure. Uses a couple neat tricks with ranges, though. And this is probably complete gibberish to anyone not familiar with PowerShell. ### Explanation First we take input with `param($n,$k)` and expect `$k` to be an array, e.g. `.\compute-the-multinomial-coefficient.ps1 11 @(1,4,4)`. We'll start with the numerator (everything to the left of `/`). That's simply a range from `1..$n` that has been `-join`ed together with `*` and then evaluated with `iex` to compute the factorial (i.e., `1*2*3*...*$n`). Next, we loop over `$k|%{...}` and each iteration we subtract the current value `$_` from `$n` (which we don't care about anymore) to formulate `$k_m` later. Additionally, we generate the range `1..$k_i` each iteration, which gets left on the pipeline. Those pipeline objects get array-concatenated with the second expression, range `1..$n` (which is `$k_m` at this point). All of that is finally `-join`ed together with `*` and evaluated with `iex`, similar to the numerator (this works because `x! * y! = 1*2*3*...*x * 1*2*3*...*y`, so we don't care about individual ordering). Finally, the `/` happens, the numerator is divided by the denominator, and output. Handles output correctly for larger numbers, since we're not explicitly casting any variables as any particular datatypes, so PowerShell will silently re-cast as different datatypes on the fly as needed. For the larger numbers, outputs via scientific notation to best preserve significant figures as the datatypes get re-cast. For example, `.\compute-the-multinomial-coefficient.ps1 55 @(28)` will output `3.82434530038022E+15`. I'm presuming this to be OK given *"Output format is similarly flexible"* is specified in the challenge and quintopia's comments *"If the final result can fit within the natively supported integer types, then the result must be accurate. If it cannot, there is no restriction on what may be output."* --- ### Alternatively Depending upon output formatting decisions, the following at **92 bytes** ``` param($n,$k)((1..$n-join'*'|iex)/(($k|%{$n-=$_;1..$_})+(1..$n)-join'*'|iex)).ToString('G17') ``` Which is the same as the above, just uses [explicit output formatting](https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx) with `.ToString('G17')` to achieve the desired number of digits. For `55 @(28)` this will output `3824345300380220.5` --- Edit1 -- Saved 17 bytes by getting rid of `$d` and just calculating it directly, and getting rid of the calculation for `$k_m` by stringing it along while we loop `$k` Edit2 -- Added alternate version with explicit formatting [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 bytes ``` ×/2!/+\⍛, ``` [Try it online!](https://tio.run/##LYw9CsJAEIX7PcVaa8j@aiysBNHKkFimCeSnCWphoYiVkEJYUUQsvIBdGm0s9SZzkThZbN689@abiZeFk2ziYpE76XqVzpM0qeF49X2KOgqgPElFufB69ffmipbbjsDcO3WGCzBHZCZTOOw/lYTyjCkMhqiz8SSsc0QyMI/BFi/BvFpg3k47@lQcygvrYLMjkuZUUGYnp5xwbo2iiijrBOEajcZKYug3oastIEVDaDDPP6TQSsIZY82CUc9FwUikfd8juqGE9wM "APL (Dyalog Extended) – Try It Online") Using the idea from [my APL answer on another challenge that involves multinomials](https://codegolf.stackexchange.com/a/196373/78410). A tacit function whose left argument is the list of k's, and right argument is n. The test cases check if it agrees with [Adam's solution](https://codegolf.stackexchange.com/a/153924/78410) with left and right arguments flipped. ### How it works ``` ×/2!/+\⍛, +\ ⍝ Cumulative sum of k's (up to m-1'th element) ⍛, ⍝ Append n (sum of k_1 to k_m) 2!/ ⍝ Binomial of consecutive pairs ×/ ⍝ Product ``` $$ \frac{(k\_1 + k\_2 + \cdots + k\_m)!}{k\_1! k\_2! \cdots k\_m!} = \frac{(k\_1 + k\_2)!}{k\_1! k\_2!} \times \frac{(k\_1 + k\_2 + \cdots + k\_m)!}{(k\_1 + k\_2)! k\_3! \cdots k\_m!} $$ $$ = \frac{(k\_1 + k\_2)!}{k\_1! k\_2!} \times \frac{(k\_1 + k\_2 + k\_3)!}{(k\_1 + k\_2)! k\_3!} \times \frac{(k\_1 + k\_2 + \cdots + k\_m)!}{(k\_1 + k\_2 + k\_3)! \cdots k\_m!} $$ $$ = \cdots = \binom{k\_1 + k\_2}{k\_1} \binom{k\_1 + k\_2 + k\_3}{k\_1 + k\_2} \cdots \binom{k\_1 + \cdots + k\_m}{k\_1 + \cdots + k\_{m-1}} $$ [Answer] # Mathematica, 26 bytes ``` #!/Times@@({#-+##2,##2}!)& ``` Example: ``` In[1]:= #!/Times@@({#-+##2,##2}!)&[95,65,4,4] Out[1]= 1934550571913396675776550070308250 ``` [Answer] # Python 3, ~~93~~ 91 Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) and [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman). ``` f=lambda x:0**x or x*f(x-1) def g(n,k): r=f(n) for i in k:r//=f(i) return r//f(n-sum(k)) ``` `n` as integer, `k` as iterable. Ungolfed: ``` import functools #cache @functools.lru_cache(maxsize=None) #cache results to speed up calculations def factorial(x): if x <= 1: return 1 else: return x * factorial(x-1) def multinomial(n, k): ret = factorial(n) for i in k: ret //= factorial(i) km = n - sum(k) return ret//factorial(km) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte charater set") Entirely based on the mathematical skill of [my colleague Marshall](http://www.dyalog.com/meet-team-dyalog.htm#Marshall). Anonymous infix function. Takes *k* as right argument and *n* as left argument. ``` {×/⍵!⍺-+\¯1↓0,⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qQIACkHQLetQ2wdhEwdDIwvx/GpBdfXi6/qPerYqPenfpasccWm/4qG2ygQ5QpPb/f2OFNAUjBQMuEG2oYMhlaAhmmCiYcJmAWUZchqZAhilQyBjIsQRxzEzBCoyNQCpMH/VugSoyATKNuQwNDAxAEgYKFvpAAsjlMgYbb85lClJlZAEA "APL (Dyalog Unicode) – Try It Online") `{`…`}` anonymous lambda; `⍺` is left argument (*n*) and `⍵` is right argument (*k*)  `0,⍵` prepend a zero to *k*  `¯1↓` drop the last item from that  `+\` cumulative sum of that  `⍺-` subtract that from *n*  `⍵!` (*k*) that  `×/` product of that [Answer] ## PARI/GP, 43 bytes Pretty straightforward; aside from formatting, the ungolfed version might well be identical. ``` m(n,v)=n!/prod(i=1,#v,v[i]!)/(n-vecsum(v))! ``` [Answer] # Matlab 48 bytes You need to set `format` to `long` in advance to get the higher precision. Then, it's quite straightforward: ``` @(n,k)factorial(n)/prod(factorial([k,n-sum(k)])) ans(95, [65,4,4]) ans = 1.934550571913395e+33 ``` [Answer] # Pyth, 10 bytes ``` /F.!MaQ-FQ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%2FF.!MaQ-FQ&input=[95%2C%2065%2C4%2C4]&debug=0) ### Explanation: ``` /F.!MaQ-FQ implicit: Q = input list -FQ reduce Q by subtraction aQ append the result to Q .!M compute the factorial for each number /F reduce by division ``` [Answer] # J, 16 bytes ``` [(%*/)&:!],(-+/) ``` ## Usage For larger values, a suffix of `x` is used to denote extended precision integers. ``` f =: [(%*/)&:!],(-+/) 11 f 1 4 4 34650 15x f 5 4 3 2 37837800 ``` ## Explanation ``` [(%*/)&:!],(-+/) Input: n on LHS, A on RHS +/ Reduce A using addition - Subtract that sum from n, this is the missing term ] Get A , Append the missing term to A to make A' [ Get n &:! Take the factorial of n and each value in A' */ Reduce using multiplication the factorials of A' % Divide n! by that product and return ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` Ƹ«!R.«÷ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cNuhHYdWKwbpHVp9ePv//9GGhjoKQGQCRLEA "05AB1E – Try It Online") Explanation: ``` Æ Subtract all the elements from the first ¸« Append to the original list ! Take the factorial of all the elements R.«÷ Reduce by integer division ``` I can't seem to find better ways of performing step 2 or step 4. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 17 bytes ``` ⊢∘!÷(×/∘!⊣,⊢-1⊥⊣) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qQIACkHQLetQ2wdhEwdDIwvx/GpD9qGvRo44Zioe3axyerg9iPeparAMU1DV81LUUyNb8/9847VHvCgUjBQMuCMtQwZDL0BDKNFEw4TKBso24DE3BTFOgsDGQawnhmpmClRkbQdSZPurdAldqAuQYcxkaGBiAuRqGBkABQwNNHQ0LMMNAk8sYaq05lylEj5EFAA "APL (Dyalog Unicode) – Try It Online") Infix tacit function (Thanks to @Adám for the 2 bytes it saves.) --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), 19 bytes ``` {(!⍺)÷×/!(⍺-+/⍵),⍵} ``` [Try it online!](https://tio.run/##JYw9CsJAEIX7OcWk28WEzOyPiRewDt4gIGsT0FYkrd2KjXgRRbDNTfYi6yQ2730z7/H601Dtz/1wPOR0e3Qdim536Xq3Dtm0TQ7CF1Wk@NXTZ3rWhRKsVnWKb12KjDnbgAYJxBgZmGd36MDNYIB9QC8PK7wRXvsltUZin@Lr33BCFpiIAiomuZh0qdoFSIOd5xvwUjXtDw "APL (Dyalog Unicode) – Try It Online") Infix Dfn. Both functions above compute the given formula. [Answer] # [Haskell](https://www.haskell.org/), ~~59~~ 58 bytes ``` f n=product[1..n] n#k=foldl((.f).div)(f n)k`div`f(n-sum k) ``` [Try it online!](https://tio.run/##fZTLThxHFIb38xQNZAHSGNW5Vp0FG28dxYsskSWsDAjEeLAMRPbTk6@AxJ4saHpEd9e5/Zeq68/3t5fb7dPT1bI7@/rtbvP418O5nJ7uPq12R7dnV3fbzfb4@PTq5HRz8/fJMVEntxc8Xlwd797dP35Zbk@evi8X99d3j9vN@8uL5cdytnx9fPjz4dvvu@W35eZq@X529mN5uL7cLYcfP5weLpfb@8vl8I@7h@Xjh4ODg8PV6svnmx1pm7vVauGyo3NdL@3Tr2XtvyVZL7K3lC9LIs9rzr2f6RntJcRnhO6tir5mx9F5rH1t/1u3Prjba4EiKmfYfgsp84gWXUrMKrNH78mX1pu1of/2N53I3vjbq@pNZs2yTGkmNnoM18j2cv2c29bPf/sj5eD@GcYT4Nv6zfvN3375UarZhqWI98yWPqzGSOnWuqYOUx1SkOfdvCy8lWQov2ZdUqFmGP@pQ4my1mJQFLordBBuJsO7eHSD06gsOnWHB48ho1eY0KAV9NZwo8UzXandaJ2aolA/qjRJ4JNDHwX6IEqgtFsI7xEjqhoqa5RQl2sGlHq5O2JyVxexRE5lMuaA3hHaGqnByJbNJXu1ygZExh08RWT1dKNsQU0CcmhTOHJXgzveu@dwmVPyAl6h3FBLCxD06jFxWPmoAWNQ3FLJK9PpsISkGLTw9GQ4avWwwQQ8tvlGvejUhj5QVm/VlDEZNyiDPOgTqk5DiG7wEs11KsLbhAYuIqWiN1WFacAJ0glyiSeGb50higkiUN3FvYY0eGqzuzEwKMojcxSkk1eTTmwyRW34BhI6KJu4wii7B887OFCccgqmoj9mmCDhaXSECyeUmkThgXRaUCwN60HwlHLMbiAgNGaDOfdAYeiBSHUr/DhmWp/eC@qDW32kJdOUY2UKOc1bTA1oDebK0U3wgLLTCcKIjkx9DsZJQB6ETcAYBbEm4cU@QQ9nK0/iMBps9MSoSImDoFjpjEbgmK6covKm81hJLGnAa0wcwhxJCpERTAZVwefpCsDYtH6bj20Aii/SsWYMtiS6ktL7RFotZU7gqgZGnKg6m2AdzWn6hMG5pRRrus29x36sjhPnsKbTasaOHmg4hy4clvgWabEKHJigIs6evv7lej0I5zne908UIZ9jTtrq6R8 "Haskell – Try It Online") Thanks to [BMO](https://codegolf.stackexchange.com/users/48198/bmo) for saving 1 byte! [Answer] # Clojure, 70 bytes ``` #(let[a apply](a /(map(fn[x](a *(map inc(range x))))(conj %(a - %))))) ``` Creates an anonymous function taking all of the arguments as a single list, with `n` first. 30 characters are "wasted" just defining the damn factorial function. Oh well. [Answer] # [Perl 6](https://perl6.org), ~~ 52 ~~ 50 bytes ``` ->\n,\k{[*](1..n)div[*] ([*] 1..$_ for |k,[-] n,|k)} ``` [Test it](https://tio.run/##fZTNblw3DIX38xR3EdR2ej2RSIoSbSRIF10UKNBN0Y1jFEE8LQw744F/0gZJnt35aAeeySYzd@wriSLPOTzSZnV96fd3N6vpgy/fHS/ef5x@end1tppe3h@@erOe31x8Onl@ul@Xy/XB2fkH3qf9/MPEs7@nf66up88X88nh6bSeP18cfLln/@vb1c3t9HK6PF@vbvYPlv9erzb7L/aO9l4cLN@/3RxNz5c3m8vz2/29o2nv4KSeLn/965ffjxeLRPEne48Xm8u36@nnx0RUneR4kaUeJw5fTa/P15u722n/2Xp@fXEwP1v9v1m9u12dTZ8W03R@c3i2Wm0uP05J5FvMcv32@vrqv3l6ip2/ZVlukOB48eX@txwdTTpPJzJP5XTxx93t48xisbNW56lu1/xprdbHRePZ2WveylOMPYTIdrnKdn9jsc02626A9sFTtikiwzzjdqrUUGuttF6jqoZ7b707M6UXLUN2IKg88PvBd5vWSs2koe61aNXR2zBpXh4/30PX@eG7A8oHz3dxDFKBMv/w@eFvJ/8IES9DvVbr7sVtaIzhtWvp4jJUZNRAQOtqoc1KVG/Cr2ivLqgzlP/kIUVoKW2QFMmjySBctQ7r1VpXZG3hQaVuKGFt1NGjaaVACRSOYUqJB8FculLaxaug/ogQZwNThoAk6IOoiqhdW2Xc2mgRhU5Li0pePhkQYmFm9JMneq3qdFRABg70HU1KYWsDsnqx6j1KeIEicAdvrXl0NyVtII1DckgRNDITRTvG3XxYTZQM4FtJN0RdGwx69JY8NGzEQDEkLi7sC5U0mSNSG5QwNwccuXrTAQJeS47I1zq5kQ@W0UsUASZwG2loD/1pIkZBhC7o0opJdoRRUoMXkTVaLyKC0pCrtK7SrmqO50sHRICgNbpu1SxGLehUsroCGBZhzX0EorMvUk5skk0t@AYROixLNUFRDhCuN3jQcdIJnIL6mCFJotPoNK4ZoeQkCg@4UYJkrlgPgbOVI6vBgNCWBRL3oMPIg5BiGvhx5Lae3mvkh7fYcHXQhGFlEhnFS8seUBrO4aNrxQPCYScIIxpt6gmMy4B9CJaEMQrNSsGDc0I/jMOcwmE01OiOUWklDkJioTI9gke6MpvKSPJmcSyp0CsgbhUczhYiWwMZUjWm0xWQ0bR@ydcyIMVM7VizDY4kfWVL78k0itdEYCIKR5wokkWwjnia3lEwj5RgTdM8e5zH6Dgxwaqk1ZQTPehhgg4c5viW1mIVNNBKF3F2@nrns70LH@7zvnOlVBJw09VtTMu7TcbOjZxNAxjG5bRK@Qo "Perl 6 – Try It Online") ``` ->\n,\k{[*](1..n)/[*] ([*] 1..$_ for |k,[-] n,|k)} ``` [Test it](https://tio.run/##fZTPT1w3EMfv@1e8Q1QgfSz2zHjsASVKDz1UqtRL1QtBVRS2FYIsKyBpoyR/O/kMROzmkt238GyPZ@b7w96sbq78/v3tavrgy7cni3cfp5/eXp@vphf3hy9fr@fXl59On5/t1@VyfXDE27Sffxg@@3v65/pm@nw5nx6eTev58@XBl3t2v7pb3d5NL6ari/Xqdv9g@e/NarN/tHe8d3SwfPdmczw9X95uri7u9veOp72D03q2/PWvX34/WSyyhz/Ze7LYXL1ZTz8/Jjq/@DDJySJLPU4cvpxeXaw37@@m/Wfr@dXlwfxs9f9m9fZudT59WkzTxe3h@Wq1ufo4JYxvMcv1m5ub6//m6Sl2/pZluYGAk8WX@99ydDzpPJ3KPJWzxR/v7x5nFoudtTpPdbvmT2u1Pi4az85e81aeYuwhRLbLVbb7G4tttll3A7QPnrJNERnmGbdTpYZaa6X1GlU13Hvr3ZkpvWgZstOCygO@H3y3aa3UTBrqXotWHb0Nk@bl8fN96zo/fHea8sHzXRyDZKDMP3x@@NvJP0LEy1Cv1bp7cRsaY3jtWrq4DBUZNSDQulposxLVm/Ar2qsL7AzlP3lIEVpKGySF8mgyCFetw3q11hVaW3hQqRtMWBt19GhaKVAChmOYUuKBMJeulHbxKrA/IsTZwJRBIAn6IKpCatdWGbc2WkRBaWlRycsnA0IszAw9eaLXqo6iQmf0Ab@jSSlsbbSsXqx6jxJegEi7g7fWPLqbkjagxgE5pAgcmYnCHeNuPqxmlwzAW0k3RF0bCHr0ljg0bMSAMSguLuwLlTSZQ1IblDA3pzly9aaDDngtOSJf6@SGPlBGL1GENmm3kQZ50KeJGAUhusBLKyapCKOEBi4ia7ReRASmAVeRriJXNcfzpdNE0EFrqG7VLEYt8FSyutIwKMKa@whIZ18kndgkRS34BhI6KEs1gVEOEK43cKA46QRMQX3MkCDhaXSEa0YoOYnCA26UIJkr1oPglHJkNRAQ2rJA9j1QGHogUkwDP47c1tN7jfzgFhuuTjdhWJlERvHSUgNKgzl8dK14QDjsBGFEQ6aejXEZsA/CEjBGQawkPDgn6GEc5iQOo8FGd4yKlDgIioXKaASOdGWKykjyZnEsqcArdNwqfThbiGyNzqCqMZ2uAIym9Uu@lgEoZmrHmm1wJNGVLb0n0iheswMTUTDiRJEsgnXE0/QOg3mkBGua5tnjPEbHidmsSlpNOdEDDbPpwGGOb5EWq8CBVlTE2enrnc/2Lny4z/vOlVJJwE1XtzEt7zYZOzdyikZjGJfTKuUr "Perl 6 – Try It Online") (result is a Rational with denominator of 1) ## Expanded: ``` -> # pointy block lambda \n, \k { [*]( 1 .. n ) # factorial of 「n」 / # divide (produces Rational) [*] # reduce the following using &infix:«*» ( [*] 1..$_ # the factorial of for # each of the following |k, # the values of 「k」 (slipped into list) [-] n,|k # 「n」 minus the values in 「k」 ) } ``` ]
[Question] [ In this challenge you will take a an ascii art image of a highway like so ``` | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ``` And you need to put rain across its lanes like so ``` |\\\|\\\| |\\|\\| |\\\\\\\| |\\\\\| |\\\|\\\| |\\|\\| |\\\\\\\| |\\\\\| |\\\|\\\| |\\|\\| |\\\\\\\| |\\\\\| |\\\|\\\| |\\|\\| ``` --- A highway will be defined as an ascii art string containing only the characters `|`, and newlines. All rows of the image will have exactly the same number of characters. Every column will be one of the following * **Empty space**, all spaces * **A line**, all `|` * **A lane divider**, alternating `|` and space Furthermore there will always be a line before and after every lane divider. So ``` | | | | | | | | | | | | | ``` would be valid but ``` | | | | | | | | | ``` would not be since there is no line after the last lane divider. And a lane divider will never be exactly next to a line. So ``` || | | | || | ``` Is invalid but ``` | || || | | || | || || | | || | || || ``` is fine. Additionally a highway must be at least two rows high and one column wide. ## Task Your job is to write a program or function that takes a valid highway (as a string or list of lines) as input and outputs the highway with rain across its lanes. To put rain across a highway's lanes you must replace all space characters that appear between two consecutive lines, where those lines have at least one lane divider between them, with `\`s. And leave all other characters the same. So in the following diagram: ``` A B C 1 2 D | | | | | | | | | | | | | | | | | | | | ``` No rain should be put between `A` and `B` or `B` and `C` since there are no lane dividers between them, but rain should be put between `C` and `D` since lane dividers `1` and `2` are between them. You may output an additional trailing newline, or add/remove trailing spaces from all lines equally if you wish. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better. ## Test cases Simple case ``` | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ``` --- ``` |\\\|\\\| |\\|\\| |\\\\\\\| |\\\\\| |\\\|\\\| |\\|\\| |\\\\\\\| |\\\\\| |\\\|\\\| |\\|\\| |\\\\\\\| |\\\\\| |\\\|\\\| |\\|\\| ``` --- Extra line ``` | | | | | | | | | | | | | ``` --- ``` |\\\\|\\\|\| | |\\\\\\\\\\| | |\\\\|\\\|\| | ``` --- Unsynced lane dividers ``` | | | | | | | | | | | | | | | ``` --- ``` |\\\\|\\\\\\| |\\\\\\\\|\\| |\\\\|\\\\\\| |\\\\\\\\|\\| |\\\\|\\\\\\| ``` --- Empty road ``` | | | | | | | | | | | | | | | | | | | | ``` --- ``` | | |\\\\\\\|\\| | | |\\\|\\\\\\| | | |\\\\\\\|\\| | | |\\\|\\\\\\| ``` --- False roads (suggested by [Arnauld](https://codegolf.stackexchange.com/u/58563)) ``` | | | | | | | | | | | | | | | | | | ``` --- ``` | |\|\| | | |\\\| | | |\|\| | | |\\\| | ``` --- Hard lane divider ``` | | | | | | | | | | | | | | | | ``` --- ``` |\\|\\|\\|\\| |\\\\\|\\\\\| |\\|\\|\\|\\| |\\\\\|\\\\\| ``` --- Adjacent lane dividers ``` | || || | | || | || || | | || | || || ``` --- ``` |\\\||\\|| |\\\\\|\|| |\\\||\\|| |\\\\\|\|| |\\\||\\|| ``` --- No lanes ``` | | | | | | | | | | | | ``` --- ``` | | | | | | | | | | | | ``` --- One line ``` | | | ``` --- ``` | | | ``` --- No lines ``` ``` --- ``` ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ZḢ”\E?€ṣ”|»Ṁ$€K» ``` A monadic Link accepting a list of lines, each of which is a list of characters, which yields another, similar list. **[Try it online!](https://tio.run/##y0rNyan8/z/q4Y5FjxrmxrjaP2pa83DnYiC75tDuhzsbVIB870O7/z/cveVwe@T//zUKChCkUAOia7gQAiASRYBYFQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z/q4Y5FjxrmxrjaP2pa83DnYiC75tDuhzsbVIB870O7/x@dDBadc2ib3qFtQNmHu7ccbo881gWUzkIS/v9foUZBAYahiAvMV4CLKcDFaKxOj6tGAS4KJrlgOmHCmCr0uKACMFtquBBsmANIVwFxSw2SwhqY9WgSNSSohJmK7L0aFL/hkgPrRAqrGgWEc2vwykHtBMkgpKBMvKJI0YFsMB4@OC7gIYzGgEjiJAA "Jelly – Try It Online"). ### How? ``` ZḢ”\E?€ṣ”|»Ṁ$€K» - Link: list of lists of characters (i.e. rows of text) Z - transpose - i.e. columns (each being: all spaces; all pipes; or a mix) € - for each (column): ? - if... E - ...condition: all equal? - i.e. if not dashed Ḣ - ...then: head - i.e. the unique character ”\ - ...else: literal '\' character ”| - literal '|' character ṣ - split at - i.e. highway chunks now contain spaces and '\' characters € - for each (chunk): $ - last two links as a monad: Ṁ - maximum - N.B. '\' > ' ' » - maximum (vectorises across the chunk) - - i.e highway chunks become all '\', others remain as is K - join with space characters » - maximum (vectorises across the rows) - - N.B. '|' > ' ' so the solid lines are not replaced by spaces; and - '|' > '\' so the dashed lines are not replaced with rain. ``` [Answer] # JavaScript (ES6), ~~118 ... 105~~ 103 bytes I/O format: matrix of characters. ``` a=>a.map(r=>r.map((c,i)=>(a[k=0][i]+a[1][i]<'||'?r:r=a.some(r=>r[a[k^=1].indexOf(c,i+1)]<c))/c?'\\':c)) ``` [Try it online!](https://tio.run/##vVPLboMwELzzFatcbIvULdcoJp/QDzCuZBGoSBM7MlXVw/47DQRoeUlEssrFq50Z73hsTvpLl6krrp9Pxh6zKheVFrHmF32lTsSuKWi6LZiIqZYf4kXJQoVaRvW6J4jk4HZOaF7aS9ZI5I32JiLFC3PMvl/zWh1GTO1Txp7TA0kSsruVVWpNac8ZP9t3mlMZAEjO@QYQ7h9CW@JGbQco9ijOoP@nDRS7BwUiBsdPtjCUEMbaKjGEQQjNGgQLx0XoN8bRzM5QRxhDA5UPL@2eXRKD8/fdaXCeVL7SxD9TcRrbiLIEr1b7sz3/AnDh@lfwPVmb/V0Qfm9v1F/D95ZaPWZuzqT5OPMBj9UP "JavaScript (Node.js) – Try It Online") ### How? To detect lines, we test whether the first and the second row both contain a `|` at a given position \$i\$: ``` a[0][i] + a[1][i] < '||' // true if it's not a line ``` When a line is detected: * We know for sure that the character \$c\$ at the same position in the current row is a `|`, because lines are guaranteed to go all the way from top to bottom. So we can now use \$c\$ instead of `'|'`. * We update the flag \$r\$ which is set to \$1\$ when we're located on a road with a lane divider. We update \$r\$ by testing if, for some \$n\$, the next `|` (starting from \$i+1\$) in either the first or the second row (depending on the parity of \$n\$) is facing a space in the \$n\$-th row: ``` r = a.some(r => r[a[k ^= 1].indexOf(c, i + 1)] < c // starting with k = 0 ``` Finally, we must replace \$c\$ with a `\` if \$c\$ is a space and \$r=1\$. Because a space is the only road character that is coerced to \$0\$, we can simply do: ``` r / c ``` The only truthy value is given by `1/' '` (\$+\infty\$). Something like `1/'|'` would result in `NaN`, and so does `0/' '` (\$0/0\$). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes ``` ₆F€SøíJ„ \S„\|N_èì`: ``` [Try it online!](https://tio.run/##yy9OTMpM/V/z/1FTm9ujpjXBh3ccXuv1qGGeQkwwkIyp8Ys/vOLwmgSr/7WHdv9XqFFQgGEo4gLzFeBiCnAx2qoDAA "05AB1E – Try It Online") ``` ₆F # repeat the following 36 times: €SøíJ # rotate 90 degrees „ \S # character array [' ', '\'] „\| # string "\|" N # 0-based iteration count _ # logical not: 0 => 1, anything else => 0 è # use that to index in the string "\|" ì # prepend (first loop: ["| ", "|\"], then ["\ ", "\\"]) `: # recursive replace ("| " => "|\" or "\ " => "\\") ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~52~~ 51 bytes ``` / /;s/(\S(.{@{-}})|\\)\K | (?=(?2)\S|\\)/\\/s&&redo ``` Replace space character with a backslash if there is a non-space character above or below it or a backslash on the right or the left of it. And redo while no more space can be replaced. One byte saved diverting recursive regex thanks to Grimmy. [Try it online!](https://tio.run/##K0gtyjH9/1@fS9@6WF8jJlhDr9qhWre2VrMmJkYzxluhRkHD3lbD3kgzJhgkoh8To1@splaUmpL//z9QUgGGoYgLzFeAiynAxWisjqtGAS4IJrlgGmHCmCq4oHyYHTVcCDbMetJVcCG5DqEMWRCulHiVXDUovq1RQFhZg1cOYhxIAiEDZeIV5ULyVA1K6OHgcykgBREag@tffkFJZn5e8X9dA4MCAA "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~198~~ ~~196~~ ~~186~~ 159 bytes ``` def g(x): for _ in x[0]:x=[''.join([q,'\\'][q<'!'and(x[a-1][b]>'['or'\\'in r[b-1]+r[-~b%len(r)])]for(b,q)in enumerate(x[a]))for(a,r)in enumerate(x)] return x ``` [Try it online!](https://tio.run/##hZDRCoJQDIbvfYp1ETsji6I7qV5kHuJIRzPsqMvAQHp1O2IFedNgbHz/9jNWPZpz6bZ9f7IpZKqlKIC0FDhC7qDltY7aPSOuLmXuFNchxjFqrnc4Q@NOqmWz3GhO9AEZSxlUvyeceLoQXj6TeWGdEtKkva1Kwpr8gHX3qxXT2MFAEw2SCWUikQ5AbHMXf0lv9ogIHcA3YawdBD@4G/kU/5v27kEluWuUoXfzqRi79wMyZVa3qshHRj76Fw "Python 3 – Try It Online") ## Explanation This implements a simple automaton. At every step a space is replaced with an `\` iff one of the following is true * There is a `|` or `\` above it (indexing wraps around) * There is `\` to the left or right of it. This means that rain starts at the gaps in the lane dividers and spreads until it hits `|`s. [Answer] # [Python 2](https://docs.python.org/2/), ~~112~~ ~~109~~ 107 bytes ``` lambda r:reduce(lambda r,c:[''.join(l[::-1]).replace(c+' ',c+'\\')for l in zip(*r)],r'|\|\\\\:'*len(`r`),r) ``` [Try it online!](https://tio.run/##jY7BCsIwEETv/YrBS5IaC3qM9EuaQmubYiSmYakHJf8ea4sexIMLs8vum4UJ9@k8@kMaSp1cez31LUiR6W@d4e9ddqpirLiM1nNXKbXb16IgE1w7m7otA5Nz15qJYSQ4WI@HDTwnUUtiUUc9l2K5M5431AhJIhFKVBk2iMBHWGfERn6juLJf6M@v@pgt8aw3r4QDJ6EyBLJ@Wo7pCQ "Python 2 – Try It Online") ## [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 109 bytes *Thanks to Kevin Cruijssen for this version!* ``` lambda r:[(r:=[''.join(l[::-1]).replace(c+' ',c+'\\')for l in zip(*r)])for c in r'|\|\\\\:'*len(repr(r))][-1] ``` [Try it online!](https://tio.run/##jY7BCsIwEETv/Yqll01qLYgXifRLkhxqTTESk7D0ouTfY9qCB/Hgwu7CPGaY@JxvwR9PkfLUq@yGx@U6AAnJSPQSsbsH65mTQuwPmndkohtGw8YdArblKoV8CgQOrIeXjawhrldlXBTCpJIqI7BxxrPiJ0aca1niMkEPsoIaEsBnYfsJ6vYbpY39Qn@69Lla21pvlnpT6SIqiGT9zBaR5zc "Python 3.8 (pre-release) – Try It Online") Port of [my 05AB1E answer](https://codegolf.stackexchange.com/a/200841/6484). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` n⁶Zṣ1€oFẸḤƊ$€j1€W$Zị“|\ ” ``` [Try it online!](https://tio.run/##y0rNyan8/z/vUeO2qIc7Fxs@alqT7/Zw146HO5Yc61IB8rJAQuEqUQ93dz9qmFMTo/CoYe7/h7u3HG6P/P@/RgEEIQSMCWFzQUSgEgpwqRqwFHV1AQA "Jelly – Try It Online") `oFẸḤƊ$€` is "borrowed" from @Riolku lol [go upvote him](https://codegolf.stackexchange.com/a/200852/68942) # Explanation ``` n⁶Zṣ1€oFẸḤƊ$€j1€W$Zị“|\ ” Main Link n⁶ vectorized inequality to space; "|" becomes 1, " " becomes 0 Z transpose into a list of columns ṣ1€ split by [1, 1, ..., 1] (length of original; number of rows) € for each block (space between two lines) o vectorized OR with FẸḤ (flatten) (any) (double): 0 if there are only spaces; 2 if there are lane dividers j join on 1€W$ [1, 1, ..., 1] wrapped ([[1, 1, ..., 1]]) Z zip back into original orientation ị“|\ ” index into "|\ "; 0s are spaces, 1s are lines, and 2s are the replaced spaces which become \ ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` Zn⁶ṣoFẸḤƊ$€jW} ç1€ị“|\ ”Z ``` [Try it online!](https://tio.run/##y0rNyan8/z8q71Hjtoc7F@e7Pdy14@GOJce6VB41rckKr@U6vNwQyHq4u/tRw5yaGIVHDXOj/j/cveVwe@T//zUKCgo1YAikuSA8BRQeVjkA "Jelly – Try It Online") I/O is a list of strings # Explanation ``` Zn⁶ṣoFẸḤƊ$€jW} Primary Link (dyad); takes the input on the left and [1, 1, ..., 1] on the right Z zip the input into a list of columns n⁶ vectorized inequality to space; "|" becomes 1, " " becomes 0 ṣ split (on [1, 1, ..., 1]) € for each block (between lines) o vectorized or with FẸḤ (flatten) (any) (double): 0 if there are only spaces; 2 if there are lane dividers jW} join on ([1, 1, ..., 1] wrapped) (2,2-chain using }) ç1€ị“|\ ”Z Main Link ç call the primary link with (default left argument), 1€ [1, 1, ..., 1] ị“|\ ” index into "|\ " Z zip back into original orientation ``` [Answer] # [Haskell](https://www.haskell.org/), 151 bytes ``` a#b=a!!mod b(length a) z=zip[0..] s%_=[[(['\\'|b<'!'&&(s#(x-1)#y>'['||elem '\\'[a#(y-1),a#(y+1)])]++[b])!!0|(y,b)<-z a]|(x,a)<-z s] g x=foldl(%)x(x!!0) ``` [Try it online!](https://tio.run/##hYoxb8MgGER3fsWHnASQ7SjZTZau7dSRoAhk6qBibBUqYYv/7jqNFCldOpzu9O5dVfg0zi2LKjRXGPdDC5o647t4BcXQzGc7isN@L1HYXrgQVJDzmWTdEEx2OxoKmuojK6YTESRn40wPN0Gogk7rUd26PDLJZFkKLRnGh0ynSrOmnkHJTFOlfneQqIPEPwbXOrpliaZVZUuvrOftgAAsNDU4602AZnOCzsSXwUfjY1jPXo1vFxi/43v8evWwgQ7sAhngEbh3BvSE853/xf/ZPw "Haskell – Try It Online") ## Explanation This implements the same algorithm as [my python answer](https://codegolf.stackexchange.com/a/200842). It implements a simple automaton. At every step a space is replaced with an `\` iff at least one of the following is true * There is a `|` or `\` above it (indexing wraps around) * There is `\` to the left or right of it. This means that rain starts at the gaps in the lane dividers and spreads until it hits `|`s. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 79 bytes ``` +m`(?<=(.)+) ((?<=(?(1).)^(?<-1>.)+\S.*¶.+|\\ )|(?=\\|.*¶(?<-1>.)+(?(1)$)\S)) \ ``` [Try it online!](https://tio.run/##K0otycxL/P9fOzdBw97GVkNPU1tTQQPMtNcw1NTTjAOydQ3tgOIxwXpah7bpadfExCho1mjY28bE1IBE4ArAOlQ0Y4I1Nbli/v9XqFFQgGEo4gLzFeBiCnAx2qoDAA "Retina 0.8.2 – Try It Online") Same flood fill approach that @WheatWizard uses in his answers but using .NET balancing groups to detect vertical matches. Would save two bytes if the wind was blowing the other direction. Explanation: ``` +m` ``` Repeatedly replace and turn on line detection. ``` (?<=(.)+) ``` Replace a space but count the number of preceding characters on that line. ``` ((?<=...|...)|(?=...|...))) \ ``` Replace with a backslash if one of the four conditions is true. The four conditions are: ``` (?(1).)^(?<-1>.)+\S.*¶.+ ``` This space is below rain or a lane divider. The `(?(1).)` can only succeed if the characters are in the same column. ``` \\ ``` This space is to the right of existing rain. ``` \\ ``` This space is to the left of existing rain. ``` .*¶(?<-1>.)+(?(1)$)\S ``` This space is above rain or a lane divider. The `(?(1)$)` can only succeed if the characters are in the same column. [Answer] # [Ruby](https://www.ruby-lang.org/), 144 bytes ``` ->s{s.map{|l|((r=s[0]).size.times.map{|i|r[i]!=s[1][i]?[r.rindex(?|,i-1),r.index(?|,i+1)]:p}-[p]).map{|a,b|a.upto(b){|i|l[i]=?\\if l[i]<?!}};l}} ``` [Try it online!](https://tio.run/##xVLLboMwELzzFZv0AipYIe@0TfkQgipoQLJEKAIitY35dmoextgmSqoeigCtZ2dmd63NzsFXFcEeKus1v@To5KcXEhNdz/a5O/MMlOPvEBX4FHY5TDIXexOatT0aOG6GMpwcw0/dISa2bMPMED8/2ob3lJaWm1KrRu@bAfHROS0@9MCo7WLqsncOBxxBHb44k7J8jsuy0oowL95s2purAX2mQOi/@7p3ag5S0KdATv2rytPaUeZ8FAI9kQwNmDXLCrjIZ66LwQV1DXUuvK0ekib5O591sRRnIwMLIs0h5Udzd@pY9ZVcfeRaydid3mSyCmuhgroUBPjFDMHbTFZhI81QaxSRiPyKw@psR7ZwpMN7YGa5E1ZQXqVrZ6a2Z6J8SJViKjmGEdQyHSfpuTAhMhoGjXNooP7I8Qi9@3HcKjhdC5Nj24Le9tGYPQBH5gqyUJClgqwUZK0gGwXZKshOQexZDVU/ "Ruby – Try It Online") I thought I would try a different approach to the automaton. This finds lane dividers by checking for which indices the first two rows differ. It then goes through each of these indices and finds the previous and next line. It then fills in all space characters with the rain character. This takes a list of strings for each row of the road. ### Golfy Tricks: * Using `l[i]<?!` instead of `l[i]==" "`. This checks to see whether the character comes before `!` (which [only space does](http://www.asciitable.com/) of the allowed charactersin this challenge). * `-[p]` to remove all `nil` elements in an array. * `map` instead of `each`. * `size.times` instead of `chars.each_index` * Using `map` with a condition (where failures result in `nil` and `nil`s are then removed), rather than a `select` followed by a `map`. ### Explanation: ``` ->s{s.map{|l|((r=s[0]).size.times.map{|i|r[i]!=s[1][i]?[r.rindex(?|,i-1),r.index(?|,i+1)]:p}-[p]).map{|a,b|a.upto(b){|i|l[i]=?\\if l[i]<?!}};l}} # Go through each character in the first row (saving the row in a variable for later use) ((r=s[0]).size.times.map # Check if it's a line divider r[i]!=s[1][i] # If it is, save the nearest road lines [r.rindex(?|,i-1),r.index(?|,i+1)] # If it isn't save nil p # Remove all the nils -[p] # So we have all the indices of the lanes ((r=s[0]).size.times.map{|i|r[i]!=s[1][i]?[r.rindex(?|,i-1),r.index(?|,i+1)]:p}-[p]) # For each row in the road ->s{s.map{|l| # Go through each index within the lane .map{|a,b|a.upto(b) # And set any empty charaters to rain l[i]=?\\if l[i]<?! # And then return the new rainy row l ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + Core utilities, ~~154~~ ~~152~~ ~~145~~ ~~142~~ ~~136~~ 119 bytes ``` IFS=\ read t d=`sed s/././g<<<$t` sed -E ":l;s/([|%]$d|%) /\1%/;tl;s/ ($d[|%]|%)/%\1/;tl;"'y/%@/\\\ /'<<<$t@`tr ' ' @` ``` [Try it online!](https://tio.run/##S0oszvj/39Mt2DaGi6soNTFFoYQrxTahODVFoVhfDwjTbWxsVEoSuEAiuq4KSlY51sX6GtE1qrEqKTWqmgr6MYaq@tYlIFEFDZUUkARQWF81xhAsqqReqa/qoB8TE8Olrw42yiGhpEhBnUtdwSHh/3@FGgUFGIYiLjBfAS6mABejrToA "Bash – Try It Online") Input on stdin, and output on stdout. (The script has spurious output to stderr in one case, but that's considered acceptable.) Here are the outputs for the test cases: ``` highway-1-simple |\\\|\\\| |\\|\\| |\\\\\\\| |\\\\\| |\\\|\\\| |\\|\\| |\\\\\\\| |\\\\\| |\\\|\\\| |\\|\\| |\\\\\\\| |\\\\\| |\\\|\\\| |\\|\\| highway-2-extraline |\\\\|\\\|\| | |\\\\\\\\\\| | |\\\\|\\\|\| | highway-3-unsyncedlanedividers |\\\\|\\\\\\| |\\\\\\\\|\\| |\\\\|\\\\\\| |\\\\\\\\|\\| |\\\\|\\\\\\| highway-4-emptyroad | | |\\\\\\\|\\| | | |\\\|\\\\\\| | | |\\\\\\\|\\| | | |\\\|\\\\\\| highway-5-falseroads | |\|\| | | |\\\| | | |\|\| | | |\\\| | highway-6-hardlanedivider |\\|\\|\\|\\| |\\\\\|\\\\\| |\\|\\|\\|\\| |\\\\\|\\\\\| highway-7-adjacentlanedividers |\\\||\\|| |\\\\\|\|| |\\\||\\|| |\\\\\|\|| |\\\||\\|| highway-8-nolanes | | | | | | | | | | | | highway-9-oneline | | | highway-A-nolines ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~21~~ ~~20~~ 15 bytes *-5 bytes thanks to [Zgarb](https://codegolf.stackexchange.com/users/32014)!* ``` Tṁ?mσ' '\IV≠ġ▼T ``` [Try it online!](https://tio.run/##yygtzv5/aNujpsZD2/6HPNzZaJ97vlldQT3GM@xR54IjCx9N2xPy//9/JYUaBQUYhiIuMF8BLqYAF6OtOiUA////Sgo1CgowDEVcYL4CXEwBLkZbdUoA "Husk – Try It Online") Takes input as a list of rows. Works by transposing rows and columns, splitting the columns into groups based on whether they have any spaces, adding rain to the column groups with lane divisions, recombining the column groups, and transposing back. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` WS⊞υ⪫⪪ι ψP⪫υ¶F⊟υ¿⊖№KD²↓|KK«¤\↓¤\↗ ``` [Try it online!](https://tio.run/##tY09j8IwDIZn@iusTI5UFkYYrzrpkJAqEFsX1DPUupBEIQEh4LcHt3xMrCfZg18/ftx2m9C6jcn51LEhwB/rU1zFwHaHWkOdDh2mEuaOLa684YhcggKlSzhrPSsWyUT2gkccGGFVY1W/2roAWDuPSUS8BayoDbQnG@kXv1ySk5ror@JAbWRncVLCtHInK251FYW8H8Q9hb2RzIHgUoy@2RhUTaMkGy3ckfBxN/u4Wvsl77oowS1nuAK8@lnFMMM7g3f2z1weH80d "Charcoal – Try It Online") Link is to verbose version of code. Expects rectangular input with newline terminator. Explanation: ``` WS⊞υ⪫⪪ι ψ ``` Read the input but change spaces into nulls. ``` P⪫υ¶ ``` Copy the input to the output; nulls turn into fillable spaces. ``` F⊟υ ``` Loop over the width of the input. ``` ¿⊖№KD²↓| ``` Is this a lane divider? It isn't if it doesn't alternate between `|`s and empty cells. ``` KK ``` If it's not a divider then print the current character thus moving the cursor one step right. Simply moving right doesn't help because this needs to be a two-character Move command to avoid confusion with printing a lambda in a rightwards direction, and negating the condition doesn't help because when there are no lanes then Charcoal prints nulls instead of spaces for some inexplicable reason. ``` «¤\↓¤\↗ ``` Fill the area with rain. Both the current cell and the cell below need to be checked as we don't know which one is empty. The cursor is then moved to the right of its original position. ]
[Question] [ # Introduction The [**\$n\$-ellipse**](https://en.wikipedia.org/wiki/N-ellipse) is a generalization of the ellipse with possibly more than two foci. Specifically, given \$n\$ points on the plane, called foci, the \$n\$-ellipse is the set of points of the plane whose sum of distances to the \$n\$ foci is equal to a constant \$t\$. This challenge is about plotting the \$n\$-ellipse together with its **interior**; that is, the set of points whose sum of distances to the \$n\$ foci is **less than or equal to** equal to \$t\$. Note that the resulting set is always convex. To simplify, only points with **integer coordinates** need to be considered. # The challenge **Input**: * Number of points \$n\$: positive integer; * List of \$n\$ foci (possibly repeated) with integer coordinates, \$(x\_1, y\_1)\$, ..., \$(x\_n, y\_n)\$; * Threshold \$t\$: positive integer. **Output**: An **image** representing all points \$P\$ with integer coordinates such the sum of Euclidean distances from \$P\$ to the \$n\$ foci is less than or equal to \$t\$. Each pixel in the image should correspond to a point with integer coordinates; that is, **pixel size** is \$1 \times 1\$. Alternatively, you can use a **finer resolution** (smaller pixels), or vector graphics. The image should consistently use **two different colours** for points satisfying the condition ("active" pixels) or not satisfying it ("inactive"). # Additional rules * Graphical output is required, in [any format](https://codegolf.meta.stackexchange.com/questions/9093/default-acceptable-image-i-o-methods-for-image-related-challenges). (ASCII art is not allowed because of size limitations and aspect ratio). * Both axes should have the **same scale**. The \$x\$ axis should be horizontal, and can consistently increase left to right or right to left. Similarly, the \$y\$ axis should be vertical and can consistently increase upwards or downwards. * Axis labels, auxiliary grid lines and similar elements are allowed. * The output image can have an arbitrarily large "**frame**" of inactive pixels around the set of active pixels. * The set of active points is guaranteed to be **non-empty**. * Input format is [flexible as usual](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). A [program or a function can be provided](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet). [Standard loopholes are forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). * The code should work in theory for inputs containing arbitrarily large numbers. In practice, it is acceptable if the program is limited by time, memory or data-type restrictions. * Shortest code in bytes wins. # Test cases Input is shown as a list of \$n\$ foci defined as coordinate pairs, followed by \$t\$, and an optional comment. In the output images, \$x\$ axis increases left to right, \$y\$ axis increases upwards. ``` (5,8), 100 % A circle ``` [![enter image description here](https://i.stack.imgur.com/1vjPKm.png)](https://i.stack.imgur.com/1vjPKm.png) ``` (0,0), (70, 150), 220 % An ellipse ``` [![enter image description here](https://i.stack.imgur.com/kPGtYm.png)](https://i.stack.imgur.com/kPGtYm.png) ``` (-100, 0), (100, 0), (100, 0), 480 % Repeated point ``` [![enter image description here](https://i.stack.imgur.com/Q7ZfMm.png)](https://i.stack.imgur.com/Q7ZfMm.png) ``` (-90, -90), (-90, 90), (90, -90), (90, 90), (90, -90), 670 % Repeated; arbitrary order ``` [![enter image description here](https://i.stack.imgur.com/NXXxWm.png)](https://i.stack.imgur.com/NXXxWm.png) ``` (200, 600), (320, -60), (-350, 220), (-410, 130), (40, -140), 2100 ``` [![enter image description here](https://i.stack.imgur.com/RIhwKm.png)](https://i.stack.imgur.com/RIhwKm.png) ``` (-250, -250), (-250, 250), (250, -250), 1000 ``` [![enter image description here](https://i.stack.imgur.com/FaWPbm.png)](https://i.stack.imgur.com/FaWPbm.png) ``` (-250, -250), (-250, 250), (250, -250), 1200 ``` [![enter image description here](https://i.stack.imgur.com/YleNMm.png)](https://i.stack.imgur.com/YleNMm.png) ``` (-390, 0), (-130, 120), (130, -120), (390, 0), 1180 % Finally, a pair of lips? ``` [![enter image description here](https://i.stack.imgur.com/2RZApm.png)](https://i.stack.imgur.com/2RZApm.png) [Answer] # [Python 3](https://docs.python.org/3/) + numpy + pylab, ~~168~~ ~~163~~ 156 bytes ``` import numpy,pylab f,t=eval(input()) s=max(map(abs,sum(f,())))+t k=numpy.r_[-s:s+1] pylab.imsave('a.png',sum(((k-x)**2+(k[:,None]-y)**2)**.5for x,y in f)>t) ``` Outputs to a file called `a.png`, the y-axis increases downwards. **Sample outputs** (click for full-res versions) `[(5, 8)], 100`: [![enter image description here](https://i.stack.imgur.com/ZURSXm.png)](https://i.stack.imgur.com/ZURSX.png) `[(0, 0), (70, 150)], 220`: [![enter image description here](https://i.stack.imgur.com/l41bBm.png)](https://i.stack.imgur.com/l41bB.png) `[(-90, -90), (-90, 90), (90, -90), (90, 90), (90, -90)], 670`: [![enter image description here](https://i.stack.imgur.com/vMXXRm.png)](https://i.stack.imgur.com/vMXXR.png) `[(-390, 0), (-130, 120), (130, -120), (390, 0)], 1180`: [![enter image description here](https://i.stack.imgur.com/11VLQm.png)](https://i.stack.imgur.com/11VLQ.png) # [Python 2](https://docs.python.org/2/), 152 bytes ``` f,t=input() s=max(map(abs,sum(f,())))+t w=s*2+1 k=range(-s,s+1) print'P1',w,w for y in k: for x in k:print+(sum(((a-x)**2+(b-y)**2)**.5for a,b in f)>t) ``` [Try it online!](https://tio.run/##JYxBCoMwFET3OUV2/m@@xQhCEdIzdF@6iNC0IsaQRNTTp0k7MDAPHuPO@Fltl5KhqCbrtgjIglr0AYt2oMdAYVvAEGCOiGxXoe6EZLPy2r5f0GRBSGTOTzZWd1nRTjszq@cnnyyfB8YLHH/4WQLKJYBuDqzzGYzNWUbupS@yprHoBm8RU3pAT1d8Epdt@wU "Python 2 – Try It Online") Outputs a [PBM](http://netpbm.sourceforge.net/doc/pbm.html) file to STDOUT. Sample output: [![enter image description here](https://i.stack.imgur.com/Ik6XRm.png)](https://i.stack.imgur.com/Ik6XR.png) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 67 bytes (SBCS) `⎕IO←0` ``` +{(⎕NEW'Bitmap'(⊂'Cbits'(⍵≥+⌿⍺∘.(.5*⍨-+.×-)(⊢,-)⍳2×⍵ ⍵))).MakePNG}⊢ ``` ## NB * This image is very low contrast (made from a boolean matrix) - the output can be white interior shape on black background by multiplying the boolean matrix: +{(⎕NEW'Bitmap'(⊂'Cbits'(16777215×~⍵≥+⌿⍺∘.(.5\*⍨-+.×-)(⊢,-)⍳2×⍵ ⍵))).MakePNG}⊢ * Images are transposed compared to many other solutions, but you can flip the indices of each focus * Only works on Dyalog for Windows ## Explanation This function is a 3-train (fork), the arguments to the inner function are the results of the outer functions: ``` + ``` `+` (plus): Translate the image by adding distance to the foci (please comment if this is a misinterpretation of the challenge) ``` ⊢ ``` `⊢` (right): given two arguments (left and right), return the right argument APL is parsed (glossing over some binding rules) as Brackets, long Right scope, short Left scope. We break it down as follows: ``` ⍳2×⍵ ⍵ ``` Indices from 0 to 2×⍵ in 2 dimensions (our integer pixels) ``` (⊢,-)⍳2×⍵ ``` `(⊢,-)` (Same catenate negate) to cover positive and negative coordinates ``` (.5*⍨-+.×-) ``` Euclidean distance from focus to pixel... ``` ⍺∘.(.5*⍨-+.×-) ``` ... applied between each focus and every pixel ``` +⌿⍺∘.(.5*⍨-+.×-) ``` Sum the distances between all foci and each pixel (n-ellipse) ``` ⍵≥+⌿⍺∘.(.5*⍨-+.×-) ``` Boolean matrix where 1 indicates interior (active) pixels (i.e. sum of distances between foci and pixel is less than *t*) ``` (⎕NEW'Bitmap'(⊂'Cbits'(*boolean matrix*))).MakePNG ``` Output signed integer PNG. This can be written to file using ``` ∇ WritePNG png;tn tn←'img.png'⎕NCREATE 0 png ⎕NAPPEND tn 83 ⎕NUNTIE tn ∇ ``` ## Output Images First is to demonstrate, the written PNG has very low contrast ``` f ← +{(⎕NEW'Bitmap'(⊂'Cbits'(⍵≥+⌿⍺∘.(.5*⍨-+.×-)(⊢,-)⍳2×⍵ ⍵))).MakePNG}⊢ WritePNG 5 8 f 100 ``` [![enter image description here](https://i.stack.imgur.com/baNLa.png)](https://i.stack.imgur.com/baNLa.png) Below I'm using the black and white version. ``` WritePNG (0 0)(70 150) f 220 ``` [![enter image description here](https://i.stack.imgur.com/iZkF4.png)](https://i.stack.imgur.com/iZkF4.png) ``` WritePNG (¯100 0)(100 0)(100 0) f 480 ``` [![enter image description here](https://i.stack.imgur.com/LZPf3.png)](https://i.stack.imgur.com/LZPf3.png) Very resource hungry algorithm so I did a low res version of this ``` WritePNG (20 60)(32 ¯6)(¯35 22)(¯41 13)(4 ¯14) f 210 ``` [![enter image description here](https://i.stack.imgur.com/tqic0.png)](https://i.stack.imgur.com/tqic0.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~36~~ 35 bytes ``` «/_⁹r»/+¥,þ/_Ɱ⁸²§½S>⁹µ;L;ZL$;1ṚK”P; ``` [Try it online!](https://tio.run/##y0rNyan8///Qav34R407iw7t1tc@tFTn8D4gd@O6R407Dm06tPzQ3mA7oOShrdY@1lE@KtaGD3fO8n7UMDfA@v///xoGOgaaOgoa5joKhqaa/42MAA "Jelly – Try It Online") A full program that takes a list of lists of integers as the first argument, representing the foci, and the threshold as an integer as its second argument. Prints a PBM file to STDOUT. ### Example * First argument: `(0,0), (7, 15)` * Second argument: `220` * Output (converted to PNG): [![enter image description here](https://i.stack.imgur.com/Brgtz.png)](https://i.stack.imgur.com/Brgtz.png) [Answer] # [Haskell](https://www.haskell.org/) + [Gloss](https://hackage.haskell.org/package/gloss), 165 bytes ``` import Graphics.Gloss i=fromIntegral h t=[i(-t)*3..i t*3] d f t=display(InWindow""(t*3,t*3)(0,0))red$Line[(x,y)|x<-h t,y<-h t,i t>sum[sqrt$(x-u)^2+(y-v)^2|(u,v)<-f]] ``` Draws the shapes to the screen. It sometimes draws the images REALLY BIG, so I have cropped accordingly. `main = d [(5,8)] 100` [![enter image description here](https://i.stack.imgur.com/6hmcD.png)](https://i.stack.imgur.com/6hmcD.png) `main = d [(0,0), (70, 150)] 220` [![enter image description here](https://i.stack.imgur.com/dTDFZ.png)](https://i.stack.imgur.com/dTDFZ.png) `main = d [(-100, 0), (100, 0), (100, 0)] 480` [![enter image description here](https://i.stack.imgur.com/Etkeu.png)](https://i.stack.imgur.com/Etkeu.png) `main = d [(-250, -250), (-250, 250), (250, -250)] 1000` [![enter image description here](https://i.stack.imgur.com/xMHp0.png)](https://i.stack.imgur.com/xMHp0.png) [Answer] ## JavaScript (ES7), ~~212~~ 196 bytes ``` with(Math)f=(c,l,...p)=>{m=l-max(...p) c.height=c.width=s=min(...p)+l+m for(i=0;i<s;i++)for(j=0;j<s;j++){for(d=k=0;1/p[k];)d+=hypot(p[k++]+m-i,p[k++]+m-j) d>l||c.getContext`2d`.fillRect(i,j,1,1)}} eval(`f(c,${e.value})`) ``` ``` input{position:fixed} ``` ``` <input id=e oninput=eval(`f(c,${e.value})`) value="100,-25,-25,-25,25,25,-25"><canvas id=c> ``` Outputs via first parameter which is a canvas element to draw on, second parameter is the threshold, then the remaining parameters are the loci. Edit: Saved 16 bytes thanks to @Arnauld, however the code is now dead slow and will trigger slow script warnings for large thresholds. [Answer] # [Red](http://www.red-lang.org), 300 bytes ``` Red[]f: func[p t][a: :absolute m: last sort collect[foreach n p[keep a n/x keep a n/y]]s: t + m * 2 u: as-pair s s i: make image! reduce[u]k: 0 repeat y s[repeat x s[d: 0 foreach a p[d: d +(sqrt x - t - m - a/x ** 2 +(y - t - m - a/y ** 2))]k: k + 1 if d <= t[i/:k: 0.0.255]]]save/as %1.jpg i 'jpeg] ``` `f [5x8] 100` [![enter image description here](https://i.stack.imgur.com/LEdBr.jpg)](https://i.stack.imgur.com/LEdBr.jpg) `f [0x0 70x150] 220` [![enter image description here](https://i.stack.imgur.com/J9Snl.jpg)](https://i.stack.imgur.com/J9Snl.jpg) `f [-100x0 100x0 100x0] 480` [![enter image description here](https://i.stack.imgur.com/wgPiF.jpg)](https://i.stack.imgur.com/wgPiF.jpg) `f [200x600 320x-60 -350x220 -410x130 40x-140] 2100` [![enter image description here](https://i.stack.imgur.com/HAM4W.jpg)](https://i.stack.imgur.com/HAM4W.jpg) `f [-390x0 -130x120 130x-120 390x0] 1180` [![enter image description here](https://i.stack.imgur.com/QcOLR.jpg)](https://i.stack.imgur.com/QcOLR.jpg) Note: I scaled all the images to 256x256 pixels and croped the last two images so that they don't take too much space - they had a large "frame" [Answer] # Applescript + grapher, 601 This will almost certainly be the longest answer, but I thought this would be a fun challenge in Applescript. ``` on f(l, t) set y to 0 tell application "Grapher" to activate tell application "System Events" keystroke "n" using command down keystroke return keystroke "a" using command down repeat with d in l keystroke "sqrt((x-"&d's item 1&")^2)+(y-"&d's item 2&")^2))+" set y to y+d's item 2 end repeat click application process "Grapher"'s menu bar 1's menu bar item 8's menu 1's menu item 3 set c to l's items count keystroke " "&(y-t)/c as text&" "&(y+t)/c as text&" " keystroke "c" using command down keystroke " " keystroke "v" using command down keystroke return&"0<"&t as text&return end tell end f ``` This is an applescript function. It may be called as follows for the testcases: ``` my f({{5, 8}}, 100) my f({{0, 0}, {70, 150}}, 220) my f({{-100, 0}, {100, 0}, {100, 0}}, 480) my f({{-90, -90}, {-90, 90}, {90, -90}, {90, 90}, {90, -90}}, 670) my f({{200, 600}, {320, -60}, {-350, 220}, {-410, 130}, {40, -140}}, 2100) my f({{-250, -250}, {-250, 250}, {250, -250}}, 1000) my f({{-250, -250}, {-250, 250}, {250, -250}}, 1200) my f({{-390, 0}, {-130, 120}, {130, -120}, {390, 0}}, 1180) ``` Output looks like this, e.g. for the 5th testcase: [![enter image description here](https://i.stack.imgur.com/SyaWe.jpg)](https://i.stack.imgur.com/SyaWe.jpg) [Answer] # MATLAB + [DIPimage](https://diplib.github.io/DIPimage.html) toolbox, ~~133~~ ~~121~~ ~~117~~ 111 bytes (shaved off ~~12~~ 16 bytes thanks to flawr and LuisMendo) ``` function s(c,r),c=c-min(c)+r;a=zeros(max(c)+r);l='corner';for x=c',a=a+hypot(xx(a,l)-x(1),yy(a,l)-x(2));end,a>r ``` Use: ``` c = [-390, 0; -130, 120; 130, -120; 390, 0]; r = 1180; s(c,r) ``` In a more readable fashion: ``` function s(c,r) c=c-min(c)+r; % offset coordinates so all points within shape have non-negative coordinates a=zeros(max(c)+r); % compute image size and create empty output image l='corner'; % long argument used twice below for x=c' a=a+hypot(xx(a,l)-x(1),yy(a,l)-x(2)); % add distance to each point end a>r % threshold and display (leaving semi-colon off causes graphical display of image) ``` [Answer] # [Desmos](https://www.desmos.com/calculator), ~~50~~ 49 bytes ``` \sum_{n=1}^c \sqrt{(x-a[n].x)^2+(y-a[n].y)^2}<=t ``` -1 byte from finding a new quirk in Desmos' syntax while working on another problem. [View it online](https://www.desmos.com/calculator/ps2nlafz9g) It just kinda... works. Input `n` in the variable `c`, `t` in the variable `t`, and the points as an array `a` of coordinates. Lips example: [!["lips" n-ellipse in Desmos](https://i.stack.imgur.com/VuDHN.png)](https://i.stack.imgur.com/VuDHN.png) Guitar pick example: [!["guitar pick" n-ellipse in Desmos](https://i.stack.imgur.com/1pH14.png)](https://i.stack.imgur.com/1pH14.png) Note: If you try to copy the equation from the editor, you'll find a bunch of `\left`s and `\right`s and such. These have been golfed out of this answer, as you can paste this text in and it works. The editor automatically re-adds those when parsing input from the clipboard, but it accepts the code without them. Note two: I'm not 100% sure if this counts due to the infill being transparent, but hopefully it's ok. If not, there's a couple options: 1. Stack a bunch of whole bunch of these equations on top of each other. I tried this and it turns out that a quirk of their rendering engine is that the fill color can never drop below #010101, while the outline is at #000000. Additionally, the area is a little larger than would be ideal because the outline looks like part of the fill. 2. Rewrite the n-ellipse equation in parametric form. I don't know if this is possible or not, but if it is, Desmos's enhanced visual options for parametric equations allows us to remove the outline. [Answer] # [Bash](https://www.gnu.org/software/bash/) + Standard utilities (but no graphics library), ~~194~~ ~~190~~ 186 bytes ``` t=$1 shift L=H=$1 for n do L=$[n<L?n:L] H=$[n>H?n:H] done echo P2 $[L-=t,H+=t+1,H-L] $[H-L] 1 for((x=y=L;y<H;++x>=H?x=L,y++:0)){ bc -l<<<`printf "sqrt(($x- %d)^2+($y- %d)^2)+" $@`0\>$t;} ``` [Try it online!](https://tio.run/##Lcw9C4MwGATgPb/iRVKIxIAKhaKJdsyQobu1WL9QKLHVDJHS355q6XT33HD1fRmcMwJHaBnG3iAl5I5@mkFDO23GheYq14kqkdyRyQ2yRO2kO9Q1wwSXGHChmDCBpMLQKJBMldv0i98XIVasQqUrlymlNhMyt0IFK6VJ6PtvqBtgD8559ZxHbXrwltdsCMGWwaH1bzEleP1Xn3qAz1V4zbBJP865KAzd0Z2@ "Bash – Try It Online") (If you do, though, try a tiny example: even the circle test times out on TIO.) --- Input is passed in the arguments: first \$t\$, then \$x\_1\$, \$y\_1\$, \$x\_2\$, \$y\_2\$, ..., \$x\_n\$, \$y\_n\$. Output is a PGM image on stdout. Save it in a file named `something.pgm` and view it in your favorite graphics program. The x-axis goes from left to right, and the y-axis goes from top to bottom. White is the background, and black is the n-ellipse being drawn. For example, to view the first example (the circle), you could execute: ``` lips 100 5 8 > lips-circle.pgm ``` (where the program is named `lips`). Then open the image`lips-circle.pgm`. Here's the result: [![enter image description here](https://i.stack.imgur.com/BsF8g.png)](https://i.stack.imgur.com/BsF8g.png) Here's the second test, the output of `lips 220 0 0 70 150 > lips-ellipse.pgm`:[![enter image description here](https://i.stack.imgur.com/rTbHP.png)](https://i.stack.imgur.com/rTbHP.png) Next is `lips 480 -100 0 100 0 100 0 > lips-repeatedpoint.pgm`: [![enter image description here](https://i.stack.imgur.com/XXguW.png)](https://i.stack.imgur.com/XXguW.png) Here is `lips 670 -90 -90 -90 90 90 -90 90 90 90 -90 > lips-repeated-arbitaryOrder.pgm`: [![enter image description here](https://i.stack.imgur.com/g9p1y.png)](https://i.stack.imgur.com/g9p1y.png) The next test is `lips 2100 200 600 320 -60 -350 220 -410 130 40 -140 > lips-shape1.pgm`: [![enter image description here](https://i.stack.imgur.com/gDdRL.png)](https://i.stack.imgur.com/gDdRL.png) --- *This script is very slow (but runnable). I will post more sample images as my computer gets around to finishing them :) ....* *Well, after waiting overnight again, the other tests are finally done!* --- Here's the guitar pick: `lips 1000 -250 -250 -250 250 250 -250 > lips-guitarpick.pgm` [![enter image description here](https://i.stack.imgur.com/2wDIy.png)](https://i.stack.imgur.com/2wDIy.png) The next test is `lips 1200 -250 -250 -250 250 250 -250 > lips-shape2.pgm`: [![enter image description here](https://i.stack.imgur.com/y2u6Q.png)](https://i.stack.imgur.com/y2u6Q.png) And finally the pair of lips! `lips 1180 -390 0 -130 120 130 -120 390 0 > lips-pairOfLips.pgm`: [![enter image description here](https://i.stack.imgur.com/C7U3Z.png)](https://i.stack.imgur.com/C7U3Z.png) [Answer] # Shadertoy (GLSL) 125 bytes + input data ``` vec2 a[]=vec2[](vec2(-390, 0),vec2(-130,120),vec2(130,-120),vec2(390,0)); float d=1180.; void mainImage(out vec4 o,vec2 c){c-=iResolution.xy/2.;o-=o;for(int i=0;i<a.length();o.a+=length(c-a[i++]));o.b=step(o.a,d);} ``` [Shadertoy](https://www.shadertoy.com/view/ttVXW3) link for the last testcase. As the input array's size is known, this could be further reduced by replacing the `a.length()` by `n`. [Answer] # [Desmos](https://desmos.com/calculator), 39 bytes ``` \distance((x,y),\ans_0).\total<=\ans_1 ``` The other Desmos answer to this challenge is invalid because it assumes that the input is stored in hardcoded variables, which is [heavily](https://codegolf.meta.stackexchange.com/a/8731/96039) [discouraged](https://codegolf.meta.stackexchange.com/a/2423/96039). Instead, this program takes input through `\ans`, which is an [acceptable form of input](https://codegolf.meta.stackexchange.com/a/8580/96039). Input the list of points in the first line, and the threshold in the second line. [Try It On Desmos!](https://www.desmos.com/calculator/7wwa6edioa) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/vghn0l7hhp) ]
[Question] [ **This question already has answers here**: [Find two integers from an unordered list to sum to the input](/questions/113365/find-two-integers-from-an-unordered-list-to-sum-to-the-input) (26 answers) Closed 6 years ago. # The Task This is my first challenge so apologies if it is very simple! In this challenge, your task is to write a program or function which takes in a list of integers and a desired sum and outputs a truthy or falsey value based on whether the list contains two numbers that can be summed together to achieve the desired sum. # Input The input must be acquired in a standard way for your language. The list of integers can be any standard collection type for your language but cannot be a hashed set, sorted set, or any highly functional collection type. Don't assume the input is sorted, any valid integer type is acceptable. The desired sum is also an integer and must be provided to your program as input. # Output The output may be a function return, console log, writing to a file, etc... Any valid Truthy or Falsey value is acceptable. # Additional Rules * The input list may or may not be sorted. * Duplicate values may occur in the list * The same item in the list may not be summed to itself to achieve the desired sum (Eg. [3,4,5] with desired sum 6 will expect False because 3 cannot be used twice) * Standard loopholes are not allowed. Test Cases ``` INPUT OUTPUT [3,4,5], 6 Falsey [1,2,3,4,5,6],11 Truthy [4,23,8174,42,-1],41 Truthy [1,1,1,1,1,3],3 Falsey [2,1,1,1,53,2],4 Truthy [2,2,2,2],4 Truthy [3],3 Falsey [],-43 Falsey ``` 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), 3 bytes ``` ⊇Ċ+ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/@oq/1Il/b//9GGOkY6xjomOqY6ZrH/DQ0B "Brachylog – TIO Nexus") ``` ⊇Ċ+ input as STDIN, output as ARG1 (prove that:) ⊇ the input is a superset of Ċ a list of two elements + which sums up to the output ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ ~~6~~ 5 bytes ``` ŒcS€ċ ``` [Try it online!](https://tio.run/nexus/jelly#@390UnLwo6Y1R7r///8fbaJjZKxjYWhuomNipKNrGPvfxBAA "Jelly – TIO Nexus") -1 byte by using the Unordered Pairs atom ``` ŒcS€ċ Main Link; left argument is the array, right argument is the required sum S€ Take the sum of each... Œc ...unordered pair... ċ Check if the sum array contains the right argument ``` -1 byte thanks to Erik! # 4 bytes ``` Œc§i ``` This does the same thing but with a newer language feature of vectorize-at-depth-1 sum. Thanks Dennis! :D Credit to [@Riolku](https://codegolf.stackexchange.com/users/90304/riolku) for noticing this. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` æ2ùOIå ``` [Try it online!](https://tio.run/nexus/05ab1e#@394mdHhnf6eh5f@/x9tomNkrGNhaG6iY2Kko2sYy2ViCAA "05AB1E – TIO Nexus") **Explanation** ``` æ # get powerset of first input 2ù # keep only those of size 2 O # sum each Iå # check if 2nd input is in the list of sums ``` [Answer] # Mathematica, 29 bytes ``` !FreeQ[Tr/@#~Subsets~{2},#2]& ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~43~~ 42 bytes -1 byte thanks to mbomb007 ``` lambda a,b:any(b-a.pop()in a for x in a*1) ``` [Try it online!](https://tio.run/nexus/python2#NYpBDoIwFAX3nOIvW/Iw@W1BQ@JJahcFITTR0hCMenDXKKiZzbyX6Y@n5eKvzdmTR1P7@BRN4XdpTEKGSJ76caIHrZqzXO5DuHTEdZpCnKkXeYjpNgspF6thUDpQlVmGwjZROTBn1kBpHHhvYBQKdjC8Vn@0g86s@q1SQ32K9djY/Js4FEa/4li0vh26Nw "Python 2 – TIO Nexus") [Answer] # [Haskell](https://www.haskell.org/), ~~39 37~~ 36 bytes ``` (a:t)#n=n`elem`map(a+)t||t#n _#n=1<0 ``` [Try it online!](https://tio.run/nexus/haskell#NYpBCsIwEEX3niIwmxa/4CRpFbFH8AQh2Cy6KJihlCx79zgE5a/ee7926VF6kknm5bPkOaetS@e@HEchOb018PNac1rFTEbjy2z7KsWE4OAxRBphAsOiIcZIzGo8rMOdbx7e4sKRPLfffy6SU2F/ODhY/TTTphDrFw "Haskell – TIO Nexus") Example usage: `[1,3,2,5] # 3`. Returns `True` or `False`. --- **Alternative** (also 36 bytes) ``` f(a:t)=map(a+)t++f t f e=e (.f).elem ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` 2XN!sm ``` [Try it online!](https://tio.run/nexus/matl#NYq7DYAwFAN7b0HvFO@TwADUVBRI0ZNYgIr9FSCArvFZtzfdluE82ry2anTmQEEVKruxBERQnWqcZHS6MknA5al@LGCo@lk26l08R6fvNwkktws "MATL – TIO Nexus") ### Explanation ``` 2XN % Implicitly input an array. Combinations of elements taken 2 at a time % The result is a matrix where each row is a combination !s % Sum of each row m % Implicitly input a number. Ismember function. Implicitly display ``` [Answer] # C, ~~114~~ 113 bytes ``` i,j,k="F";main(c,v)char**v;{for(--c;++i<c;)for(j=0;++j<c;)k=j^i&atoi(v[i])+atoi(v[j])==atoi(v[c])?"T":k;puts(k);} ``` Here's the output ``` C:\eng\golf>a.exe 3 4 5 6 F C:\eng\golf>a.exe 1 2 3 4 5 6 11 T C:\eng\golf>a.exe 4 23 8174 42 -1 41 T C:\eng\golf>a.exe 1 1 1 1 1 3 F C:\eng\golf>a.exe 2 1 1 1 53 2 4 T C:\eng\golf>a.exe 2 2 2 2 4 T ``` [Answer] # JavaScript (ES6), ~~38~~ 43 bytes ``` a=>n=>[...a].some(_=>a.includes(n-a.pop())) ``` --- ## Try It ``` f= a=>n=>[...a].some(_=>a.includes(n-a.pop())) o.innerText=` f([3,4,5])(6) = ${f([3,4,5])(6)} f([1,2,3,4,5,6])(11) = ${f([1,2,3,4,5,6])(11)} f([4,23,8174,42,-1])(41) = ${f([4,23,8174,42,-1])(41)} f([1,1,1,1,1,3])(3) = ${f([1,1,1,1,1,3])(3)} f([2,1,1,1,53,2])(4) = ${f([2,1,1,1,53,2])(4)} f([2,2,2,2])(4) = ${f([2,2,2,2])(4)} f([3])(3) = ${f([3])(3)} f([])(-43) = ${f([])(-43)} f([1,2,3,4,5,6])(3) = ${f([1,2,3,4,5,6])(3)}` ``` ``` pre{font-size:14px;line-height:1.75} ``` ``` <pre id=o> ``` [Answer] # Ruby, ~~59~~ ~~53~~ 37 bytes [inspiration comes from this answer](https://codegolf.stackexchange.com/a/120806/46172) ``` ->a,b{a.map{|e|a.include?(b-e)}.any?} ``` will now look where can I chop a few bytes -)) **HISTORY** ``` #53 bytes ->a,b{a.combination(2).map{|e|e.reduce(&:+)==b}.any?} #59 bytes ->a,b{a.combination(2).map{|e|e.reduce(&:+)}.any?{|x|x==b}} ``` [Answer] ## Clojure, 53 bytes ``` #(loop[[v & r]%](if v(or((set r)(- %2 v))(recur r)))) ``` Uses destructuring to take the first and rest of the input list (and subsequent `recur` of rest), and returns the number "target - value1" if found in the set of remaining numbers (a "truthy"), nil otherwise. [Answer] # Java 7, 138 bytes ``` boolean c(int[]a,int s){String r="";for(int l=a.length,i=0,j;i<l;i++)for(j=-1;++j<l;)if(i!=j)r+=(a[i]+a[j])+",";return r.contains(s+",");} ``` **Explanation:** ``` boolean c(int[]a,int s){ // Method with integer-array and integer parameters and boolean return-type String r=""; // Temp String for(int l=a.length,i=0,j;i<l;i++) // Loop (1) over the input array for(j=-1;++j<l;) // Inner loop (2) over the input array again if(i!=j) // If the index of both loops aren't equal (so not the same item in the list) r+=(a[i]+a[j])+","; // Append the sum with a comma to the temp-String // End of loop (2) (implicit / single-line body) // End of loop (1) (implicit / single-line body) return r.contains(s+","); // Return whether the temp-String contains the given sum (+ comma) } // End of method ``` **Test code:** [Try it here.](https://tio.run/nexus/java-openjdk#jZBBbsMgEEX3OcXUKxATq9hOWolyhK6ytLwgrpNgEYgAt6oszp7aTrutrL9AmvmP@TOtUSHA@7gBCFFF3cL96JzplIWWaBvrRuH0QKDjIXptz@BllomT83MXjFS56ew5XlDLZ@yFfjNCM0ZnQy@3XDDWTyWqT0Q/yZ56JomqdcNU3TeUZZgJ38XBW/B562xU2gYS5joV6Q5wG45mCvWb7dPpD7hOHvIIUzeg6Jwd4PAdYnfN3RDz29SKxpKW2O4LliVGjgWWWOEO9wk5p1SsoSosSnzlLxVWBW55wmotWSBftCuxmLDV1KL/gXVfcfxTmbBcOX@5UML9w5426f4D) ``` class M{ static boolean c(int[]a,int s){String r="";for(int l=a.length,i=0,j;i<l;i++)for(j=-1;++j<l;)if(i!=j)r+=(a[i]+a[j])+",";return r.contains(s+",");} public static void main(String[] a){ System.out.println(c(new int[]{1,2,3,4,5,6},11)); System.out.println(c(new int[]{4,23,8174,42,-1},41)); System.out.println(c(new int[]{2,1,1,1,53,2},4)); System.out.println(c(new int[]{2,2,2,2},4)); System.out.println(); System.out.println(c(new int[]{1,1,1,1,1,3},3)); System.out.println(c(new int[]{3,4,5},6)); } } ``` **Output:** ``` true true true true false false ``` [Answer] # [TAESGL](https://github.com/tomdevs/taesgl), 8 bytes ``` Ş⇒AĨB-AĖ ``` [**Interpreter**](https://tomdevs.github.io/TAESGL/v/1.2.0/index.html?code=XHUwMTVlXHUyMWQyQVx1MDEyOEItQVx1MDExNg==&input=WzQsMjMsODE3NCw0MiwtMV0sNDE=) **Explanation** ``` Ş⇒ Array.some with anonymous function on implicit input AĨ first input includes B- second input minus AĖ first input popped ``` [Answer] ## PHP (>= 7.1), ~~53~~ ~~51~~ ~~50~~ 46 Bytes ``` <?foreach($_GET[0]as$c)+$$c||${$_GET[1]-$c}=a; ``` sadly it's quite big but at least better than 2 loops. `+a` fails with a warning if the sum can be made => non empty output => *truthy*. Outputs nothing if the sum can not be made => *falsey*. Thanks @user63956 ! [Answer] ## Mathematica, 38 bytes ``` MemberQ[Total/@#~Permutations~{2},#2]& ``` input style [{1,2,3,4,5,6},11] [Answer] # [Python 3](https://docs.python.org/3/), 41 bytes ``` f=lambda a,b,*c:a-b in c or c and f(a,*c) ``` [Try it online!](https://tio.run/nexus/python3#NY5LCsMwDET3PYWWdpks/ElbAj2J8EJOMARat4Te35WbFAnBvHkLtXJ/yDMvQoKM8zzJkGmtNNNr0yN1oWJEC9uKEpV6y8wBEWMCXRKYHTx@ABqd6yjCB9zcNSJ6DIqi283/hNSX2R95DPBqpTSd6L2t9WOK0Y/E2vYF "Python 3 – TIO Nexus") Recursive aproach with *flexible* input and output. Returns an empty set as falsy. [Answer] # R, 32 bytes ``` function(x,l)x%in%combn(l,2,sum) ``` Returns an anonymous function. `combn` returns all combinations of `l` taken `m` at a time, in this case 2, and then optionally applies a function, in this case `sum`. Returns an empty logical vector `logical(0)` for an empty first input, which I define for this problem as falsey, and `TRUE` or `FALSE` corresponding to the other elements otherwise. [Try it online!](https://tio.run/nexus/r#S7P9n1aal1ySmZ@nUaGTo1mhmpmnmpyfm5SnkaNjpFNcmqv5P03DSCdZwxDINdYx0THV1PwPAA) [Answer] # Pyth - 9 bytes ``` /msd.cE2E ``` [Try it](https://pyth.herokuapp.com/?code=%2Fmsd.cE2E&input=%5B3%2C4%2C5%5D6%20%20%20%20%20%20%20%20%20%20%20%20Falsey%0A%5B1%2C2%2C3%2C4%2C5%2C6%5D%2C11%20%20%20%20%20%20Truthy%0A%5B4%2C23%2C8174%2C42%2C-1%5D%2C41%20%20Truthy%0A%5B1%2C1%2C1%2C1%2C1%2C3%5D%2C3%20%20%20%20%20%20%20Falsey%0A%5B2%2C1%2C1%2C1%2C53%2C2%5D%2C4%20%20%20%20%20%20Truthy%0A%5B2%2C2%2C2%2C2%5D%2C4%20%20%20%20%20%20%20%20%20%20%20Truthy%0A%5B3%5D%2C3%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20Falsey%0A%5B%5D%2C-43%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20Falsey&test_suite=1&test_suite_input=%5B3%2C4%2C5%5D%0A6%0A%5B1%2C2%2C3%2C4%2C5%2C6%5D%0A11%0A%5B4%2C23%2C8174%2C42%2C-1%5D%0A41%0A%5B1%2C1%2C1%2C1%2C1%2C3%5D%0A3%0A%5B2%2C1%2C1%2C1%2C53%2C2%5D%0A4%0A%5B2%2C2%2C2%2C2%5D%0A4%0A%5B3%5D%0A3%0A%5B%5D%0A-43&debug=0&input_size=2) ``` /msd.cE2E .cE2 # All subsets of length 2 msd # The sum of each subset / E # Number of occurrences of the input number ``` [Answer] # MATLAB, 28 bytes ``` @(a,b)any(pdist(a,@plus)==b) ``` This defines an anonymous function with inputs `a`: column vector (possibly empty); `b`: number. The code also works in Octave except if the first input is empty, which causes an error. **[Try it online!](https://tio.run/nexus/octave#RYrLCsIwEEX3fkWXCaSBebQKl0D/o3TRIgVBpFBd@PVxDLFyN3POnDXFGPPg5rD4@fF22/W2P42G7f7afUqLz6sbBYpuakLvT0YERjHop9AQFalgwYXOCmW0ZA@lWv8mJqU4rqYT8Lessuzgf25Hq@LzBw)** ### Explanation `pdist(a,@fun)` applies function `fun` (in our case, addition) to each combination of two rows of the input matrix `a` (in our case, a column vector). The output is a column vector. `any(...==b)` gives true if any of the results equals the input number `b`. [Answer] # Python 2, 71 bytes ``` from itertools import* lambda L,n:n in map(sum,list(combinations(L,2))) ``` [**Try it online**](https://tio.run/nexus/python2#NYpNDoIwGAX3PUWXLXks@gMaEm/ADbCLqhC/hLYESjw@Cmpm8@Zlhst1G324PTxvEZvIKfLgJ7GsASMtWdxTuFH0mVJcRAstpWTDnAKn3M85pXHhFKY052J7PWnsuWqmmWLmgygoTmsWUm6dgUXlwGvWKWgcitpBKdZZaIOzOllYjVI5WLVXf4yDYZ3@WWWgP8V@HBz7mziU1rwB) Yes, I know there is already a better solution posted. [Answer] ## C#, ~~96~~ 90 bytes ``` using System.Linq;a=>n=>Enumerable.Range(0,a.Count).Any(i=>a.Skip(i+1).Any(j=>a[i]+j==n)); ``` Compiles to a `Func<List<int>, Func<int, bool>>`. Formatted version: ``` Func<List<int>, Func<int, bool>> f = a => n => Enumerable.Range(0, a.Count).Any(i => a.Skip(i + 1).Any(j => a[i] + j == n)); ``` Old `for` loop version for 96 bytes: ``` a=>n=>{for(int i=0,j,l=a.Count;i<l;++i)for(j=i+1;j<l;)if(a[i]+a[j++]==n)return 1>0;return 1<0;}; ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 77 bytes ``` {for(s=i=0;++i<NF;)for(j=0;++j<NF;){if(i==j)continue if($i+$j==$NF)s=1}$0=s}1 ``` [Try it online!](https://tio.run/nexus/awk#VY2xDoMwDER3vuKGDCCEhBPTVqJeGfmJqkjJAFIpE@Lb05DQitoefO/Osl@H6ZXPYqVuy9Le@64tduKidlGvdsitiCse0/i24/LMAlC2VE5E9V0xC22qlnkj7w0YDXDBqTIQNJITDKIEGdrgRlcGa1QBMu3JbxvsE5P6QI0Ja7g7YOqkE/vdnH5X/I@yDw "AWK – TIO Nexus") I could save 2 bytes by removing the `i=` in the `for(s=i=0...)`, but then it would only work for one line of data. Since this isn't the shortest answer, I thought I'd make a general solution :) Input is whitespace separated numbers with the last value being the desired sum. [Answer] # [Jellyfish](https://github.com/iatorm/jellyfish), 13 bytes ``` p cd!i i 2 1 ``` [Try it online!](https://tio.run/nexus/jellyfish#@1/AlZyimMmVqWDEpWD4/3@0iYKRsYKFobmJgomRgq5hLJeJIQA "Jellyfish – TIO Nexus") ## How it works ``` print(exists(i,from_base(1,permutations(i,2))) ``` where `i` are the inputs. [Answer] # Axiom, ~~90~~ 92 bytes ``` f(a,k)==(for i in 1..#a-1 repeat for j in i+1..#a repeat(q:=a.i+a.j;q=k=>return true);false) ``` test ``` (42) -> f([3,4,5],6) (42) false Type: Boolean (43) -> f([1,2,3,4,5,6],11) (43) true Type: Boolean (44) -> f([4,23,8174,42,-1],11) (44) false Type: Boolean (45) -> f([4,23,8174,42,-1],41) (45) true Type: Boolean (46) -> f([2,23,8174,42,2],2) (46) false ``` [Answer] ## [C#](http://csharppad.com/gist/e11a62dffa6ce06e38335c5da1f8ac52), ~~103~~ 102 bytes --- ### Data * **Input** `Int32[]` `l` A list of `Int32` to sum * **Input** `Int32` `r` The result to check against * **Output** `Boolean` A result indicating if the sum can be performed --- ### Golfed ``` (int[] l,int r)=>{for(int x=l.Length,y;--x>=0;)for(y=0;y<x;)if(l[x]+l[y++]==r)return 1>0;return 0>1;}; ``` --- ### Ungolfed ``` ( int[] l, int r ) => { for( int x = l.Length, y; --x >= 0; ) for( y = 0; y < x; ) if( l[ x ] + l[ y++ ] == r ) return 1 > 0; return 0 > 1; }; ``` --- ### Ungolfed readable *`Working on it...`* --- ### Full code ``` using System; using System.Collections.Generic; namespace Namespace { class Program { static void Main( String[] args ) { Func<Int32[], Int32, Boolean> f = ( int[] l, int r ) => { for( int x = l.Length, y; --x >= 0; ) for( y = 0; y < x; ) if( l[ x ] + l[ y++ ] == r ) return 1 > 0; return 0 > 1; }; List<KeyValuePair<Int32[], Int32>> testCases = new List<KeyValuePair<Int32[], Int32>>() { new KeyValuePair<Int32[], Int32>( new Int32[] { 3, 4, 5 }, 6 ), new KeyValuePair<Int32[], Int32>( new Int32[] { 1, 2, 3, 4, 5, 6 }, 11 ), new KeyValuePair<Int32[], Int32>( new Int32[] { 4, 23, 8174, 42, -1 }, 41 ), new KeyValuePair<Int32[], Int32>( new Int32[] { 1, 1, 1, 1, 1, 3 }, 3 ), new KeyValuePair<Int32[], Int32>( new Int32[] { 2, 1, 1, 1, 53, 2 }, 4 ), new KeyValuePair<Int32[], Int32>( new Int32[] { 2, 2, 2, 2 }, 4 ), new KeyValuePair<Int32[], Int32>( new Int32[] { 3 }, 3 ), new KeyValuePair<Int32[], Int32>( new Int32[] { }, -43 ), }; foreach( var testCase in testCases ) { Console.WriteLine( $" Input: {testCase.Value}; {{ {String.Join(", ", testCase.Key)} }}\nOutput: {f( testCase.Key, testCase.Value )}\n" ); } Console.ReadLine(); } } } ``` --- ### Releases * **v1.1** - `-1 byte` - Thanks to [TheLethalCoder](https://codegolf.stackexchange.com/posts/comments/296698?noredirect=1) suggestion. * **v1.0** - `103 bytes` - Initial solution. --- ### Notes * None ]
[Question] [ I thought of a new way to generate my passwords, and even though it's probably not very clever in the long run, it could still make for a fun code-golf. Taking a string of words, the password is generated thus: * Pick the *nth* character in the *nth* word * If *n* is larger than the word, continue counting backwards Example: ``` This is a fun task! T s a u ! ``` T is the first character s is the second a is the first, but going back and forth it is also the third u is the second but because of counting backwards it's also the fourth '!' is the fifth character in 'task!' and thus will be included in the final password, `Tsau!` **Rules** * Input will be a string * Separate the string on spaces, all other characters must be included * Uppercase letters must remain uppercase, same with lowercase * You take *n* steps in each word, where *n* is the number of words that have come before plus one * If *n* is larger than the word, you must step backwards through the word, if you hit the start, you go forward again until you have stepped *n* times * The first and last character is only stepped once, so 'fun' on the seventh position as an example goes 'funufun' and ends on n, not 'funnuff' and ends on f * Output must be a string Examples: ``` Input Output Once Upon A Time OpAe There was a man Taaa Who made a task Waak That was neat! Taa This is a long string to display how the generator is supposed to work Tsagnoyotoipto ``` The shortest code in bytes wins! [Answer] # [Python 2](https://docs.python.org/2/), 72 bytes ``` lambda s:''.join((-~i*(w+w[-2:0:-1]))[i]for i,w in enumerate(s.split())) ``` [Try it online!](https://tio.run/##bZCxTsNADIb3PIUjhtwBqaBjJIY@QZegDqWDIU5ybWKfchedsvDq4Q5R6IDlzZ8@@7ddfC@8XduXt3XA8b1BcFVRbM5iWKny09yr8BCO5bZ6qsrnk9ZHc2plAvMYwDAQzyNN6Em5jbOD8UprvdrJsIdWFXVvHMRGaGcGj@6SF/oOaodznv1Se/4geLXCsIPajJSQWHu7o@xGRRNBwCQbkX8YqBHxDzr0EocNRSYtu0IHxMutCf23iAl9fmWSKfvn8EG4A@fjoAMv0JgYExfoJYDvCTrilD99xIGbrRVHTQKDTHE/RHlM27Es4sVYkfUL "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` #vyN©Fû}®è? ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fuazS79BKt8O7aw@tO7zC/v//kIzMYgUgSlTIyc9LVyguKcoEUiX5CimZxQU5iZUKGfnlCiUZqQrpqXmpRYkl@UUg1cWlBQX5xakpIIXl@UXZAA "05AB1E – Try It Online") **Explanation** ``` # # split input on spaces vy # for each word in input N©F # N times do, where N is the current iteration û} # palendromize the word ®è # use N to index into the resulting word ? # print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ḲJị"ŒBṖȯ$€$Ɗ ``` [Try it online!](https://tio.run/##y0rNyan8///hjk1eD3d3Kx2d5PRw57QT61UeNa1ROdb1////kIzMYgUgSlTIyc9LVyguKcoEUiX5CimZxQU5iZUKGfnlCiUZqQrpqXmpRYkl@UUg1cWlBQX5xakpIIXl@UXZAA "Jelly – Try It Online") [Answer] # Java 10, ~~148~~ ~~117~~ ~~114~~ 110 bytes ``` s->{int i=-1,j;for(var a:s.split(" "))System.out.print(a.charAt((j=a.length()-1)>0*i++?i/j%2<1?i%j:j-i%j:0));} ``` -31 bytes thanks to *@SamYonnou* by creating a port of [*@user71546*'s JavaScript answer](https://codegolf.stackexchange.com/a/165808/52210). -4 bytes thanks to *@SamYonnou* again, optimizing the algorithm for Java. [Try it online.](https://tio.run/##hVJNTwIxEL37KwYSk1bdRTyyouHgUT2I8WA8jLsD22Vpm3YWJIbfjt0PFdHEpm3SZl7f67xX4AqjIlvs0hK9h1tU@v0IQGkmN8OU4K4@AqyMyiAVD@yUnoOXSbjdhhWmZ2SVwh1oGMPOR1fvAQ1qHA3PimRmnFihAxz52NtSsehDX8qHjWdaxqbi2IYXWWCc5ugmLEQxxrgkPedcyGgor85P1OnptRoUxxeXw2t1XIyKqN7PpUy2u6TVYKvXMmjopDRil@Ernd7nF0DZ/oPJBwnTXHkIE2FWaWD0i15fJgCDAdy8WUqZshFMPVa9PdC9Du14tEbDBKZqSQ0CDkD3dkI/iMgRrLGmWqL@hBwQIeIe5ik3oTajAKmV/Y15Qlz84EFuaDQh974gv3j@7EFpaktbZ9lApoJRuIHcrIFzgjlpcsjG1dW@stZ4yurCtXG1uiP4dxz2da7NxrBRlk2To@8UNdY1AruoKW0r7szTcSrac0t6mKJSiy6Y290H) **Explanation:** ``` s->{ // Method with String parameter and no return-type int i=-1, // Step integer, starting at -1 j; // Temp integer for(var a:s.split(" ")) // Loop over the parts split by spaces System.out.print( // Print: a.charAt((j=a.length()-1) // Set `j` to the the length of the part minus 1 >0 // If the length of the part is larger than 1 (`j` > 0) *i++? // (and increase `i` by 1 in the process with `i++`) i/j%2<1? // If `i` integer-divided by `j` is even: i%j // Print the character at index `i` modulo-`j` : // Else: j-i%j // Print the character at index `j` minus `i` modulo-`j` : // Else: 0));} // Print the first (and only) character // (the >0 check is added to prevent divided-by-0 errors) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` ⭆⪪S §⁺ι✂ι±²¦⁰±¹κ ``` [Try it online!](https://tio.run/##PYzBCsIwEETvfsXiaQsV1Ksnjz0ohfoDS7skoSEbkq3Vr4@pgrDMzgyPGS2lUciX0icXFAetz9wo4hC9U@xCXPRXYtPCHvZVr9qFiV/Y@yWja2HwbuTN3NmQMp4rc/ynU9PUPFe9lPKwLkM9Ai/BQP4ugwpMLkdPb7CygloGw4ETqaSNzkuMknnawFXSvCuHp/8A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` S Input string ⪪ Split on spaces ⭆ Map over words and join ι ι Current word ✂ ±²¦⁰±¹ Slice backwards from 2nd last character to start exclusive ⁺ Concatenate § κ Cyclically index on current word index Implicitly print ``` I don't often get to use Slice's last parameter. [Answer] # [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` éñ~╗D¡┤Gq ``` [Run and debug it](https://staxlang.xyz/#p=82a47ebb44adb44771&i=Once+Upon+A+Time%0AThere+was+a+man%0AWho+made+a+task%0AThat+was+neat%21%0AThis+is+a+long+string+to+display+how+the+generator+is+supposed+to+work&a=1&m=2) Unpacked, ungolfed, and commented, it looks like this. ``` j split into words { start block for mapping cDrD copy word; remove first and last character; reverse + concatenate with original word i@ modularly (wrap-around) index using map iteration index m perform map ``` [Run this one](https://staxlang.xyz/#c=j+++++%09split+into+words%0A%7B+++++%09start+block+for+mapping%0A++cDrD%09copy+word%3B+remove+first+and+last+character%3B+reverse%0A++%2B+++%09concatenate+with+original+word%0A++i%40++%09modularly+%28wrap-around%29+index+using+map+iteration+index%0Am+++++%09perform+map&i=Once+Upon+A+Time%0AThere+was+a+man%0AWho+made+a+task%0AThat+was+neat%21%0AThis+is+a+long+string+to+display+how+the+generator+is+supposed+to+work&a=1&m=2) [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~78~~ ~~70~~ ~~69~~ 68 bytes -1 byte @Arnauld ``` x=>x.split` `.map((y,i)=>y[a=i%(l=y.length-1)|0,i/l&1?l-a:a]).join`` ``` [Try it online!](https://tio.run/##ddDBasMwDAbg@55CLWwk0HjrdSUde4JdMnYYg4hEid06krHdpYG9e@YUdhktCHTQxy@hA35jaLxxsWBpae7K@Vzuzyo4a2INtRrQZdm0MXm5nz6xNPeZLSdlifuoi23@87Qxj/Zh@2ILfMavXB3EcF3Pu0Y4iCVlpc@6bF1pEyAVQndiiBiOq3We7@7@uzduCN6dMLxCZQa6iipNnmDEJW5Avmo@tKRZS4ks227kYLzEMGFc3SB/d1vhHkL0JrUo0Jr0IpxAywhRE/TE5DGKX3Q4OSeB2gWO4i/b518 "JavaScript (Node.js) – Try It Online") **Explanation** ``` x=> x.split` ` // Split the words by spaces .map((y,i)=> // For each word: y[ // Get the character at index: // A walk has cycle of length (2 * y.length - 2) a=i%(l=y.length-1)|0, // Calculate index a = i % (y.length - 1) i/l&1 // Check in which half the index i in ?l-a // If in the second half of cycle, use y.length - 1 - a :a // If in the first half of cycle, use a ] ).join`` // Join back the letters ``` [Answer] # [Red](http://www.red-lang.org), 135 bytes ``` func[s][n: 0 p: copy""foreach w split s" "[append/dup r: copy""append w reverse copy/part next w back tail w n: n + 1 append p r/(n)]p] ``` [Try it online!](https://tio.run/##VZDBTsMwEETv/YppTiAOgWtufAESCuIQ5bDEm9hKul7ZDqFC/fbgFIpaaQ@reTPjlQOb9ZVN0@76au1n6ZrYNlLhEVqh83osit4Hps5iQdTJJcQCRUOqLKY0syJcjL8all3gTw6Rz3KpFBKEv1Iu@KBuRCI35T0/InjAE/5iuai8k/tW21WDk4Qe37V1EXkI@bQcjOP@tPunL9Ix3tQLnlG7A1@h2nJgLLRFDyRX5N36rBjOYOu7yVA6R4Qp7W/A5YrJy4CYMhiQPIzLP0JHWL8gWcbAwoGSD5s7zqo@stmMiw/jaf0B "Red – Try It Online") ## Readable: ``` f: func[s][ n: 0 p: copy "" foreach w split s " "[ r: copy "" append/dup r append w reverse copy/part next w back tail w n: n + 1 append p r/(n) ] p ] ``` [Answer] # [Perl 5](https://www.perl.org/), 76 bytes ``` print map{$l=length;substr$_.reverse,$i++%(2*$l-2||1)*(1+1/$l),1}split" ",<> ``` [Try it online!](https://tio.run/##FczLCsIwEIXhVxlKhN5UUnDl5SncS6RDExyTMJNaxPrsMcKBf/NxIjIdco7sfIKniR9FZ0I/JXuU@S6J1W3H@EIW7JXruk09tIq2w7rqpq11p/eKml5/JZJLFVT96ZLz1TqBMgMU/ATlxZWkAKMrzrzBhgWSRZjQI5sU@K9ljjEIjn@4BH78AA "Perl 5 – Try It Online") [Answer] # [k](https://en.wikipedia.org/wiki/K_(programming_language)), ~~31~~ ~~30~~ 28 bytes ``` {x{*|y#x,1_|1_x}'1+!#x}@" "\ ``` [Try it online!](https://tio.run/##NYzLCoMwEEV/ZYwL@1y4bTftF3Rj6aYgQx0bUTMhiRhRv91GoTBwL4dzpz5zvSzlZfTjYRpif0rzKc39nKTHKPbzTYB4L2WyE5msLIRDKDsFDm0diat4qA/BU7OCO2RVSwFlkgxBj6vaogrkJTm0ggJYd5uDblMUoYs28P/esPqCdaYK4RiKyuoGB5Dcg5MEX1Jk0LFZbdtpzZaKVezZ1GK//AA "K (oK) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~14~~ 11 bytes ``` SzS!ö!…¢ŀŀw ``` [Try it online!](https://tio.run/##RYyxDcIwFER7T/E9ChNQJIj6i3xiy4m/ZTuyoAqMQsEIGSAoi2QRY9MgnXQ63btTUzB53J@PdcnNvZGfRe7ze31t8zannHOrdIAihOtkIWIwUhztheDk2MIBWj2SaBV5goQVG9GKs@LiHZVYF6XH@KstYZTi/zmw7SFEr4tFhk4HN@ANFCeIiqAnSx4j@0qHyTkO1FUwsTdf "Husk – Try It Online") Inspiration was taken from [this program](https://codegolf.stackexchange.com/a/174140) by Zgarb for the forward-and-reverse stepping. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes ``` s.e@+b_Ptbkc ``` [Try it online](https://pyth.herokuapp.com/?code=s.e%40%2Bb_Ptbkc&test_suite=1&test_suite_input=%22This%20is%20a%20fun%20task%21%22%0A%22Once%20Upon%20A%20Time%22%0A%22There%20was%20a%20man%22%0A%22Who%20made%20a%20task%22%0A%22That%20was%20neat%21%22%0A%22This%20is%20a%20long%20string%20to%20display%20how%20the%20generator%20is%20supposed%20to%20work%22&debug=0) ``` s.e@+b_PtbkcQ Final Q (input) implicit cQ Split on spaces .e Map the above with b=element, k=index Ptb Remove 1st and last character _ Reverse +b Prepend the unaltered element ('abcd' -> 'abcdcb') @ k Get the kth character (0 indexed, wrapping) s Join on empty string, implicit output ``` [Answer] # Japt, `-P`, 11 bytes ``` ¸Ëê ŪD gEÉ ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=uMvqIMWqRCBnRck=&input=IlRoaXMgaXMgYSBsb25nIHN0cmluZyB0byBkaXNwbGF5IGhvdyB0aGUgZ2VuZXJhdG9yIGlzIHN1cHBvc2VkIHRvIHdvcmsiCi1Q) ``` ¸Ë+s1J w)gE ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=uMsrczFKIHcpZ0U=&input=IlRoaXMgaXMgYSBsb25nIHN0cmluZyB0byBkaXNwbGF5IGhvdyB0aGUgZ2VuZXJhdG9yIGlzIHN1cHBvc2VkIHRvIHdvcmsiCi1Q) --- ## Explanations ``` ¸Ëê ŪD gEÉ ¸ :Split on spaces Ë :Map over each element D at index E ê : Palindromise Å : Slice off the first character ªD : Logical OR with the original element (the above will return an empty string for single character words) g : Get the character at index EÉ : E-1 ``` ``` ¸Ë+s1J w)gE ¸ :Split on spaces Ë :Map over each element D at index E s1J : Slice off the first and last characters w : Reverse + ) : Append to D gE : Get the character at index E ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 148 bytes (string version), 114 bytes (print version) If I must return a string (long version): ``` char c[99]={0};char*f(s,t,u,i,j,k)char*s,*t,*u;{for(u=c,i=0;t=strtok(s," ");s=0,i++)*u++=t[j=strlen(t),k=2*j-(j>1)-1,(i%k<j?i%k:k-i%k)%j];return c;} ``` [Try it online!](https://tio.run/##TU/LboMwELzzFatUkWxjqtBb4jj9id4QB2QcMFAb2etEFeLbqUkvlVajnYdGu6rolNrejFVTbDVcA7bGvfe37L/kje2Stqm@8aCq87mWy2kVO2V3EjjyyA0f@EhfUuAMOYtiuTtPolTcyJNAmXrQjSl@gAMVQZ64yXPKYp5LrIbdnrQlSPkoP9hQkOFW0qLkxBzH6/CZ8DIWCelxqIXXGL0FJdbNWITvxliyL43vFH@dyVjaHxSWDMDcyW6kPpgjBvKij6qsKRXZum1fvQmQpoHJ2Q7@HgZ00JowT80P9O4J2GvotNW@Qef3dIjz7IJu9@DT@fEX "C (gcc) – Try It Online") Otherwise, I just print and don't worry about a buffer (short version): ``` f(s,t,i,j,k)char*s,*t;{for(i=0;t=strtok(s," ");s=0,i++)putchar(t[j=strlen(t),k=2*j-(j>1)-1,(i%k<j?i%k:k-i%k)%j]);} ``` [Try it online!](https://tio.run/##TY/BasMwEETv/oolJSApcol7jOP0J3oLPQhZtldyJSOtE0rIt7tSeykswzD7dmB1PWq9vaDX89obOCfqMbxOl@p/FNGPOdsGliRJlFY6ricVRZKC2scQIsPu2FKXUQouUzvY8TZ1R4mHA19WKjSjqy3EbDwjLl33JmzN7KXhdSMZ7t3Zvmc9uTor39tP3j439ARfCj0rRsVRy1IFQmR/4/CoAHBgZZF74Nfdrk0@rZ7b9jFhgjwK5uBH@HsEKECPaZnVN0zhDjQZGI03UVGIhU7rsoRk@gLeQ3Q/ "C (gcc) – Try It Online") [Answer] # AWK, 79 bytes Mostly because I'm curious to see any better awk or bash solutions! ``` {for(i=1;i<=NF;i++){l=length($i);k=int(i/l)%2?l-i%l:k%l;printf substr($i,k,1)}} ``` [Try it online!](https://tio.run/##FcrBCsMgEATQX9lDA5GklPRYK7n12FN/wBITFxdX1BBKyLdbAwMDM09vrpR95tiiGiQ@1fslsevEToqMX7JtLyikU@hzizcSzX2kKzb0cA3JEOs8Q1q/KccKe9cP4jhK@VhMUKOB2C9QX6yVGSZMgfQPLG@QrYHFeBN15njqtIbAyUwn3Di6Pw "AWK – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 111 bytes ``` s=>{int i=-1,j;return String.Concat(s.Split(' ').Select(a=>a[++i>(j=a.Length-1)?j>0?i/j%2<1?i%j:j-i%j:0:i]));}; ``` [Try it online!](https://tio.run/##fdFBa8IwFAfws/0UT0Fs0Xa6o7WVMdjJsYEOD@Lh0T7bdG3SJa8TET9711oGO0whJCT88k9eEhk3UprqygiZwPpkmArf@jvzVkJ@@VaUozHwrlWisYCz1TOMLCL4ViKGVxTSNqybXbs9oE6M05KXSkaLbnkC3RjCAQLo1SYIz0IyiMCdTTJfE1dawvpqvGclI2TbeOsyF2yPYOR4a8opYhuDEHfjsQjtLEBvRTLh1J05yyycLsVDNnxczJZimM0zt@2nc7F3HP/i102kUTl5Wy2YmorIPtiDTSoMNA3hUElgNJ/9QcOtf/GbjAg@SiXhCTaioNtyk5ImOGIbXKC8DbepakBMjWsPv5eIfA2UhNy/534LylXzgd2TAyuIhSlzPEGqjsApQUKSNLLSrTZVWSpDcQuPSnf3sHoX61L/AA "C# (.NET Core) – Try It Online") [Answer] ## Haskell, ~~65~~ ~~62~~ 61 bytes ``` zipWith(\i->(!!i).cycle.(id<>reverse.drop 1.init))[0..].words ``` [Try it online!](https://tio.run/##FYyxTsNADEB3vsKtGJKhJ9hpJ0a2VmKgDKecc7F6OVu2QxU@niOVnvSWpzdFu2EpjWZhdXiPHsMZZ8rKizyNcLy2X5JP8qm70uHU7XbUh2EdCoaO0ttJ8QfVMCRlgddAlbzvv15C@A531mRtjlThCLL42fWjwjOMsL9MZLARoXDNYK60yRkSmZS4wsR38AkhY0WNzvqobRFhw/QIt/lt39rFYq68sjOJ898wlpitHQaRfw "Haskell – Try It Online") It requires the latest version of `Prelude` which features the `<>` function. ``` words -- split the input string into a list of words zipWith(\i-> )[0..] -- zip the elements i of [0..] and the words pairwise -- with the function ... <> ... -- call the functions with a word and concatenate -- the results. The functions are id -- id: do nothing reverse.drop 1.init -- drop last and first element and reverse cycle -- repeat infinitely (!!i) -- take the ith elemnt of ``` Edit: -3 bytes thanks to @user28667, -1 byte thanks to @B. Mehta [Answer] # [PHP](https://php.net/), 77 bytes ``` while(ord($w=$argv[++$i]))echo($w.=strrev(substr($w,1,-1)))[~-$i%strlen($w)]; ``` [Try it online!](https://tio.run/##FYrBCsMgEER/xkIkSSHnNs1P9BZysHVRqbiymkgv/fXtBoaZ4c1kn/m@ZPHmQ4QOyXaqzcqQO9a@V2HTGt4eBV7nUong6Mr@kiZkmIZx0lqvv1GFi7AISbDebrw8mJ8@FBYZjpgcyx4kKrINJUfzZY@Nqwd2kIBMRTrfZc8ZC9jz2JA@fw "PHP – Try It Online") * -3 bytes thanks to Kevin * -10 bytes thanks to Titus [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` ⌈₅(ʁ):ẏ¨£i∑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLijIjigoUoyoEpOuG6j8KowqNp4oiRIiwiIiwiVGhpcyBpcyBhIGZ1biB0YXNrISJd) ``` ⌈ # Input split on spaces ₅( ) # repeat len(that) times... ʁ # Palindromise each word ¨£ # Zipping... : # Words ẏ # range(0, len(words)) i # Index the numbers into the words ∑ # Stringify ``` [Answer] # Powershell ~~208~~ ~~186~~ 170 bytes ``` $args|%{$i=0;-join($_.Split()|%{$l=($b=($a=$_)).Length;if($l-gt2){$b=($a|%{-join$a[($l-2)..1]})}for($j=0;$a.Length-le$i;$j++){$a+=($b,$_)[$j%2]}$a.Substring($i,1);$i++})} ``` Ungolfed: ``` $args|%{ $i=0; -join($_.Split()|%{ $l=($b=($a=$_)).Length; if($l-gt2){ $b=($a|%{-join$a[($l-2)..1]}) } for($j=0;$a.Length-le$i;$j++){ $a+=($b,$_)[$j%2] } $a.Substring($i,1); $i++ }) } ``` Test cases below or [try it online](https://tio.run/##TY7BasMwDIZfRQsqxKQJa66hh94HO7Rjh1KKuqiJU9cOtkMYXZ49s9MdBjKIX9//4d6MbF3LSs0zkm3cz@qBcvta5Z2ROsVzse@V9KmIudqmeAmPtngWonhj3fi2ktcUVd74Ujye14AubaRjvJSiKDanSUxXY1Psghvpr5srRllhl2WhS1nUr4P6iN2qPE0B2w8X563UTYpyvREVyiwLpnmek0MrHYQhuA4aPLnbSzIn7/qL4aM3GnZwkHdOIsiWYaSI3kmH5LM1Yas5BLG3MOQXRDP55L9cGd3A8w/gDdTS9Yq@oTUj@JahYc2WvLGRdkPfG8d1BEdjb8kv) ``` @( "This is a fun task!", "Once Upon A Time", "There was a man", "Who made a task", "That was neat", "This is a long string to display how the generator is supposed to work" )|%{$i=0;-join($_.Split()|%{$l=($b=($a=$_)).Length;if($l-gt2){$b=($a|%{-join$a[($l-2)..1]})}for($j=0;$a.Length-le$i;$j++){$a+=($b,$_)[$j%2]}$a.Substring($i,1);$i++})} ``` [Answer] # J, 43 bytes ``` [:(>{~"_1#@>|i.@#)[:(,}.@}:)&.>[:<;._1' '&, ``` ## ungolfed ``` [: (> {~"_1 #@> | i.@#) [: (, }.@}:)&.> [: <;._1 ' '&, ``` * `<;._1 ' '&,` split on spaces * `(, }.@}:)&.>` for each word, kill the first and last elm and append to word * `#@> | i.@#` take the remainder of each word's length divided into its index * `> {~"_1` take that result and pluck it from each word. [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6007KrrlOINlR3sajL1HJQ1gSI6tXoOtVaaanp20VY21nrxhuoK6mo6/zW5uFKTM/IV0hTUQzIyixWAKFEhrTRPoSSxOFtRHS7pn5ecqhBakJ@n4KgQkpmbqo6kLbUoVaE8EaQxNzFP/T8A "J – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), 22 bytes ``` qS/{_);1>W%+T_):T@*=}% ``` [Try it online!](https://tio.run/##FcqxCsIwEIDhVzmHDtWCuCqKo7uFjiVNr3j1cqdJahDx2aNZ/@@3s3E5P6/bT18fdqeu2rR9vW/P6@O3yvmiqQGPhvndQCJmUB4hoJB6mJTvoeR4Ax1mtJFUzMAIViV6faEPhP9jWpBBTOFEIwK5R1GHElc/ "CJam – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) `-pl`, 60 bytes ``` gsub(/(\S+) ?/){w=$1+$1.reverse[1..-2] w[(-2+$.+=1)%w.size]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnm0km5BjlLsgqWlJWm6Fjdt0otLkzT0NWKCtTUV7PU1q8ttVQy1VQz1ilLLUouKU6MN9fR0jWK5yqM1dI20VfS0bQ01Vcv1ijOrUmNrIWZAjVpw0y0kI7NYAYgSFXLy89IVikuKMoFUSb5CSmZxQU5ipUJGfrlCSUaqQnpqXmpRYkl-EUh1cWlBQX5xagpIYXl-UTbEOAA) ]
[Question] [ ## Task Given two positive integers, output the number of carries needed to add them together in long addition in base 10. ## Examples ``` ¹¹¹ <-- carries 999 + 1 ---- 1000 ``` Three carries are needed. ``` ¹ 348 + 91 ---- 439 ``` One carry is needed. ## Testcases ``` 999, 1 -> 3 398, 91 -> 1 348, 51 -> 0 348, 52 -> 2 5, 15 -> 1 999, 999 -> 3 505, 505 -> 2 ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. [Answer] # Mathematica, ~~46~~ 39 bytes ``` x=Tr@*IntegerDigits;(x@#+x@#2-x@+##)/9& ``` **input** > > [348,51] > > > *-7 bytes from JungHwan* [Answer] # JavaScript (ES6), 50 bytes ~~Fixed~~ Stolen from [ovs' solution](https://codegolf.stackexchange.com/a/125829/39244) ``` f=(a,b,c=0)=>a|b|c&&c+f(a/10,b/10,a%10+b%10+c>=10) ``` ### Explanation ``` f=(a,b,c=0)=> Function taking two numbers and optional carry a|b|c If a number or the carry are nonzero && Then c+f(a/10,b/10,a%10+b%10+c>=10) Return carry plus all other carries ``` ### Carry explanation ``` a%10+b%10+c Sum of mod 10 of the numbers and c - remember these are not floordiv'ed >=10 Greater than or equals to 10 (we can't use greater than 9 here) ``` ``` f=(a,b,c=0)=>a|b|c&&c+f(a/10,b/10,a%10+b%10+c>=10) console.log([[999,1],[398,91],[348,51],[348,52],[5,15],[999,999],[256,64],[190192,90909]].map(test=>`${(test[0]+'').padStart(6,' ')}, ${(test[1]+'').padStart(6,' ')} -> ${f(...test)}`).join('\n')); ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 65 bytes ``` i,l;f(a,b){for(i=l=0;a+b;a/=10,b/=10)i+=a%10+b%10+l>9?l=1:0;a=i;} ``` [Try it online!](https://tio.run/##VYxRCsIwEESvIoVClqyYqIWuYfUsSSSyEFsp/hXPHhMURJgZ3sdj4vYWYymC2SXlMcCa5kUJZzbO6@D8jq3B0BZEs@@t0aFNPtMlsz1VjcW9yt3LpGB9LDI9k@r66@Y/HSZFRGihwoFGpA8dRxx@tG80oB3gq9cC1Ps3 "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13 12 11~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte by porting [Jenny\_mathy's Mathematic answer](https://codegolf.stackexchange.com/a/125834/53748). -2 more bytes by better golfing :p ``` ;SN$DFS:9 ``` **[See the test suite](https://tio.run/##y0rNyan8/9862E/FxS3YyvL/0T2H2x81rfn/Pzra0tJSxzBWJ9rY0kLHEswwsdAxhTOMgAxTHUNTIAVSCcQgAQNTHSAGsgwtDQwtjXQsDYAwNhYA)**. ### How? ``` ;SN$DFS:9 - Main link: list of numbers, [a,b] e.g. [348,53] $ - last two links as a monad S - sum 401 N - negate -401 ; - concatenate [348,53,-401] D - convert to decimal lists [[3,4,8],[5,3],[-4,0,-1]] F - flatten [3,4,8,5,3,-4,0,-1] S - sum 18 :9 - integer divide by nine 2 ``` --- My 12 byte solution... ``` :⁵+ DUSç\>9S ``` A monadic link taking a pair of integers and returning the number of carries as an integer. ~~*There is probably a shorter way though!*~~ There was! **[Try it online!](https://tio.run/##y0rNyan8/9/qUeNWbS6X0ODDy2PsLIP///8fbWhpYGhppGNpAISxAA "Jelly – Try It Online")** or see the [test suite](https://tio.run/##y0rNyan8/9/qUeNWbS6X0ODDy2PsLIP/H91zuP1R05r//6OjLS0tdQxjdaKNLS10LMEMEwsdUzjDCMgw1TE0BVIglUAMEjAw1QFiIMvQ0sDQ0kjH0gAIY2MB). ### How ``` :⁵+ · Link 1: perform a carry: right-column's-digit-sum, a; left-colum's-digit-sum; b ⁵ · literal 10 : · a integer-divided by 10 - the carry amount + · add to b DUSç\>9S · Main link: list of summands e.g. [348,52] D · convert to decimal lists [[3,4,8],[5,2]] U · upend (reverse each) [[8,4,3],[2,5]] S · sum (add the digits up) [10,9,3] \ · cumulative reduce with: ç · last link (1) as a dyad [10,10,4] 9 · literal 9 > · greater than? [ 1, 1,0] S · sum 2 ``` [Answer] # [Python](https://docs.python.org/2/), 48 bytes ``` f=lambda a,b,m=1:m<1e99and(~a%m<b%m)+f(a,b,m*10) ``` [Try it online!](https://tio.run/##Tc3BCoMwDADQ@74iFzFx3bBuwiK6Hxk7VLRMWKu4Xoa4X@9ad1kC4YUkZHq7x2gL73XzVKbtFCjRCtPIytSyZ1a2w49KTN0mhvYat2kmc/J6nMH1LweDhRsyswBJAvDEFwH84zmw/GMRWYbFMmK7CSVaci65CG0eku7VDkJM82AdpssKhyssa3oMP41yGN8K0JhFEJH/Ag "Python 2 – Try It Online") For each place value `m=1, 10, 100, ..., 10**99`, checks if there is a carry at that place value. The overflow check `a%m+b%m>=m` is shortened to `~a%m<b%m`. A nicer [45-byte variant](https://tio.run/##Tc3BCsIwDAbgu0@Ry1hrq66bAzPYXkQ8pMziwHVj9iJjz15TvZhA@AIJ//wOj8lXMbr2SaPtCUjbhpQF8r2gzCibma41UjlBJ1Noy0NGNy0Q7q8Ag4erQEQNRmoQFV404I9nZv3HMrHmwzrh@8Mj2WBhsOS14Ja3Zgdc8zL4IPJ1g0MH65YfOXOkIFKsBif2CVLK@AE) where floats `a` and `b` shifted down instead ``` f=lambda a,b:a+b and(a%1+b%1>=1)+f(a/10,b/10) ``` sadly runs into float precision issues. [Answer] ## JavaScript (ES6), ~~53~~ 45 bytes ``` f=(a,b,d=1)=>a+b<d?0:(a%d+b%d>=d)+f(a,b,d*10) ``` Saved 1 byte by adding an extra do-nothing iteration for carries into 1's place. Saved 7 bytes by appropriating @xnor's carry check. I also had a more elegant 45-byte version but it suffers from floating-point inaccuracy; it would work great translated to a language with exact decimal arithmetic: ``` f=(a,b,c=a+b)=>c<1?0:a%1+b%1-c%1+f(a/10,b/10) ``` [Answer] # [Python 2](https://docs.python.org/2/), 55 bytes ``` f=lambda a,b,c=0:c+a+b and c+f(a/10,b/10,a%10+b%10+c>9) ``` [Try it online!](https://tio.run/##Tc3BCsIwDAbgu0@Ri6y1VdvpwAy2FxEPaWdx4Loxe5GxZ6@tXkzg5wskZHqHx@jLGF3zpMF0BCSNtI2qrSBhgHwHVjhGR62kyUFbrYTJYVvk0Y0zhPsrQO/hyhBRguYS2AkvEvDHc2L1xzKzSotVxvcmRbZGpbFMo0rNb/UGUk1z7wMrlhX2LSxrcUg/Bwosv5Xg2C6Dcx4/ "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 10 bytes ``` |DO‚€SOÆ9÷ ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/xsX/UcOsR01rgv0Pt1ke3v7/v6GlgaGlEZelARACAA "05AB1E – Try It Online") [Answer] # [Neim](https://github.com/okx-code/Neim), 10 bytes ``` 𝔸𝐣𝐬₁₂𝔻𝐬𝕊λ𝕍 ``` Explanation: ``` 𝔸 𝔸ppend the two inputs into a list 𝐣 𝐣oin them together 𝐬 𝐬um the characters ₁₂ Push the first input, then the second 𝔻 A𝔻d. 𝐬 𝐬um the characters 𝕊 𝕊ubtract 𝕍 Integer di𝕍ision by λ nine (variable) ``` [Try it!](http://178.62.56.56:80/neim?code=%F0%9D%94%B8%F0%9D%90%A3%F0%9D%90%AC%E2%82%81%E2%82%82%F0%9D%94%BB%F0%9D%90%AC%F0%9D%95%8A%CE%BB%F0%9D%95%8D&input=190192%0A90909) Alternative solution, also 10 bytes: ``` 𝔸D𝐣𝐬S𝐬𝐬𝕊9𝕍 ``` Explanation: ``` 𝔸 𝔸ppend the two inputs into a list D Duplicate 𝐣 𝐣oin 𝐬 𝐬um S Swap 𝐬 𝐬um 𝐬 𝐬um the characters 𝕊 𝕊ubtract 𝕍 integer di𝕍ide by λ nine (variable) ``` [Try it!](http://178.62.56.56:80/neim?code=%F0%9D%94%B8D%F0%9D%90%A3%F0%9D%90%ACS%F0%9D%90%AC%F0%9D%90%AC%F0%9D%95%8A%CE%BB%F0%9D%95%8D&input=190192%0A90909) [Answer] # PHP>=7.1, 81 Bytes ``` for([,$x,$y]=$argv,$i=1;($x+$y)/$i|0;$i*=10)$d+=$c=$x/$i%10+$y/$i%10+$c>9;echo$d; ``` -2 Bytes removing `|0` In this case the loop runs until `$i` is `INF` [Test Cases](http://sandbox.onlinephpfunctions.com/code/d47c0f55e9fbbc6779bc835f88ed1061292d5dd4) [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), 20 bytes ``` VR{.M}d<d&+v+d&+c-9/ ``` [Try it online!](https://tio.run/##SypKzMxLz89J@/8/LKhaz7c2xSZFTbtMG0gk61rq////39DSwNDS6L@lARB@zcvXTU5MzkgFAA "Braingolf – Try It Online") Uses the same method as everyone else. Could've saved a byte or 2 had I had the foresight to allow `d` to use the greedy modifier, then I could've replaced `d<d` with `&d` ah well, next time. ## Explanation ``` VR{.M}d<d&+v+d&+c-9/ Implicit input from commandline args VR Create stack2 and return to stack1 {..} Foreach loop, runs on each item in stack1 .M Duplicate and move duplicate to stack2 d<d Split both items on stack into digits &+ Sum entire stack v+ Switch to stack2 and sum last 2 items on stack d&+ Split result into digits and sum all digits c Collapse stack2 into stack1 - Subtract last item from 2nd to last 9/ Divide by 9 Implicit output of last item on stack ``` ]
[Question] [ A list of positive integers can be visualized as a quantized mountain range where each list entry represents the height of one vertical section of the mountains. For example, the list ``` 1, 2, 2, 3, 4, 3, 5, 3, 2, 1, 2, 3, 3, 3, 2, 2, 1, 3 ``` can become the range ``` x x x xxxxx xxx x xxxxxxxx xxxxxx x xxxxxxxxxxxxxxxxxx ``` (Less poetic people might call this a bar chart, but I digress.) The question in this challenge is: **How many peaks are in the mountain range of some arbitrary list?** Essentially, how many [local maxima](https://en.wikipedia.org/wiki/Maxima_and_minima) are in the list? A peak is defined as a contiguous section of one or more columns of the mountain range that are all equal in height, where the columns immediately to the left and the right are lower in height. It's easy to visually tell that the example has four peaks at these parenthesized locations: ``` 1, 2, 2, 3, (4), 3, (5), 3, 2, 1, 2, (3, 3, 3), 2, 2, 1, (3) ``` Note how the `(3, 3, 3)` plateau section counts as a peak because it is a contiguous set of columns equal in height, higher than its neighboring columns. The last `(3)` counts as a peak as well because, for the purposes of this challenge, **we'll define the left neighbor of the leftmost column and the right neighbor of the rightmost column to both be height zero.** This means that a list with only one value, for example `1, 1, 1`, can be interpreted as `0, 1, 1, 1, 0`, and thus has one peak, not none: `0, (1, 1, 1), 0`. The only list with zero peaks is the empty list. # Challenge Write a function or program that takes in an arbitrary list of positive integers and prints or returns the number of peaks in the corresponding mountain range. **The shortest code in bytes wins.** Tiebreaker is earlier post. # Test Cases ``` Input List -> Output Peak Count ``` ``` [empty list] -> 0 1, 1, 1 -> 1 1, 2, 2, 3, 4, 3, 5, 3, 2, 1, 2, 3, 3, 3, 2, 2, 1, 3 -> 4 1 -> 1 1, 1 -> 1 2, 2, 2, 2, 2 -> 1 90 -> 1 2, 1, 2 -> 2 5, 2, 5, 2, 5 -> 3 2, 5, 2, 5, 2, 5, 2 -> 3 1, 2, 3, 4 -> 1 1, 2, 3, 4, 1, 2 -> 2 1, 3, 5, 3, 1 -> 1 7, 4, 2, 1, 2, 3, 7 -> 2 7, 4, 2, 1, 2, 1, 2, 3, 7 -> 3 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 -> 10 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1 -> 10 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 -> 10 1, 3, 3, 3, 1, 3, 3, 1, 3, 1, 3, 3, 3, 3, 1 -> 4 12, 1, 2, 1, 2, 3, 3, 3, 2, 4, 4, 4, 1, 5, 5, 4, 7, 9 -> 6 87, 356, 37673, 3676, 386, 909, 909, 909, 909, 454, 909, 909 -> 3 87, 356, 37673, 3676, 386, 909, 909, 909, 909, 454, 909, 908, 909 -> 4 ``` [Answer] ## CJam (32 26 24 21 bytes) ``` 0q~0]e`1f=2ew::>2,/,( ``` Expected input is space-separated numbers. [Online demo](http://cjam.tryitonline.net/#code=MHF-MF1lYDFmPTJldzo6PjIsLywo&input=MSAyIDIgMyA0IDMgNSAzIDIgMSAyIDMgMyAzIDIgMiAxIDM) ; [full test suite](http://cjam.tryitonline.net/#code=cU4veycsLSItPiIvfjpFOzpROwoKMFF-MF1lYDFmPTJldzo6PjIsLywoCgpFfj1vfS8&input=IC0-IDAKMSwgMSwgMSAtPiAxCjEsIDIsIDIsIDMsIDQsIDMsIDUsIDMsIDIsIDEsIDIsIDMsIDMsIDMsIDIsIDIsIDEsIDMgLT4gNAoxIC0-IDEKMSwgMSAtPiAxCjIsIDIsIDIsIDIsIDIgLT4gMQo5MCAtPiAxCjIsIDEsIDIgLT4gMgo1LCAyLCA1LCAyLCA1IC0-IDMKMiwgNSwgMiwgNSwgMiwgNSwgMiAtPiAzCjEsIDIsIDMsIDQgLT4gMQoxLCAyLCAzLCA0LCAxLCAyIC0-IDIKMSwgMywgNSwgMywgMSAtPiAxCjcsIDQsIDIsIDEsIDIsIDMsIDcgLT4gMgo3LCA0LCAyLCAxLCAyLCAxLCAyLCAzLCA3IC0-IDMKMSwgMiwgMSwgMiwgMSwgMiwgMSwgMiwgMSwgMiwgMSwgMiwgMSwgMiwgMSwgMiwgMSwgMiwgMSwgMiAtPiAxMAoxLCAyLCAxLCAyLCAxLCAyLCAxLCAyLCAxLCAyLCAxLCAyLCAxLCAyLCAxLCAyLCAxLCAyLCAxLCAyLCAxIC0-IDEwCjIsIDEsIDIsIDEsIDIsIDEsIDIsIDEsIDIsIDEsIDIsIDEsIDIsIDEsIDIsIDEsIDIsIDEsIDIgLT4gMTAKMSwgMywgMywgMywgMSwgMywgMywgMSwgMywgMSwgMywgMywgMywgMywgMSAtPiA0CjEyLCAxLCAyLCAxLCAyLCAzLCAzLCAzLCAyLCA0LCA0LCA0LCAxLCA1LCA1LCA0LCA3LCA5IC0-IDYKODcsIDM1NiwgMzc2NzMsIDM2NzYsIDM4NiwgOTA5LCA5MDksIDkwOSwgOTA5LCA0NTQsIDkwOSwgOTA5IC0-IDMKODcsIDM1NiwgMzc2NzMsIDM2NzYsIDM4NiwgOTA5LCA5MDksIDkwOSwgOTA5LCA0NTQsIDkwOSwgOTA4LCA5MDkgLT4gNA) (expected output is a `1` per test case). Thanks to Martin for informing me that the current version of CJam improves one of the operators used, saving 2 chars; and for a further 3-char saving. ### Dissection Two phases: deduplicate, then identify local maxima in each set of three. ``` 0q~0] e# Put the input in an array wrapped in [0 ... 0] e`1f= e# Use run-length encoding to deduplicate 2ew::> e# Map [a b c ...] to [(a>b) (b>c) ...] 2,/ e# Split on [0 1], which since we've deduplicated occurs when (a<b) (b>c) ,( e# Count the parts and decrement to give the number of [0 1]s ``` [Answer] # JavaScript (ES6), ~~54~~ 51 bytes ``` m=>m.map(n=>{h=n<p?h&&!++r:n>p||h;p=n},r=h=p=0)|r+h ``` ## Explanation Takes an array of numbers ``` m=> m.map(n=>{ // for each number n in the mountain range h= n<p? // if the number is less than the previous number: h&& // if the previous number was greater than the number before it !++r // increment the number of peaks and set h to 0 :n>p||h; // if the number is greater than the previous number, set h to 1 p=n // set p to the current number }, r= // r = number of peaks h= // h = 1 if the previous number was higher than the one before it p=0 // p = previous number )|r+h // return the output (+ 1 if the last number was higher) ``` ## Test ``` var solution = m=>m.map(n=>{h=n<p?h&&!++r:n>p||h;p=n},r=h=p=0)|r+h ``` ``` Mountain Range (space-separated) = <input type="text" id="input" value="87 356 37673 3676 386 909 909 909 909 454 909 908 909" /> <button onclick="result.textContent=solution(input.value.split(' ').map(n=>+n))">Go</button> <pre id="result"></pre> ``` [Answer] ## Pyth, ~~25~~ 23 bytes ``` L._M-M.:b2s<R0y-y+Z+QZZ ``` Explanation: ``` L y = lambda b: ._M -M .: signs of subsets b of b 2 of length 2. That is, signs of differences. s <R number of elements less than 0 0 in y - y of ... with zeroes removed y + y of Z the input with zeroes tacked on both sides + Q Z Z ``` [Answer] # Julia, 66 ``` x->(y=diff([0;x;0]);y=y[y.!=0];sum((y[1:end-1].>0)&(y[2:end].<0))) ``` Pad, differentiate: `y=diff([0;x;0])`. Ignore the plateaus: `y=y[y.!=0]`. Count `+` to `-` zero crossings: `sum((y[1:end-1].>0)&(y[2:end].<0))`. [Answer] # MATLAB, ~~29~~ 27 bytes ``` @(a)nnz(findpeaks([0 a 0])) ``` Anonymous function which finds the peaks in the data and counts how many there are. 0 is prepended and appended to the data to ensure peaks at the very edges are detected as per the question. This will also work with **Octave**. You can [try online here](http://octave-online.net/). Simply paste the above code into the command line, and then run it with `ans([1,2,1,3,4,5,6,1])` (or whatever other input). --- As the numbers are always +ve, we can assume they are greater than zero, so can save 2 bytes by using `nnz` instead of `numel`. [Answer] # Python 3, 75 bytes ``` def m(t): a=p=d=0 for n in t+[0]:a+=(n<p)&d;d=((n==p)&d)+(n>p);p=n return a ``` This is my first codegolf so there may be some places to cut down on it, especially the `d=((n==p)&d)+(n>p)` part. However it works on all the test cases [Answer] # Mathematica, 42 36 33 32 bytes Thanks to Martin Büttner for saving 1 byte. ``` Tr@PeakDetect[#&@@@Split@#,0,0]& ``` `PeakDetect` just does almost everything! Test cases: ``` Total@PeakDetect[#&@@@Split@#,0,0]&@{12,1,2,1,2,3,3,3,2,4,4,4,1,5,5,4,7,9} (* 6 *) Total@PeakDetect[#&@@@Split@#,0,0]&@{87,356,37673,3676,386,909,909,909,909,454,909,908,909} (* 4 *) ``` [Answer] # Pyth, 18 bytes ``` su_>VGtG2eMr++ZQZ8 ``` Based on @PeterTaylor's repeated greater than solution, but with a twist. `++ZQZ`: Add zeros on both sides. `eMr ... 8`: Remove repeats. `u ... 2 ...`: Apply the following twice: `>VGTG`: Map each pair of numbers to whether they are in decreasing order. `_`: And reverse. A 1 in the output corresponds to a `1, 0` in prior step, which corresponds to `a < b > c` in the input due to the reversal. `s`: Sum (and print) [Answer] # CJam, ~~27~~ 26 bytes ``` A0q~0A]e`1f=3ew{~@e>>}%1e= ``` Uses the run length coding to remove duplicates. After that we check for every triplet if the middle one is the largest number. [Try it here!](http://cjam.aditsu.net/#code=0q~0%5De%60%7B~%5C%3B%7D%253ew%7B~%40e%3E%3E%7D%251e%3D&input=1%202%202%203%204%203%205%203%202%201%202%203%203%203%202%202%201%203%20) Passes [Peter Taylor's test suite](http://cjam.aditsu.net/#code=qN%2F%7B'%2C-%22-%3E%22%2F~%3AE%3B%3AQ%3B%0A%0AA0Q~0A%5De%60%7B~%5C%3B%7D%253ew%7B~%40e%3E%3E%7D%251e%3D%0A%0AE~%3Do%7D%2F&input=%20-%3E%200%0A1%2C%201%2C%201%20-%3E%201%0A1%2C%202%2C%202%2C%203%2C%204%2C%203%2C%205%2C%203%2C%202%2C%201%2C%202%2C%203%2C%203%2C%203%2C%202%2C%202%2C%201%2C%203%20-%3E%204%0A1%20-%3E%201%0A1%2C%201%20-%3E%201%0A2%2C%202%2C%202%2C%202%2C%202%20-%3E%201%0A90%20-%3E%201%0A2%2C%201%2C%202%20-%3E%202%0A5%2C%202%2C%205%2C%202%2C%205%20-%3E%203%0A2%2C%205%2C%202%2C%205%2C%202%2C%205%2C%202%20-%3E%203%0A1%2C%202%2C%203%2C%204%20-%3E%201%0A1%2C%202%2C%203%2C%204%2C%201%2C%202%20-%3E%202%0A1%2C%203%2C%205%2C%203%2C%201%20-%3E%201%0A7%2C%204%2C%202%2C%201%2C%202%2C%203%2C%207%20-%3E%202%0A7%2C%204%2C%202%2C%201%2C%202%2C%201%2C%202%2C%203%2C%207%20-%3E%203%0A1%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%20-%3E%2010%0A1%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%20-%3E%2010%0A2%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%2C%201%2C%202%20-%3E%2010%0A1%2C%203%2C%203%2C%203%2C%201%2C%203%2C%203%2C%201%2C%203%2C%201%2C%203%2C%203%2C%203%2C%203%2C%201%20-%3E%204%0A12%2C%201%2C%202%2C%201%2C%202%2C%203%2C%203%2C%203%2C%202%2C%204%2C%204%2C%204%2C%201%2C%205%2C%205%2C%204%2C%207%2C%209%20-%3E%206%0A87%2C%20356%2C%2037673%2C%203676%2C%20386%2C%20909%2C%20909%2C%20909%2C%20909%2C%20454%2C%20909%2C%20909%20-%3E%203%0A87%2C%20356%2C%2037673%2C%203676%2C%20386%2C%20909%2C%20909%2C%20909%2C%20909%2C%20454%2C%20909%2C%20908%2C%20909%20-%3E%204). [Answer] # [MATL](https://esolangs.org/wiki/MATL), 22 bytes ``` 0ih0hdZS49+c'21*?0'XXn ``` Uses [current version](https://github.com/lmendo/MATL/releases) of the language/compiler. ### Example ``` >> matl > 0ih0hdZS49+c'21*?0'XXn > > [1, 2, 2, 3, 4, 3, 5, 3, 2, 1, 2, 3, 3, 3, 2, 2, 1, 3] 4 ``` ### Explanation ``` 0ih0h % input array. Append and prepend 0 dZS % sign of difference between consecutive elements. Gives -1, 0, 1 49+c % convert to a string of '0','1','2' '21*?0'XX % use (lazy) regular expression to detect peaks: '20' or '210' or '2110'... n % number of matches. Implicity print ``` [Answer] # Mathematica, ~~55~~ ~~39~~ ~~36~~ 35 bytes ``` Length@FindPeaks[#&@@@Split@#,0,0]& ``` Now works on all of the test cases! [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~33~~ 31 bytes *Thanks to Neil for saving 2 bytes.* ``` \b(1+)(?<!\1,\1)(,\1)*\b(?!,\1) ``` [Try it online!](https://tio.run/##lVA7DsIwDN19i0ogpa2Huvm4kZB6kQyAYGBhQNw/dZIGlQUVWc/2s178yev@fjwv8ajO4dbDoYvhqqhv1XxqAmGgViXXSXVuUhYjEIqJH8U0GoEVjEiZ65wnpiGpCEZcDfwAWQZWaAassQBKC1Nj1tI6gIClUsfwhtUKbfgP7NXl1ff1K2fTx9dK2pq2S5bfMdlIzrISGT1MjNo61OxYJI4lnRz6wX/BWFPzv19MKS4 "Retina – Try It Online") Takes input as a comma-separated, [unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary) list. [Answer] ## JavaScript ES6, ~~96~~ 94 bytes ``` t=>(a=t.filter((x,i)=>x!=t[i-1])).filter((x,i)=>(x>(b=a[i-1])||!b)&&(x>(c=a[i+1])||!c)).length ``` Principle: collapse plateaus into single peaks, find the picks which are defined as being higher than both next and previous elements. Takes input as an array. Demo: ``` f=t=> (a=t.filter((x,i)=>x!=t[i-1])) //collapse every plateau into the pick .filter((x,i)=> (x>(b=a[i-1])||!b)&&(x>(c=a[i+1])||!c) //leave only those values which are greater than the succeeding and preceding ones ).length document.write( f([])+"<br>"+ f([1, 1, 1])+"<br>"+ f([1, 2, 2, 3, 4, 3, 5, 3, 2, 1, 2, 3, 3, 3, 2, 2, 1, 3])+"<br>"+ f([1])+"<br>"+ f([1, 1])+"<br>"+ f([2, 2, 2, 2, 2])+"<br>"+ f([90])+"<br>"+ f([2, 1, 2])+"<br>"+ f([5, 2, 5, 2, 5])+"<br>"+ f([2, 5, 2, 5, 2, 5, 2])+"<br>"+ f([1, 2, 3, 4])+"<br>"+ f([1, 2, 3, 4, 1, 2])+"<br>"+ f([1, 3, 5, 3, 1])+"<br>"+ f([7, 4, 2, 1, 2, 3, 7])+"<br>"+ f([7, 4, 2, 1, 2, 1, 2, 3, 7])+"<br>"+ f([1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2])+"<br>"+ f([1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1])+"<br>"+ f([2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2])+"<br>"+ f([1, 3, 3, 3, 1, 3, 3, 1, 3, 1, 3, 3, 3, 3, 1])+"<br>"+ f([12, 1, 2, 1, 2, 3, 3, 3, 2, 4, 4, 4, 1, 5, 5, 4, 7, 9])+"<br>"+ f([87, 356, 37673, 3676, 386, 909, 909, 909, 909, 454, 909, 909])+"<br>"+ f([87, 356, 37673, 3676, 386, 909, 909, 909, 909, 454, 909, 908, 909]) ) ``` [Answer] ## ES6, ~~50~~ 48 bytes ``` m=>m.map(h=>{f=h>p?c+=!f:f&&h==p;p=h},p=c=f=0)|c ``` Saved 2 bytes thanks to @user81655. Ungolfed: ``` function peaks(mountains) { var previous = 0; var count = 0; var plateau = false; for (var height of mountains) { if (height > previous) { if (!plateau) count++; plateau = true; } else if (height != previous) { plateau = false; } } return count; } ``` [Answer] # MATL, 23 Since we need to use stack based esolangs to be competitive, I reimplemented my **Julia** solution in MATL. ``` 0i0hhdtg)t5L)0>w6L)0<*s ``` Push `0`, input, `0`, concatenate twice. `0i0hh` => `x = [0, input(''), 0]` Differentiate. `d` => `x = diff(x)` Duplicate `t`, convert one to boolean and use it to index the other. `tg)` => `x=x(x!=0)` Duplicate again. `t` First: `[1,G])0>` => `y1 = x(1:end-1)>0` Exchange. `w` Second: `[2,0])0<` => `y2 = x(2:end)<0` Logic and, count the truthy values. `*s` => `sum(y1 & y2)` [Answer] # Japt, 19 bytes That was easier than I thought, but the beginning is slightly wasteful due to a bug. ``` Uu0;Up0 ä< ä> f_} l ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=VXUwO1VwMCDkPCDkPiBmX30gbA==&input=WzUsNCwzLDIsMSwyXQ==) ### How it works ``` Uu0;Up0 ä< ä> f_} l // Implicit: U = input Uu0;Up0 // Add 0 to the beginning and end of U. If this isn't done, the algorithm fails on peaks at the end. ä< // Compare each pair of items, returning true if the first is less than the second, false otherwise. // This leaves us with a list e.g. [true, false, false, true, false]. ä> // Repeat the above process, but with greater-than instead of less-than. // JS compares true as greater than false, so this returns a list filled with false, with true wherever there is a peak. f_} l // Filter out the falsy items and return the length. ``` ### Non-competing version, 15 bytes ``` Uu0 p0 ä< ä> è_ ``` Earlier today, I added the `è` function, which is like `f` but returns the number of matches rather than the matches themselves. I also fixed a bug where `Array.u` would return the length of the array rather than the array itself. [Try it online!](http://ethproductions.github.io/japt?v=master&code=VXUwIHAwIOQ8IOQ+IOhf&input=WzUsNCwzLDIsMSwyXQ==) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` Ô0.ø¥0‹ÔO ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8BQDvcM7Di01eNSw8/AU////ow11FIzAyFhHwQRMmoJJoIghTNwYJgIRNI4FAA "05AB1E – Try It Online") **Explanation:** ``` Ô0.ø¥0‹ÔO Full program Ô Uniquify (= remove plateaus) 0.ø Surround with zeros ¥ Push deltas 0‹ Test each element if lower than 0 --- we now have a list with 0's (= going uphill) and 1's (going downhill). Since we removed plateaus, all we have to do now is to count the number of ramps going downhill Ô Uniquify (reduce ramps to length 1) O Total sum of the list ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` ṡ2EÐḟFs2ḣ€1S€ṡ3M€Fċ2 0;⁸;0Ç ``` [Try it online!](https://tio.run/##y0rNyan8///hzoVGrocnPNwx363Y6OGOxY@a1hgGAwmguLEvkHY70m3EZWD9qHGHtcHh9v//AQ "Jelly – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` iT òÎmÎä> ò> l ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=aVQg8s5tzuQ%2bIPI%2bIGw&input=WwpbXQpbMSwgMSwgMV0KWzEsIDIsIDIsIDMsIDQsIDMsIDUsIDMsIDIsIDEsIDIsIDMsIDMsIDMsIDIsIDIsIDEsIDNdClsxXQpbMSwgMV0KWzIsIDIsIDIsIDIsIDJdCls5MF0KWzIsIDEsIDJdCls1LCAyLCA1LCAyLCA1XQpbMiwgNSwgMiwgNSwgMiwgNSwgMl0KWzEsIDIsIDMsIDRdClsxLCAyLCAzLCA0LCAxLCAyXQpbMSwgMywgNSwgMywgMV0KWzcsIDQsIDIsIDEsIDIsIDMsIDddCls3LCA0LCAyLCAxLCAyLCAxLCAyLCAzLCA3XQpbMSwgMiwgMSwgMiwgMSwgMiwgMSwgMiwgMSwgMiwgMSwgMiwgMSwgMiwgMSwgMiwgMSwgMiwgMSwgMl0KWzEsIDIsIDEsIDIsIDEsIDIsIDEsIDIsIDEsIDIsIDEsIDIsIDEsIDIsIDEsIDIsIDEsIDIsIDEsIDIsIDFdClsyLCAxLCAyLCAxLCAyLCAxLCAyLCAxLCAyLCAxLCAyLCAxLCAyLCAxLCAyLCAxLCAyLCAxLCAyXQpbMSwgMywgMywgMywgMSwgMywgMywgMSwgMywgMSwgMywgMywgMywgMywgMV0KWzEyLCAxLCAyLCAxLCAyLCAzLCAzLCAzLCAyLCA0LCA0LCA0LCAxLCA1LCA1LCA0LCA3LCA5XQpbODcsIDM1NiwgMzc2NzMsIDM2NzYsIDM4NiwgOTA5LCA5MDksIDkwOSwgOTA5LCA0NTQsIDkwOSwgOTA5XQpbODcsIDM1NiwgMzc2NzMsIDM2NzYsIDM4NiwgOTA5LCA5MDksIDkwOSwgOTA5LCA0NTQsIDkwOSwgOTA4LCA5MDldCl0tbVE) (includes all test cases) Accommodating the empty array cost 2 bytes. ``` iT òÎmÎä> ò> l :Implicit input of array iT :Prepend 0 ò :Partition between elements where Î : The sign of their difference is truthy (not 0) m :Map Î : First element ä> :Consecutive pairs reduced by > ò> :Partition after elements that are greater than the next l :Length ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` #←gẊo±>m←gΘ ``` [Try it online!](https://tio.run/##nVC7DQIxDB2G1sX58nHSsEh0NUjoRIEYAAoKKkrWoKVkAHbgFgmOk/s16ISsl7z3YjtxtsfDLrbd@RRX3eW2@Tyv@9dj3Sb@vscYQ2ggIHDIXnMo0AzDqAFFK@FJqZSVK3itoQRzX4mBIgybAvEGJWe5pR5ZqcFyaWpM7PaX00yPHk6cH1ieWUZa2jN/Cw5r7@QJcPrc/H9aAnlIwzuB5zRHoIwFRZY4yRJTZ8FXfgZtdM//qHFS13wB "Husk – Try It Online") ``` #←gẊo±>m←gΘ # # how many truthy elements in list of ← # first element of each sublist of g # grouped identical elements of Ẋ # apply to each pair in list o±> # sign of greater than (1 if greater than, 0 otherwise) m← # make list from first element of each sublist of g # grouped identical elements of Θ # input prepended with zero ``` [Answer] ## GolfScript, 35 ``` ~0+0\{.@=!},+:a,2-,{a\>3<.$2=?1=},, ``` [Test online](http://golfscript.apphb.com/?c=O1siW10iCiJbMSAxIDFdIgoiWzEgMiAyIDMgNCAzIDUgMyAyIDEgMiAzIDMgMyAyIDIgMSAzXSIKIlsxXSIKIlsxIDFdIgoiWzIgMiAyIDIgMl0iCiJbOTBdIgoiWzIgMSAyXSIKIls1IDIgNSAyIDVdIgoiWzIgNSAyIDUgMiA1IDJdIgoiWzEgMiAzIDRdIgoiWzEgMiAzIDQgMSAyXSIKIlsxIDMgNSAzIDFdIgoiWzcgNCAyIDEgMiAzIDddIgoiWzcgNCAyIDEgMiAxIDIgMyA3XSIKIlsxIDIgMSAyIDEgMiAxIDIgMSAyIDEgMiAxIDIgMSAyIDEgMiAxIDJdIgoiWzEgMiAxIDIgMSAyIDEgMiAxIDIgMSAyIDEgMiAxIDIgMSAyIDEgMiAxXSIKIlsyIDEgMiAxIDIgMSAyIDEgMiAxIDIgMSAyIDEgMiAxIDIgMSAyXSIKIlsxIDMgMyAzIDEgMyAzIDEgMyAxIDMgMyAzIDMgMV0iCiJbMTIgMSAyIDEgMiAzIDMgMyAyIDQgNCA0IDEgNSA1IDQgNyA5XSIKIls4NyAzNTYgMzc2NzMgMzY3NiAzODYgOTA5IDkwOSA5MDkgOTA5IDQ1NCA5MDkgOTA5XSIKIls4NyAzNTYgMzc2NzMgMzY3NiAzODYgOTA5IDkwOSA5MDkgOTA5IDQ1NCA5MDkgOTA4IDkwOV0iCl17Cn4wKzBcey5APSF9LCs6YSwyLSx7YVw%2BMzwuJDI9PzE9fSwsCnB9Lw%3D%3D) Basically removes duplicates, adds a 0 to both ends, and checks how many triples have a maximum in the center. [Answer] # Java 8, 141 bytes ``` l->{int r=0,i=1,t;for(l.add(0,0),l.add(0);i<l.size()-1;r+=t>l.get(i-1)&t>l.get(++i)?1:0)for(;(t=l.get(i))==l.get(i+1);)l.remove(i);return r;} ``` Can probably be golfed by using a different approach, or an array as input instead of List. **Explanation:** [Try it here.](https://tio.run/##zVVRT8IwEH7nV/TJtGE0K2wMrMP4aKK@@Gh8qKOSYulIVzBo@O3YFYYgidGHS0hul7tr9913t2s3FUvRKefSTMdvm0KLqkL3QpnPFkLKOGlfRSHRQ@2GACrw1L9BF05pemOtWN2pyl3d@q0TaUdIE@63rv3jpXLCqQI9IINytNGd0WeNYPM4UjmLHH8tLdZUjMc4jmIS7UzC1ZWmlfqQmHQYt@3cjTSdSIdVh5GLxmm3FblmlzGpUTh2@W4PIXljthnhRFMrZ@VS@hVupVtYgyxfb/iW4nzxoj3FHdNlqcZo5svHj84qM3l6RoJsa39cVU7OaLlwdO6XnDbY0AIb@Y5@awgmJHTk3wCjn32uqKjqFcwiVAsBQe4G6UUoCToNuhsybuO9JrIN9iBowJQGAdttWlELAP4whiHNYOimoRE7DcP8KAVMFftZT0DBwb4COzi6EEOfBfKHl0IGnwU0FztJ9Fd9VmTA7rjz6cz@D8SOjcMloLFnp7O4/xkmjbBw8NJg@wkeAvAYeNxe2vcq62c1g35WOwOvhvHwRCVp8u2eF53BEad1a735Ag) ``` l->{ // Method with ArrayList<Integer> parameter and int return-type int r=0, // Result-integer i=1, // Index-integer t; // Temp integer for(l.add(0,0), // Add a 0 at the start of the list l.add(0); // Add a 0 at the end of the list i<l.size()-1; // Loop (1) from index 1 through length-1 (0-indexed) r+= // After every iteration, raise the result-integer by: t>l.get(i-1) // If the current item is larger than the previous &t>l.get(++i)? // and larger than the next: 1 // Increase `r` by 1 : // Else: 0) // `r` remains the same for(;(t=l.get(i))==l.get(i+1); // Inner loop (2) as long as there are two adjacent equal items l.remove(i) // And remove one of those two equal integers ); // End of inner loop (2) // End of loop (1) (implicit / single-line body) return r; // Return the result-integer } // End of method ``` [Answer] # [Python 3](https://docs.python.org/3/), 68 bytes ``` f=lambda a,*b,p=0:(p<a>[*b,0][0])+(len(b)and f(*b,p=[p,a][a!=b[0]])) ``` [Try it online!](https://tio.run/##NYyxCsMwDET3foW7Sa0Gp26XEvdHjAeZxKSQuiJkyde7wsWcOLjH6eTYl29xtWa/8idNbJguicTbJ8jIr6DBxmAjXmGdCyTkMpkMrROEOAY@@6SFiFhle5cdMgxkbu0cmXvzR3MlQ@eukz90iKf@bkmlcz8 "Python 3 – Try It Online") [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), 59 bytes ``` 0i:0(?v:@)$! v&01~~/ l 1 - ? \?v >^&+\ & \:?^v \n; \&1/ ``` [Try it online!](https://tio.run/##S8sszvj/3yDTykDDvszKQVNFkatMzcCwrk6fK4fLkEuXy54rxr5MQcEuTk07RoFLTSHGyj6ujCsmz1pBQSFGzVD////EpMTklNS0pLREAA "><> – Try It Online") - [Animated Version](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiMGk6MCg/djpAKSQhXG52JjAxfn4vXG5sXG4xXG4tXG4/XG5cXD92ICA+XiYrXFwgXG4mIFxcOj9edlxuXFxuOyAgIFxcJjEvIiwiaW5wdXQiOiIiLCJzdGFjayI6IiIsIm1vZGUiOiJudW1iZXJzIn0=) ## Explanation [![enter image description here](https://i.stack.imgur.com/max5o.png)](https://i.stack.imgur.com/max5o.png) **Green:** Read the input, push 1 if the value is less than the previous, 0 if it's more. Add a 0 and a 1 to the ends of the stack. Set the register to 0. **Blue:** While the stack is not empty, check for a 0 followed by a 1. If so increment the register. In all other cases just pop a value. **Yellow:** Print the result when the stack is empty. ]
[Question] [ The objective of this challenge is to write a program to convert an inputed string of what can be assumed as containing *only* letters and numbers from as many bases between 2 and 36 as possible, and find the base 10 sum of the results. The input string will be converted to all the bases in which the number would be defined according to the standard alphabet for bases up to 36: `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ`. For example, the input `2T` would be valid in only bases 30 and up. The program would convert 2T from bases 30 through 36 to decimal and sum the results. You may assume that the input string contains only letters and numbers. Your program may use uppercase or lowercase; it can, but does not need to, support both. --- **Test cases** *Sample input:* `2T` Chart of possible bases ``` Base Value 30 89 31 91 32 93 33 95 34 97 35 99 36 101 ``` Output: 665 *Sample input:* `1012` Chart of possible bases: ``` Base Value 3 32 4 70 5 132 6 224 7 352 8 522 9 740 10 1012 11 1344 12 1742 13 2212 14 2760 15 3392 16 4114 17 4932 18 5852 19 6880 20 8022 21 9284 22 10672 23 12192 24 13850 25 15652 26 17604 27 19712 28 21982 29 24420 30 27032 31 29824 32 32802 33 35972 34 39340 35 42912 36 46694 ``` Output: `444278` *Sample input:* `HELLOworld` Chart of possible bases ``` Base Value 33 809608041709942 34 1058326557132355 35 1372783151310948 36 1767707668033969 ``` Output: `5008425418187214` An input of `0` would be read as `0` in all bases between 2 and 36 inclusive. There is no such thing as base 1. --- This is code golf. Standard rules apply. Shortest code in bytes wins. [Answer] # Python 3, ~~72~~ ~~71~~ 69 bytes Thanks to FryAmTheEggman for saving a byte! Thanks to DSM for saving 2 bytes! ``` N=x=0 y=input() while N<36: N+=1 try:x+=int(y,N) except:0 print(x) ``` [Answer] # Pyth, 20 19 11 bytes ``` sm.xizd0S36 ``` Blatantly stole Adnan's idea from his Python answer. [Try it here](https://pyth.herokuapp.com/?code=sm.xizd0S36&input=HELLOworld&debug=0) [Answer] # Pure [Bash](https://www.gnu.org/software/bash/), 26 ``` ((s+={36..2}#$1,)) echo $s ``` [Try it online!](https://tio.run/##S0oszvhfnpGZk6pQlJqYopCZV1BaYq2Qks9VnFqioKuroAIW@a@hUaxtW21spqdnVKusYqijqcmVmpyRr6BS/D8lPy/1vwGXUQiXoYGhEZeHq4@Pf3l@UU4KFwA "Bash – Try It Online") --- Old answer from 5 years ago: # Pure Bash (no utilities), 38 Assuming built-in base conversions are allowed: ``` for((b=36;s+=$b#$1;b--));{ :;} echo $s ``` This will output an error to STDERR. I'm assuming this is OK as per [this meta answer](https://codegolf.meta.stackexchange.com/a/4781/11259). ### Test output: ``` $ for t in 0 2T 1012 HELLOworld; do ./basesum.sh $t; done 2> /dev/null 0 665 444278 5008425418187214 $ ``` [Answer] ## Seriously, 65 bytes ``` ,û;╗rk`"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"íu`MSd:37:@x`╜¿`MΣ. ``` Contains unprintables, hexdump: ``` 2c963bbb726b6022303132333435363738394142434445464748494a4b4c4d4e4f505152535455565758595a22a175604d53643a33373a407860bda8604de42e7f ``` Unfortunately I don't have a good way to filter from a list based on types. Note to self: add that. Takes input like `"2T"` [Try it online](http://seriouslylang.herokuapp.com/link/code=2c963bbb726b6022303132333435363738394142434445464748494a4b4c4d4e4f505152535455565758595a22a175604d53643a33373a407860bda8604de42e7f&input=) (you will have to manually enter input) Explanation: ``` ,û get input and convert to uppercase ;╗ make a copy and save to register 0 rk explode string into list `"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"íu`M map the function over the list: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"íu get the character's index in the string and add one to get a value in [1,36] Sd get maximum element (maximum base aka max_base) from list by sorting and popping the last element off and pushing it to the stack :37:@x push range(max_base,37) `╜¿`M map the function over the list: ╜¿ convert value in register 0 to an int, interpreting it as a base-n int (n is value from list) Σ. sum and print 0x7f quit ``` [Answer] # Mathematica, 57 bytes ``` #~Sum~{x,Max@CoefficientList[#,x]+1,36}&@FromDigits[#,x]& ``` [Answer] # Matlab, 98 bytes ``` function y=f(s) [~,m]=max(bsxfun(@eq,s,[48:57 65:90]'));y=0;for n=max(m):36 y=y+base2dec(s,n); end ``` [Answer] # Octave, ~~75~~ 73 bytes ``` function v=u(a) m([48:57 65:90])=0:35;v=sum(polyval(t=m(a),max(t)+1:36)); ``` ### Explanation: ``` function v=u(a) m([48:57 65:90])=0:35; %// create a map: '0'-'9' = 0-9 %// 'A'-'Z' = 10-35 t=m(a); %// convert string to mapped values b=max(t)+1; %// find minimum base p=polyval(t,b:36); %// calculate polynomial for each base (vectorized) v=sum(p); %// and return the sum of the resulting vector ``` `polyval` has an advantage over `base2dec` in that it's vectorized, so no `for` loop is required. Only '0'..'9' and upper-case 'A'..'Z' are supported as input. [Answer] # [Husk](https://github.com/barbuz/Husk), 22 bytes or **[21 bytes](https://tio.run/##ATUAyv9odXNr///Cp@G5gWBCw7YtMeKApjM24oaS4paybcivJTQ4JTg3Y////yJoZWxsb3dvcmxkIg)** with only lowercase input ``` §ṁ`Bö-1…36→▲mö%48%87c_ ``` [Try it online!](https://tio.run/##ATYAyf9odXNr///Cp@G5gWBCw7YtMeKApjM24oaS4paybcO2JTQ4JTg3Y1////8iSEVMTE93b3JsZCI "Husk – Try It Online") ``` §ṁ`Bö-1…36→▲mö%48%87c_ § # fork: apply 2 functions to same argument ṁ`B # function 1: ṁ # sum of elements of argument `B # interpreted as base N, with N given by ö-1…36→▲ # function 2: ö # combine 4 funcitions: -1 # remove elements equal to 1 from …36 # series from 36 to → # one less than ▲ # max value of argument mö%48%87c_ # fork argument: mö # map 4 functions over input: _ # convert to lowercase c # get ASCII value %87 # MOD 87 %48 # MOD 48 ``` [Answer] # [Haskell](https://www.haskell.org/), 77 bytes ``` f s|d<-[mod(fromEnum c+30)39|c<-s]=sum[foldl1((+).(b*))d|b<-[2..36],all(<b)d] ``` [Try it online!](https://tio.run/##Xc6xCoMwFEDRvV/xCB2SWoNJoFCIY79CHIyvQemLKUbpkn9PXdv1wIU7Den1JCrFQ8po6y5E5H6N4bHsAcbKNMLc82jr1LdpD52PhKQ4r4Tk7iIEZndEWkpz668DEbdOYF/CMC8txhPAe52XDc7ggemN/YJqlP6j6ZiJn7gSsvIF "Haskell – Try It Online") [Answer] # [R](https://www.r-project.org/), 44 bytes ``` sum(sapply(2:36,strtoi,x=scan(,"")),na.rm=T) ``` [Try it online!](https://tio.run/##K/r/v7g0V6M4saAgp1LDyMrYTKe4pKgkP1OnwrY4OTFPQ0dJSVNTJy9RryjXNkTzv1HIfwA "R – Try It Online") R has a builtin, `strtoi`, to convert from a string to an integer in base `2:36` using only digits and capital letters, returning `NA` if it's invalid in that base. We can then `sum` them up, removing the `NA`s with `na.rm=T`. Luckily, `sapply` is smart enough about named arguments to make this work. [Answer] # [Desmos](https://www.desmos.com/calculator), 85 bytes ``` f(x)=x+3.5sign(60-x)-51.5 l=i.length \sum_{n=f(i).max+1}^{36}\sum_{m=1}^lf(i[m])n^{l-m} ``` [View it on Desmos](https://www.desmos.com/calculator/kxezhs3aon) (includes a bonus version that costs 2 extra bytes) Explanation: Input is through an array of integers `i`, as Desmos doesn't support strings. Capital letters are required. The first function transforms a codepoint to the value in base-36, or any other base that it's valid in. The second function simply stores `i.length`, as it's expensive to call. The third function can be understood as such: ``` \sum_{n=f(i).max+1}^{36} Iterate n from 1+the largest codepoint value, which will be the smallest valid base, to 36, the largest valid base \sum_{m=1}^l Iterate m over the indices of i (Desmos is 1-indexed) f(i[m]) Find the value of the mth character n^{l-m} Multiply by the base to the power of its distance to the right Add everything up (due to using sums earlier) ``` [Answer] # Scala, 64 bytes Requires uppercase input ``` s=>(s.map(_%55%48).max+1 to 36).map(b=>(0L/:s)(_*b+_%55%48)).sum ``` [Try it in Scastie](https://scastie.scala-lang.org/LMGf9P2ySS26B42PXIfTDQ) -7 bytes by using a Long (`0L`) instead of a BigInt (`BigInt(0)`) This might have been shorter if I'd used `try`/`catch` with `BigInt(number, base)`, but I didn't want to do that. ~~Still wish I could inline `n`, but I need it to determine the first valid base.~~ Apparently, it's one byte shorter by not doing `val n=s.map(_%55%48)` and reusing `n`. Explanation: ``` s => //Input (s.map(_ % 55 % 48) //Turn the characters into numbers 0-35 .max+1 //The maximum of that (minimum base) to 36) //Range of bases up to 36 .map(b => //For each base b, interpret the input in that base (BigInt(0) //Starting with 0, /:s) //Fold left over the input (_ * b + //Multiply the accumulator by the base _ % 55 % 48) //And add the next digit (put it in the range [0, 35]) ).sum //Take the sum ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` ØBiⱮµ’ḅṀr36ƊS ``` [Try it online!](https://tio.run/##ASwA0/9qZWxsef//w5hCaeKxrsK14oCZ4biF4bmAcjM2xopT////SEVMTE9XT1JMRA "Jelly – Try It Online") Works only for uppercase letters. ## Explanation ``` ØBiⱮµ’ḅṀr36ƊS Monadic link Ɱ Map over argument: i Find 1-based index in... ØB ...base digits: "0123456789ABCD...YZabcd...yz" µ Use as argument to new monadic chain ’ Decrement (to get 0-based indices) ḅ Convert to base... (auto-mapped) Ɗ ...treat 3 preceding atoms as a single link: Ṁ Maximum [of argument, which is the 1-based indices] r36 Inclusive range to 36 S Sum ``` [Answer] ## CJam, ~~28~~ 27 bytes *Thanks to Reto Koradi for saving 1 byte.* This is kinda horrible... ``` qA,s'[,65>+f#_:e>)37,>\fb:+ ``` Requires upper case letters. [Test it here.](http://cjam.aditsu.net/#code=qA%2Cs'%5B%2C65%3E%2Bf%23_%3Ae%3E)37%2C%3E%5Cfb%3A%2B&input=2T) CJam doesn't have built-in base-36 conversion from strings, so we have to letters out the strings ourselves. I've been trying all sorts of divmod shenanigans, but it seems to be shortest to build a string of all 36 digits and just find the index of each character in that string. [Answer] # C function, 93 (32 bit integer output only) Assuming its OK for the output to only go up to INT\_MAX, then we can do this: ``` i,n,x;f(char *s){char *e;for(i=36,x=0;n=strtol(s,&e,i--),!*e&&i;)x+=*e?0:n;printf("%d\n",x);} ``` --- The last testcase implies that this is probably not sufficient. If so, then with 64-bit integers we have: # C function, 122 ``` #include<stdlib.h> f(char *s){long long i=36,n,x=0;char *e;for(;n=strtoll(s,&e,i--),!*e&&i;)x+=*e?0:n;printf("%lld\n",x);} ``` Unfortunately the `#include <stdlib.h>` is required so the return type of `strtoll()` is correct. We need to use `long long` to handle the `HELLOworld` testcase. Otherwise this could be a fair bit shorter. ### Test driver: ``` #include<stdlib.h> f(char *s){long long i=36,n,x=0;char *e;for(;n=strtoll(s,&e,i--),!*e&&i;)x+=*e?0:n;printf("%lld\n",x);} int main (int argc, char **argv) { f("0"); f("2T"); f("1012"); f("HELLOworld"); } ``` ### Test output: ``` $ ./basesum 0 665 444278 5008425418187214 $ ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~17~~ 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` 36õ2 k@kUnXXãnX ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=Mzb1MiBrQGtVblhYw6NuWA&input=IjJUIg) [Answer] # [Factor](https://factorcode.org/), 38 bytes ``` [ 37 iota [ base> ] with map sift Σ ] ``` [Try it online!](https://tio.run/##JcwxCsIwFIfx3VP8yQGKrYOgIC6iQtFBnUqHmL7SYE3iyyvF83gfrxQLTt9v@lptxHO6XY6n/QoPYkc9nlq6LGiOxH8PzhrfEAKTyDuwdYJIr4GcoYj1TBVXNVP5PC@mHHZleR49941KFRZLWC8aFe460gY1RivdtA2IthV8P6iTsN0iizA9aU4/ "Factor – Try It Online") ## Explanation: It's a quotation (anonymous function) that takes a string from the data stack as input and leaves an integer on the data stack as output. * `37 iota` Create a range from 0 to 36 inclusive. * `[ base> ] with map` Convert the input to base 10 from each base between 0 and 36. If the input can't be converted from particular base, `base>` returns `f`. * `sift` Remove all the `f` from a sequence. * `Σ` Sum. [Answer] # [Japt](https://github.com/ETHproductions/Japt), 26 bytes ``` 1+U¬r@XwYn36}0)o37 £UnX} x ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=MStVrHJAWHdZbjM2fTApbzM3IKNVblh9IHg=&input=IkhFTExPd29ybGQi) ### Ungolfed and explanation ``` 1+U¬ r@ XwYn36}0)o37 £ UnX} x 1+Uq rXYZ{XwYn36}0)o37 mXYZ{UnX} x // Implicit: U = input string Uq rXYZ{ // Split U into chars, and reduce each item Y and previous value X by: XwYn36 // Choosing the larger of X and parseInt(Y,36), }0 // starting at 0. 1+ )o37 // Add 1 and create a range from this number to 36. mXYZ{UnX} // Map each item X in this range to parseInt(U,X) x // and sum. // Implicit: output last expression ``` [Answer] # Python 3, 142 bytes [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) has me soundly beat with their solution, but I did want to add my own attempt. ``` def f(s): t=0 for x in range(37): n=0 for i in s: try:m=int(i) except:m=ord(i)-55 if x<=m:n=0;break n=n*x+m t+=n return t ``` This function only handles uppercase inputs. Add `.upper()` to `for i in s`, and it will handle both uppercase and lowercase. [Answer] # Pyth, 16 bytes ``` V36 .x=+ZizhN ;Z ``` [Try it online](https://pyth.herokuapp.com/?code=V36%20.x%3D%2BZizhN%20%3BZ&input=1012&debug=0) Explaination: ``` # Implicit: Z = 0, z = input V36 # For N in range 36 .x # Try except =+Z # Z = Z + izhN izhN # Convert z from base N+1 to decimal ; # Infinite ), for closing the for loop Z # Print Z ``` [Answer] # Scala 2.11, 93 bytes This is run on the scala console. ``` val i=readLine var s=0 for(j<-2 to 36)try{s=s+Integer.parseInt(i,j)}catch{case _:Exception=>} ``` [Answer] ## Haskell, 97 bytes ``` i c|'_'<c=fromEnum c-87|1<2=read[c] f s=sum$map((`foldl1`map i s).((+).).(*))[1+i(maximum s)..36] ``` Supports only lowercase characters. Usage example: ``` f "2t" -> 665 f "helloworld" -> 5008425418187214 ``` It's so massive, because I have to implement both char-to-ASCII and base conversion myself. The corresponding pre-defined functions are in modules which require even more expensive imports. How it works: `i` converts a character `c` to it's digit value (e.g. `i 't'` -> `29`). `f` calculates the value of the input string for every possible base and sums it. A non-pointfree version of the inner loop is `map (\base -> foldl1 (\value digit -> value*base + digit) (map i s)) [ ...bases... ]`. [Answer] # JavaScript (ES6), 86 bytes ``` s=>eval(`p=parseInt;b=2;[...s].map(d=>(v=p(d,36))>b?b=v:0);for(r=0;++b<37;)r+=p(s,b)`) ``` ## Explanation ``` s=> eval(` // use eval to enable for loop without return keyword or {} p=parseInt; b=2; // b = minimum base of s [...s].map(d=> // iterate through each digit d (v=p(d,36)) // get it's base-36 value >b?b=v:0 // set b to the max value ); for(r=0;++b<37;) // r = sum of all base values r+=p(s,b) // add each base value from b to 36 to r `) // implicit: return r ``` ## Test ``` <input type="text" id="input" value="HELLOworld" /> <button onclick="result.textContent=( s=>eval(`p=parseInt;b=2;[...s].map(d=>(v=p(d,36))>b?b=v:0);for(r=0;++b<37;)r+=p(s,b)`) )(input.value)">Go</button> <pre id="result"></pre> ``` [Answer] ## [Perl 6](http://perl6.org), 35 bytes ``` {[+] map {+(":$^a"~"<$_>")||0},^37} ``` usage: ``` # store it somewhere my &code = {[+] map {+(":$^a"~"<$_>")||0},^37} say code 'HELLOworld' # 5008425418187214 say map &code, <2T 1012> # (665 444278) say code 'qwertyuiopasdfghjklzxcvbnm1234567890' # 79495849566202185148466281109757186006261081372450955140 ``` [Answer] ## Ceylon, ~~100~~ 96 bytes ``` Integer b(String s)=>sum(((any(s*.letter)then 11else 2)..36).map((r)=>parseInteger(s,r)else 0)); ``` I first had this simpler version taking just 69 bytes: ``` Integer b(String s)=>sum((2..36).map((r)=>parseInteger(s,r)else 0)); ``` But this fails with the first test case, returning `2000000000665` instead of `665`. ([The reason is that the `T` in `2T` is parsed as Tera, i.e. multiplies the 2 with 10^12, when the radix is 10.](https://github.com/ceylon/ceylon/issues/5796)) Therefore we need to catch this case separately. Thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) for suggesting a different way of doing this which saved 4 bytes. Formatted: ``` // Find sum of all possible base representations. // // Question: https://codegolf.stackexchange.com/q/65748/2338 // My Answer: https://codegolf.stackexchange.com/a/65836/2338 Integer b(String s) => // take the sum of ... sum( // span from 2 to 36. (Though // if there are letters in there, we start at 11, // because the other ones can't be valid. // Also, parseInteger(s, 10) behaves a bit strange in Ceylon.) ((any(s*.letter) then 11 else 2) .. 36) // map each r of them to ... .map((r) => // try parsing s as a number using base r parseInteger(s, r) // if that didn't succeed, use 0. else 0 ) ); ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~38~~ 35 bytes ``` {+/t{y/x}/:(|/t:x+7*3>x-:55)_1+!36} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/Nqlpbv6S6Ur@iVt9Ko0a/xKpC21zL2K5C18rUVDPeUFvR2Kz2f5q6hpJRiJK1kqGBoRGQ8nD18fEP9w/ycQFyDJQ0/wMA "K (ngn/k) – Try It Online") Takes capitalized input, e.g. "2T". * `t:x+7*3>x-:55` map input from characters to 0..35, storing in `t` * `(|/t...)_1+!36` identify the valid bases (those larger than the largest value in the input) * `t{y/x}/:` convert `t`, interpreted as each valid base, to decimal * `+/` take the sum and return ]
[Question] [ In Python, one can save bytes by aliasing functions that are used repeatedly. For example: ``` r=range a=r(100) b=r(200) c=r(300) ``` However, when the functions are member functions together, I don't know how to alias them in a way that allows chaining. For example: ``` s='Hello' // Plain code s=s.replace('H','J').replace('e','i').replace('l','m').replace('o','y') // What I am trying to do q=replace s=s.q('H','J').q('e','i').q('l','m').q('o','y') ``` Obviously, what I am trying to do is not valid. And neither is this: ``` q=s.replace s=q('H','J') // Replaces the 'H' in 'Hello' s=q('e','i') // Replaces the 'e' in 'Hello'... and the J is gone. s=q('l','m') s=q('o','y') ``` Is there a another way to alias member functions and chained functions that saves characters? [Answer] **No problemo!** You can alias a method, but you have to know how to use it: ``` >>> r=str.replace >>> a='hello' >>> r(r(r(r(a,'h','j'),'e','i'),'l','m'),'o','y') 'jimmy' ``` The key is that you have to pass `self` explicitly, because the alias is a kind of function that takes an extra argument that takes `self`: ``` >>> type(r) <type 'method_descriptor'> ``` [Answer] Define your own class, with a shorter method name. For example, if you're using the method `replace()` belonging to the `String` class, you could make your own class `S` have a method called `q` which does the same thing. Here is one implementation: ``` class m(str): def q(a,b,c):return m(a.replace(b,c)) ``` Here is a much better implementation: ``` class m(str):q=lambda a,b,c:m(a.replace(b,c)) ``` Use it like so: ``` s="Hello" s=m(s).q('H','J').q('e','i').q('l','m').q('o','y') ``` [Answer] This is a few characters shorter anyway ``` j=iter('HJeilmoy') for i in j:s=s.replace(i,next(j)) ``` even shorter for a small number of replacements is ``` for i in['HJ','ei','lm','oy']:s=s.replace(*i) ``` of course this just covers one particular case. However code golf is all about finding those special cases that can save you bytes. It's possible to write a wrapper function that handles the general case, but the code will be too large to have a place in most code golf challenges. You instead need to think "I can do this transformation efficiently (strokewise) with str.replace. Can I shift the internal representation of my solution to take advantage of that? (without wasting so many strokes to negate the advantage)" [Answer] You may use the `reduce` function. ``` reduce(lambda s,(a,b):s.replace(a,b),[('H','J'),('e','i'),('l','m'),('o','y')],'Hello') ``` [Answer] If you're doing a *lot* of replaces, you could do this: ``` s=''.join({'H':'J','e':'i','l':'m','o':'y'}[a] for a in list(s)) ``` [Answer] How about defining a lambda function? ``` r=lambda s,a,b:s.replace(a,b) s=r(r(r(r(s,'H','J'),'e','i'),'l','m'),'o','y') ``` [Answer] If your replacements don't need to be chained, you can use `str.translate'. The numbers are the ASCII ordinals. Using it this way requires Python 3: ``` print("Hello".translate({72:74,101:105,108:109,111:121})) ``` [**Try it online**](http://ideone.com/3mXbsY) ]
[Question] [ Being a big fan of the Rubik's cube and of cool art, I've been working on combining the two together to do some really cool stuff. Basically solving miniature Rubik's cubes to form rudimentary pixels in the formation of Rubik's cube art. Examples of such art can be seen via this link: <http://google.com/search?q=rubik%27s+cube+art> Now, the purpose of this Code Golf is to create code that accepts an image as input, and then converts it in the following manner: The image is initially reduced to web-safe grayscale colors. The reason behind this is because we need to isolate the web-safe grayscale palette (i.e. 000000, 333333, 666666, 999999, CCCCCC, and FFFFFF). An algorithm on the colorimetric method of converting to grayscale is available at: <http://en.wikipedia.org/wiki/Grayscale#Colorimetric_.28luminance-preserving.29_conversion_to_grayscale>, should you wish to use that as inspiration. One would then render out the grayscale to the appropriate colors. To break it down quickly: 000000 will refer to Rubik's blue, 333333 will refer to Rubik's red, 666666 will refer to Rubik's green, 999999 will refer to Rubik's orange, CCCCCC will refer to Rubik's yellow, and FFFFFF will refer to Rubik's white. I would rather that your resulting code can render from the photo's palette straight to Rubik's colors. The two-stage method from converting to web-safe grayscale and then to the corresponding Rubik's palette is just to give you an idea on the logic behind the process, but if it is easier for you to do this, by all means do so. The actual RGB values for the Rubik's palette must correspond to the following: * Red: #C41E3A * Green: #009E60 * Blue: #0051BA * Orange: #FF5800 * Yellow: #FFD500 * White: #FFFFFF To give you an example, I have cropped Abraham Lincoln's head from the following picture: ![enter image description here](https://i.stack.imgur.com/Ei856.png), and rendered the algorithm to produce the following: ![enter image description here](https://i.stack.imgur.com/TkvQd.png) The grid is there so that you can see how each individual miniature Rubik's cube would have to be configured to make up the image. The true size of the resulting image is 45 pixels by 45 pixels, meaning (45/3) \* (45/3) = 15 \* 15 = 225 miniature Rubik's cubes would be used to make this image. I am not expecting you to present the resulting image with a grid as I have. So this is what's required: 1. The image to be processed by this algorithm must be x pixels wide by y pixels high, such that x and y are multiples of 3. This is to aid with the ease of rendering as part of a Rubik's cube mosaic. If your image is quite large, reducing it to something around the 45 x 45 to 75 x 75 or thereabouts in dimensions prior to processing is advised. Bear in mind, this resizing component is OPTIONAL. 2. The image needs to be converted to the sextacolored Rubik's cube palette to create the mosaic. 3. The resulting image needs to be a valid graphic file after processing. To prove your code works, run it against an image of one of the presidents of the United States of America, or a well known Hollywood celebrity. I have already used Abraham Lincoln in my example, so this president can no longer be used. Ensure that you provide the language you have used, the byte count as well as the president/celebrity used to test your code, including before and after shots... 4. Each entry must have a unique president/celebrity as their test case. I will not accept duplicates. This will ensure that duplicate results are not used to test different code entries. It's all very well to say that your code works, it's another thing to prove it. 5. Shortest code wins. I'm changing this to a popularity contest... I'd rather see who can do this without having to compete on byte count... So I'll award this along with a bounty after the 28th of February, 2014. [Answer] # Imagemagick (108) Version: ImageMagick 6.8.7-7 Q16 x86\_64 2013-11-27 The following call: ``` $ convert -resize 75x75 -fx "q=p.intensity;q<1/6?#0051BA:q<2/6?#C41E3A:q<3/6?#009e60:q<4/6?#ff5800:q<5/6?#FFD500:#FFF" input output ``` where `input` and `output` have to be modified for the input and output filename. I only counted the chars between `-resize` and `#FFF"`, if you think this is invalid feel free to comment. I used Lenna as image (she appeared in a Playboy, and anyone doing that should count as a Hollywood celebrity, right?) Input: ![Input image](https://i.stack.imgur.com/azjq4.png) Output: ``` $ convert -resize 75x75 -fx "q=p.intensity;q<1/6?#0051BA:q<2/6?#C41E3A:q<3/6?#009e60:q<4/6?#ff5800:q<5/6?#FFD500:#FFF" Lenna.png LennaRubik.png ``` ![Generated image](https://i.stack.imgur.com/lru9H.png) Output enlarged: ![Enlarged image](https://i.stack.imgur.com/XK33N.png) Notes: according to the imagemagick docs you cannot have more than one conditional operator in a statement, but the call still seems to work fine, so probably this was fixed and the docs were just not updated. Running identify on the result image (to show the colors are indeed fine): ``` $ identify -verbose LennaRubik.png (...) Colors: 6 Histogram: 338: ( 0, 81,186) #0051BA srgb(0,81,186) 1652: ( 0,158, 96) #009E60 srgb(0,158,96) 1187: (196, 30, 58) #C41E3A srgb(196,30,58) 1674: (255, 88, 0) #FF5800 srgb(255,88,0) 706: (255,213, 0) #FFD500 srgb(255,213,0) 68: (255,255,255) #FFFFFF white (...) ``` If you think Lenna doesn't count as a proper celebrity, here is Bruce Willis: ![Bruce Original](https://i.stack.imgur.com/jxB78.jpg) ![Bruce Small](https://i.stack.imgur.com/HLnF4.png) ![Bruce Large](https://i.stack.imgur.com/ZcSYa.png) [Answer] # Mathematica We'll work with a square region from a U.S. stamp featuring Greta Garbo. It will be referred to as `j`. ![j](https://i.stack.imgur.com/U8Kvb.png) ``` f[i_,rs_,m_:True]:= Module[{(*rs=rastersize-4*)r={0.77,0.12,0.23},gr={0,0.62,0.38},b={0,0.32,0.73},o={1,0.35,0},y={1,0.84,0},w={1,1,1}, c1={r,gr,b,o,y,w},grayGreta,garboColors}, grayGreta=(*Reverse@*)ImageData[ColorQuantize[Rasterize[i,(*ImageResolution \[Rule]15*)RasterSize->rs+1,ImageSize->rs],6]]; garboColors=Union@Flatten[grayGreta,1]; ArrayPlot[grayGreta/.Thread[garboColors-> RGBColor@@@c1], Mesh->If[m==True,{rs-1,rs-1},None],MeshStyle->Black]] ``` The function f takes 3 parameters: * `i` which refers to the image * `rs`, the raster size * `m`, a boolean variable that states whether Mesh lines should be used. (The default setting is True). --- Using raster sizes of 15, 30, 45, and 75: ``` GraphicsGrid[{{f[j, 15], f[j, 30]}, {f[j, 45], f[j, 75]}}, ImageSize -> 800] ``` ![4 garbos](https://i.stack.imgur.com/uI8oo.png) I can't imagine anyone making a Rubrik's cube with so many pieces! Interesting exercise nonetheless. --- ## Playing around with colors This is from an earlier entry. The code is slightly different. `Graphics` is used instead of `ArrayPlot`. Also, we use the full stamp even though it is not square. There are 6!=720 permutations of the Rubrik cube colors. The following displays the center image of the upper row (set 6 images below). When the grayscale values are arranged from darkest to lightest, the colors are {r,gr,b,o,y,w}. Other variations nonetheless work. `i` is the original image in grayscale. ``` Graphics[Raster[(g=Reverse@ImageData[ColorQuantize[Rasterize[i,RasterSize->75],6]]) /.Thread[Union@Flatten[g,1]-> {{7,1,2},{0,6,4},{0,3,7},{10,4,0},{10,8,0},{10,10,10}}/10]]] ``` --- `i` is the original grayscale image of the full Greta Garbo stamp. `Rasterize[garbo,RasterSize->75` rasterizes the image into a 75 by 75 array. `ColorQuantize[<>, 6]` reduces the grayscale values to a set of 6. `ImageData` retrieves the data array from the image; it comes upside-down. `Reverse` flips the data array, hence the picture, right-side up. `garboColors` are the 6 grayscale values in the quantized image. `Graphics[Raster` displays the final image. `rubrikColors` are RGB values of the 6 Rubrik cube colors. Various color permutations of Red, Green, Blue, Orange, Yellow, and White are given. ``` r={0.77,0.12,0.23};gr={0,0.62,0.38};b={0,0.32,0.73};o={1,0.35,0};y={1,0.84,0};w={1,1,1}; c1={r,gr,b,o,y,w}; c2={r,b,gr,o,y,w}; c3={b,r,gr,o,y,w}; c4={gr,b,r,o,y,w}; c5={b,r,gr,y,o,w}; ``` And the code: ``` grayGreta=Reverse@ImageData[ColorQuantize[Rasterize[i,RasterSize->75],6]]; garboColors=Union@Flatten[grayGreta,1]; Grid[{{i, Graphics[Raster[grayGreta/.Thread[garboColors-> c1]]], Graphics[Raster[grayGreta/.Thread[garboColors-> c2]]]}, {Graphics[Raster[grayGreta/.Thread[garboColors-> c3]]], Graphics[Raster[grayGreta/.Thread[garboColors-> c4]]], Graphics[Raster[grayGreta/.Thread[garboColors-> c5]]]}}] ``` ![garbos](https://i.stack.imgur.com/dwRgh.png) --- ## Garbos Galore Here are 72 (of the 720) images of Greta Garbo that use the 6 Rubrik cube colors. Some images work better than others, don't you think? ``` GraphicsGrid@Partition[(Graphics[Raster[grayGreta /. Thread[garboColors -> #]]] & /@ Take[Permutations[{r, gr, b, o, y, w}, {6}], 72]), 12] ``` ![garbos galore](https://i.stack.imgur.com/fvqAa.jpg) [Answer] # Smalltalk (Smalltalk/X), 289 139\* input: i; output: r ``` r:=i magnifiedTo:75@75. r colorMapProcessing:[:c||b|b:=c brightness.Color rgbValue:(#(16r0051BA 16rC41E3A 16r009e60 16rff5800 16rFFD500 16rFFFFFF)at:(b*6)ceiling)] ``` input: ![enter image description here](https://i.stack.imgur.com/w28Wu.jpg) output: ![enter image description here](https://i.stack.imgur.com/GOFKK.png) enlarged: ![enter image description here](https://i.stack.imgur.com/FLsDW.png) (for all youngsters: this is NOT Madonna ;-) [\*] I have not counted the magnification to 75x75 (the first line) - could have used an already resized as input. Hope that is ok with you. [Answer] ## Postscript, and TRUE Rubik colors! ;-) Well, this solution is a bit of off-topic here, as it's restricted to somewhat highly specialized sphere. But after much frustration with e.g. "weird numbers question" (being unable to produce something practically working) I decided to publish something and so pulled this out of my pile of half-finished scribbles and made it presentable. The solution exploits the fact, that 1st revision of this question defines required colors by link to a site, which clearly states, that Pantone(R) colors are to be used, and RGB colors are approximations only. Then I thought, why would I do approximations, when I can do genuine color? -:) ``` 10 dict begin /Size 75 def /Names [(PMS 012C) (PMS 021C) (PMS 347C) (PMS 200C) (PMS 293C) ] def /Colors [[0 .16 1 0][0 .65 1 0][1 0 .39 .38][0 .9 .72 .28][1 .56 0 .27]] def <</PageSize [Size dup]>> setpagedevice Size dup scale true setoverprint (%stdin) (r) file 100 string readline pop (r) file <</CloseSource true>>/DCTDecode filter 0 1000000 string dup <</CloseTarget true>>/NullEncode filter { 3 index 3 string readstring { 4 -1 roll 1 add 4 1 roll {} forall 0.11 mul exch 0.59 mul add exch 0.3 mul add cvi 1 index exch write } {pop exit} ifelse } loop closefile 0 3 -1 roll getinterval exch closefile /data exch def /n data length sqrt cvi def 1 1 Names length { /N exch def { dup N Names length 1 add div gt {N 1 add Names length 1 add div gt {1} {0} ifelse} {pop 1} ifelse } settransfer [/Separation Names N 1 sub get /DeviceCMYK { Colors N 1 sub get { 1 index mul exch } forall pop }] setcolorspace << /ImageType 1 /Width n /Height n /ImageMatrix [n 0 0 n neg 0 n] /BitsPerComponent 8 /Decode [0 1] /DataSource data >> image } for showpage end ``` This code is to be saved as e.g. `rubik.ps` and then fed to Ghostscript with usual incantation: ``` gs -q -sDEVICE=psdcmyk -o out.psd rubik.ps ``` It then waits you on the next line, for input of JPG file name e.g. ``` kelly.jpg ``` and, if all goes well, saves the output to `out.psd` file. Input must be square RGB JPEG (any size), output is PSD with spot color channels. You'll need Photoshop to view the file. Changing GS device from `psdcmyk` to anything else will produce nothing usable. JPEG as input - because postscript interpreter can decode data stream from it directly. Square shape - because the program relies on `sqrt` of string length to find width (and height) of the image. First lines define output image size (can be changed from default 75) and the color palette (colors and their number can be changed too). Anything else is not hard-coded, I think. What's going on? Stream of RGB triplets is converted on the fly to the string of grayscale values (with simple formula), usual 8-bit contone image dictionary is built and used to paint 5 identical images on top of each other in 5 `Separation` color spaces. The trick is to apply transfer functions before each invocation of `image` operator. E.g. for yellow paint this function returns 0 for input values in 0.167 .. 0.333 range only, and 1 otherwise. Input: ![enter image description here](https://i.stack.imgur.com/OgZpc.jpg) Screenshot of output 75x75 open in Photoshop, enlarged 800%: ![enter image description here](https://i.stack.imgur.com/WDULv.png) And Photoshop channels palette: ![enter image description here](https://i.stack.imgur.com/zmFrI.png) [Answer] # Brainfuck ``` ++++[->+[,.----------]<]>>>>---->->++++++++++>>------------>+++>+++>-- --->++++++[->+++++<]---->+[-<+++++++<+++<+++++<+++<+++<++++++<++++++<+ <++>>>>>>>>>]<[<]<<,+[,<++++++>[>++++++[->+++++++<]>+[<<[->]>[<]>-]<<< ->]+<[-[-[-[-[[-].>>>>>>>>.<.<<<<<<-<]>[->>>>>[.<]<<]<]>[-.>>>[>]<<<.< .[<]<<]<]>[--.+>>>[>]<<.[<].<<]<]>[--.+>>>[>]<.[<].<<]<]>[--...+],,+] ``` This requires a BF interpreter/compiler that has -1 as EOF and that has higher than 8 bit cells IF one of the red pixels are 255. Or else it will stop premature since it won't be able to differ between EOF and value 0xFF. With jitbf you have whatever the machine has as integer size and can do this to force -1 as EOF: ``` jitbf --eof -1 rubiks.bf < angelina.pnm > angelina-rubix.pnm ``` The image file format rendered is the full RGB PNM file (P6), raw as option in Gimp. It uses the green channel only (which is one of many ways to convert a color image to greyscale). It reduces the value by 43 without reduceing the value below zero to find out which rubiks color to use and have a switch that prints out the correct RBG color that corresponds. Image of Angelina Jolie from [Hackers (1995)](http://www.imdb.com/title/tt0113243/?ref_=fn_al_tt_1) scaled down to 75x75 and processed with the application: ![Angelina Jolie 75x75 / Fair Use](https://i.stack.imgur.com/1v4Ty.png) ![Angelina Jolie 75x75 in Rubiks cube colors / Fair Use](https://i.stack.imgur.com/6S86B.png) ![Same scaled 6x](https://i.stack.imgur.com/BFHM1.png) Same, only I used [the original size](http://girlcrushzine.tumblr.com/post/7054073876/remember-angelina-jolie-as-acid-burn-in-hackers): ![Same only not scaled down first / Fair use](https://i.stack.imgur.com/E9TyS.png) And since I'm psychic here's a president as well: ![Arnold Schwarzenegger CC from Wikipedia](https://i.stack.imgur.com/iXRLf.png) [Answer] # C# ``` using System; using System.Drawing; using System.Drawing.Imaging; using System.Linq; class Program { static void Main(string[] args) { unchecked { var t = new[] { 0xFFC41E3A, 0xFF009E60, 0xFF0051BA, 0xFFFF5800, 0xFFFFD500, 0xFFFFFFFF }.Select(v => Color.FromArgb((int)v)).ToArray(); var o = new Bitmap(Bitmap.FromFile(args[1])); var m = double.Parse(args[0]); var r = Math.Min(m / o.Width, m / o.Height); var w = (int)(o.Width * r); var h = (int)(o.Height * r); o = new Bitmap(o, w - (w % 3), h - (h % 3)); for (int y = 0; y < o.Height; y++) for (int x = 0; x < o.Width; x++) o.SetPixel(x, y, N(o.GetPixel(x, y), t)); o.Save(args[2], ImageFormat.Png); } } static Color N(Color c, Color[] t) { return t.OrderBy(v => Math.Abs(W(v) - W(c))).First(); } static double W(Color c) { return .11 * c.B + .59 * c.G + .30 * c.R; } } ``` You need to run it with 3 parameters: `foo.exe 75 d:\test.jpg d:\out.png` Where `75` is max. width/height, `d:\test.jpg` is input file and `d:\out.png` is the output file. Output for various images in this contest: ![WallyWest](https://i.stack.imgur.com/qbcrg.png) ![SztupY 1](https://i.stack.imgur.com/sRkte.png) ![SztupY 2](https://i.stack.imgur.com/Tncwh.png) ![blabla999](https://i.stack.imgur.com/SejDG.png) My own celebrity: ![Garth!](https://i.stack.imgur.com/GKlq9.jpg) Output: ![Garth 75](https://i.stack.imgur.com/SssLt.png) ![Garth 225](https://i.stack.imgur.com/jialg.png) However, other (larger than 75x75) sizes do result in better images: ![150](https://i.stack.imgur.com/7nPIp.png) ![300](https://i.stack.imgur.com/1fALX.png) And, if we stick with presidents: ![DubbaYa 294](https://i.stack.imgur.com/Zu2aS.jpg) ![DubbaYa 75](https://i.stack.imgur.com/DT6vH.png) ![DubbaYa 225](https://i.stack.imgur.com/57INM.png) Since this is no (longer?) codegolf I didn't bother to "minimize" the code too much. Also, since the instructions did not specifically mention the image had to be the same width as height (square) I didn't bother with cropping; I *do*, however, make sure the image is a multiple of 3 pixels wide/high. If you want square images, use square inputs ![:P](https://tweakimg.net/g/s/puh2.gif) Finally; the algorithm is far from optimal. A few more (since people upvote hot chicks / internet heroes more ![:P](https://tweakimg.net/g/s/puh2.gif) ) ![Kari Byron 300](https://i.stack.imgur.com/ttn2q.jpg) ![Kari Byron 75](https://i.stack.imgur.com/q2kWx.png) ![Kari Byron 225](https://i.stack.imgur.com/ffTvT.png) ![The Hoff 300](https://i.stack.imgur.com/lAxDx.jpg) ![The Hoff 75](https://i.stack.imgur.com/Amzwg.png) ![The Hoff 225](https://i.stack.imgur.com/6Mmii.png) [Answer] # [Piet](https://www.dangermouse.net/esoteric/piet.html) [![enter image description here](https://i.stack.imgur.com/IuUZM.png)](https://i.stack.imgur.com/IuUZM.png) It is presented here with a codel size of 20 for readability's sake. To counter that same aspiration, it has been half-heartedly if not golfed then at least been subject to compacting efforts. Tested with [npiet](https://www.bertnase.de/npiet/) like so: ``` npiet -q rc.png < infile.ppm > outfile.ppm ``` Assumes the files are of the "plain" RGB variety (P3), i.e. with the image data as numbers in plaintext and not binary. It ignores the maximum colour value and just assumes that it is 255. In the output, every whitespace is a newline. Looping over each pixel, the following happens: 1. The colours we are to choose from are pushed to stack, lightest first, so that the darkest colours end up on top. 2. The RGB triplet is read in and converted to greyscale. Since floating point mathematics is not built-in nor trivial to implement, integer maths is used: `grey = (red * 299 + green * 587 + blue * 114) / 1000`. 3. The greyscale value is divided by 43, to obtain a number 0..5 (colour index = ci). 4. This number is increased by 1, multiplied by 3 and duplicated on stack. The top value is then decreased by 3, giving us two values on top of stack: `[(ci - 1) * 3] [ci * 3]`. 5. These new values are used with the `roll` instruction, which will - with the parameters given above - bring the desired RGB triplet to the top of the stack. (You can think of it as taking a deck of cards and cutting it so that you hold `ci * 3` cards in your hand, and then taking the top card of that little stack you're holding and putting it down on the pile still on the table, then placing what you hold top of that; repeat this `(ci - 1) * 3` times.) 6. Triplet is output in the usual way. 7. The unused triplets are popped from stack. 8. If at the end, we exit, otherwise we go back to step 1. Input: [![enter image description here](https://i.stack.imgur.com/hcK8F.png)](https://i.stack.imgur.com/hcK8F.png) Output 75x75 (input was scaled before passing it to the program itself): [![enter image description here](https://i.stack.imgur.com/BkLwb.png)](https://i.stack.imgur.com/BkLwb.png) [![enter image description here](https://i.stack.imgur.com/Islrp.png)](https://i.stack.imgur.com/Islrp.png) Output very large indeed: [![enter image description here](https://i.stack.imgur.com/TD9M9.png)](https://i.stack.imgur.com/TD9M9.png) [Answer] # Objective-C I saw this challenge last night and had an ever so slightly confusing time with `-[NSArray indexOfObject:inSortedRange:options:usingComparator:]`, hence the delay. ``` - (UIImage *)rubiksImage:(UIImage *)inputImg { //Thank you http://stackoverflow.com/a/11687434/1153630 for the greyscale code CGRect imageRect = CGRectMake(0, 0, inputImg.size.width, inputImg.size.height); int width = imageRect.size.width; int height = imageRect.size.height; uint32_t *pixels = (uint32_t*)malloc(width * height * sizeof(uint32_t)); memset(pixels, 0, width * height * sizeof(uint32_t)); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast); CGContextDrawImage(context, imageRect, [inputImg CGImage]); const int RED = 1; const int GREEN = 2; const int BLUE = 3; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { uint8_t* rgbaPixel = (uint8_t*)&pixels[y * width + x]; uint32_t grayPixel = 0.3 * rgbaPixel[RED] + 0.59 * rgbaPixel[GREEN] + 0.11 * rgbaPixel[BLUE]; NSArray *r = [self rubixColorFromGrey:grayPixel]; rgbaPixel[RED] = [r[2] integerValue]; rgbaPixel[GREEN] = [r[1] integerValue]; rgbaPixel[BLUE] = [r[0] integerValue]; } } CGImageRef newCGImage = CGBitmapContextCreateImage(context); CGContextRelease(context); CGColorSpaceRelease(colorSpace); free(pixels); UIImage* newUIImage = [UIImage imageWithCGImage:newCGImage]; CGImageRelease(newCGImage); return newUIImage; } - (NSArray *)rubixColorFromGrey:(uint32_t)p { NSArray *colors = @[@0, @51, @102, @153, @204, @255]; NSUInteger index = [colors indexOfObject:@(p) inSortedRange:NSMakeRange(0, colors.count) options:NSBinarySearchingInsertionIndex | NSBinarySearchingFirstEqual usingComparator:^(id a, id b) { return [a compare:b]; }]; switch (index) { case 0: return rgb(0, 81, 186); break; case 1: return rgb(196, 30, 58); break; case 2: return rgb(0, 156, 96); break; case 3: return rgb(255, 82, 0); break; case 4: return rgb(255, 213, 0); break; case 5: return rgb(255, 255, 255); break; default: break; } return colors; //go wild } NSArray *rgb(int r, int g, int b) { return @[@(r), @(g), @(b)]; } ``` I ran it on my iPad like so: ``` UIImageView *img = [[UIImageView alloc] initWithImage:[self rubiksImage:[UIImage imageNamed:@"danny.png"]]]; [img setCenter:self.view.center]; [self.view addSubview:img]; ``` **Before** ![Danny DeVito Before](https://i.stack.imgur.com/INK6z.jpg) **After** ![Danny DeVito After](https://i.stack.imgur.com/dADkt.jpg) **Before** ![Grace Kelly Before](https://i.stack.imgur.com/ZFzvl.jpg) **After** ![Grace Kelly After](https://i.stack.imgur.com/jfhjq.png) [Answer] # Python Format: `python rubik.py <input> <max_cubes> <output>`. Coverts pixel to grayscale using suggested algorithm. ``` import Image, sys def rubik(x, max_cubes = 25): img = x max_cubes *= 3 if x.size[0] > max_cubes or x.size[1] > max_cubes: print "Resizing image...", if x.size[0] > x.size[1]: img = x.resize((max_cubes, int(max_cubes * float(x.size[1]) / x.size[0])), Image.ANTIALIAS) else: img = x.resize((int((max_cubes * float(x.size[0]) / x.size[1])), max_cubes), Image.ANTIALIAS) if x.size[0] % 3 or x.size[1] % 3: print "Sizes aren't multiples of 3" return print "Image resized to %i x %i pixels" % img.size out = Image.new('RGB', img.size) print "Converting image...", for x in xrange(out.size[0]): for y in xrange(out.size[1]): r, g, b = img.getpixel((x, y)) if r == g == b == 255: out.putpixel((x,y), (255, 255, 255)) else: l = 0.2126 * r + 0.7152 * g + 0.0722 * b l /= 255 out.putpixel((x,y), ( (0x00, 0x51, 0xBA), (0xC4, 0x1E, 0x3A), (0x00, 0x9E, 0x60), (0xFF, 0x58, 0x00), (0xFF, 0xD5, 0x00) )[int(5 * (l <= 0.0031308 and 12.92 * l or 1.055 * l ** (1/2.4) - 0.055))]) print "Image converted successfully." print "Stats:" h, v = img.size[0] / 3, img.size[1] / 3 print " ", h, "horiz. Rubik cubes" print " ", v, "vert. Rubik cubes" print " ", h * v, "total Rubik cubes" return out.resize((out.size[0], out.size[1])) if __name__ == "__main__": rubik(Image.open(sys.argv[1]).convert("RGB"), int(sys.argv[2])).save(sys.argv[3]) ``` Input: [![Sandro Pertini](https://i.stack.imgur.com/h3E4Z.jpg)](https://i.stack.imgur.com/h3E4Z.jpg) (source: [ilmamilio.it](http://www.ilmamilio.it/m/images/images2/Varie/sandropertini.jpg)) Output with `max_cubes = 25`: ![Sandro Pertini, Rubik'd 1](https://i.stack.imgur.com/7G4Jr.png) Output with `max_cubes = 75`: ![Sandro Pertini, Rubik'd 2](https://i.stack.imgur.com/DYkn8.png) Output with `max_cubes = 225`: ![Sandro Pertini, Rubik'd 3](https://i.stack.imgur.com/XQh1A.png) ]
[Question] [ Let's consider the sequence of the binary representation of positive integers (without any leading zero): ``` 1 2 3 4 5 6 7 8 9 10 11 12 ... 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 ... ``` If we join them together, we get: ``` 1101110010111011110001001101010111100 ... ``` If we now look for the patterns `/1+0+/`, we can split it as follows: ``` 110 11100 10 1110 1111000 100 110 10 10 111100 ... ``` We define \$s\_n\$ as the length of the \$n\$-th pattern built that way. Your task is to generate this sequence. The first few terms are: ``` 3, 5, 2, 4, 7, 3, 3, 2, 2, 6, 3, 5, 9, 4, 4, 2, 3, 4, 3, 2, 2, 3, 3, 2, 8, 4, 4, 2, 3, 7, 4, 6, 11, 5, 5, ... ``` Related OEIS sequence: [A056062](https://oeis.org/A056062), which includes the binary representation of \$0\$ in the initial string and counts \$0\$'s and \$1\$'s separately. ## Rules You may either: * take \$n\$ as input and return the \$n\$-th term, 1-indexed * take \$n\$ as input and return the \$n\$-th term, 0-indexed * take \$n\$ as input and return the \$n\$ first terms * take no input and print the sequence forever This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. ## Some more examples The following terms are 1-indexed. ``` s(81) = 13 s(100) = 3 s(101) = 2 s(200) = 5 s(1000) = 5 s(1025) = 19 s(53249) = 29 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` mLġ≤ṁḋN ``` [Try it online!](https://tio.run/##yygtzv7/P9fnyMJHnUse7mx8uKPb7/9/AA "Husk – Try It Online") Takes no input and prints ALL the numbers! ### Explanation ``` mLġ≤ṁḋN N The list of all positive integers [1,2,3...] ṁḋ Convert each to binary and concatenate the resulting digits ġ≤ Split them in groups where each digit is less than or equal to the previous one (basically cuts wherever there is a 0 followed by a 1) mL Compute the length of each group ``` [Answer] # [Python](https://docs.python.org/3.8/), ~~77~~ 67 bytes ``` lambda n:len(''.join(f'{i:b}'for i in range(9*n)).split('01')[n])+2 ``` [Try it online!](https://tio.run/##VVDLToUwEN3zFbNrK@MNbUEeSV36Be64LLhatAYLKbBQwrcjd4w3MZnHyZmTk5kZv@b3wetiDHtnznvffl5eW/BVbz1n7PQxOM87trrqsrFuCODAeQitf7O8vPNCnKaxdzNniWSi9o2I1R7M@hwWWy3svKhcaobw1PbTH5G@sC2yptYIGYJCSBFyBE2hKB4IH9OSpimRmsBNc9MX/zU54cNBSrLIsIlocbTX1b/dyHs3zfz3BonXQ62IpRBxXUiUSXKkREWdisow0yotG7RxLTVqVHhQKEtUZSOqCCbTcSciGIPzM71rg/tHWKcN1lBbY6ZmY2L/AQ "Python 3.8 (pre-release) – Try It Online") Returns the \$n^\text{th}\$ term, 1-indexed. [Answer] # [MATL](https://github.com/lmendo/MATL), 15 bytes ``` E:"@B]v&Y'2esG) ``` This takes `n` as input and outputs the `n`-th term, 1-indexed. [Try it online!](https://tio.run/##y00syfn/39VKycEptkwtUt0otdhd8/9/QwMjUwA "MATL – Try It Online") ### Explanation A binary pattern of the specified form ends at least as often as every even number. So for input `n`, considering the numbers `1`, `2`, ..., `2*n` guarantees that at least `n` patterns are obtained. ``` E % Implicit input: n. Push 2*n :" % For each k in [| 2 ... 2*n] @ % Push k B % Binary expansion. Gives a row vector containing 1's and 0's ] % End v % Concatenate everything into a column vector &Y' % Lengths of run-length encoding. Runs contain 1's and 0's alternately 2e % Reshape as a two-column matrix, in column-major order s % Sum of each column. This gives the lenghts of the desired patterns G) % Take the n-th entry. Implicit display ``` [Answer] # [Haskell](https://www.haskell.org/), 80 bytes ``` ([1..]>>=f)#0 f 0=[] f x=f(div x 2)++[mod x 2] (0:1:x)#l=l+1:x#1 (a:x)#l=x#(l+1) ``` [Try it online!](https://tio.run/##JYhLCsMgEED3nmLALBRp0C4Dk4tYF5LEKjGpNKF4@kwtXb1P9Me65EwRHySs6Xs3jhgk1yyARusaKgYxpw9UuEul7Paaf@qY0IMZquQZs2rCDRP@35WLtiRtPu2AUN5pP6GD068LGA2Rrilk/zzoNpXyBQ "Haskell – Try It Online") Inspired by [Leo's Husk answer](https://codegolf.stackexchange.com/a/201403/64121), calculates an infinite list. [Answer] # [Octave](https://www.gnu.org/software/octave/), 62 bytes ``` @(n)diff(regexp([arrayfun(@dec2bin,1:4*n,'un',0){:}],'1+'))(n) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI08zJTMtTaMoNT21okAjOrGoKLEyrTRPwyElNdkoKTNPx9DKRCtPR700T13HQLPaqjZWR91QW11TE6jzf0lqcYmCrUK0haGCoYEBEBsqGIFpMGFkGmvNBTcwTUcBpFzzPwA "Octave – Try It Online") ### Explanation ``` @(n) % function with input n 1:4*n % range [1, 2, ... 4*n] arrayfun(@dec2bin, ,'un',0) % convert each to binary string [ {:}] % concat into one string regexp( ,'1+') % starting indices of runs of 1's diff( ) % consecutive differences (n) % take n-th entry ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes ``` ḤB€FI»0kƲẈḣ ``` [Try it online!](https://tio.run/##ASEA3v9qZWxsef//4bikQuKCrEZJwrswa8ay4bqI4bij////MjA "Jelly – Try It Online") A monadic link taking an integer \$n\$ and returning the first \$n\$ terms of the series. Change from `×9` to `Ḥ` inspired by @JonathanAllan’s answer. Thanks! [Answer] # [Ruby](https://www.ruby-lang.org/), 48 bytes ``` ->n{("%b%b"*n%[*1..n*2]).scan(/1+0+/)[n-1].size} ``` [Try it online!](https://tio.run/##VYzRCoJAEEV/ZREEdce1cTXroX5kWUJLaR9aJIu21G/fbB6E4DIc5h7u/dm8fXfw6dGOURA2YRMkNlQJCmGTXMdiONc2ypBveBYrm6IWg/m0s1cSWAksB1YAq4BJSk7ZEi/tntqCnpJgdVZ/9@9UxMsCIk2UWtzqXrzM43oy9tK6cXJgpp4pwxG639Xg9Oy/ "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞bSγ2ôεSg ``` ~~Untested, since TIO isn't working.. >.> But it should work (unless one of those builtins used isn't lazy). I'll try to finally install 05AB1E locally later today to verify if it indeed works.~~ EDIT: Installed 05AB1E locally, and apparently it didn't work due to the `J`oin on the infinite list. So here an alternative 9-byter that does actually work. Outputs the infinite sequence. [Try it online.](https://tio.run/##yy9OTMpM/f//Uce8pOBzm40Obzm3NTj9/38A) **Explanation:** ``` ∞ # Push an infinite list of positive integers: [1,2,3,4,5,6,...] b # Convert each to a binary string # → ["1","10","11","100","101","110",...] S # Convert it to a flattened list of digits # → [1,1,0,1,1,1,0,0,1,0,1,1,1,0,...] γ # Split them into parts of consecutive equal digits # → [[1,1],[0],[1,1,1],[0,0],[1],[0],[1,1,1],[0],...] 2ô # Split all that into parts of size 2 # → [[[1,1],[0]],[[1,1,1],[0,0]],[[1],[0]],[[1,1,1],[0]],...] ε # Map over each pair S # Convert it to a flattened list of digits again # → [[1,1,0],[1,1,1,0,0],[1,0],[1,1,1,0],...] g # Pop and push its length # → [3,5,2,4,...] # (after which the mapped infinite list is output implicitly as result) ``` [Answer] # [Perl 5](https://www.perl.org/) -n, 73 bytes ``` $_=join'',map{sprintf"%b",$_}1..($n=$_)*2;say y///c for(/1+0+/g)[0..$n-1] ``` [Try it online!](https://tio.run/##BcFdCoJAEADgq4hMqOnOT@BTeIROELFYZGzU7LLri0RXb/q@dM@v0Qz89IxBm2Z4z@lTUg66LvXuWg/gv4LYgk7gu/3hWOat2ojoVi0xtyQ99/TozowI6uRiJsy/mNYQtZg7jcjC5vQP "Perl 5 – Try It Online") Takes input `n` via stdin, prints the first `n` numbers in the sequence. [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 26 bytes ``` {x##'(&0>':t)_t:,/2\'!2*x} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqrpCWVldQ83ATt2qRDO@xEpH3yhGXdFIq6L2f5qCscF/AA "K (ngn/k) – Try It Online") Returns the first `n` items. # [J](http://jsoftware.com/), 35 bytes ``` {[:((1,2</\])#;.1])@;[:#:&.>[:i.3&* ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/q6OtNDQMdYxs9GNiNZWt9QxjNR2so62UrdT07KKtMvWM1bT@a3IpcKUmZ@QraFinaSoZaBhqZ@oZGWj@BwA "J – Try It Online") Returns the `n`th item [Answer] # [Haskell](https://www.haskell.org/), ~~135~~ 128 bytes * Saved seven bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs). ``` g$b=<<[1..] b 0=[];b n=b(div n 2)++[mod n 2] l(1:r)1=1+l r 1;l(0:r)0=1+l r 0;l(0:r)1=1+l r 0;l(1:r)0=0 g a=l a 1:g(drop(l a 1)a) ``` [Try it online!](https://tio.run/##Tcy7CoNAFATQfr9ighYrouyapPCxhYRgE4JNKmOxohhxfaCSJuTbjRELbzVnBu5LjnWh1PyxNNzCe/QIoysucQzN@pJRPOdSz0QQJNy2U5KBiST1M7Qio3n1RgvHMM2k6fJ/TImi3BsMLripMID7irLFbDPbzHfm685ICSkUJLhX0nzoerrCkMbcyKqFQN4RLNcPVTvBxiTrAq4LHeOuX4TDAfR8dE4urOXB/AM "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḤB€FŒgẈ+2/ḣ ``` A monadic Link accepting an integer, `n`, which yields a list of the first `n` values. **[Try it online!](https://tio.run/##ASAA3/9qZWxsef//4bikQuKCrEbFkmfhuogrMi/huKP///8xMA "Jelly – Try It Online")** ### How? ``` ḤB€FŒgẈ+2/ḣ - Link: integer, n Ḥ - double (n) € - for each v in (implicit range = [1..2n]): B - (v) to binary F - flatten Œg - group runs Ẉ - get lengths 2/ - 2-wise reduce by: + - addition ḣ - head to index (n) ``` [Answer] # bash + GNU utilities, ~~76~~ ~~58~~ 57 bytes ``` seq -f 2o%.fn $[2*$1]|dc|sed -E "s/(1*0*){$1}.*/\1Zp/"|dc ``` [Try it online!](https://tio.run/##FYo7DsIwEAV7TvG0MhJYss0GpYSOS/ApIF4rNGvAdEnObkwz0ozmcS9jTfkDxVMxsff7flkBMTfIMGY4BRnF4Qhqqcj3r1SLvOESurz2SWEunTV8m@MwF4lwJ1AJG7Y7u50ML96GK59fgdpQY1apPw "Bash – Try It Online") *Thanks to user41805 for suggestions that ended up shaving 18 bytes off! And for 1 more byte now too.* Takes \$n\$ as an argument, and prints the \$n^\text{th}\$ entry in the sequence (with 1-based indexing). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~34~~ 22 bytes ``` ≔…⌕A⭆⊗⊕θ⍘ι²01⊕θηI⁻⊟η⊟η ``` [Try it online!](https://tio.run/##VY3BCsIwEETvfkXoaQMRrNeeaqTgoVDwC2IamsC6qUkq@PVxpSfnMsPMg7HeJBsN1trnHBYC/bHotI8rDIHmHhHuJQVaRrPCNW4PdDPcyCb3dFQ4v6RU4mKy2zEISpx/VXNqG7Z/VAkvu8PEYAFtcoEx0JZh4jfP4@6srta2Ht/4BQ "Charcoal – Try It Online") Link is to verbose version of code. Based on @LuisMendo's observation that the numbers up to `2n` provide sufficient digits, although I search for `01` so I actually need `0` through `2n+1`. Explanation: ``` ⭆⊗⊕θ⍘ι² ``` Convert all the numbers from `0` to `2n+1` to base 2 and concatenate them. ``` ≔…⌕A...01⊕θη ``` Find the positions of the substrings `01` but truncated after the `n`th entry. ``` I⁻⊟η⊟η ``` Output the difference between the last two positions. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes ``` ×3ŻBFœṣØ.ḊẈ+2ḣ ``` [Try it online!](https://tio.run/##ASYA2f9qZWxsef//w5czxbtCRsWT4bmjw5gu4biK4bqIKzLhuKP///8xMA "Jelly – Try It Online") Thanks to @JonathanAllan and @NickKennedy for helping me out, in chat, to finish this solution. I came up with [`×3RBFœṣØ.Ẉ+2ḣ`](https://tio.run/##ASIA3f9qZWxsef//w5czUkJGxZPhuaPDmC7huogrMuG4o////zEw) but that fails for `n = 1`! **How it works**: ``` ×3ŻBFœṣØ.ḊẈ+2ḣ Monadic link: takes `n` as input and returns the first `n` terms ×3 Multiply input by three and Ż create the list [0, 1, ..., 3n]. B Get the binary representation of each number and F flatten to get [0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, ...] Now we find the /1+0+/ patterns by looking at occurrences of [0, 1], i.e. when one pattern ends and the next begins: œṣ Split the [0, 1, 1, 0, 1, 1, 1, 0 ...] list at occurrences of Ø. [0, 1], so [0, 1, 1, 0, 1, 1, 1, 0 ...] -> [[], [1], [1, 1, ...], ...] Ḋ and drop the first element of the resulting list (the empty one). Ẉ Finally we get the length of each sublist, +2 add 2 (to compensate for the lost 1 and 0), ḣ and take the first `n` elements of that. ``` [Answer] # [Red](http://www.red-lang.org), ~~122~~ 111 bytes ``` func[n][b: copy""repeat i 2 * n[append b find enbase/base to#{}i 2"1"]parse b[n copy i[any"1"any"0"]]length? i] ``` [Try it online!](https://tio.run/##PYyxDsIwDET3foVlNiREga0D/AOr5SFpHIiEXCtNhwrx7SFlYHkn3Z1ellDvEoi7ONS46EjK5AcYJ1sRs5i4AgnOsAclZyYawENMLUS9m@W4oSvT7v1pNzwhm8uzgCf9SSCR07X1G3tkfok@yvMGietff@nJctJCCfBwRYht5foF "Red – Try It Online") [Answer] # [PHP](https://php.net/), 108 bytes ``` for($a=[$p=$i=1];;$p=$c,$o++){if(!$a)$a=str_split(decbin(++$i));if($p<$c=array_shift($a)){echo$o,',';$o=0;}} ``` [Try it online!](https://tio.run/##FYxBCsMgEADfUliIix6as1n6kFKCtREXSndRLyHk7dZchjkMo1n78tDBJMVAoCcoAdP88v6y6ECsxYOTuUHAEdRW1qpfbuazxTf/jLXAiH4UoAtECqWEfa2ZUxtDxGOLWUDc5CYPQnd/nr3/AQ "PHP – Try It Online") Will print the sequence indefinitely. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 13 bytes ``` ḣ┅b¦_ėt(2/Σ¦E ``` [Try it online!](https://tio.run/##AR4A4f9nYWlh///huKPilIViwqZfxJd0KDIvzqPCpkX//zM "Gaia – Try It Online") Port of Luis' [MATL answer](https://codegolf.stackexchange.com/a/201400/67312). [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs the `n`th 1-indexed term. ``` g°U²ô¤¬ò<)l ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z7BVsvSkrPI8KWw&input=OA) ``` g°U²ô¤¬ò<)l :Implicit input of integer U g :Index into °U : Increment U ² : Square it ô : Range [0,result] ¤ : To binary strings ¬ : Join ò< : Partition after characters that are less than the next ) :End indexing l :Length ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~124~~ \$\cdots\$ ~~109~~ 104 bytes Saved ~~2~~ ~~3~~ ~~4~~ ~~8~~ ~~9~~ 14 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` c;t;b;i;f(n){for(i=c=0,t=1;++i;){for(b=0;i>>++b;);for(;b--;++c)if(t^i>>b&1&&(t^=1)?c*=!--n:0)return c;}} ``` [Try it online!](https://tio.run/##dY3NCsIwEITvPsUqWBLTQOvPQdfUFxHBrEYCGqWNGJC@ujH17@achvlmd0geiGIk9KjRomGO3825ZlaRKnKvShTC4jvTqkBbVUJo5NgFqKVMnLg1zG8S0lmZZcmqkq9opPpSukXB672/1g4I2zaettYxDvceJL2GnIeQZsJSTWYYhPjCTh1sQIFhgeMvvdQpN2ww3IGsYLhbu0EOIYfm02l7f1uzyXg6z9O/l@HpoI0PMsftoYny9gQ "C (gcc) – Try It Online") Goes through positive integers \$i\$ catching transitions from \$0\$ to \$1\$ as it rolls through the non-leading-zero bits of the \$i\$'s. Returns the \$n^\text{th}\$ term, 1-indexed. [Answer] # [W](https://github.com/A-ee/w) [`x`](https://codegolf.meta.stackexchange.com/questions/14337/command-line-flags-on-front-ends/14339#14339), 7 [bytes](https://github.com/A-ee/w/wiki/Code-Page) REALLY slow. The array is 1-indexed and it outputs all upto the input. (Glad that I tie with Husk BTW. Special bonus: it doesn't involve infinite lists!) ``` ♫│x╤►U╟ ``` Uncompressed: ``` ^k2BLHkr ``` # Explanation ``` ^ % 10 ^ input. Make sure that enough items are calculated. k % Find the length range of that. 2B % Convert every item to binary. % Since at least 1 item >= the base, this vectorizes. % Automatic flatten before grouping LH % Grouping: Is the previous item >= current item? kr % Reduce by length Flag:x % Output all items upto the input, including input-indexed item. 1-indexed. ``` # [W](https://github.com/A-ee/w) [`x`](https://codegolf.meta.stackexchange.com/questions/14337/command-line-flags-on-front-ends/14339#14339), 8 [bytes](https://github.com/A-ee/w/wiki/Code-Page) You can try this without having to wait for a long time. ``` ☺│╪å∟↕c╟ ``` Uncompressed: ``` 3*k2BLHkr ``` # Explanation ``` 3* % Input times 3, idea copied from RGS's answer. k % Provide a length-range 2B % Convert all to binary LH % Group by >= % Automatic flattening before grouping kr % Reduce by length Flag:x % Output all less than the input index. INCLUDING the input index item. ``` ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 17 bytes ``` {⍵⊃≢¨⊆⍨1+∊⊤¨⍳+⍨⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR79ZHXc2POhcdWvGoq@1R7wpD7UcdXY@6lgD5vZu1gQJAFbX/0x61TXjU2/eob6qnP1D9ofXGj9omAnnBQc5AMsTDM/i/uYKCrUKagimXoTGYYWHIZQwRMjQw4DKCMQ25TCFMI6CoKVyBAZehJZRtZMplBGGbGhuZWAIA "APL (Dyalog Extended) – Try It Online") Gives nth term, 1-indexed. ### How it works ``` {⍵⊃≢¨⊆⍨1+∊⊤¨⍳+⍨⍵} { } ⍝ ⍵←n +⍨⍵ ⍝ Double of n ⍳ ⍝ 1 .. 2n, inclusive ∊⊤¨ ⍝ Convert each to binary and flatten 1+ ⍝ Add 1 ⊆⍨ ⍝ Partition self into non-increasing segments ⍝ (Without 1+, zero items are dropped) ≢¨ ⍝ Lengths of each segment ⍵⊃ ⍝ Take nth item ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 67 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 8.375 bytes ``` Þ∞bfĠ2ẇvf@ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwiw57iiJ5iZsSgMuG6h3ZmQCIsIiIsIiJd) Bitstring: ``` 0010011101110110001111101100111001011111001011101000111011000011110 ``` [Answer] # [Factor](https://factorcode.org/), 92 bytes ``` : f ( n -- n ) dup 3 * [0,b] [ >bin ] map concat "01" " " replace " " split nth length 2 + ; ``` [Try it online!](https://tio.run/##LY49D4JAEER7f8XEyi8MSgeJhY2xoTFWhOI4F7yI67kshb8eTzCbzLzqzdbG6kuG6@Wcn1I8SJhaPI3ex9h6Ix3JxGK4oQ4dvXti@yPfOlXHDbyQ6seLY0U2O@cpjo6NfCJvVIOzG1LUWIARRSGWuPUeCVYo4k1VosChcowy7HjYF1ujmMe7OX4n5FtjaeRxERy@a4mbUHuskQ1JjGI3ieq/ZTt8AQ "Factor – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 29 bytes ``` {⍵+.=+\2</∊,(2∘⊥⍣¯1)¨⍳3+⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20Tqh/1btXWs9WOMbLRf9TRpaNh9KhjxqOupY96Fx9ab6h5aMWj3s3G2kBFtUD1//8DAA "APL (Dyalog Classic) – Try It Online") *Will post explanation soon!* [Answer] # [Zpr'(h](https://www.github.com/jfrech/Zpr-h/), 369 bytes ``` s |> \ ``` ``` (g (foldr (op-> ++) () (map b |N))) (e ())|>o (e (S ()))|>z (e (S (S .n)))|>(e n) (h ())|>() (h (S ()))|>() (h (S (S .n)))|>(S (h n)) (b ())|>() (b (S .n))|>((b (h (S n))) ++ (' (e n) ())) (l (' z (' o .r)))|>1 (l (' z (' z .r)))|>(S (l (' z r))) (l (' o (' o .r)))|>(S (l (' o r))) (l (' o (' z .r)))|>(S (l (' z r))) (g .a)|>(' (l a) (g (drop (l a) a))) <|prelude.zpr ``` ``` main |> (take 8 s) ``` # Execution ``` Zpr-h-master/stdlib$ ../Zprh --de-peano above.zpr (' 3 (' 5 (' 2 (' 4 (' 7 (' 3 (' 3 (' 2 0)))))))) ``` # Explanation ``` ; build the sequence by splitting the bits of all natural numbers |N sequence |> (generate (foldr (op-> ++) () (map bits |N))) ; compute if a natural number is even (parity shifted by one) (even ()) |> one (even (S ())) |> zero (even (S (S .n))) |> (even n) ; halve a natural number, rounding down (halve ()) |> () (halve (S ())) |> () (halve (S (S .n))) |> (S (halve n)) ; compute a natural number's binary representation (bits ()) |> () (bits (S .n)) |> ((bits (halve (S n))) ++ (' (even n) ())) ; compute the length of the pattern sought after at the bit stream's beginning (len (' zero (' one .rest))) |> 1 (len (' zero (' zero .rest))) |> (S (len (' zero rest))) (len (' one (' one .rest))) |> (S (len (' one rest))) (len (' one (' zero .rest))) |> (S (len (' zero rest))) (generate .all-bits) |> (' (len all-bits) \ (generate (drop (len all-bits) all-bits))) ; include from the standard library <| prelude.zpr ; output the first eight sequence members main |> (take 8 sequence) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 70 bytes ``` Tr[1^Join@@Partition[Split[Join@@IntegerDigits[Range[2#],2]],2][[#]]]& ``` [Try it online!](https://tio.run/##JYixCsIwEEB/RSg4BdqkFnQQMrjoVNTtOOGQEA/aq6S3id9@ah3ee/BG0kcaSflOlvd2LeBvp4klxp6KsvIkcHkOrPC/R9GUUzlwZp3hTJIThApdwB8AFSKurS8suqpjruNr651vmi/ehaWLQue6Nmx2b7MP "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ This challenge is a simple ASCII-art challenge inspired by the [solar eclipse](https://www.timeanddate.com/eclipse/globe/2017-august-21) that happened on August 21, 2017. Given an input `0 <= n <= 4`, output the corresponding stage of the eclipse described below: ``` n=0: ***** ** ** * * * * ** ** ******* n=1: ***** ** ***** * ******* * ******* ** ****** ******* n=2: ***** ********* *********** *********** *********** ******* n=3: ***** ***** ** ******* * ******* * ****** ** ******* n=4: ***** ** ** * * * * ** ** ******* ``` --- # Rules * You can 0 or 1 index, state what you chose. * The chars used are space and `*`, you may use any printable char for `*` (other than space). * Trailing spaces are optional (you may or may not have them). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count is the winner. [Answer] # [Python 2](https://docs.python.org/2/), ~~161~~ ~~149~~ ~~142~~ 135 bytes ``` lambda n,u=u' *':u''' ***** **** ** ** **** *******'''.translate({1:u[0<n<3],2:u[0<n<4],3:u[1<n<4]}) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPp9S2VF1BS92qVF1dXUFBQQsEuIAUMzMTIyOQCWQwMzEB2YxobDCHEawGqk1LC2iGXklRYl5xTmJJqka1oVVptIFNno1xrI4RlGkSq2MMZBqCmbWa/wuKMvNKFNI0MvMKSks0NDX/mwAA "Python 2 – Try It Online") -7 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~82~~ ~~81~~ ~~55~~ 43 bytes *-38 bytes thanks to Neil!* ``` Nν”{“⟲FEd⧴_³⟲”‖O¿﹪ν⁴«F﹪ν²G↗³↑²↖²↙³*↑¤*¿⁼ν¹‖ ``` [Try it online!](https://tio.run/##TU7BCsIwDL33K8JO7dgOU096VUFwOgbevMzZboPYzq6biPjttd0EhZDk5SXvpawLXaoCrd3JtjeH/nbhmkpGMt1IQwMACMPwLMGnb3jop2HASM4F8tIcB66xaCkjpBFAU3XtUVEZwYIxeBGnAkLpf2LmiEzhs1KSLk9t3lS1iWAegQOOHeueCzP1a/WQE3IbgTceNVM1cH/NRrRtEOmP9I9s7n2BnfdLnN/3WcpW5G1tYuPBxh1@AA "Charcoal – Try It Online") Link is to verbose version. I did for the heck of it. :P ~~I'll probably get out-golfed by 40 bytes.~~ ~~26~~ 38 bytes... Close enough? [Answer] # [Cinnamon Gum](https://github.com/quartata/cinnamon-gum), 70 bytes Hexdump: ``` 0000000: 6c33 5053 5050 d002 012e 20a5 0002 4026 l3PSPP.... ...@& 0000010: 9001 0568 6c20 07a6 0648 4080 b521 8a19 ...hl ...H@..!.. 0000020: 30a6 1644 1093 0de3 a098 6184 6206 422d 0..D......a.b.B- 0000030: 6136 c20c 6374 3380 3cb8 5aa0 1436 36ba a6..ct3.<.Z..66. 0000040: 5f4c 280f 0f00 _L(... ``` [Try it online!](https://tio.run/##dY@xTsRADER7vmJoEM1Zs@td3wZRnBAFBUUkOhq02VwA6S408P3BudAykm1Z1jzb7XOe6/lr3r3/nJeFm@5gTRWZ@ZKIkYxgiEdE1gyubWI04KT9S9@LCx6Hm6sLIDii8wJmKw6LBPfVQEvFjYUYcgwoNXRYfR@nNT8dRK5FNkR0hNI9wVJCYKfgeFRUdk4MJcEiDSnGEaDIo1xUZZCH3YbQ9ZGgBt/fYLpPUPXd2oaCXCsRkk/VhgpUE2nfKvfyKmL2d0VyRJ5SQyycwInE/3p7vvULlkV/AQ "Cinnamon Gum – Try It Online") I have been waiting *so long* to find out how to use this language. :P So, Cinnamon Gum is Bubblegum, but it's more of a "real" language than Bubblegum. The first byte (`l`) sets the mode to dictionary mode. The rest of the bytes is the following string compressed. ``` 0& ***** ** ** * * * * ** ** *******;1& ***** ** ***** * ******* * ******* ** ****** *******;2& ***** ********* *********** *********** *********** *******;3& ***** ***** ** ******* * ******* * ****** ** *******;4& ***** ** ** * * * * ** ** ******* ``` This essentially makes a lookup table with each text assigned to a number. The program then takes input and outputs the respective text. [Answer] ## JavaScript (ES6), ~~103~~ 102 bytes ``` f= n=>` ***** **66733**${s=` *666777333*`}${s} **6667333** *******`.replace(/\d/g,c=>" *"[c*2>>n&1]) ``` ``` <input type=number min=0 max=4 oninput=o.textContent=f(this.value)><pre id=o> ``` Edit: Saved 1 byte thanks to @darrylyeo. [Answer] # VI, 108 bytes ``` D:let@a=@"%2?@":@"%4?"X":"\\d"<CR> 3i <Esc>5a*<Esc>Yphr*$a*<Esc>O**1110333**<Esc>YPi <Esc>3lx3lx"0px4lyl2p$xYp :%s/<C-r>a/ /g<CR> :%s/\d/*/g<CR> ``` `<CR>` is the `Enter` stroke, `<C-?>` corresponds to `Control + ?`, and `<Esc>` to `Escape` obviously. Each of these count for 1 byte (see [meta](https://codegolf.meta.stackexchange.com/questions/8995/how-should-vim-answers-be-scored)). The line breaks in the solution is for readability. Only `<CR>` represents real `Enter` strokes. ## Input The input file should contain only 1 character, representing `n`. ## Launch VI should be started like : ``` vi -u NONE input ``` ## Explanations There are 3 parts in the solution. I will describe the 2nd part first (2nd line), since it is the easiest to explain. ### Drawing the sun The command to draw the sun is : ``` 3i <Esc>5a*<Esc>Yphr*$a*<Esc>O**1110333**<Esc>YPi <Esc>3lx3lx"0px4lyl2p$xYp ``` The sun must be drawn with , `*`, `0`, `1` and `3`, like this : ``` ***** **11033** *111000333* *111000333* **1110333** ******* ``` A symmetry would have helped to reduce the bytes size of this part, but it's not that important. I will not explain the full line, but the pattern `*****` is used to easily generate the last line, and the pattern `**1110333**` has been taken as a reference to generate the 3 other lines containing `0`, `1` and `3`. It is important to use `0`, `1` and `3` for sun parts that can be filled (see next explanations). Drawing this sun takes **55 bytes**, and can probably be golfed with some tricks. ### Filling the sun according to `n` To correctly fill the sun, the instructions to follow are : * if `n = 0`, then `0`, `1` and `3` (all digits) should be replaced with * if `n = 1`, then `1` should be replaced with , the other digits with `*` * if `n = 2`, then `0`, `1` and `3` (all digits) should be replaced with `*` * if `n = 3`, then `3` should be replaced with , the other digits with `*` * if `n = 4`, then `0`, `1` and `3` (all digits) should be replaced with (like `n = 0`) From that, we can infer that the substitutions required are : * replace some digits by (**first substitution**) * replace all other digits by `*` (**second substitution**) Note that "some digits" can mean "no digits" (`n = 2` for example). And "all other digits" can also represent "no digits", if all digits have already been replaced by the first substitution (`n = 0` for example). The **second substitution** can be easily written in **11 bytes** : ``` :%s/\d/*/g<CR> ``` The **first substitution** depends on `n`, so first we have to calculate what digits are going to be replaced. If replaced characters are stored in register `a`, the substitution command is written in also **11 bytes** : ``` :%s/<C-r>a/ /g<CR> ``` `<C-r>a` is replaced by the content of register `a` when the command is typed. To calculate the value of `a`, following the previous instructions, the algorithm is (in pseudo-code) : ``` n := read() if (n % 2 != 0) then a := n else if(n % 4 != 0) then a := "X" else a := "\d" ``` `"X"` string is used because when `n = 2`, no digits are replaced by spaces. Any string that is not the sun could be used here, as long as the first substitution does nothing. This could be written in **31 bytes** : ``` D # yank and delete the first character of the file (n) to register "" (yank by default) : n = @" :let@a= # define register "a content @"%2 # if (n % 2 != 0) ? # then @" # n : # else @"%4 # if (n % 4 != 0) ? # then "X" # "X" : # else "\\d" # "\\d" <CR> # calculate "a ``` ## Solution Put all these parts in the right order, and you have the solution : ``` D:let@a=@"%2?@":@"%4?"X":"\\d"<CR> # calculate the digits to replace with spaces 3i <Esc>5a*<Esc>Yphr*$a*<Esc>O**1110333**<Esc>YPi <Esc>3lx3lx"0px4lyl2p$xYp # draw the sun with spaces, stars, 0, 1 and 3 :%s/<C-r>a/ /g<CR> # replace the pattern stored in register "a with spaces :%s/\d/*/g<CR> # replace the remaining digits with stars ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~40~~ 39 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` "⁽Ρūa╔Ƨ ‘╥▓.4%?52"¹ο1¹‘╬¡╬5.H?:±}.2=?╬8 ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIyJXUyMDdEJXUwM0ExJXUwMTZCYSV1MjU1NCV1MDFBNyUwOSV1MjAxOCV1MjU2NSV1MjU5My40JTI1JTNGNTIlMjIlQjkldTAzQkYxJUI5JXUyMDE4JXUyNTZDJUExJXUyNTZDNS5IJTNGJTNBJUIxJTdELjIlM0QlM0YldTI1NkM4,inputs=Mw__) [Answer] # PHP, 114+1 bytes +1 byte for `-R`. Thanks @Neil for the shifting hint. ``` for(;$c=" ***** **66733** *666777333* *666777333* **6667333** *******"[$i++];)echo+$c?" *"[$c*2>>$argn&1]:$c; ``` uses underscore for `*`, 0-indexed. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/b401e2216289548411f20cea123052be7d84e144). Requires PHP 5.5 or later: older PHP does not understand literal string indexing (parse error); PHP 7.1 complains about non-numeric values (replace `+$c` with `$c>0` to fix). [Answer] # Java 8, ~~225~~ ~~213~~ ~~211~~ 200 bytes ``` n->{String y=" ",z="***",a=n<2|n>3?y:z,b=n<1|n>2?y:z,c=n%4<1?" ":"*",d=a+(n%4<1?y:z)+b;return y+z+"**\n **"+(n<2|n>3?" ":"**")+c+(n<1|n>2?" ":"**")+"**\n*"+d+"*\n*"+d+"*\n**"+a+c+b+"**\n *"+z+z;} ``` -11 bytes thanks to *@ceilingcat*. [Try it here.](https://tio.run/##dVDLboMwELz3K1aWKgEmqElzCjj5gubSY9uDeaRyShYEJhKkfDudgA@5VLLlnd2ZsXbO@qpXVV3wOf@ZslK3Lb1pw7cnIsO2aE46K@h4h0TvtjH8TZmHCbEfozni4rRWW5PRkZgUTbza3xy3VwJCEQ5KBEEgQq042fzy/vXQ74YwBVoDbWaUKX7eJuuDILET4OZKS29pYezLNG4K2zVMvRwk7D6ZYAmKc8RPd2EgfJndu4vzQ3fWQJGjeixQaUhSZ0rAgxzicYqX7eouLbGdW/JamZwuyMhbdvz4Iu0vAZ2qZs7GqJeYTKJoi0dKN0WAfWuLS1R1NqohtSV7HCFOf87yH4abjXPa4/QH) [Answer] # [Python 2](https://docs.python.org/2/), ~~170~~ 169 bytes * -1 byte thanks to @TheIOSCoder: use of exec ``` def f(x,k=0):exec'print"".join(ord(i)*" *"[j%2]for j,i in enumerate(["  "," "," !",""][x%4]))[11*k:][:11];k+=1;'*6 ``` [Try it online!](https://tio.run/##RY7RCoIwGEbZv8z0KdZA2kyimXSh@CRjF5EbTWkTMbCnt/BC7w7n48DXf8eXd/k8N9oQw6asq6@81JN@nvrBupHSS@utY35omOUpJSmVbZIr4wfSZpZYR7T7vPXwGDWTFAc7CAChCCIcAoRAs8VBgBA@4AjvVxeh48oBAAr/e4iXRskpKRTnUoi0K5UshVBVd65FdUrvs2GCx8u52LB8w9uGBZ@LHw "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 181 bytes ``` lambda n,s=' ',a='*':""" ***** **%s** *%s* *%s* **%s** *******"""%[(s*5,s*9,s*9,s*7),(s*2+a*3,s*3+a*6,s*3+a*6,s*3+a*4),(a*5,a*9,a*9,a*7),(a*3+s*2,a*6+s*3,a*6+s*3,a*4+s*3)][n%4] ``` [Try it online!](https://tio.run/##XY7NCoMwEITvfYpFkJg1PWj8oYJPYj1saW0DNorx0qdPN9WDdGH3Y4YZ2Pmzviab@6G9@pHetzuBVa4VIBS1AkUTRREAYJgTI3bMcPezGXsAkdNxlzgslcPLvrVU7OQpoWalmdUfC04Qd4jz29Y/R6fcY1Ux9YFFoOw7Gxe9H6YFDBgLC9nnIyllw@8AzIuxKwyJkQcpzgKzzH8B "Python 2 – Try It Online") Very naive approach, ~~workin' on golfin'~~ nvm. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 46 bytes ``` „* •zÇRéóĀ—ÚÂÐoʒ<]ÜA›¶Ò¿H¶ ∞m•b3äûIèSèJ6äIií}» ``` [Try it online!](https://tio.run/##AVkApv8wNWFiMWX//@KAniog4oCiesOHUsOpw7PEgOKAlMOaw4LDkG/Kkjxdw5xB4oC6wrbDksK/SMK2IOKInm3igKJiM8Okw7tJw6hTw6hKNsOkSWnDrX3Cu///MQ "05AB1E – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 48 bytes ``` ‛* »>ṪÞ£Ǔḟṅ↲Ṅ²3@qx⋎ ṡµ⌈İ∆µ^X1»bṅ3/∞?if⌊İṅ6/?1=[R ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwi4oCbKiDCuz7huarDnsKjx5PhuJ/huYXihrLhuYTCsjNAcXjii45cbuG5ocK14oyIxLDiiIbCtV5YMcK7YuG5hTMv4oieP2lm4oyKxLDhuYU2Lz8xPVtSIiwiIiwiMSJd) ## How? ``` ‛* »>ṪÞ£Ǔḟṅ↲Ṅ²3@qx⋎ ṡµ⌈İ∆µ^X1»bṅ3/∞?if⌊İṅ6/?1=[R ‛* # Push string "* " »>ṪÞ£Ǔḟṅ↲Ṅ²3@qx⋎\nṡµ⌈İ∆µ^X1» # Push compressed integer 90018261496673587326026870693610373816328976440801592144686583 b # Convert it to binary ṅ # Join by nothing 3/ # Split it into 3 equal parts ∞ # Palindromise this list ? # Push the input i # Index it into the list f # Convert to list of characters ⌊ # Convert each to an integer İ # Index each into the other string ("* ") ṅ # Join by nothing 6/ # Split into six equal parts ?1=[ # If the input is equal to one: R # Reverse each ``` ]
[Question] [ 2013 has the prime factorization `3*11*61`. 2014 has the prime factorization `2*19*53`. An interesting property regarding these factorizations is that there exist distinct primes in the factorizations of 2013 and 2014 that sum to the same number: `11+61=19+53=72`. Write a program or function that takes as its input two positive integers greater than 1 and returns a truthy value if there exist a sum of selected prime factors of one number that is equal to a sum of selected prime factors in the second number, and a falsey value otherwise. --- **Clarifications** * More than two prime factors can be used. Not all of the prime factors of the number need to be used in the sum. It is not necessary for the number of primes used from the two numbers to be equal. * Even if a prime is raised to some power greater than 1 in the factorization of a number, it can only be used once in the sum of primes for the number. * 1 is not prime. * Both input numbers will be less than `2^32-1`. --- **Test cases** ``` 5,6 5=5 6=2*3 5=2+3 ==>True 2013,2014 2013=3*11*61 2014=2*19*53 11+61=19+53 ==>True 8,15 8=2^3 15=3*5 No possible sum ==>False 21,25 21=3*7 25=5^2 No possible sum (can't do 3+7=5+5 because of exponent) ==>False ``` --- This is code golf. Standard rules apply. Shortest code in bytes wins. [Answer] # Julia, ~~95~~ 93 bytes ``` g(x)=reduce(vcat,map(p->map(sum,p),partitions([keys(factor(x))...]))) f(a,b)=g(a)∩g(b)!=[] ``` The primary function is `f` and it calls a helper function `g`. Ungolfed: ``` function g(x::Integer) # Find the sum of each combination of prime factors of the input return reduce(vcat, map(p -> map(sum, p), partitions([keys(factor(x))...]))) end function f(a::Integer, b::Integer) # Determine whether there's a nonzero intersection of the factor # sums of a and b return !isempty(g(a) ∩ g(b)) end ``` Saved 2 bytes thanks to Darth Alephalpha [Answer] ## Pyth, 11 bytes ``` t@FmsMy{PdQ ``` Input in the form `30,7`. ``` t@FmsMy{PdQ implicit: Q=input tuple y powerset of { unique elements of Pd prime factorizations of d sM Map sum over each element of the powerset sMy{Pd lambda d: all sums of unique prime factors of d m Q Map over Q. Produces a two-element list. @F Fold list intersection t Remove first element, which is a 0. If no other common sums, the remaining empty list is falsy. ``` [Answer] # Pyth - ~~17~~ ~~12~~ 11 bytes *Thanks to @FryAmTheEggman for fixing my answer and saving a byte.* ``` @FmsMty{PdQ ``` [Test Suite](http://pyth.herokuapp.com/?code=%40FmsMty%7BPdQ&test_suite=1&test_suite_input=5%2C+6%0A2014%2C+2013%0A8%2C+15%0A21%2C+25&debug=0). [Answer] ## Haskell, ~~115~~ 106 bytes ``` import Data.Numbers.Primes import Data.List p=map sum.tail.subsequences.nub.primeFactors a#b=p a/=p a\\p b ``` Usage example: `2013 # 2014` -> `True`. `p` makes a list of all prime factors of it's argument, removes duplicates, makes a list of all subsequences, drops the first one (which is always the empty list) and finally sums the subsequences. `#` checks whether `p a` is not equal to the difference `p a \\ p b`. If not equal, they have at least one common element. [Answer] # Japt, 25 bytes ``` [UV]=N®k â à mx};Ud@J<VbX ``` Outputs `true` or `false`. [Try it online!](http://ethproductions.github.io/japt?v=master&code=W1VWXT1Ormsg4iDgIG14fTtVZEBKPFZiWA==&input=MjAxMyAyMDE0) ### Ungolfed and explanation ``` [UV]=N® k â à mx};Ud@ J<VbX [UV]=NmZ{Zk â à mx};UdX{J<VbX // Implicit: N = list of inputs [UV]=N // Set variables U and V to the first to items in N, mZ{ } // with each item Z mapped to: Zk // Generate list of Z's factors. â // Keep only the unique items. à // Generate all combinations. mx // Sum each combination. UdX{ // Check if any item X in U fulfills this condition: J<VbX // -1 is less than V.indexOf(X). // Implicit: output last expression ``` For an extra byte, you can split up the factorize-unique-combine-sum code between both inputs, with the added advantage of having a time complexity of `O(O(25-byte version)^2)`: ``` Uk â à mx d@J<Vk â à mx bX ``` [Answer] ## CJam, 23 bytes ``` q~{mf_&0a\{1$f++}/}/&0- ``` [Test it here.](http://cjam.aditsu.net/#code=q~%7Bmf_%260a%5C%7B1%24f%2B%2B%7D%2F%7D%2F%260-&input=%5B2013%202014%5D) The truthy value will be all common sums concatenated, the falsy value is the empty string. ### Explanation ``` q~ e# Read and evaluate input. { e# For each of the two numbers... mf e# Get the prime factors. _& e# Remove duplicates. 0a\ e# Put an array containing a 0 below to initialise the list of possible sums. { e# For each prime factor... 1$ e# Make a copy of the available sums so far. f+ e# Add the current factor to each of them. + e# Combine with the list of sums without that factor. }/ }/ & e# Set intersection between the two lists of sums. 0- e# Remove the 0 which is always in the intersection. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~10~~ 9 bytes ``` {ḋd⊇+ℕ₁}ᵛ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompkcdy5VKikpTlfRqQMy0xJziVKXa04vK/1c/3NGd8qirXftRy9RHTY21D7fO/v8/OtpUxyxWJ9rIwNBYB0iYANkWOoamICFDHSPT2FgA "Brachylog – Try It Online") The predicate succeeds returning `[the sum, the sum]` if it exists, and fails if the sum does not exist. ``` { Start of inline predicate. ḋ The prime factors of the input, d with duplicates removed. ⊇ Some subset of the unique prime factors +ℕ₁ has a sum greater than 0 which is output. }ᵛ The predicate can have the same output for both elements of the input. ``` -1 byte thanks to Fatalize (the creator of Brachylog) reminding me that the *verify* meta-predicate exists. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 23 bytes ``` 2:"iYfutn2w^1-:B!Y*]!=z ``` Uses current release, [2.0.2](https://github.com/lmendo/MATL/releases/tag/2.0.2), which is earlier than this challenge. The numbers are provided as two separate inputs. Output is `0` or `1`. ### Example ``` >> matl 2:"iYfutn2w^1-:B!Y*]!=z > 2013 > 2014 1 ``` ### Explanation ``` 2: % vector of two numbers, to generate two iterations " % for loop i % input number Yfu % get prime factors without repetitions tn % duplicate and get number of elements in array N 2w^1-: % numbers from 1 to 2^N B!Y* % convert to binary, transpose and matrix multiply to produce all sums ] % end !=z % true if any value is equal to any other ``` [Answer] # Mathematica, 58 bytes ``` Tr/@Rest@Subsets[#&@@@FactorInteger@#]&/@IntersectingQ@##& ``` ### Explanation: This is an anonymous function. First, `IntersectingQ` checks if two lists are intersecting. But the inputs are numbers instead of lists, so it remains unevaluated. For example, if the inputs are `2013` and `2014`, then `IntersectingQ@##&` returns `IntersectingQ[2013, 2014]`. `Tr/@Rest@Subsets[#&@@@FactorInteger@#]&` is another anonymous function that takes an integer, gets a list of its prime factors without repetitions, takes the power set, removes the empty set, and then takes the sum of each set. So `Tr/@Rest@Subsets[#&@@@FactorInteger@#]&[2013]` returns `{3, 11, 61, 14, 64, 72, 75}`. Then map `Tr/@Rest@Subsets[#&@@@FactorInteger@#]&` over the expression `IntersectingQ[2013, 2014]`. `Tr/@Rest@Subsets[#&@@@FactorInteger@#]&[2013]` and `Tr/@Rest@Subsets[#&@@@FactorInteger@#]&[2014]]` are lists, so we can get the collect result this time. [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), 98 bytes Factor, grab primes (`[,1]`), loop over nonempty subsets, sum, and uniq, then intersect the result of this for the two numbers. The returned value is the number of intersections, which is truthy unless they are 0. ``` f(n,v=factor(n)[,1])=Set(vector(2^#v-1,i,vecsum(vecextract(v,i)))) g(m,n)=#setintersect(f(m),f(n)) ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~23~~ 17 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") -5 thanks to ngn Anonymous tacit infix function. ``` 1<≢⍤∩⍥(∊0+⍀.,∪⍤⍭) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/w0fdXTZPupteNS7tLpAW@/w9EddSwwftU1@1LvZSOtR56ICoKpHHase9a591Lu19n8aiNvbB9Hf1XxovfGjtolAXnCQM5AM8fAM/m@qkKZgxmVkYGgMZAApEy4LIMPQlMvIECRgCgA "APL (Dyalog Extended) – Try It Online") `⍥{`…`}` apply the following anonymous function to both arguments:  `⍭` prime factors  `⍤` then  `∪` the unique ones of those  `0+⍀.,` addition table reduction of zero concatenated to each factor  `∊` **ϵ**nlist (flatten) `∩` the intersection `⍤` then `≢` the tally of those `1<` is there more than one? (one because the sums of no factors) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` f€æO`å¦à ``` -2 bytes thanks to *@Emigna*. [Try it online](https://tio.run/##yy9OTMpM/f8/7VHTmsPL/BMOLz207PCC//@jjQwMjXWAhEksAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/tEdNaw4v8084vPTQssML/uv8j4421TGL1Yk2MjA01gESJkC2hY6hKUjIUMfINDYWAA). **Explanation:** ``` f # Get all distinct prime factors of both values in the (implicit) input-list # i.e. [2013,2014] → [[3,11,61],[2,19,53]] €æ # Get the powerset for each # → [[[],[3],[11],[3,11],[61],[3,61],[11,61],[3,11,61]], # [[],[2],[19],[2,19],[53],[2,53],[19,53],[2,19,53]]] O # Sum each inner-most list # → [[0,3,11,14,61,64,72,75],[0,2,19,21,53,55,72,74]] ` # Push both lists to the stack å # Check for each value in the second list if it's present in the first list # → [1,0,0,0,0,0,1,0] ¦ # Remove the first item (since the powerset included empty leading lists) # → [0,0,0,0,0,1,0] à # Check if any are truthy by taking the maximum (which is output implicitly) # → 1 ``` [Answer] # Japt, 12 bytes ``` ®k â à mx rø ``` [Run it online](https://ethproductions.github.io/japt/?v=1.4.6&code=rmsg4iDgIG14CnL4&input=WwpbNSw2XSwKWzIwMTMsMjAxNF0sCls4LDE1XSwKWzIxLDI1XQpdCi1tUg==) [Answer] # [Python 3](https://docs.python.org/3/), 206 bytes This is a lambda function (m), which takes in 2 numbers and returns a set containing any sums of prime factors that they have in common. In Python this is a truthy value when non-empty, and a falsey value when empty. Edit: Turns out my original answer didn't work for prime inputs, as pointed out by @JoKing. This has been fixed (along with some other bugs) at the tragic cost of 40 bytes. ``` q=__import__('itertools').permutations def p(n): i,s=2,set() while~-n: if n%i:i+=1 else:n//=i;s|={i} return s s=lambda f:{sum(i)for l in range(1,len(f)+1)for i in q(f,l)} m=lambda a,b:s(p(a))&s(p(b)) ``` Quick explanation using comments: ``` #Alias for permutations function q=__import__('itertools').permutations #Returns set of prime factors of n, including n, if prime def p(n): i,s=2,set() while~-n: if n%i:i+=1 else:n//=i;s|={i} return s #Returns all possible sums of 2 or more elements in the given set s=lambda f:{sum(i)for l in range(1,len(f)+1)for i in q(f,l)} #Returns any shared possible sums of prime factors of a and b (the intersection of the sets) m=lambda a,b:s(p(a))&s(p(b)) ``` [Try it online!](https://tio.run/##TYvdagMhEIXvfQpvmswQ29RNU8IWn2VxiTYDOhp1KSVNX327KQRycw7f@cnf7ZR4N89nMwwUcyptGGBNzZWWUqhrfMmuxKnZRomrODovMzD2QpKqplPVNUAhv04U3O8zL7kkL/mJetoYvZAL1fW83Rr6qD/mQlchi2tTYVlFNcHG8Wil7y91ikDoU5FBEsti@dOBVsExeNzo/4ZuzRm8CngV8X62auwrZLCIq5uPiHMuxA0i7NU7orhT96p3apG3h@yg9P5xolW38PwH "Python 3 – Try It Online") [Answer] # APL(NARS), 50 char, 100 bytes ``` {⍬≢↑∩/+/¨¨{⍵∼⊂⍬}¨{0=⍴⍵:⊂⍬⋄s,(⊂1⌷⍵),¨s←∇1↓⍵}¨∪¨π¨⍵} ``` here π would find the array of factors on its argument; ``` {0=⍴⍵:⊂⍬⋄s,(⊂1⌷⍵),¨s←∇1↓⍵} ``` would be the function that find all subsets... i have to say that it seems {⍵operator itsArguments}¨ (for each left) and ¨ (for each right) can imitate loop with fixed number of cycles and ¨¨ is ok in to see subsets of one set... this way of see it seems reduce symbols in describe loops...; test ``` h←{⍬≢↑∩/+/¨¨{⍵∼⊂⍬}¨{0=⍴⍵:⊂⍬⋄s,(⊂1⌷⍵),¨s←∇1↓⍵}¨∪¨π¨⍵} h 5 6 1 h 2013 2014 1 h 8 15 0 h 21 25 0 ``` One little analysis: ``` π¨⍵ for each arg apply factor ∪¨ for each arg apply unique {0=⍴⍵:⊂⍬⋄s,(⊂1⌷⍵),¨s←∇1↓⍵}¨ for each arg apply subsets {⍵∼⊂⍬}¨ for each argument subtract Zilde enclosed (that would be the void set) +/¨¨ for each arg (for each arg apply +/) ⍬≢↑∩/ apply intersection, get the first argument and see if it is Zilde (this it is right because enclosed Zilde it seems is the void set) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-¡`](https://codegolf.meta.stackexchange.com/a/14339/), 14 bytes ``` ®k â ã mx rf Ê ``` Saved 3 bytes thanks to @Shaggy [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LaE&code=rmsg4iDjIG14CnJmIMo&input=WzIwMTMsMjAxNF0) [Answer] # [Gaia](https://github.com/splcurran/Gaia), ~~16~~ 11 bytes ``` ḍzΣ¦ ↑@↑&ỵ! ``` [Try it online!](https://tio.run/##S0/MTPz//@GO3qpziw8t43rUNtEBiNUe7t6q@P@/kYGhCReQMAYA "Gaia – Try It Online") The top function (first line) calculates the sums of the powerset of prime factors, and the second function finds if any of the elements of the intersection are nonzero. ]
[Question] [ I recently decided to download some dictation software, in order to help with my writing. However, it doesn't work very well when I'm coding, since I have to change from saying words to symbols and back again. It's even worse when I'm coding in an esoteric language which is *all* symbols. In order to make my use of the dictation program more consistent, I decided to switch it over to character mode, where I just say the name of each character instead. Problem solved! Though this does delay my novel's release date a little bit... So, assuming that the longer the name of a character, the longer it takes to say, how long will it take me to spell out some of my programs/sentences? ## Specifications Given a string consisting of only printable ASCII, return the sum of each character's unicode name. For example, `/` is called `SOLIDUS` with 7 characters, and `A` is `LATIN CAPITAL LETTER A` with 22 characters. But remember, I have to say your programs out loud to execute them, so their score will be based on how long it takes me to say them, i.e. as the sum of the lengths of each character's unicode name. ## Test Cases: In format `input => output` with no trailing/leading spaces in input. ``` A => 22 / => 7 Once upon a time... => 304 slurp.uninames>>.comb.sum.say => 530 JoKing => 124 !" #$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ => 1591 Double-check your \s on the last test case ;) => 755 <say "<$_>~~.EVAL">~~.EVAL => 388 ,[.,] => 58 19 => 19 ``` ### Rules: * Input to your program will only consist of printable ASCII characters, that is, the codepoints 32 (space) to 126 (tilde). + For convenience sake, here is the list of lengths of the characters you have to handle: `[5,16,14,11,11,12,9,10,16,17,8,9,5,12,9,7,10,9,9,11,10,10,9,11,11,10,5,9,14,11,17,13,13,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,19,15,20,17,8,12,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,18,13,19,5]` * Here is a [reference program](https://tio.run/##dY89C8IwEIZ3f8URqGgNh6h1KXSwq6NuLlFjW2yTkA@xiP71GlOHOnhwB8dzH@@ruK7XXWdYCyQvmQaAvagEazgMY8tFYUvIpRMWdtKSdBRWgNxhNX@Z2mmFJ9kcccMKNFLbSYxX3k6zDMcPpSthL0AiA9Ei8WV5higJeRCEwmeyr@j65xRmwzacpnhjteO/g4HEPUn/gSca13iTQeWXG68sCPYIvZc3) you can use to score your program. + Peter Taylor has pointed out that the reference program normalises some [unicode characters](https://tio.run/##K0gtyjH7/784sVLBwsTCTC85o0gvvyjl/38A). It should still work for most solutions, but feel free to correct it if you need * Since you're saying what the characters actually look like, your solution will be scored by the *characters* that are displayed, not the bytes involved. This is directed at languages with custom encodings. + You can assume that I've memorised the entire Unicode library and can say whatever strange characters you use. * Sorry Rogem, but answers have to be composed of displayable characters. Unprintables are fine, I just have to be able to read the characters out loud. * Whatever you do, do not use [`ﯹ`](https://tio.run/##K0gtyjH7/784sVJBoybOoMLIAAg09XITKzS09ErzMvMSc1P1kjMSi4o1YVzr//8B) in your program. [Answer] # Java 8, score ~~[846](https://tio.run/##dU9NC4JAEL33K4ZFwzUb@r4EHuoaneoWxGabSrrKfkQS9ddN14sdGpgHM@@9GV7JZbaqa8UqINuESQA4ilSwnEO/dlzEOoFtYYSGQ6HJemAtQJ6wmHxUZmSJUZFfcMNiVIXUno93XtEwxOGrlKnQNyCuAne2bGB@BXdp@yRIAK2yQzTd8wBG/dGeDvDBMsN/hZbxO2b9j3ijMnldO@PQwZyV3nk6DtuwLNJcYsz1vjE0W4qZzelR2jo8@gU)~~ ~~[838](https://tio.run/##dU@7DoJAEOz9is0FDIe4Mb4aEgppjZV2NqeeYISD3MNojMbaT/UnEI4GCzfZSXZnZjdTcpnNq0qxG5A4ZRIANuIkWM6hW0suEp1CXBihYV1oEvasBcgVpqOnyowscV/kO1ywBFUhtefjmd9oFGH/XsqT0EcgrgJ3PKthcgB3ZnsrSACNskU07fMABt3Rng7wwjLDf4WW8Vsm/Ec8UJm8qpxh5GDOSu/zeg@jJi3bay4x4XpVO5o1xcwm9ShtPB79Ag)~~ ~~[822](https://tio.run/##dU@7DoJAEOz9is0FDIe4MSo2JBTSGivtbE49gQgHuYfRGG39OD8K4Wi0cJOdZHdmdjM1l8WiaRS7AUkyJgFgK3LBSg7fteIi1RkklREaNpUm0cBagFxhPnmqwsgaD1W5xyVLUVVSez6e@Y3GMQ7vtcyFPgFxFbjTsIXZEdzQ9k6QADplj2j65wGMvkd7OsALKwz/FVrG75noH/FAZcqmccaxgyWrvfdrHHdh2UFziSnX69bQbikWNqdHaefw6Ac)~~ [816](https://tio.run/##dU87CsJAEO09xbAQycZkEH@NkEJbsdLOZtU1EZNN2I8YRFtbb@JBvIQ3icmmiYUD82DmvTfDy7lMJmWpWAFkHjMJAGtxFCzl0K4FF5GOYZ4ZoWGVaTLtWAuQC4z6d5UYmeMuS7c4YxGqTGrXwxMvaBhi95rLo9AHII4CZzCuYLgHZ2x7I4gPtbJBNM1zH3rt0Z728cwSw3@FlvEaZvqPuKEyaVl@Xs8grABTlrvvRxDWgdlOc4kR18vKVG0pJjarS2ntcukX) ``` ௐ->ௐ.map(ˇ->Character.getName(ˇ).length()).sum() ``` -8 score thanks to *@tsh* replacing the `_1` with `ꀊ`. -22 score thanks to *@ASCII-only* replacing the `ꀊ` with `ˇ` and `$` with `ௐ`. [Try it online.](https://tio.run/##nVLLetJAFN73KY6xaiLk1HpvoVFsq9ILqGi9EKzDMCWBZBIzMyhW2Lr1Tbr2GXwJ38BHwEOgi3jZuJlvzj///P@5DdiIuYPecMYjphQcslCergCEUovshHEBjXmYA8DtAbHR6DBCpTPBYqxL3cpvoJwKEScrdCjNdMihARK2YPbj7Kvr0YExS@3vX1xvO2AZ46SPfaEbLBaEOhgJ2deB7TioTGw7s8pcKTXdiJSWgqMk7EFMGdrkGcp@uwPMWaSnhdK29X9WVp75uUatGK4Vw6aklpg0kcBAh7FAxCJBRSZL0chQkpvyPORJ3J37oGLjInUv2aciihhc8K2Lq5cuX7Gdq6Wyi2vX1q/fuHnr9p27G5uV6pZ3737twfbO7sNHj@t7@weHjeaTp89az18cvXz1@k3b9ztvj9@xLu@Jk34QDoZRLJP0faa0GX34OP50@nkyLdrtJNRg4fJA8CGME5OB7yug6nQggBZC5zzgTAmo/NaoKhUEvlVdPfamU9w9qh341vmtyCy3sdwpQusbxfjn2bciYP2xTvn088fF9GnjFrNvjZUWMSZGY0oPOpK2VZep0ZsAVkktZf/Gahqd06ySRG4r5LQuivbi31@WWU1mvwA) **Explanation:** The `ௐ` and `ˇ` are used instead of the `s` and `c` I would normally use, because lowercase letters are all 20 (i.e. `LATIN SMALL LETTER S`), but `ௐ` (`TAMIL OM`) is 8 and `ˇ` (`CARON`) is 5. ``` ௐ-> // Method with IntStream parameter and integer return-type ௐ.map(ˇ-> // Map each character to: Character.getName(ˇ) // Get the name of the character .length()) // Get the length of that name .sum() // And after the map: sum all lengths together, // and return it as result ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), score [337](https://tio.run/##dY1PC4JAEMXvfYphQSmVISq7CB7y2rFO1WGrTSXdlf0TSeRX32olsEMD82D4vfemYbJaWqtoCyQrqASALS85rRkMZ814rgvIhOEaNkKTZOQiQO6wmHaqMrLBk6iPuKI5KiH1OMAraydpiv6jkSXXFyCeAm8Wv2V@Bi92u@ckgo@zVzT98wjC4emqI7zRyrBfoyNBT5J/4InK1NaGwRcq9HfdAYU8qxc "Perl 6 – Try It Online") ``` +*.uninames.&[~].ords ``` [Try it online!](https://tio.run/##bVFrV4JAEP3c/orJSEBpFZXSEMre7/dbzRCXpGDXWKjowV839JT1ofkw596Ze87MnRmQwJsf@jFkHTCG@RyOqEstn3CcbSZtzIIeH@qIWzFkuM0CsggZBRxJ/FcpyjpyWACS51LCZXhHU34BJJxbkqHF8yAapjgGUquXl6Ggp/0YJIErIFAZDBCKKVLT8migIyUClxUQQVQgEaiOPocNGIdhQqmEChOygA6pTSAaMAoWhK5PMMbwG6mkXKwg7kXBYLK3aWKb@V3MIx@P5qUirVxEO2zXpfcjppYqaDoDM8JsVpTkXF6Zw4WiWipXtPmFam1Rrxvm0nJjZXVtfWNza3tnd2//4PDo@OT07Pzi8ur6ptlq33burK7dI85933149HzKBk8BD6Pnl9f47f3jM/mzIKhaTUVrLOp6ZM7uE/sRYhYF6b0gdRX2CXgWDyEkabItTkCXv81rGqqPP1QXOmaS4PWLxl7mB0z8V6tIaWKlPWZaFam1n5Za@wI "Perl 6 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a1 `-x`, Score ~~926~~ ~~908~~ ~~875~~ ~~865~~ ~~829~~ ~~791~~ [789](https://tio.run/##dY3NasJAFIUh1Fn0CUpXlykRq@FOEjOxIAjVbZe6E@o0nUZpMgnzUxSxj9SH8MXSNtnYRS/cA5fvnHNrqYu0aYw4AF1shQaAldopUUq4nCepcruFReWUhWVl6fS6jQDdQxJ@msLpGrOqfMG5yNFU2g6G@C4P97MZ9o@13in7BtQ34Mf8R8av4PN214oG8OvsFF33PIDR5dlWB/ghCif/Glsy7Mj0P3BC48qmOX9l@aYX3qTRxPOSmLGQYMJ7xAvJFRLCEAlj6JGY8Si6nYwf@CYb8Qj0@vG5jtMTgLqDbw) Takes input as an array of characters. ``` ®cg`061742//0.450./..//.2/5117385`c+51 r\A_p26} n# ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a1&code=rmNnYAUwGDYxNwICNDIvLzAGLjQ1BQYCMAYELgYGLy4uBi8vLgIGMi81MTEaNzM4NWBjKzUxIHJcQV9wMjZ9ICBuIyA=&input=WyJPIiwibiIsImMiLCJlIiwiICIsInUiLCJwIiwibyIsIm4iLCIgIiwiYSIsIiAiLCJ0IiwiaSIsIm0iLCJlIiwiLiIsIi4iLCIuIl0KLXg=) or [run all test cases on TIO](https://tio.run/##RZDtUtpAFIZnGM0PrsDx12n8oCpsCBLwA7FRqRatICq2RYQlrCRKdkN2t4KtXFIvojdGz9Rx/LGzz57z7vl4H2ikZqPZ3z/eoDufXSjYxUQin7OsrEHyzryRyBpzxDAsQgzLIgkjZzm2vVjc3HK63oZjQ2yuuGYnyhVeAPgSzJrj2blQbAfceu3yqlGrn1QgkCDCQCnWh/tYhKB8BjIYKx8Ukwo8KhlQCVWcBB@cCwU@5f0hg55AkQz4ABkj0Be6hzjS2EJCwF9L0ZAhR1qBVDGKk61kyk0lUxaeGvcY6EhwoKCCkBFCMCqHOo6I5gHHv7JcJp4Ie0TqkEg6wXxVnGIdhA8mLC2vrH5cW99IZ4iVtXObeadQ3Nre2S3tlfc/uQeHR5XPxydfqqdnX89r9YvG5dV18@bb9x@t2/Zdp0t7Xp/dD/zg4XEYchGNYqn0z6fx5PnX75cpNjj6v1HG85n3CBOhY7hFt14XG1J0592i3TXUl3BAMEvLnfJ0SipN98x8A0ymWyTdxtveTiXbmbAB/wA) (`APOSTROPHE` is omitted from the 6th test case on TIO as Japt can't handle both single and double quotes in the same input string) --- ## Explanation ``` ®cg`...`c+51 r\A_p26} n# :Implicit input of character array ® :Map c : Character code g : Index into (0-based, with wrapping) `...` : The string described below c+51 : Increment the codepoint of each by 51 (="8cKidj55gebbc9agh895c97a99baa9bba59ebhddMjfkh") : (Space closes the above method) r : Replace \A : RegEx /[A-Z]/g _ : Pass each match through a function p26 : Repeat 26 times } : End function : (Space closes the replace method) : (Space closes the indexing method) n : Convert to integer # : From base 32 (note the trailing space) :Implicitly reduce by addition and output ``` --- ## Building The String (Scores include the steps and extra characters needed to reverse each modification) 1. The array gave a baseline score of [2161](https://tio.run/##rU49T8MwEN35FadIQVBOVs6pm0aVOtCVESZgMGDaisSJ/IGoEPz1EF8YysBW@/nk9975@XrjmsUweH2AbLPTDgDu7N7q1sDxujF2G3aw6aINcNuFbHXGTyD7gHnx7ZvoevHctU/iWm@F71y4mIk3c7hcr8X5Z@/2NrxClnvIpRpL@QK54vNgM4TUOVURp88Rro4pR6N41000fxvZmU3O6j/jS/jYDsP9EkmiLE4JGjNLpBrVuGmBNEcihsQaqWCtwiWmDtaqpNbJJPaL3yszlcgUUXFwiVKeEuOkpHjw6vEH). 2. Converting each to a single character in a base `>=23` and joining to a string scored [1832](https://tio.run/##dY1Pj4IwEMXvfopJDcZV0hjd7tKQeFive9SblykUikAh/bPRmPWro8JFD7xkXjL5vXnTSlN9dZ3FC5CdQgMAB11orCW86lfq3CnYNV472DeOxJP@BMgZPlc3W3nT0qSpBf3BnNrGuPmClvLysd3S2bU1hXYZkMBCsGYP26QQsH6OmoTwTA5O/fA8hOXr2leH9A8rL9@DPVkMJB4D/9T6uutIlJSjKtITY7kUIuGYq4izhH8j5wKRC4GMS6HStB7VKSsVAT2FOw). 3. Replacing both runs of `m` and `k` with a single, uppercase character scored [963](https://tio.run/##dY1PS8NAEMXvforHSsTWsEh12y6FQtujetNbocwm22zaZBP2j1ikfvWoyaUeHJgHw@@9N6121bTrPJ3ANoYcgDdbWqo1LudZ2yIYbJpoA16bwBZXfQTsA4/3X76KruVZUyu@poL7xoXbMT/q02i55DefrStt2IMlHslE/MhDjkT0u7Usxa9zUB6H5ynuLs@@OuXvVEX919iT8UAW/4Ez97HuOjbPnsr8IEShlcokFWYuRSZnJKUikkqRkFqZPH857I@Gue1q106mZ8Be4xs). 4. There were still too many expensive letters so next I tried to get rid of them by reducing the codepoints of all characters. `5` was the character with the lowest codepoint (`53`) so I started with 52, which scored [756](https://tio.run/##dY1LS8NAFIUJdjb@AXF3GIlom7lJ83JRKGi3Lu2uIGMd22IyCfMQi9S/HjXZ1EUv3AOX75xzW2Wqsuus3IMvttIAWOqdlrXC8TwqvXFbLBqvHZ4ax2fnfQT8E3nybStvWlo39Qs9yA3ZxribMb2r/e18Ttdfrdlp9wYeWoRp8SvZK8Ki35XmEf6cg5IfnkeYHJ99dUQfsvLqv7En44HMToEDWV93HR/FF0VSBkE2JYqZyPIRC2J2JhgjIRiRCNiU8iS5LNO7nK8nRQqzun9u0/IA6Cv8AA) 5. After trying all numbers that would leave *no* letters in the string, `51` gave the best score of [738](https://tio.run/##dY1PS8NAEMUh2D34CcTTYyWibZhN0mwqFAraq0e9FWSta1tMNmH/iEXqV4@aXOrBgXkw/N5702pblV3n1B58uVUWwKPZGVVrHM@9Nhu/xbIJxuOh8Xx@2kfAP1CkX64KtqV1Uz/TndqQa6y/GtOb3l8vFnT52dqd8a/gsUOcyx@ZviCW/a4MT/DrHJTC8DzB5PjsqxN6V1XQf409GQ9k/h84kAt11/FRelZmsygqciFSRoUcsShlJ8SYIGJCUMRyIbPsfDa9kXw9kRns6vapzcsDYC7wDQ) 6. Finally, replacing the quotation marks with slightly cheaper backticks gave a score of [734](https://tio.run/##dY1BS8NAEIUh2D34C8TTYyWibZhN0mwqFAraq0e9Fexa17aYbMLuRixS/3rU5NIeOjAPhu@9N7W2Rd62Tu3A5xtlATybrVGlxuE8arP2G8yrxng8VZ5Pz7sI@Bey@McVja1pVZWv9KDW5Crrb4b0oXe3sxldf9d2a/w7eOgQpvJPxm8IZbcLwyP8O3ulpn8eYXR4dtURfaqi0cfGjgx7Mj0F9uSasm2Xg/giTyZBkKVCxIwyOWBBzM6IMUHEhKCApUImyeVkfCeXq5FMYBf3L3Wa7wFzhV8). Backticks in Japt are usually used to enclose and decompress a compressed string but, luckily, none of the characters in this string are contained in Shoco's library The final string, so, contains the characters at the following codepoints: ``` [5,48,24,54,49,55,2,2,52,50,47,47,48,6,46,52,53,5,6,2,48,6,4,46,6,6,47,46,46,6,47,47,46,2,6,50,47,53,49,49,26,55,51,56,53] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score [963](https://tio.run/##K0gtyjH7/784sVJByTkjsUhBQSE0LzMvMTdVARn4pOall2QoOOeX5pUohOSXKFlzgbUoKFUomBjUFeeUFhXoJefnJuk5JabrFecXlWho6WWnVmra2empVRcUZeaVpCkoqRYrqBqZAgnjFAVVUzCOyVPSUQCphJB6pRDLdRS0kblgo3X0yhJzSlNRFYJltCAy1rgkavWKS3P//z/cV/aoYZHbuS2HFzxqmGVjYG95aG/uucUOh6cf2@b8qKmxLFn3Ucui0nNT4s9tVQeqNDK8sOncVhfjRw07M42Mzm181NR0YUdt7ek5lYfbjY10D6/QBgA) ``` Îv•Fδà‚<0?9½mΣ@×ƶC₁vc-™uΔ_ε'•21вεD3‹i22α₂и}}˜yÇ32-è+ ``` [Try it online](https://tio.run/##AbsARP9vc2FiaWX//8OOduKAokbOtMOg4oCaPDA/OcK9bc6jQMOXxrZD4oKBdmMt4oSidc6UX861J@KAojIx0LLOtUQz4oC5aTIyzrHigoLQuH19y5x5w4czMi3DqCv//yAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1@) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkr1B5f@yRw2L3M5tObzgUcMsGwN7y0N7c88tdjg8/dg250dNjWXJuo9aFpWemxJ/bqs6UKWR4YVN57a6GD9q2JlpZFSp@6ip6cKO2trTcyoPtxsb6R5eof2/Vue/I5c@l39ecqpCaUF@nkKiQklmbqqenh5XcU5pUYFeaV5mXmJuarGdnV5yfm6SXnFprl5xYiWXV753Zl46l6KSgrKKqpq6hqaWto6unr6BoZGxiamZuYWllbWNrZ29g6OTs4urm7uHp5e3j6@ff0BgUHBIaFh4RGRUdExsXHxCYlJySmpaekZmVnZObl5@QWFRcUlpWXlFZVV1TW0dl0t@aVJOqm5yRmpytkJlfmmRQkyxAtCZJRmpCjmJxSUKJalAIjmxOFXBWpPLBugyBSUblXi7ujo91zBHHyUYg0snWk8nlsvQEgA). **Explanation:** ``` Î # Push 0 and the input-string v # Loop `y` over the characters of this input-string: •Fδà‚<0?9½mΣ@×ƶC₁vc-™uΔ_ε'• '# Push compressed integer 87235805968599116032550323044578484972930006625267106917841 21в # Converted to Base-21 as list: [5,16,14,11,11,12,9,10,16,17,8,9,5,12,9,7,10,9,9,11,10,10,9,11,11,10,5,9,14,11,17,13,13,0,19,15,20,17,8,12,2,18,13,19,5] ε # Map over this list: D3‹i # If the value is smaller than 3: 22α # Take the absolute difference of this value with 22 ₂и # Repeat it 26 times as list }} # Close the if-statement and map ˜ # Flatten the list yÇ # Get the unicode value of the current character 32- # Subtract 32 è # Index it into the list of integers + # And add it to the sum # (and output the sum implicitly as result after the loop) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•Fδà‚<0?9½mΣ@×ƶC₁vc-™uΔ_ε'•21в` is `[5,16,14,11,11,12,9,10,16,17,8,9,5,12,9,7,10,9,9,11,10,10,9,11,11,10,5,9,14,11,17,13,13,0,19,15,20,17,8,12,2,18,13,19,5]`. [Answer] ## C# (Visual C# Interactive Compiler) (score 1627 1116 1096 1037 1019 902) ``` Ω=>Ω.Sum(ˇ=>(31&-ˇ)>5&ˇ>62?22-ˇ/91*2:"♁♌♊♇♇♈♅♆♌♍♄♅♁♈♅♃♆♅♅♇♆♆♅♇♇♆♁♅♊♇♍♉♉♏♋♐♍♄♈♎♉♏♁"[ˇ-6-ˇ/33*26]-9788) ``` This uses no built-in database: just some special-casing for letters and a lookup table. [Online test suite](https://tio.run/##rVLtVtNAEP2/T7GsiAlN0yYhbUPbIAqoUEVBQW0rpumWrrRJzUcBazinR6B@69@8gC/Tt8iL1M2mRfzPnjnJ3Luzd2dmx3TTpksmG75lllzPIdahQCxPb5Un0fmfsk4/4q7f5cajss4p0kJ6POJ1dWE80nPyiixTmNGkRXkZReEwCr9H4dcoHDH7HIUXUXjJyB9ReM7gcMZ/YlsXzEbMv5z5CRwymKjR41@Y/YrCb1H4eyZIpX7O@CGqjkfpXJyQoizKuXpayxcK/KQIaDnVOsQnPWx6uAnL0MLHkJEDVZBygrQkSBIzWdAEKcu4vFCgQE24fMxq8abE9rNTlyE1BokEjVNik@WbNInqq4KcTZKiCVH3Bk0qsKxpsUERgJbtQI42BxLaqGyR/kpXrRMr2Dr02pRMpXg4AJCuvuFAu@Fip89a2@IQginImW3D4TlCXUXm@SILJS3IzaSqpA7nylcnZ2rx2neIhyvEwtw8Wt/Z2d6BA5JS5AAO/lelxDU1imZiAZpeGIAA/FNDG8QibpumabaxeUQHnQ5Bk/RJ0zc6sIM9DztufDTuATbMNhfXZtCgeGDosAC0igSYyUBZBiiTuHmAti0TQ79nWzTWI10simKyp2SXAHI7vtMTfYtYRhe7ui6adrchun5XdI3TJE5VsgBt2ls0o4SQZHpwrobgrfnbC3c4fjElpMVMVpKVJTWXL2jLxVJZX7m7eu/@2vrGg4ePNrcqj59sP322s/v8xd7@y1evq7Va/c3BW6NhNnHrsE3eHXW6lt1777ie3z8@Of0w@BicTe9SNQmgNdtvdHCaNQae2r4DazUX0pK8NoYdw/Wgh@nHNFwMi/y0dFUFqESrgDVUmj/Qz87E9b3VSg3NvGkXCgWAhKoo1KfVUihp08s1EPDg@oMPDEFTAwjLOoSDFmfw8WNO/gI). It can't score itself, because most of the characters are not in range, including the variables `CARON` and `OHM SIGN` and the zodiac symbols used to encode the lookup table. Thanks to [ASCII-only](/users/39244) for many suggestions. [Answer] # R; Score: 3330 1586 1443 Also challenging in R due to lack of built-ins. Well the code is now mostly @Giuseppe's but that's alright. I was able to make a small edit to golf further by replacing the \* with the ~, and the s with the dot. Thanks to @Nick Kennedy for getting this down to 1443 by using arcane magic "a UTF8 encoded version of the number sequence" ``` function(.)sum((c(+",752230178/0,30.1002110221,052844",61~26,+":6;8/3",59~26,+"94:,")-39)[+.-31]);`+`=utf8ToInt;`~`=rep ``` [Try it online](https://tio.run/##xc09DoIwFADgu3ShTR/w3usPBeQA7m7GpAmxCYPFIKxcvQ4ewvGbvq2kS13Sked9WbNs1Od4STlLLaBzzAapCy2CwYYQmQiZCdBxsFaAp5M9aDH4MbRGgOt/7u0AQtWmV3fd1IYeaow6Tseewm295n2MZ5y257skWf2prlT5Ag) [Answer] # [Python 3](https://docs.python.org/3/), Score of 993 ``` lambda _:len(''.join(map(__import__('unicodedata').name,_))) ``` [Try it online!](https://tio.run/##NU5ZU8IwGHzPr/hEtKmWAOLFVUXBA1A88QCMoQQItEltUxUP/jpWZ9yHnd2d2dn1Z3qsZG4xLHcXLvP6Awa04HKJDYNMlJDYYz6mVHi@CjSl2IikcNSAD5hmhkkk87hFTdNcDFUAFISEgMkRx9mMWUAQQ0A5Tv1IY/PP@4GQGgsLjLJtWDDEIi5XUBq1pMMh8pUEBlp4nBCCQjcKfBJP/u6Etk0c5fVJGHkkZDNUVw0hR2gpAcvJlVUDm2vrVoqkM9mN3ObW9s5uvlAsle29/crBYbV2dHxyWm80z85bF5dX1ze37bv7h8dOt/dEn1nfGfDhaCwmU9eTyn8JQh29vr3PPj6/vueoqqK@y1POmDtTmKkogG4I8U095uCyUIPmMTks5FA0USl@BolSktrzOam1K83Ev0BWh1g9lM3/AA "Python 3 – Try It Online") Below 1000 now, any tips still appreciated. -16 thanks to Kirill L. [Answer] # [Perl 5](https://www.perl.org/) `-pl`, score [723](https://tio.run/##dY/LCsJADEX3fkUYrI8agvjaiC50K7pRcCHI2I612M6UeYhF6q9rbTe6MJAL4dwk3EzoZPJ6GZ4DW164BoCdjCVPBXzXSsjIXmCpnLSwVZZNG9UKsDuM@k@TOJ1RoNITLXhERmnb8ekq8u58Tq1HpmNpz8A8A95gXMowBG9c9UEyhI@zVnL1c4Te91idRrrxxIlfY0X8mkz/gYKMS8uQeFg/NvvCJzwGZdaPzbRvMQ9UKEDpsNnCSGDzOMsRMXgD "Perl 6 – Try It Online") ``` s,\N{OX}*.,_charnames'viacode ord$&,ge,$_=y,,,c ``` [Try it online!](https://tio.run/##NY7LUsIwAADv@YpYKwiGICoqAlUUfACCT0QBaxpiW2mT2jRoRfh0K@OMl5097WzAQq@YJBINO7Nuf57FyKQOCTnxmUxPXULFmEERjvUUshnSzWqMEKJJUgN50OWUQRUIDgmMXJ9hjIH0VBhgxd2/gmFgKnwLS@VjSWLQFC2X22BFg6v6Wiq9nsluoBzObxa2tneKu3v7pYNypWocHtWOT@qN07Pzi2arfdnpXl3f3N7d9x76j0@D4ejZfCEWHbNX23HfJp7PRfAeykhNPz7jr9n3fAHqQlkey1GH0QmMhQrhUMLlZuQw6BEZwYgtQYlksJwBleUZ1Cq6aSwWuNGrtbV/AWiA0QgUSj8iiFzBZZILvF8 "Perl 5 – Try It Online") ### Explanation ``` s, , ,ge # Replace globally \N{OX}* # zero or more OX characters 🐂, loads the # _charnames module as side effect, . # any character _charnames'viacode ord$& # with its Unicode character name # (using old package delimiter). ,$_=y,,,c # Set $_ to its length ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), [1934](https://tio.run/##dU1tT4JQFP7erzhexcjwzoG0KWUONz@ZtSmrLKQroLCAy@5Li5n9dTL4Yh8623l2znleTh6y5KosOSkATSLCAMDJ4oykIZzWLMx2IoIJlZmAJRXIOqssgD6h3/vmiWQ59mm6wTbZYU6ZUDv4PSwuRiPc3ucszsQWkMJB0c0jGAEoZtWvGdLgV1kjlvVzDS5P1ypawx8kkeFfYcV0asb6jzhgLtOyXMh0vF9Sm/DwZcpoWg33LOBj1FjZBZM3zcHWft60iLGIe@vc0VYPTaPlB@eq3/WSSLqR6ppW4/Hr9q4/vPbW3LHm7afp/E0MJeoaujYwXU033DrUO17cww8) ``` Sum@{ToBase[FromBase[Ords@"!ZByru=#9fBYb$a3Si0^pU,ZP#3$cd'(c-_lhu]h(]5;!W|?M4:<_^sU;N&XFN`t:u"-32,95],23][Ords@_-32]} ``` [Try it online!](https://tio.run/##rZBLTwIxFIX3/IpSJopJqcrIgqeAysIHkAA@GMtQSmEa55Vpu5io/PWxEcadrryr7z5yzs2hSlHm8WwDGu1sooPu@zTqU8mdQRIF3zBK1rILi/N@muh2qb7pv6wsak/E2SKeofm4ZFtsfVxmFdf3NPHKpNYsPn1cPlw0Wu5CzprDo@fBcKkaGlbsKqrXCKraZC/qmgn5zIacr6VjxTHbksI4EaGacqmujLd0Ngg4BWAK9iDaw2kOo5BxoOMoBBQoEXCMcb6Svk5irEMR0oDLTgezKFhhqQMsaZof3UZ3ItweOiqZEHtcwutIr3xeMbmwN5BGOgGvEhgf5XHgU6mAMg8CZj4EzZNcrmWkAYQty@3sdvjmsXcP4Q8dbpCDEcmb83pOf@T@H8H/ljwsEJJ9AQ "Attache – Try It Online") Simple compression and indexing. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), Score: ~~4007~~ ~~3988~~ ~~3759~~ ~~3551~~ 2551 ``` ˇ=>ˇ.Sum(_=>new[]{5,16,14,11,11,12,9,10,16,17,8,9,5,12,9,7,10,9,9,11,10,10,9,11,11,10,5,9,14,11,17,13,13,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,19,15,20,17,8,12,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,18,13,19,5}[_-32]) ``` I feel crushed by Peter Taylor's solution up above. Thanks to Peter Taylor for pointing out a simple lookup table was better than my previous dictionary solution. [Try it online!](https://tio.run/##rVHhWtMwFP3PU8Q6tdUsNB1lq1sLU0CFKSoK6jpnFjMWWdPZNMCY3V8ejoeat52@AflOknvPSW5OEq7rXMvVgVG8o/NMqnMsVR6Nw9XdbRjd3ZITk9jDMFLiqj9Y@JhuY7qFKa3g4QBTt@KauAWJv@aaJRuUIq10919YZX6ZrEvAukYJz7tPUKjvY89dmwJDEN4jaKtyDZct@sN6wxs4q/bGOM0E4xP7kmWIIanQ@r2sroWtTejHigtkZqkCNZeJIIQAq6cmmxGjpGKJ0FFEeJqMiDYJ0WwO@mF6BB8CwYPYQg9rjx4/sZ2nz3CdbLrUa2z5281W8LzdCaOd3e6Ll3v7B69evzk86r19d/z@w8eTT59Pz758/daP48H34Q824j/F@Hwif11ME5XOfmc6N5dX1/ObxZ9iCWfspWY0FXU@EfwCzVOToTjWCBznE4GmTOcoFzBwpgVqO7ChAyZRbHVqw2i5JPun3V5s/Y9Axn2CBzDTwCqcjbNM5qInlbBr1oLhwC0QtDAqx8XYZk5hOe3VXw "C# (Visual C# Interactive Compiler) – Try It Online") ]
[Question] [ A number spiral is an infinite grid whose upper-left square has number 1. Here are the first five layers of the spiral: [![enter image description here](https://i.stack.imgur.com/m4ei9.png)](https://i.stack.imgur.com/m4ei9.png) **Your task is to find out the number in row y and column x.** --- Example: ``` Input: 2 3 Out : 8 Input: 1 1 Out : 1 Input: 4 2 Out : 15 ``` --- Note: 1. Any programming language is allowed. 2. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge so shortest code wins. 3. Best of Luck! Source: <https://cses.fi/problemset/task/1071> [Answer] ## C (gcc), ~~44~~ 43 bytes ``` f(x,y,z){z=x>y?x:y;z=z*z-~(z%2?y-x:x-y)-z;} ``` [Try it online!](https://tio.run/##Zc7BDoIwDAbgu0/RkJBssh0AvTAnL@LFQGY4iAQxWUfw1ecmQlzoZfu7L@0qfqsqaxXRDJmho5H6jKUuUBhp9oa/iYmzErkuNEfKjZjs/dq0hMK4A1fq0QNp2gE0SEiFO04SjgKSRC8kYDgzXBn@M19d75wiUZzXEQP/MUBKxWqm9da9hieJot/b3A97yyxFMpZTtzquL@13qs8blLI0QD5v0IFlAfLZocl@AA) The spiral has several "arms": ``` 12345 22345 33345 44445 55555 ``` The position \$(x, y)\$ is located on arm \$\max(x, y)\$ (assigned to variable `z`). Then, the largest number on arm \$n\$ is \$n^2\$, which alternates between being in the bottom left and top right position on the arm. Subtracting \$x\$ from \$y\$ gives the sequence \$-n+1, -n+2, \ldots, -1, 0, 1, \ldots, n-1, n-2\$ moving along arm \$n\$, so we choose the appropriate sign based on the parity of \$n\$, adjust by \$n-1\$ to get a sequence starting at 0, and subtract this value from \$n^2\$. Thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for saving a byte. [Answer] ## Python, ~~54~~ ~~50~~ 49 bytes ``` def f(a,b):M=max(a,b);return(a-b)*(-1)**M+M*M-M+1 ``` -4 bytes thanks to @ChasBrown -1 bytes thanks to @Shaggy [Try it Online!](https://tio.run/##VYxBCoMwFETX9RTZ5Sd@hcRCwWJvkBOIYKSmVWiUNIKePtUUCt0Mj2HezJt/TlaGcO8NMaCxY6WqXnqNeHW9X5wFnXWMQyYY5ypVXGUqFcFMjqy4kcGSupZYNFgLFHueUe4p8dw0ZXKa3WA9gX3JkFY3iiZyEvsknhwXTttHDwIv7OdQmo/TYKH9Gm3uxuXtoWDksLZ/i4UP) First time golfing! I'm more than aware this is not optimal, but whatever. Essentially runs on the same principle as @Doorknob C code. [Answer] # [MATL](https://github.com/lmendo/MATL), 15 bytes ``` X>ttq*QwoEqGd*+ ``` [Try it online!](https://tio.run/##y00syfn/P8KupKRQK7A837XQPUVL@///aBMdBaNYAA "MATL – Try It Online") [Collect and print as a matrix](https://tio.run/##y00syflvaGBVEqWlqOQQ4fk/wq6kpFArsDzftdAzRUv7f2yZoUGq4n8A "MATL – Try It Online") ### How? *Edit: Same technique as @Doorknob's answer, just arrived at differently.* The difference between the diagonal elements of the spiral is the arithmetic sequence \$ 0, 2, 4, 6, 8, \ldots \$. Sum of \$ n \$ terms of this is \$ n(n - 1) \$ (by the usual AP formula). This sum, incremented by 1, gives the diagonal element at position \$ (n, n) \$. Given \$ (x, y) \$, we find the maximum of these two, which is the "layer" of the spiral that this point belongs to. Then, we find the diagonal value of that layer as \$ v = n(n-1) + 1 \$. For even layers, the value at \$ (x, y) \$ is then \$ v + x - y \$, for odd layers \$ v - x + y \$. ``` X> % Get the maximum of the input coordinates, say n ttq* % Duplicate that and multiply by n-1 Q % Add 1 to that. This is the diagonal value v at layer n wo % Bring the original n on top and check if it's odd (1 or 0) Eq % Change 1 or 0 to 1 or -1 Gd % Push input (x, y) again, get y - x * % Multiply by 1 or -1 % For odd layers, no change. For even layers, y-x becomes x-y + % Add that to the diagonal value v % Implicit output ``` --- **Alternate 21 byte solution:** ``` Pdt|Gs+ttqq*4/QJb^b*+ ``` [Try it online!](https://tio.run/##y00syfn/PyClpMa9WLukpLBQy0Q/0CspLklL@///aBMdBaNYAA "MATL – Try It Online") [Collect and print as a matrix](https://tio.run/##y00syflvaGBVEqWlqOQQ4fk/IKWkxrNYu6SksFDLRD/QKykuSUv7f2yZoUGq4n8A "MATL – Try It Online") From the above, we know that the function we want is $$ f = m \* (m - 1) + 1 + (-1)^m \* (x - y) $$ where \$ m = max(x, y) \$. Some basic calculation will show that one expression for max of two numbers is $$ m = max(x, y) = \frac{x + y + abs(x - y)}{2} $$ Plugging one into another, we [find](https://www.wolframalpha.com/input/?i=f%20%3D%20m%20*%20(m%20-%201)%20%2B%201%20%2B%20(-1)%5Em%20*%20(x%20-%20y)%20where%20m%20%3D%20(x%20%2B%20y%20%2B%20abs(x-y))%2F2) that one alternate form for \$ f \$ is: $$ f = (x-y)\cdot i^{k} + \frac{1}{4}((k-2)\cdot k) + 1 $$ where \$ k = abs(x-y) + x + y \$. This is the function the solution implements. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~16~~ ~~14~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) (Originally) Adapted from [Doorknob's solution](https://codegolf.stackexchange.com/a/170795/58974) over a few beers. ``` wV nU²ÒNra ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=d1YKblWy0k5yYQ&input=OAo4) ``` wV\nnU²ÒNra :Implicit input of integers N=[U=y, V=X] wV :Maximum of U & V \n :Reassign to U, leaving the value in N unchanged n :Subtract U from U² : U squared Ò : Subtract the bitwise NOT of Nr : N reduced by a : Absolute difference ``` [Answer] # Pyth, 20 bytes ``` A~Qh.MZQh-+*-GH^_1Q* ``` [Test suite](http://pyth.herokuapp.com/?code=A%7EQh.MZQh-%2B%2a-GH%5E_1Q%2a&test_suite=1&test_suite_input=2%2C3%0A1%2C1%0A4%2C2&debug=0) An almost literal translation of [Rushabh Mehta](https://codegolf.stackexchange.com/users/82007/rushabh-mehta)['s answer](https://codegolf.stackexchange.com/questions/170794/number-spiral-problem/170814#170814). Explanation: ``` A~Qh.MZQh-+*-GH^_1Q* | Full code A~Qh.MZQh-+*-GH^_1Q*QQQ | Code with implicit variables filled | Assign Q as the evaluated input (implicit) A | Assign [G,H] as ~Q | Q, then assign Q as h.MZQ | Q's maximal value. | Print (implicit) h-+*-GH^_1Q*QQQ | (G-H)*(-1)^Q+Q*Q-Q+1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` »Ḃ-*×_‘+»×’$¥ ``` [Try it online!](https://tio.run/##y0rNyan8///Q7oc7mnS1Dk@Pf9QwQ/vQ7sPTHzXMVDm09P/h5fqPmta4//8fHW2oo2AYq6MQbaSjYAyiTXQUjGJjAQ "Jelly – Try It Online") Uses [Doorknob's method](https://codegolf.stackexchange.com/a/170795/59487). Way too long. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes ``` ṀḂḤ’×I+²_’ṀƲ ``` [Try it online!](https://tio.run/##y0rNyan8///hzoaHO5oe7ljyqGHm4eme2oc2xQNZQNFjm/7//2@iYwQA "Jelly – Try It Online") Computes the diagonal term with `²_’Ṁ` and adds/subtracts to the correct index value with `ṀḂḤ’×I`. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 76 bytes ``` ((({}<>))<>[(({}))]<{({}[()])<>}>)<>{}((){({}[()])({})<><([{}])><>}{}<>{}<>) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0NDo7rWxk5T08YuGsTU1Iy1qQbS0RqasUCxWjsgUV2roaEJFwQpsrGz0Yiuro3VtAMqAekHm/H/v4mCEQA "Brain-Flak – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ZÐ<*>ŠGR}¥+ ``` -1 byte thanks to *@Emigna* changing `Èi` to `G`. Port of [*@sundar*'s MATL answer](https://codegolf.stackexchange.com/a/170815/52210), so make sure to upvote him! [Try it online](https://tio.run/##yy9OTMpM/f8/6vAEGy27owvcg2oPLdX@/z/aRMcoFgA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/m5nl4gr2SwqO2SQpK9v@jDk@w0bI7usA9qPbQUu3/Ov@jjXSMY7miDXUMgaSJjhGYNAGSpjqmYLZpLAA). **Explanation:** ``` Z # Get the maximum of the (implicit) input-coordinate # i.e. [4,5] → 5 Ð # Triplicate this maximum < # Decrease it by 1 # i.e. 5 - 1 → 4 * # Multiply it # i.e. 5 * 4 → 20 > # Increase it by 1 # i.e. 20 + 1 → 21 Š # Triple swap the top threes values on the stack (a,b,c to c,a,b) # i.e. [4,5], 5, 21 → 21, [4,5], 5 G } # Loop n amount of times R # Reverse the input-coordinate each iteration # i.e. 5 and [4,5] → [5,4]→[4,5]→[5,4]→[4,5] → [5,4] ¥ # Calculate the delta of the coordinate # [5,4] → [1] + # And add it to the earlier calculate value (output the result implicitly) # 21 + [1] → [22] ``` [Answer] # [Pascal (FPC)](https://www.freepascal.org/), 90 bytes ``` uses math;var x,y,z:word;begin read(x,y);z:=max(x,y);write(z*z-z+1+(1and z*2-1)*(y-x))end. ``` [Try it online!](https://tio.run/##JchLDoMgEADQq8ySj5hQu5L0MKOMlUSpAVtxLo8m3b28DfOIi5m2sdZvpgwr7rP7YYLSnA33xyd5N9A7REiEXtwrHfevFcvfRwo7CVZsWFstLEYPrB7GSiVOU6Sk6NtaO3he "Pascal (FPC) – Try It Online") Port of [Doorknob's answer](https://codegolf.stackexchange.com/a/170795/60517), but [sundar's answer](https://codegolf.stackexchange.com/a/170815/60517) gave me idea for `z mod 2*2-1` which I transformed into `1and z*2-1` to remove space. [Answer] # Mathematica 34 bytes ``` x = {5, 8}; ``` so: ``` m = Max[x]; Subtract @@ x (-1)^m + m^2 - m + 1 ``` (\* 54 \*) [Answer] # [Julia 1.0](http://julialang.org/), 35 bytes ``` x\y=(m=max(x,y))*~-m+1+(-1)^m*(x-y) ``` [Try it online!](https://tio.run/##PY2xCoMwFAD3fMXD6cVG6LOdBKfObt2MhaAWUkyUJEKy9NfTFtpuB8dxj33RimLOUaYWTWtUxCgS5@WzMgc6YEX8ZkqMVeJ5c9qGxWJxnX2AUfnZNwVnRm34VQL6Wp4EkCQBZ1kPnLF/dVmtD24fwzyBUcHp@Kk7aKF/3@G@OoigLVBDRwHphwObtN8WlbDjLL8A "Julia 1.0 – Try It Online") [Answer] # JavaScript (ES6), 46 bytes ``` f=(r,c,x)=>r<c?f(c,r,1):r%2-!x?r*r-c+1:--r*r+c ``` [Answer] # [Java (JDK 10)](http://jdk.java.net/), 39 bytes ``` x->y->(y-x)*((y=x>y?x:y)%2*2-1)+y*y-y+1 ``` [Try it online!](https://tio.run/##TZAxa8MwEIX3/IojEJAc2dRup6R26VLoUDqETsGD6thBqSMb6Rx0BP92V7Hd0EGne@@O78Gd5EWGp8PPoM5tYxBOXkcdqjqqOl2ganQUbBdt912rAopaWgsfUmm4LgBm16JE/10adYCzn7EdGqWP@xykOVo@rgK8a3ybic@@/9LS0GdbGomNyaCCdHBhRmHGKHQ8YIxSl9GL2xBfJUESxnxNAYW0joftyFMa97nPwNKihXROAbhCIuARenHXsYD4v34SkNx1P9GqxgAbkSNwM2H5nepH4HzKzd4/5ALoT8T5dt7ZkcXyHDUdRq0/AFZs6dLVwe@O1ZS2q9G3K70U4LwtoIpk29bEHJ@aV@tPw4jzidkvbq8ffgE "Java (JDK 10) – Try It Online") ## Credits * Port of [Doorknob's answer](https://codegolf.stackexchange.com/a/170795/16236). [Answer] # [Rockstar](https://codewithrockstar.com/), ~~127~~ ~~118~~ 115 bytes [Also](https://codegolf.stackexchange.com/a/170823/58974) adapted from [Doorknob's solution](https://codegolf.stackexchange.com/a/170795/58974). ``` listen to Y listen to X let M be Y is less than X and X-0 or Y-0 let R be M*M-M let R be-M-Y and Y-X or X-Y say R+1 ``` [Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in, with each input integer on an individual line) ]
[Question] [ The [London Underground A.K.A. The Tube](https://simple.wikipedia.org/wiki/London_Underground) is the oldest underground railway in the world, it currently consists of eleven lines\* servicing 267 named stations (strictly 269\*\* stations since "Edgware Road" and "Hammersmith" each occupy two locations) ### The challenge Output the names of the lines servicing a station given by name as input. **Input:** A string or list of characters * This may be assumed to be a *valid* station name (as listed in the code-block below). * You may assume any `&` in the input will *consistently* be the word `and` (or `And`) instead if you wish, just state it clearly in your answer. **Output:** *Separated* output listing those of the eleven lines servicing that station: * A list of strings, a list of lists of characters, printed text, a string, a list of characters; if in doubt ask. * You may *consistently* output the word `and` (or `And`) in place of any `&` if you wish, just state this clearly in your answer. * With the caveat that if printing or returning a string or list of characters that the separator-substring used is not present in any of the line names (including the `&` or `and` or `And` used) - this therefore excludes the use of a single space character as the separator. **The Tube Network**: - Note: This is the final state, even if it happens to contain a spelling mistake (unless addressed prior to any answers) ``` Input (Station Name) : Output (list of tube line names) ---------------------------------------------------------------------------------------------------------------- "Acton Town" : ["District","Piccadilly"] "Aldgate" : ["Circle","Metropolitan"] "Aldgate East" : ["District","Hammersmith & City"] "Alperton" : ["Piccadilly"] "Amersham" : ["Metropolitan"] "Angel" : ["Northern"] "Archway" : ["Northern"] "Arnos Grove" : ["Piccadilly"] "Arsenal" : ["Piccadilly"] "Baker Street" : ["Bakerloo","Circle","Hammersmith & City","Jubilee","Metropolitan"] "Balham" : ["Northern"] "Bank" : ["Central","Northern","Waterloo & City"] "Barbican" : ["Circle","Hammersmith & City","Metropolitan"] "Barking" : ["District","Hammersmith & City"] "Barkingside" : ["Central"] "Barons Court" : ["District","Piccadilly"] "Bayswater" : ["Circle","District"] "Becontree" : ["District"] "Belsize Park" : ["Northern"] "Bermondsey" : ["Jubilee"] "Bethnal Green" : ["Central"] "Blackfriars" : ["Circle","District"] "Blackhorse Road" : ["Victoria"] "Bond Street" : ["Central","Jubilee"] "Borough" : ["Northern"] "Boston Manor" : ["Piccadilly"] "Bounds Green" : ["Piccadilly"] "Bow Road" : ["District","Hammersmith & City"] "Brent Cross" : ["Northern"] "Brixton" : ["Victoria"] "Bromley-by-Bow" : ["District","Hammersmith & City"] "Buckhurst Hill" : ["Central"] "Burnt Oak" : ["Northern"] "Caledonian Road" : ["Piccadilly"] "Camden Town" : ["Northern"] "Canada Water" : ["Jubilee"] "Canary Wharf" : ["Jubilee"] "Canning Town" : ["Jubilee"] "Cannon Street" : ["Circle","District"] "Canons Park" : ["Jubilee"] "Chalfont & Latimer" : ["Metropolitan"] "Chalk Farm" : ["Northern"] "Chancery Lane" : ["Central"] "Charing Cross" : ["Bakerloo","Northern"] "Chesham" : ["Metropolitan"] "Chigwell" : ["Central"] "Chiswick Park" : ["District"] "Chorleywood" : ["Metropolitan"] "Clapham Common" : ["Northern"] "Clapham North" : ["Northern"] "Clapham South" : ["Northern"] "Cockfosters" : ["Piccadilly"] "Colindale" : ["Northern"] "Colliers Wood" : ["Northern"] "Covent Garden" : ["Piccadilly"] "Croxley" : ["Metropolitan"] "Dagenham East" : ["District"] "Dagenham Heathway" : ["District"] "Debden" : ["Central"] "Dollis Hill" : ["Jubilee"] "Ealing Broadway" : ["Central","District"] "Ealing Common" : ["District","Piccadilly"] "Earl's Court" : ["District","Piccadilly"] "East Acton" : ["Central"] "East Finchley" : ["Northern"] "East Ham" : ["District","Hammersmith & City"] "East Putney" : ["District"] "Eastcote" : ["Metropolitan","Piccadilly"] "Edgware" : ["Northern"] "Edgware Road" : ["Bakerloo","Circle","District","Hammersmith & City"] "Elephant & Castle" : ["Bakerloo","Northern"] "Elm Park" : ["District"] "Embankment" : ["Bakerloo","Circle","District","Northern"] "Epping" : ["Central"] "Euston" : ["Northern","Victoria"] "Euston Square" : ["Circle","Hammersmith & City","Metropolitan"] "Fairlop" : ["Central"] "Farringdon" : ["Circle","Hammersmith & City","Metropolitan"] "Finchley Central" : ["Northern"] "Finchley Road" : ["Jubilee","Metropolitan"] "Finsbury Park" : ["Piccadilly","Victoria"] "Fulham Broadway" : ["District"] "Gants Hill" : ["Central"] "Gloucester Road" : ["Circle","District","Piccadilly"] "Golders Green" : ["Northern"] "Goldhawk Road" : ["Circle","Hammersmith & City"] "Goodge Street" : ["Northern"] "Grange Hill" : ["Central"] "Great Portland Street" : ["Circle","Hammersmith & City","Metropolitan"] "Greenford" : ["Central"] "Green Park" : ["Jubilee","Piccadilly","Victoria"] "Gunnersbury" : ["District"] "Hainault" : ["Central"] "Hammersmith" : ["Circle","District","Hammersmith & City","Piccadilly"] "Hampstead" : ["Northern"] "Hanger Lane" : ["Central"] "Harlesden" : ["Bakerloo"] "Harrow & Wealdstone" : ["Bakerloo"] "Harrow-on-the-Hill" : ["Metropolitan"] "Hatton Cross" : ["Piccadilly"] "Heathrow Terminals 1, 2, 3" : ["Piccadilly"] "Heathrow Terminal 4" : ["Piccadilly"] "Heathrow Terminal 5" : ["Piccadilly"] "Hendon Central" : ["Northern"] "High Barnet" : ["Northern"] "Highbury & Islington" : ["Victoria"] "Highgate" : ["Northern"] "High Street Kensington" : ["Circle","District"] "Hillingdon" : ["Metropolitan","Piccadilly"] "Holborn" : ["Central","Piccadilly"] "Holland Park" : ["Central"] "Holloway Road" : ["Piccadilly"] "Hornchurch" : ["District"] "Hounslow Central" : ["Piccadilly"] "Hounslow East" : ["Piccadilly"] "Hounslow West" : ["Piccadilly"] "Hyde Park Corner" : ["Piccadilly"] "Ickenham" : ["Metropolitan","Piccadilly"] "Kennington" : ["Northern"] "Kensal Green" : ["Bakerloo"] "Kensington (Olympia)" : ["District"] "Kentish Town" : ["Northern"] "Kenton" : ["Bakerloo"] "Kew Gardens" : ["District"] "Kilburn" : ["Jubilee"] "Kilburn Park" : ["Bakerloo"] "Kingsbury" : ["Jubilee"] "King's Cross St. Pancras" : ["Circle","Hammersmith & City","Metropolitan","Northern","Piccadilly","Victoria"] "Knightsbridge" : ["Piccadilly"] "Ladbroke Grove" : ["Circle","Hammersmith & City"] "Lambeth North" : ["Bakerloo"] "Lancaster Gate" : ["Central"] "Latimer Road" : ["Circle","Hammersmith & City"] "Leicester Square" : ["Northern","Piccadilly"] "Leyton" : ["Central"] "Leytonstone" : ["Central"] "Liverpool Street" : ["Central","Circle","Hammersmith & City","Metropolitan"] "London Bridge" : ["Jubilee","Northern"] "Loughton" : ["Central"] "Maida Vale" : ["Bakerloo"] "Manor House" : ["Piccadilly"] "Mansion House" : ["Circle","District"] "Marble Arch" : ["Central"] "Marylebone" : ["Bakerloo"] "Mile End" : ["Central","District","Hammersmith & City"] "Mill Hill East" : ["Northern"] "Monument" : ["Circle","District"] "Moorgate" : ["Circle","Hammersmith & City","Metropolitan","Northern"] "Moor Park" : ["Metropolitan"] "Morden" : ["Northern"] "Mornington Crescent" : ["Northern"] "Neasden" : ["Jubilee"] "Newbury Park" : ["Central"] "North Acton" : ["Central"] "North Ealing" : ["Piccadilly"] "North Greenwich" : ["Jubilee"] "North Harrow" : ["Metropolitan"] "North Wembley" : ["Bakerloo"] "Northfields" : ["Piccadilly"] "Northolt" : ["Central"] "Northwick Park" : ["Metropolitan"] "Northwood" : ["Metropolitan"] "Northwood Hills" : ["Metropolitan"] "Notting Hill Gate" : ["Central","Circle","District"] "Oakwood" : ["Piccadilly"] "Old Street" : ["Northern"] "Osterley" : ["Piccadilly"] "Oval" : ["Northern"] "Oxford Circus" : ["Bakerloo","Central","Victoria"] "Paddington" : ["Bakerloo","Circle","District","Hammersmith & City"] "Park Royal" : ["Piccadilly"] "Parsons Green" : ["District"] "Perivale" : ["Central"] "Piccadilly Circus" : ["Bakerloo","Piccadilly"] "Pimlico" : ["Victoria"] "Pinner" : ["Metropolitan"] "Plaistow" : ["District","Hammersmith & City"] "Preston Road" : ["Metropolitan"] "Putney Bridge" : ["District"] "Queen's Park" : ["Bakerloo"] "Queensbury" : ["Jubilee"] "Queensway" : ["Central"] "Ravenscourt Park" : ["District"] "Rayners Lane" : ["Metropolitan","Piccadilly"] "Redbridge" : ["Central"] "Regent's Park" : ["Bakerloo"] "Richmond" : ["District"] "Rickmansworth" : ["Metropolitan"] "Roding Valley" : ["Central"] "Royal Oak" : ["Circle","Hammersmith & City"] "Ruislip" : ["Metropolitan","Piccadilly"] "Ruislip Gardens" : ["Central"] "Ruislip Manor" : ["Metropolitan","Piccadilly"] "Russell Square" : ["Piccadilly"] "St. James's Park" : ["Circle","District"] "St. John's Wood" : ["Jubilee"] "St. Paul's" : ["Central"] "Seven Sisters" : ["Victoria"] "Shepherd's Bush" : ["Central"] "Shepherd's Bush Market" : ["Circle","Hammersmith & City"] "Sloane Square" : ["Circle","District"] "Snaresbrook" : ["Central"] "South Ealing" : ["Piccadilly"] "South Harrow" : ["Piccadilly"] "South Kensington" : ["Circle","District","Piccadilly"] "South Kenton" : ["Bakerloo"] "South Ruislip" : ["Central"] "South Wimbledon" : ["Northern"] "South Woodford" : ["Central"] "Southfields" : ["District"] "Southgate" : ["Piccadilly"] "Southwark" : ["Jubilee"] "Stamford Brook" : ["District"] "Stanmore" : ["Jubilee"] "Stepney Green" : ["District","Hammersmith & City"] "Stockwell" : ["Northern","Victoria"] "Stonebridge Park" : ["Bakerloo"] "Stratford" : ["Central","Jubilee"] "Sudbury Hill" : ["Piccadilly"] "Sudbury Town" : ["Piccadilly"] "Swiss Cottage" : ["Jubilee"] "Temple" : ["Circle","District"] "Theydon Bois" : ["Central"] "Tooting Bec" : ["Northern"] "Tooting Broadway" : ["Northern"] "Tottenham Court Road" : ["Central","Northern"] "Tottenham Hale" : ["Victoria"] "Totteridge & Whetstone" : ["Northern"] "Tower Hill" : ["Circle","District"] "Tufnell Park" : ["Northern"] "Turnham Green" : ["District","Piccadilly"] "Turnpike Lane" : ["Piccadilly"] "Upminster" : ["District"] "Upminster Bridge" : ["District"] "Upney" : ["District"] "Upton Park" : ["District","Hammersmith & City"] "Uxbridge" : ["Metropolitan","Piccadilly"] "Vauxhall" : ["Victoria"] "Victoria" : ["Circle","District","Victoria"] "Walthamstow Central" : ["Victoria"] "Wanstead" : ["Central"] "Warren Street" : ["Northern","Victoria"] "Warwick Avenue" : ["Bakerloo"] "Waterloo" : ["Bakerloo","Jubilee","Northern","Waterloo & City"] "Watford" : ["Metropolitan"] "Wembley Central" : ["Bakerloo"] "Wembley Park" : ["Jubilee","Metropolitan"] "West Acton" : ["Central"] "West Brompton" : ["District"] "West Finchley" : ["Northern"] "West Ham" : ["District","Hammersmith & City","Jubilee"] "West Hampstead" : ["Jubilee"] "West Harrow" : ["Metropolitan"] "West Kensington" : ["District"] "West Ruislip" : ["Central"] "Westbourne Park" : ["Circle","Hammersmith & City"] "Westminster" : ["Circle","District","Jubilee"] "White City" : ["Central"] "Whitechapel" : ["District","Hammersmith & City"] "Willesden Green" : ["Jubilee"] "Willesden Junction" : ["Bakerloo"] "Wimbledon" : ["District"] "Wimbledon Park" : ["District"] "Wood Green" : ["Piccadilly"] "Wood Lane" : ["Circle","Hammersmith & City"] "Woodford" : ["Central"] "Woodside Park" : ["Northern"] ``` ...the eleven line names are: ``` Bakerloo Central Circle District Hammersmith & City Jubilee Metropolitan Northern Piccadilly Victoria Waterloo & City ``` \* Transport For London do manage other train lines too, some may also be referred to as being part of "The Tube" (most likely the "Docklands Light Railway" or "DLR") but we shall stick to the eleven listed here. \*\* The linked Wikipedia page currently states 270, but I believe they are mistakenly counting the second location of Canary Wharf even though it only services the "DLR") --- Heaps of imaginary brownie points (and most likely many upvotes too) for a golfed submission using [Mornington Crescent](https://esolangs.org/wiki/Mornington_Crescent) (a compatible IDE is available [here](https://github.com/Timwi/EsotericIDE/))! --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins per language and the shortest solution wins (don't let golfing languages put you off golfing in other languages). Have fun! [Answer] # Mathematica 8+, 266 bytes ``` t=Merge[Cases[<<ExamplePages/TripPlanning.nb,_@v__~_~{_->l_}:>(#->l&/@{v}),-1],Union@@#&]; x(r=t@@Nearest[Keys@t]@StringReplace[__~~"d Lane"|"ket"->"Royal Oak"]@x;DeleteCases[ If[x<>r[[1]]//StringFreeQ@"sm",{},{"Circle"}]⋃r,"Overground"|"Docklands Light Rail"]) ``` This solution originally had the same number of bytes as there are stations. I suppose it could be golfed down another 50 or so bytes, but this seemed like a fitting place to stop for now. --- ## Introduction Mathematica is well known for its large standard library and access to a large online "computable knowledge base." I brazenly searched Wolfram|Alpha hoping to easily find the relevant transit data, but [although it understands the domain of my query, the data is not yet available](http://www.wolframalpha.com/input/?i=Piccadilly+Line). Fortunately, Mathematica's extensive built-in documentation comes with neat examples. [Several of those pages](http://reference.wolfram.com/search/?q=London%20Underground) just happen to use the London Underground network to demonstrate graph-related functionality. We will use the graph from the ["Trip Planning" featured example](http://reference.wolfram.com/language/example/TripPlanning.html) due to its short name. > > ![](https://i.stack.imgur.com/vONyz.png) > > > [Here are other cool uses of the same network](https://visualign.wordpress.com/2012/07/11/london-tube-map-and-graph-visualizations/). I do not believe that programmatically accessing Mathematica's own documentation falls into the ["Fetching from an external source"](https://codegolf.meta.stackexchange.com/a/1062/20007)-type loopholes. --- ## Import the example page We can import the example page as a [notebook expression](http://reference.wolfram.com/language/tutorial/NotebooksAsWolframLanguageExpressions.html): ``` <<ExamplePages/TripPlanning.nb ``` > > > ``` > Notebook[{Cell[ ... ], ... }, Saveable -> False, ...] > > ``` > > It is possible to extract the whole graph from deep inside the notebook expression: ``` g = FirstCase[<< ExamplePages/TripPlanning.nb, _Graph, , -1]; VertexList[g] ``` > > > ``` > {"Acton Central", "Acton Town", "Aldgate", ...} > > ``` > > Note that the vertices of the graph are just the station names. The edges have a custom `"Lines"` property that is a list of strings representing the lines that pass between its two stations: ``` # -> PropertyValue[{g, #}, "Lines"] & /@ EdgeList[g] ``` > > > ``` > {..., > "Acton Town" <-> "Chiswick Park" -> {"District"}, > "Acton Town" <-> "Ealing Common" -> {"District", "Piccadilly"}, > ...} > > ``` > > Now, we could find all the lines passing through a vertex by getting all its incident edges from `IncidenceList[g, vertex]`, mapping `PropertyValue[{g, edge}, "Lines"]` over them, and so on. However, we will skip the above method and save many bytes by pattern matching for the relevant part of the `Graph` constructor – the [`Properties`](http://reference.wolfram.com/language/ref/Graph.html#598959375) option. ## Extract the lines The `Graph` constructor has the following format: ``` Graph[ {v1, v2, ...}, {e1, e2, ...}, Properties -> { v1 -> {propertyName -> propertyValue}, e1 -> {propertyName -> propertyValue}, (* one edge property *) ... } ] ``` (You can see this by inspecting `FullForm[g]` or reading the source code of `TripPlanning.nb` – for its full path, run `FindFile["ExamplePages/TripPlanning.nb"]`.) Here is an example of one edge property: ``` UndirectedEdge["Embankment", "Waterloo"] -> {"Lines" -> {"Bakerloo", "Northern"}} ``` Let's turn this expression into a compact pattern: ``` UndirectedEdge[v1_, v2_] -> {"Lines" -> lines_} UndirectedEdge[v1_, v2_] ~Rule~ {"Lines" -> lines_} UndirectedEdge[v__] ~Rule~ {_ -> lines_} _[v__] ~Rule~ {_ -> l_ } _@v__ ~_~ {_ -> l_ } _@v__~_~{_->l_} ``` ## Make a lookup table Now we can match `v1`, `v2`, and `lines`, but we want `{v1 -> lines, v2 -> lines}`. Helpfully, [`Cases`](http://reference.wolfram.com/language/ref/Cases.html) can simultaneously match a pattern and transform it. ``` Cases[notebook, _@v__~_~{_->l_} :> (# -> l & /@ { v }), -1] [ the pattern ] [ the replacement ] ``` This produces a list of the form `{{v1 -> lines, v2 -> lines}, {v1 -> lines, v3 -> lines}, ...}`. Finally, we merge the list by vertex: ``` t=Merge[Cases[...], Union@@#&]; ``` In under 90 bytes, we have produced an almost-perfect lookup table for each station's lines. ``` t=Merge[Cases[<<ExamplePages/TripPlanning.nb,_@s__~_~{_->l_}:>(#->l&/@{s}),-1],Union@@#&] ``` > > > ``` > <| "Embankment" -> {"Bakerloo", "Circle", "District", "Northern"}, > "Waterloo" -> {"Bakerloo", "Jubilee", "Northern", "Waterloo & City"}, > "Brondesbury" -> {"Overground"}, > ... |> > > ``` > > --- ## Fix typos Unfortunately, some station names are misspelled or missing. Fuzzy string matching should take care of the typos. We can find the [`Nearest`](http://reference.wolfram.com/language/ref/Nearest.html) misspelled station name to the input station name: ``` Nearest[Keys@t] ``` Replace inputs of `"Wood Lane"` and `"Shepherd's Bush Market"` (new stations) with `"Royal Oak"`, since those three stations share the same lines: ``` StringReplace[__ ~~ "d Lane" | "ket" -> "Royal Oak"] ``` Compose those functions to get the fake station name, look up its lines in the table, and store in `r`: ``` r=t@@Nearest[Keys@t]@StringReplace[__~~"d Lane"|"ket"->"Royal Oak"]@x ``` ## Fix outdated The network is also slightly outdated due to the Circle Line overhaul. If the input station is `"Hammersmith"` or if the lookup table returns only `{"Hammersmith & City"}`, then add `"Circle"` to the lines. ``` If[x <> r[[1]] // StringFreeQ@"sm", {}, {"Circle"}] ⋃ r ``` ## Remove extraneous lines The graph contains some lines that we don't care about, so remove them: ``` DeleteCases[..., "Overground"|"Docklands Light Rail"] ``` That's it! --- ## Try it! (with workarounds) If you want to play around with my solution but don't have Mathematica, you can use the free Wolfram Programming Cloud. [Go here](https://develop.open.wolframcloud.com/app/), click `Create a New Notebook`, then wait a moment. Unfortunately, the platform has some limitations that prevent my notebook-importing code from working. Here are some crude workarounds: Since the example page is not there, we can try to abuse the copy-input-to-clipboard function from the online documentation. I used my browser's developer tools and saw that a request was made to [`http://reference.wolfram.com/language/example/Files/TripPlanning.en/i_1.txt`](http://reference.wolfram.com/language/example/Files/TripPlanning.en/i_1.txt) (warning: large). However, the platform's proxy doesn't resolve the domain `reference.wolfram.com`, so I just did it manually. ``` gWorkaround = ToExpression[ FirstCase[ Import["http://140.177.205.163/language/example/Files/TripPlanning.en/i_1.txt", {"HTML","XMLObject"}], XMLElement["pre", _, {a_}] :> a, ,-1 ], InputForm, Hold]; ``` Paste this in first and press `shift+enter` to execute. Now replace `<<ExamplePages/TripPlanning.nb` with `gWorkaround`. --- ## Test data Call the function `f` and test it on the given data: ``` f = %; testData = <|"Acton Town" -> {"District", "Piccadilly"}, "Aldgate" -> {"Circle", "Metropolitan"}, "Aldgate East" -> {"District", "Hammersmith & City"}, "Alperton" -> {"Piccadilly"}, "Amersham" -> {"Metropolitan"}, "Angel" -> {"Northern"}, "Archway" -> {"Northern"}, "Arnos Grove" -> {"Piccadilly"}, "Arsenal" -> {"Piccadilly"}, "Baker Street" -> {"Bakerloo", "Circle", "Hammersmith & City", "Jubilee", "Metropolitan"}, "Balham" -> {"Northern"}, "Bank" -> {"Central", "Northern", "Waterloo & City"}, "Barbican" -> {"Circle", "Hammersmith & City", "Metropolitan"}, "Barking" -> {"District", "Hammersmith & City"}, "Barkingside" -> {"Central"}, "Barons Court" -> {"District", "Piccadilly"}, "Bayswater" -> {"Circle", "District"}, "Becontree" -> {"District"}, "Belsize Park" -> {"Northern"}, "Bermondsey" -> {"Jubilee"}, "Bethnal Green" -> {"Central"}, "Blackfriars" -> {"Circle", "District"}, "Blackhorse Road" -> {"Victoria"}, "Bond Street" -> {"Central", "Jubilee"}, "Borough" -> {"Northern"}, "Boston Manor" -> {"Piccadilly"}, "Bounds Green" -> {"Piccadilly"}, "Bow Road" -> {"District", "Hammersmith & City"}, "Brent Cross" -> {"Northern"}, "Brixton" -> {"Victoria"}, "Bromley-by-Bow" -> {"District", "Hammersmith & City"}, "Buckhurst Hill" -> {"Central"}, "Burnt Oak" -> {"Northern"}, "Caledonian Road" -> {"Piccadilly"}, "Camden Town" -> {"Northern"}, "Canada Water" -> {"Jubilee"}, "Canary Wharf" -> {"Jubilee"}, "Canning Town" -> {"Jubilee"}, "Cannon Street" -> {"Circle", "District"}, "Canons Park" -> {"Jubilee"}, "Chalfont & Latimer" -> {"Metropolitan"}, "Chalk Farm" -> {"Northern"}, "Chancery Lane" -> {"Central"}, "Charing Cross" -> {"Bakerloo", "Northern"}, "Chesham" -> {"Metropolitan"}, "Chigwell" -> {"Central"}, "Chiswick Park" -> {"District"}, "Chorleywood" -> {"Metropolitan"}, "Clapham Common" -> {"Northern"}, "Clapham North" -> {"Northern"}, "Clapham South" -> {"Northern"}, "Cockfosters" -> {"Piccadilly"}, "Colindale" -> {"Northern"}, "Colliers Wood" -> {"Northern"}, "Covent Garden" -> {"Piccadilly"}, "Croxley" -> {"Metropolitan"}, "Dagenham East" -> {"District"}, "Dagenham Heathway" -> {"District"}, "Debden" -> {"Central"}, "Dollis Hill" -> {"Jubilee"}, "Ealing Broadway" -> {"Central", "District"}, "Ealing Common" -> {"District", "Piccadilly"}, "Earl's Court" -> {"District", "Piccadilly"}, "East Acton" -> {"Central"}, "East Finchley" -> {"Northern"}, "East Ham" -> {"District", "Hammersmith & City"}, "East Putney" -> {"District"}, "Eastcote" -> {"Metropolitan", "Piccadilly"}, "Edgware" -> {"Northern"}, "Edgware Road" -> {"Bakerloo", "Circle", "District", "Hammersmith & City"}, "Elephant & Castle" -> {"Bakerloo", "Northern"}, "Elm Park" -> {"District"}, "Embankment" -> {"Bakerloo", "Circle", "District", "Northern"}, "Epping" -> {"Central"}, "Euston" -> {"Northern", "Victoria"}, "Euston Square" -> {"Circle", "Hammersmith & City", "Metropolitan"}, "Fairlop" -> {"Central"}, "Farringdon" -> {"Circle", "Hammersmith & City", "Metropolitan"}, "Finchley Central" -> {"Northern"}, "Finchley Road" -> {"Jubilee", "Metropolitan"}, "Finsbury Park" -> {"Piccadilly", "Victoria"}, "Fulham Broadway" -> {"District"}, "Gants Hill" -> {"Central"}, "Gloucester Road" -> {"Circle", "District", "Piccadilly"}, "Golders Green" -> {"Northern"}, "Goldhawk Road" -> {"Circle", "Hammersmith & City"}, "Goodge Street" -> {"Northern"}, "Grange Hill" -> {"Central"}, "Great Portland Street" -> {"Circle", "Hammersmith & City", "Metropolitan"}, "Greenford" -> {"Central"}, "Green Park" -> {"Jubilee", "Piccadilly", "Victoria"}, "Gunnersbury" -> {"District"}, "Hainault" -> {"Central"}, "Hammersmith" -> {"Circle", "District", "Hammersmith & City", "Piccadilly"}, "Hampstead" -> {"Northern"}, "Hanger Lane" -> {"Central"}, "Harlesden" -> {"Bakerloo"}, "Harrow & Wealdstone" -> {"Bakerloo"}, "Harrow-on-the-Hill" -> {"Metropolitan"}, "Hatton Cross" -> {"Piccadilly"}, "Heathrow Terminals 1, 2, 3" -> {"Piccadilly"}, "Heathrow Terminal 4" -> {"Piccadilly"}, "Heathrow Terminal 5" -> {"Piccadilly"}, "Hendon Central" -> {"Northern"}, "High Barnet" -> {"Northern"}, "Highbury & Islington" -> {"Victoria"}, "Highgate" -> {"Northern"}, "High Street Kensington" -> {"Circle", "District"}, "Hillingdon" -> {"Metropolitan", "Piccadilly"}, "Holborn" -> {"Central", "Piccadilly"}, "Holland Park" -> {"Central"}, "Holloway Road" -> {"Piccadilly"}, "Hornchurch" -> {"District"}, "Hounslow Central" -> {"Piccadilly"}, "Hounslow East" -> {"Piccadilly"}, "Hounslow West" -> {"Piccadilly"}, "Hyde Park Corner" -> {"Piccadilly"}, "Ickenham" -> {"Metropolitan", "Piccadilly"}, "Kennington" -> {"Northern"}, "Kensal Green" -> {"Bakerloo"}, "Kensington (Olympia)" -> {"District"}, "Kentish Town" -> {"Northern"}, "Kenton" -> {"Bakerloo"}, "Kew Gardens" -> {"District"}, "Kilburn" -> {"Jubilee"}, "Kilburn Park" -> {"Bakerloo"}, "Kingsbury" -> {"Jubilee"}, "King's Cross St. Pancras" -> {"Circle", "Hammersmith & City", "Metropolitan", "Northern", "Piccadilly", "Victoria"}, "Knightsbridge" -> {"Piccadilly"}, "Ladbroke Grove" -> {"Circle", "Hammersmith & City"}, "Lambeth North" -> {"Bakerloo"}, "Lancaster Gate" -> {"Central"}, "Latimer Road" -> {"Circle", "Hammersmith & City"}, "Leicester Square" -> {"Northern", "Piccadilly"}, "Leyton" -> {"Central"}, "Leytonstone" -> {"Central"}, "Liverpool Street" -> {"Central", "Circle", "Hammersmith & City", "Metropolitan"}, "London Bridge" -> {"Jubilee", "Northern"}, "Loughton" -> {"Central"}, "Maida Vale" -> {"Bakerloo"}, "Manor House" -> {"Piccadilly"}, "Mansion House" -> {"Circle", "District"}, "Marble Arch" -> {"Central"}, "Marylebone" -> {"Bakerloo"}, "Mile End" -> {"Central", "District", "Hammersmith & City"}, "Mill Hill East" -> {"Northern"}, "Monument" -> {"Circle", "District"}, "Moorgate" -> {"Circle", "Hammersmith & City", "Metropolitan", "Northern"}, "Moor Park" -> {"Metropolitan"}, "Morden" -> {"Northern"}, "Mornington Crescent" -> {"Northern"}, "Neasden" -> {"Jubilee"}, "Newbury Park" -> {"Central"}, "North Acton" -> {"Central"}, "North Ealing" -> {"Piccadilly"}, "North Greenwich" -> {"Jubilee"}, "North Harrow" -> {"Metropolitan"}, "North Wembley" -> {"Bakerloo"}, "Northfields" -> {"Piccadilly"}, "Northolt" -> {"Central"}, "Northwick Park" -> {"Metropolitan"}, "Northwood" -> {"Metropolitan"}, "Northwood Hills" -> {"Metropolitan"}, "Notting Hill Gate" -> {"Central", "Circle", "District"}, "Oakwood" -> {"Piccadilly"}, "Old Street" -> {"Northern"}, "Osterley" -> {"Piccadilly"}, "Oval" -> {"Northern"}, "Oxford Circus" -> {"Bakerloo", "Central", "Victoria"}, "Paddington" -> {"Bakerloo", "Circle", "District", "Hammersmith & City"}, "Park Royal" -> {"Piccadilly"}, "Parsons Green" -> {"District"}, "Perivale" -> {"Central"}, "Piccadilly Circus" -> {"Bakerloo", "Piccadilly"}, "Pimlico" -> {"Victoria"}, "Pinner" -> {"Metropolitan"}, "Plaistow" -> {"District", "Hammersmith & City"}, "Preston Road" -> {"Metropolitan"}, "Putney Bridge" -> {"District"}, "Queen's Park" -> {"Bakerloo"}, "Queensbury" -> {"Jubilee"}, "Queensway" -> {"Central"}, "Ravenscourt Park" -> {"District"}, "Rayners Lane" -> {"Metropolitan", "Piccadilly"}, "Redbridge" -> {"Central"}, "Regent's Park" -> {"Bakerloo"}, "Richmond" -> {"District"}, "Rickmansworth" -> {"Metropolitan"}, "Roding Valley" -> {"Central"}, "Royal Oak" -> {"Circle", "Hammersmith & City"}, "Ruislip" -> {"Metropolitan", "Piccadilly"}, "Ruislip Gardens" -> {"Central"}, "Ruislip Manor" -> {"Metropolitan", "Piccadilly"}, "Russell Square" -> {"Piccadilly"}, "St. James's Park" -> {"Circle", "District"}, "St. John's Wood" -> {"Jubilee"}, "St. Paul's" -> {"Central"}, "Seven Sisters" -> {"Victoria"}, "Shepherd's Bush" -> {"Central"}, "Shepherd's Bush Market" -> {"Circle", "Hammersmith & City"}, "Sloane Square" -> {"Circle", "District"}, "Snaresbrook" -> {"Central"}, "South Ealing" -> {"Piccadilly"}, "South Harrow" -> {"Piccadilly"}, "South Kensington" -> {"Circle", "District", "Piccadilly"}, "South Kenton" -> {"Bakerloo"}, "South Ruislip" -> {"Central"}, "South Wimbledon" -> {"Northern"}, "South Woodford" -> {"Central"}, "Southfields" -> {"District"}, "Southgate" -> {"Piccadilly"}, "Southwark" -> {"Jubilee"}, "Stamford Brook" -> {"District"}, "Stanmore" -> {"Jubilee"}, "Stepney Green" -> {"District", "Hammersmith & City"}, "Stockwell" -> {"Northern", "Victoria"}, "Stonebridge Park" -> {"Bakerloo"}, "Stratford" -> {"Central", "Jubilee"}, "Sudbury Hill" -> {"Piccadilly"}, "Sudbury Town" -> {"Piccadilly"}, "Swiss Cottage" -> {"Jubilee"}, "Temple" -> {"Circle", "District"}, "Theydon Bois" -> {"Central"}, "Tooting Bec" -> {"Northern"}, "Tooting Broadway" -> {"Northern"}, "Tottenham Court Road" -> {"Central", "Northern"}, "Tottenham Hale" -> {"Victoria"}, "Totteridge & Whetstone" -> {"Northern"}, "Tower Hill" -> {"Circle", "District"}, "Tufnell Park" -> {"Northern"}, "Turnham Green" -> {"District", "Piccadilly"}, "Turnpike Lane" -> {"Piccadilly"}, "Upminster" -> {"District"}, "Upminster Bridge" -> {"District"}, "Upney" -> {"District"}, "Upton Park" -> {"District", "Hammersmith & City"}, "Uxbridge" -> {"Metropolitan", "Piccadilly"}, "Vauxhall" -> {"Victoria"}, "Victoria" -> {"Circle", "District", "Victoria"}, "Walthamstow Central" -> {"Victoria"}, "Wanstead" -> {"Central"}, "Warren Street" -> {"Northern", "Victoria"}, "Warwick Avenue" -> {"Bakerloo"}, "Waterloo" -> {"Bakerloo", "Jubilee", "Northern", "Waterloo & City"}, "Watford" -> {"Metropolitan"}, "Wembley Central" -> {"Bakerloo"}, "Wembley Park" -> {"Jubilee", "Metropolitan"}, "West Acton" -> {"Central"}, "West Brompton" -> {"District"}, "West Finchley" -> {"Northern"}, "West Ham" -> {"District", "Hammersmith & City", "Jubilee"}, "West Hampstead" -> {"Jubilee"}, "West Harrow" -> {"Metropolitan"}, "West Kensington" -> {"District"}, "West Ruislip" -> {"Central"}, "Westbourne Park" -> {"Circle", "Hammersmith & City"}, "Westminster" -> {"Circle", "District", "Jubilee"}, "White City" -> {"Central"}, "Whitechapel" -> {"District", "Hammersmith & City"}, "Willesden Green" -> {"Jubilee"}, "Willesden Junction" -> {"Bakerloo"}, "Wimbledon" -> {"District"}, "Wimbledon Park" -> {"District"}, "Wood Green" -> {"Piccadilly"}, "Wood Lane" -> {"Circle", "Hammersmith & City"}, "Woodford" -> {"Central"}, "Woodside Park" -> {"Northern"}|>; KeyValueMap[{#, f[#] == #2} &, testData] // Grid ``` [Answer] # ES6, Node.js / Chrome, ~~989~~ ~~977~~ ~~931~~ ~~892~~ ~~889~~ 887 bytes ``` s=>"Bakerloo,Central,Circle,District,Hammersmith & City,Jubilee,Metropolitan,Northern,Piccadilly,Victoria,Waterloo & City".split`,`.filter((_,i)=>parseInt('7c1w0o741s3k39w22c020c080we80y3l0a8w0t3xhs2olc7g0km87w0176r8ao2e4g0q5w0eeb753mekwx1k18'.substr(" 5Kd5_9 5c4^5];`3]3 4]4^<`Y`0^5h3 9 ;<K 9^2b<`3 Wf9 9`E 0<a;< ; 9`;]2o4b99a33d5`; 3`3jB]Kj9b55e8m5]= KmS ;]K5`9^9]<_3^0 ;]3_3]3 99;b=]K 3 Xe95`9_Qd5_0o3b;];bKf=e=b3jH_<]4d; 3g:d45eT]J_5Kk4{2q9_Kc4c<l9vD`9; 9eIc2^D]<]5a3d8`5hF 4jKhLUm3|5]: ;a5{<> :^3d5t9]5l6_A~f9h5]5b5b9hK]9]: 5l4:a5m9}4^@oHkH^3e3c1c4nBf<bHa:w=b;]AsDl; K`H~K]3d;f8r9 4n9eV]9 <^9~3n=l<]9]5]5a9kK 5 5`: =g:aHcAb2q?_2b0tAsNc;]9]9_3e5e3qAkR^Ac5bK Mc?a;9t=y2_;]5b3_2e<vOd4_9i;^C`9w;a3p:a<j9]5 7Ke:_<3 9`5_Ga4h9t8_9^>e3]H^Eg5zAe4cZ_;ePGm2 3a3".replace(/./g,c=>c.repeat((n=c[C='charCodeAt']())<92||n-91))[C](parseInt(s.replace(/\W|\d/g,''),36)*79%2777%2328)*2-96,2),36)>>i&1) ``` ### Full test suite (Node.js) [Try it online!](https://tio.run/##pVptd9o4Fv7eX6GTc6bAlGQIxk0cILNJmoaWpMkkbdndlhfZVrCLLVHZDmGmO3999soY2wTJkJn5MCdFj6Sr@/LceyV/ww84sLg7DXcps8lfHgnRPWr/FbSPd07xhHCPseoZoSHHXvXM5ZZHqm/cIOSuFVY72PcJD3w3dNBLdOaG8@r7yHQ9QqpXJORsyjw3xLT6gfHQIZxWb1zLwrbrefPqZ1iAcRdXeziMd0lW2NkLpjBrVB3t3bseDJXLw6pbaR9PMQ/IOxqWSwfW/qzGDhr7gTbRjFm9btXqNat2WJuRw9pc82r4cFYLtUcnqDPPOhjXJv7hway2f/CaH2JWJ41x7bs@qxFiHuiaTyazx/3J/mFpL4hMOFh5B@ldWx8aSLcaA73fHGl9DTX6jUFr9J9RbaA7GjJQs9VFxqButkYa6t0byBido1oLN1uoCX83@3XWMA0Da5qtj5pIG2nfTvvdb4ap6@TQ1/tt1PXvULPf1UfGwOi3htqgBv/UhmIvw2ia7X4XaejfxADA8DcQp8Y0s9lvmt37Nmmb2rfOsNVv2LD0@Mhu6ORj//1Q704af9S/G8Ou1bBanvHwZmSANOSdVR@86bf6Otbsw5HuvEWNb13n8pOv/dD7R6iJ9T9ax@hoALKGRl/3Xg9P/rw3HL2vm7ppON2@ASjdaxxh3Tf@1xj8i3UmnYFGNGvfatDT@5bZwUezNoh3Erzxmqg76vzZ7Wt28/6QG6hBDfK5b6DWwPhTo22vBcvB0tiYdJGO9NERao@PcMc6Mevffx3WzVp4EnywmoAyhhrRifb9ZHI7OLF0s4uurF9x0wjb8/qwCdJpwzppPVzbjaHhNgdnI2PWxNr0CLe@wRbooEuOhi1Q50gfXuCGY4SHQ2NwTLR@Z3A@1n8/IQ3rv8Mmubnw60jD2s4eJ1MPW6T8y94v46rVPrbELwSH5TJtW1/O2iXLwfwMwuQkLPXLlUrLqP/4QXeN/Urly1m/nHpokK30tffjqw2rlUqVqva68vOB8VP94ODgp7pWP6z8XN81Xlfr8cjxsftyvxLHHycBaqNSqfoCwX9sAv@oLf4OQhy6jDZfvCgnf8LYFxj6gnZOIJ4o@shmdKeKvuwsg3SnupNF3U4f9asJ3LPHEHkxdhHXgMxH7ToWneMgfLr4OgesTJwSDmLFk@RiiMkO9mOEans6Jl4MWBJJfpBbzgzP1cOUBeiCswdSIATYjWJPDYiZEN2FnJCFApbUCApIlSfRRHUn4UO1bk@xtzy@RPxTTCcLEy0oGNZJUdWdp9SZn8dN18J01bxSCZVy8YlLx88ydzIncG2yIvQKgtEAnbGIh1u56SmeBzNxzNWTpNNySGIxKiy0um4e4AXu7wTdgJRKfRPuM2oHZOFQS@vlAaEDrgIeRQhVHRJCf3IPuY0Hm6UWWIeBA6Jbhu0Yv0yNeRgIlfe/zB0kIjLOorGjPCILBFFcYcp4gcezCNSQO6YCNcvE3tpLOAiPzjgLAqWM3H1c0oZMG5z5HpnvmvNdkOB5m0eg7ogHIerAWVQGjDhIeI2VbnKGPWIz6mKaHV@qoDPs2yTHytK1KLYx6qVOvm5RAeFz1IPsc6@GUAi9bCc5BAyf96ICxwS0iNQ0WCTrOdi7h5ADJV9CLvIT8RV8ItAT9BZzJdcBgloEznmJqYo/AMPFMTPvyTGxdE2yKbucOe54RpS@AMPBzLUmmSZkyoIIBoecMWYXbuXhKUgD9Of7TO0QCSoe2gS6Y1EBiAEPQbiThIjkLgpiUht7RL2K57mwBOotjycFPYiovsDcLiIMsNujl5CrQklv8JhQcbT1akMC6kB5luZ/GZCYtpKo34iTBRkTrPv4OfaEuwHhYHu5S8a9kv2SCTkLb8pw55h7peekRKEXFFd7imPFgLcutZylqiUGi0GdJDS2Zc940k0UUqJUuIBYLCksV0ysOo49nmGu9L5kOONZWem1tfwegaiJKesM5Ex8vphCzj2/MPbPfROKNB@ssI14sg2m02WhJbFlFIRPqaIqy4kLILr7Hi2V@bfKvrfYBemnCmmAvgX92uwfFJZLx0RpHMkNn@JSy2@spWFKYEaQQVJ75TxOqrW3kai@V@NbYuML8JmgqGK48FhkEcG0mbgy80sj4IJ5tuDXrNiSqEOAHDybSNYvdPkLIO0xyWd92eIcQ49VeEAORItuYKqHn5Sif8cJ4qPeM26rt4Oyaa34qG406EVEKQghvEBlzA52KY68ULF17hhKM0qPKrUtIKfgFliZODtC87yo5ulAgiDBMoul/LIC4FCIv0Q9gj1b0AAphu4yugty7Kb2Vlipg0PBKVmxJT@iSMFCgI/QPIFqvQDtV1G9irRnzEGN54D1IjC1hczF5NJxxw6CZpSqY0JAYjJ5id4FIqkXNCQCm96mqLZbxAzqEhrkViuqwYV9cnS7TTbtMM9knD4pVFTQOJbTKJO4HkAY8OKGLqcDO1rQVVmOMuagnQxgqRW7KNZKkGn5VwzrkULY3F40/FBfgbELGt531iSuKLfWNNiR5uwosbqw9MpVgSQgM29A5Wtv7k9dXFEpEbChGziF3aTAsILdZkmJHig3cT3welUPmYxmPiPbRFwBpQQsW4OORcErWAWCYg8WoxbHwXOzycpV2Ka80KUQgmFgcheyodoLLrFtcjYhuRvD7dLsJfZNAgNZ0ybRDJC8heMi4SK9el2LuaSXfm6evyRuUoDkSkC5gvKT5uo2YjGYpRMJwn0gfMqYJ7@a@luVwSWL@fs0M1SW/CX@fimuutRnuMKujdFn7CkzYnwPhoBOggK3AFAgLtszWBFtX2FuegSdLPlQJhafe8QsSNRXcGR0Tm1Vx7nBG2C6F5dzGY1KlHfFaJQ2LoUnYoyvvxY8K0RXF8sIROEGVyy9SJAuwRPuBRohgbU8gwT6geC0dlrnog9kttowrNsqXrOw314gFp2/2ocWqDgZzNzEMyQCxahFmVaknwWuR3xz2eNLnCgG3bsEisINcjFlORwPr16AFYm06QosBcXeGRRDw1DcpcRuvEaY1UKHvcaTVBLpqa89e0NPdC3IdKlc@RoP6gLz@lF0N0jIGK1dVGZnkGSqG2zbubrin1x3xIXPLZsX1VuACcRFb1alSNR5Q7j7sCTRdR/JFlYcWL6z63uuxVQ19Y1LafGV8o2HQdRnPgDcAF8I3kjTq2rx@JYrn4ckevktAqWVgsJyKMYU1UMLwNPbxWz8Fj/AuCXuBwsvom7xXLS@WSu5TRV7S@xcTSTZnIzhtw1HvAU@E89mSsmAPnxIobO0OFIo/ZYJ1xf5ehl4EomEP6ePM9sVR7eRCy3cdHutLPArtbJEkgSVPaVtt3YQEGC0XJkmxYnK@D32SZBXfhHnxROYI/wxvalf97ZFwR15JdWp7gi4G7pzs2cDSXDeOWQKjGfDXqdRoCpznqBAUXyyxa1RbgGPgTNLLzVlCqCAghKfMVUuj19LNmbqBSqXgwtQG7v56obZBd3aApP3XdWJeq6oA2x1K5rAwC0KLt1iUK5ckKlYQNJKUH2ymfrZ8C7EfpwbT1NDSZ0ZU59xolyETAU9S7LWJpcKmTVJ3/uK79TvRO@zoMdC/oNCAodripW9zd9FdlxvpjdvchUmqLTRl6NmbiDejcIQj1V6@kj8qbc5cj46ZB53XcxV0cJHxuJq7JRYKidLIfnbdCkuDBevd/GjV67TXf/IRTars6xEJCaLUQuLvUQ9h4RZ/ypdcwYNc3btXaSi6J4K2i76euRjxGMBpV4ptaGYMXUnJEvaUtinqe/SYPmBgES6FLChYPk0LXi6@zQVhdF6ibEhoj495iqIbTLgZxw9OjjRucSG6U8qRpXM6WEvBNWLcnDljlEKpdmN/Lqj94D3CZU2B4qdedwenUDajJT9/PJTraeVseRyo@i7rl6OZxQ1VNITrmhBJlACk7yxKBfe8O4cA8S3OdOQKVuJGLTpcToGbfc4LWPZ5fTcy4sStKnRjmFPsrzqWMWpWkBMIDxKJPVcYYSJmXkCkMWE5ICOG5JESXKBBMBy8DT5unLbgO9BPMcPUjmik2yfot5H1BLfqipdcaV6kSl3CSjsf0R1s@mDtRiTvbVtp/3iqkkMiy8e5ZnhRb/yYg9mn2PLKWPUPo6/7n3VRvhLrY9eoRLa3T2G/79CZY7a6L4sfq9U4pFy/DP@sh8DS6jdRhz9isps8upVFZWuu6UKOkKltyfvLkvxjMpXWqo0X7xItih9pdfdo3hxNhHjv4g/kw@H9zwCDu0A2oL2n3lkz2PjMsysNP/6Pw) ### Demo (Chrome) **NB**: Due to inconsistencies in the implementation of `parseInt()` across browsers(1), this is only guaranteed to work for all stations on Chrome. ``` let f = s=>"Bakerloo,Central,Circle,District,Hammersmith & City,Jubilee,Metropolitan,Northern,Piccadilly,Victoria,Waterloo & City".split`,`.filter((_,i)=>parseInt('7c1w0o741s3k39w22c020c080we80y3l0a8w0t3xhs2olc7g0km87w0176r8ao2e4g0q5w0eeb753mekwx1k18'.substr(" 5Kd5_9 5c4^5];`3]3 4]4^<`Y`0^5h3 9 ;<K 9^2b<`3 Wf9 9`E 0<a;< ; 9`;]2o4b99a33d5`; 3`3jB]Kj9b55e8m5]= KmS ;]K5`9^9]<_3^0 ;]3_3]3 99;b=]K 3 Xe95`9_Qd5_0o3b;];bKf=e=b3jH_<]4d; 3g:d45eT]J_5Kk4{2q9_Kc4c<l9vD`9; 9eIc2^D]<]5a3d8`5hF 4jKhLUm3|5]: ;a5{<> :^3d5t9]5l6_A~f9h5]5b5b9hK]9]: 5l4:a5m9}4^@oHkH^3e3c1c4nBf<bHa:w=b;]AsDl; K`H~K]3d;f8r9 4n9eV]9 <^9~3n=l<]9]5]5a9kK 5 5`: =g:aHcAb2q?_2b0tAsNc;]9]9_3e5e3qAkR^Ac5bK Mc?a;9t=y2_;]5b3_2e<vOd4_9i;^C`9w;a3p:a<j9]5 7Ke:_<3 9`5_Ga4h9t8_9^>e3]H^Eg5zAe4cZ_;ePGm2 3a3".replace(/./g,c=>c.repeat((n=c[C='charCodeAt']())<92||n-91))[C](parseInt(s.replace(/\W|\d/g,''),36)*79%2777%2328)*2-96,2),36)>>i&1) ``` ``` <select onclick="O.innerText=f(this.options[this.selectedIndex].text).join(', ')"> <option>-- Where do you want to go? --</option> <option>Acton Town</option> <option>Aldgate</option> <option>Aldgate East</option> <option>Alperton</option> <option>Amersham</option> <option>Angel</option> <option>Archway</option> <option>Arnos Grove</option> <option>Arsenal</option> <option>Baker Street</option> <option>Balham</option> <option>Bank</option> <option>Barbican</option> <option>Barking</option> <option>Barkingside</option> <option>Barons Court</option> <option>Bayswater</option> <option>Becontree</option> <option>Belsize Park</option> <option>Bermondsey</option> <option>Bethnal Green</option> <option>Blackfriars</option> <option>Blackhorse Road</option> <option>Bond Street</option> <option>Borough</option> <option>Boston Manor</option> <option>Bounds Green</option> <option>Bow Road</option> <option>Brent Cross</option> <option>Brixton</option> <option>Bromley-by-Bow</option> <option>Buckhurst Hill</option> <option>Burnt Oak</option> <option>Caledonian Road</option> <option>Camden Town</option> <option>Canada Water</option> <option>Canary Wharf</option> <option>Canning Town</option> <option>Cannon Street</option> <option>Canons Park</option> <option>Chalfont & Latimer</option> <option>Chalk Farm</option> <option>Chancery Lane</option> <option>Charing Cross</option> <option>Chesham</option> <option>Chigwell</option> <option>Chiswick Park</option> <option>Chorleywood</option> <option>Clapham Common</option> <option>Clapham North</option> <option>Clapham South</option> <option>Cockfosters</option> <option>Colindale</option> <option>Colliers Wood</option> <option>Covent Garden</option> <option>Croxley</option> <option>Dagenham East</option> <option>Dagenham Heathway</option> <option>Debden</option> <option>Dollis Hill</option> <option>Ealing Broadway</option> <option>Ealing Common</option> <option>Earl's Court</option> <option>East Acton</option> <option>East Finchley</option> <option>East Ham</option> <option>East Putney</option> <option>Eastcote</option> <option>Edgware</option> <option>Edgware Road</option> <option>Elephant & Castle</option> <option>Elm Park</option> <option>Embankment</option> <option>Epping</option> <option>Euston</option> <option>Euston Square</option> <option>Fairlop</option> <option>Farringdon</option> <option>Finchley Central</option> <option>Finchley Road</option> <option>Finsbury Park</option> <option>Fulham Broadway</option> <option>Gants Hill</option> <option>Gloucester Road</option> <option>Golders Green</option> <option>Goldhawk Road</option> <option>Goodge Street</option> <option>Grange Hill</option> <option>Great Portland Street</option> <option>Greenford</option> <option>Green Park</option> <option>Gunnersbury</option> <option>Hainault</option> <option>Hammersmith</option> <option>Hampstead</option> <option>Hanger Lane</option> <option>Harlesden</option> <option>Harrow & Wealdstone</option> <option>Harrow-on-the-Hill</option> <option>Hatton Cross</option> <option>Heathrow Terminals 1, 2, 3</option> <option>Heathrow Terminal 4</option> <option>Heathrow Terminal 5</option> <option>Hendon Central</option> <option>High Barnet</option> <option>Highbury & Islington</option> <option>Highgate</option> <option>High Street Kensington</option> <option>Hillingdon</option> <option>Holborn</option> <option>Holland Park</option> <option>Holloway Road</option> <option>Hornchurch</option> <option>Hounslow Central</option> <option>Hounslow East</option> <option>Hounslow West</option> <option>Hyde Park Corner</option> <option>Ickenham</option> <option>Kennington</option> <option>Kensal Green</option> <option>Kensington (Olympia)</option> <option>Kentish Town</option> <option>Kenton</option> <option>Kew Gardens</option> <option>Kilburn</option> <option>Kilburn Park</option> <option>Kingsbury</option> <option>King's Cross St. Pancras</option> <option>Knightsbridge</option> <option>Ladbroke Grove</option> <option>Lambeth North</option> <option>Lancaster Gate</option> <option>Latimer Road</option> <option>Leicester Square</option> <option>Leyton</option> <option>Leytonstone</option> <option>Liverpool Street</option> <option>London Bridge</option> <option>Loughton</option> <option>Maida Vale</option> <option>Manor House</option> <option>Mansion House</option> <option>Marble Arch</option> <option>Marylebone</option> <option>Mile End</option> <option>Mill Hill East</option> <option>Monument</option> <option>Moorgate</option> <option>Moor Park</option> <option>Morden</option> <option>Mornington Crescent</option> <option>Neasden</option> <option>Newbury Park</option> <option>North Acton</option> <option>North Ealing</option> <option>North Greenwich</option> <option>North Harrow</option> <option>North Wembley</option> <option>Northfields</option> <option>Northolt</option> <option>Northwick Park</option> <option>Northwood</option> <option>Northwood Hills</option> <option>Notting Hill Gate</option> <option>Oakwood</option> <option>Old Street</option> <option>Osterley</option> <option>Oval</option> <option>Oxford Circus</option> <option>Paddington</option> <option>Park Royal</option> <option>Parsons Green</option> <option>Perivale</option> <option>Piccadilly Circus</option> <option>Pimlico</option> <option>Pinner</option> <option>Plaistow</option> <option>Preston Road</option> <option>Putney Bridge</option> <option>Queen's Park</option> <option>Queensbury</option> <option>Queensway</option> <option>Ravenscourt Park</option> <option>Rayners Lane</option> <option>Redbridge</option> <option>Regent's Park</option> <option>Richmond</option> <option>Rickmansworth</option> <option>Roding Valley</option> <option>Royal Oak</option> <option>Ruislip</option> <option>Ruislip Gardens</option> <option>Ruislip Manor</option> <option>Russell Square</option> <option>St. James's Park</option> <option>St. John's Wood</option> <option>St. Paul's</option> <option>Seven Sisters</option> <option>Shepherd's Bush</option> <option>Shepherd's Bush Market</option> <option>Sloane Square</option> <option>Snaresbrook</option> <option>South Ealing</option> <option>South Harrow</option> <option>South Kensington</option> <option>South Kenton</option> <option>South Ruislip</option> <option>South Wimbledon</option> <option>South Woodford</option> <option>Southfields</option> <option>Southgate</option> <option>Southwark</option> <option>Stamford Brook</option> <option>Stanmore</option> <option>Stepney Green</option> <option>Stockwell</option> <option>Stonebridge Park</option> <option>Stratford</option> <option>Sudbury Hill</option> <option>Sudbury Town</option> <option>Swiss Cottage</option> <option>Temple</option> <option>Theydon Bois</option> <option>Tooting Bec</option> <option>Tooting Broadway</option> <option>Tottenham Court Road</option> <option>Tottenham Hale</option> <option>Totteridge & Whetstone</option> <option>Tower Hill</option> <option>Tufnell Park</option> <option>Turnham Green</option> <option>Turnpike Lane</option> <option>Upminster</option> <option>Upminster Bridge</option> <option>Upney</option> <option>Upton Park</option> <option>Uxbridge</option> <option>Vauxhall</option> <option>Victoria</option> <option>Walthamstow Central</option> <option>Wanstead</option> <option>Warren Street</option> <option>Warwick Avenue</option> <option>Waterloo</option> <option>Watford</option> <option>Wembley Central</option> <option>Wembley Park</option> <option>West Acton</option> <option>West Brompton</option> <option>West Finchley</option> <option>West Ham</option> <option>West Hampstead</option> <option>West Harrow</option> <option>West Kensington</option> <option>West Ruislip</option> <option>Westbourne Park</option> <option>Westminster</option> <option>White City</option> <option>Whitechapel</option> <option>Willesden Green</option> <option>Willesden Junction</option> <option>Wimbledon</option> <option>Wimbledon Park</option> <option>Wood Green</option> <option>Wood Lane</option> <option>Woodford</option> <option>Woodside Park</option> </select> <pre id=O></pre> ``` *(1) [From the specification](https://www.ecma-international.org/ecma-262/6.0/#sec-parseint-string-radix): Let mathInt be the mathematical integer value that is represented by Z in radix-R notation [...]. **If R is not 2, 4, 8, 10, 16, or 32, then mathInt may be an implementation-dependent approximation** to the mathematical integer value that is represented by Z in radix-R notation.* --- ### How? Below is a step-by-step decoding example for the input `s = "St. James's Park"`. **Step #1** We first inflate the primary lookup table (from 503 to 2,328 bytes) by expanding all its padding characters. These characters are encoded with an ASCII code greater than 92, whereas payload data is using the range 48-90. ``` tbl = " 5Kd5_9 5c4[...]" .replace( /./g, c => c.repeat((n = c.charCodeAt()) < 92 || n - 91) ) ``` **Step #2** We remove all non-alphabetic characters from the input string: ``` str = s.replace(/\W|\d/g, '') ``` which gives `"StJamessPark"`. **Step #3** We parse the resulting string as a base-36 quantity: ``` id = parseInt(str, 36) ``` which gives `3793395908848905700` (this is the approximated result returned by [Chrome V8](https://en.wikipedia.org/wiki/Chrome_V8)). **Step #4** We compute the hash value: ``` hash = id * 79 % 2777 % 2328 ``` which gives `533`. **NB**: Due to loss of precision, this result is not mathematically correct (it should be `184`). But the lookup table was -- of course -- built the same way, so that's the one we're expecting. **Step #5** We retrieve the ASCII code of the character at this position in the primary lookup table: ``` code = tbl.charCodeAt(hash) ``` which gives `58` (this is the character `':'`). **Step #6** We use this value to extract a 2-character string from the secondary lookup table: ``` msk36 = '7c1w0o74[...]'.substr(code * 2 - 96, 2) ``` which gives `0c`. **Step #7** We parse this string as a base-36 quantity: ``` msk = parseInt(msk36, 36) ``` which gives `12`. **Step #8** Finally, we filter the station list according to the bits set in `msk`, starting with the least significant one: ``` "Bakerloo,Central,Circle,District,[...]".split`,`.filter((_, i) => msk >> i & 1) ``` In our example, `msk` holds `12`, which is `00000001100` in binary. So we keep the 3rd and 4th stations, which leads to the final result: `[ 'Circle', 'District' ]`. [Answer] # [Kotlin](https://kotlinlang.org), ~~2271~~ ~~2270~~ ~~2000~~ 1694 bytes ``` {x->val r=java.util.Base64.getDecoder().decode("eJw1VcluG0cU/BWfchoC/dbuPpJDkTM2EuSUnGmFgIlQYkAzBwNEvj1VrUSHkXp7S1W90v7y/XG/vD6ev15eX09/XK7XH8/5cn+9np8/nx/321+36+Vxen8up7e38/372+Xx7dNPn+bL48fzl9v98e18f3/uTn+e79fb7fn576+X6/n8nM/vj/vp+vz99BgH/7/4DYlu98vpH83i290k0vq8nzbqptuXSa3GDiurbT+JRztMKpUf0R1OJXdTtnKcX5b9pKXgpOZ6+Dxtsuf8sp/MEGWjEm3FURSmcI15O0npvmWiKofJsyx447FyR43nKvYFqyzrMmkIUieTilZHSWHOyJKdz0vFVamNJUvKih0/YKfpKN9RsnRfpm4LWqyJb6uKLBuxjtXGiqJr6YFobLeujOfliGV0Nh8dYcOCb9KEGJnmYWoNmTIISiorE5eRuzZlLLWOTQu8qK1tJ9XM8dUVNfWO5sR0JRQ1ScFGo/Xx24yoZesMJzH6tdJ5Nb3vmas3Y+Iex5nHJhUVS5XKMqtxG2svhYGA9Bdk64XMqBQj2qU3LpGtoJtNV1u4Kt53hL8lam7BYpsDMfInLEhrj/ll6sR/g1gMJmo+gkk6MloujBHRtuNKR5AUFIogNYLvPJP3ypF9xnEyD5TW2Jo0cCcZMr5g3itwlRIDDlNH6E5irTmYbN2JiIesu6lmjHLaiORVWQDYJRNDPlpMRpIsu8FVw2M0CzAhvyOCCrkikRresZFppM0r1SK8gl4Wihow7A9oFKSw4t6IC6lJPiuoRD1y7GUtB+ZTUc6DDL1H2PpBAdS8sDkOEdVbEQGBMjhrBcihgHGk0OSRnPW2Dllo16E5Slobs+3JezWSAaaGqttoRyG5WsiFilMWSUCMSsTwB+uI6ojuzZCX1eGgyKC10wZq3ZOusv43QOwoGoYfMs/BLX2ilX5cqTetQ5xaGm6COIyQVMU0SSnliBQlOelmZT+1xE1Ahz+lqw/dBFsVVaC9aYbJNAcV8B7yjWahNMekkmgYDLzEhoFRgVI+yMCoDoITvaDTMTphOoSgA7ToIFbHSAh1j9nhn70630MCtKTGMbACOsKSegHQW2KUkG7PD9OoAFuUVTXHGGoRtJ0C9/EmCAKVLBxJGc7opWMooS5QbfCBhUmdkIK84V3FuYffo8wykmTHEGAg+XX43fC6RhNshUY5WrIwXhJBiSbUuduwXKuUcqdHELHhGzEw8cBUpbR5SwxKxSqcTCEUHVYDwvemx4UeH07TtKFSaEZgHKjTqCmFx/U6DLAq/gcs7EQaZ4cKElpgaUPk1ohw7Rhi3sIPB8Y6hTBgA7Ve6buBVgBSxXyH4RHm1RkCW4d/AeEEm1Q=") var I=java.util.zip.Inflater() I.setInput(r) I.finished() var o=ByteArray(1846) I.inflate(o) var v=String(o).split("~") Regex("(-?[0-9]+)([A-Z]+)").findAll(v[1]).filter{x.hashCode()%2897==it.groupValues[1].toInt()}.map{it.groupValues[2].map{v[0].split("|")[it-'A']}}.first()} ``` ## Beautified ``` {x-> // Parses the data line into groups of <hashcode % 2897, and line numbers within the list below as letters val r = java.util.Base64.getDecoder().decode("eJw1VcluG0cU/BWfchoC/dbuPpJDkTM2EuSUnGmFgIlQYkAzBwNEvj1VrUSHkXp7S1W90v7y/XG/vD6ev15eX09/XK7XH8/5cn+9np8/nx/321+36+Vxen8up7e38/372+Xx7dNPn+bL48fzl9v98e18f3/uTn+e79fb7fn576+X6/n8nM/vj/vp+vz99BgH/7/4DYlu98vpH83i290k0vq8nzbqptuXSa3GDiurbT+JRztMKpUf0R1OJXdTtnKcX5b9pKXgpOZ6+Dxtsuf8sp/MEGWjEm3FURSmcI15O0npvmWiKofJsyx447FyR43nKvYFqyzrMmkIUieTilZHSWHOyJKdz0vFVamNJUvKih0/YKfpKN9RsnRfpm4LWqyJb6uKLBuxjtXGiqJr6YFobLeujOfliGV0Nh8dYcOCb9KEGJnmYWoNmTIISiorE5eRuzZlLLWOTQu8qK1tJ9XM8dUVNfWO5sR0JRQ1ScFGo/Xx24yoZesMJzH6tdJ5Nb3vmas3Y+Iex5nHJhUVS5XKMqtxG2svhYGA9Bdk64XMqBQj2qU3LpGtoJtNV1u4Kt53hL8lam7BYpsDMfInLEhrj/ll6sR/g1gMJmo+gkk6MloujBHRtuNKR5AUFIogNYLvPJP3ypF9xnEyD5TW2Jo0cCcZMr5g3itwlRIDDlNH6E5irTmYbN2JiIesu6lmjHLaiORVWQDYJRNDPlpMRpIsu8FVw2M0CzAhvyOCCrkikRresZFppM0r1SK8gl4Wihow7A9oFKSw4t6IC6lJPiuoRD1y7GUtB+ZTUc6DDL1H2PpBAdS8sDkOEdVbEQGBMjhrBcihgHGk0OSRnPW2Dllo16E5Slobs+3JezWSAaaGqttoRyG5WsiFilMWSUCMSsTwB+uI6ojuzZCX1eGgyKC10wZq3ZOusv43QOwoGoYfMs/BLX2ilX5cqTetQ5xaGm6COIyQVMU0SSnliBQlOelmZT+1xE1Ahz+lqw/dBFsVVaC9aYbJNAcV8B7yjWahNMekkmgYDLzEhoFRgVI+yMCoDoITvaDTMTphOoSgA7ToIFbHSAh1j9nhn70630MCtKTGMbACOsKSegHQW2KUkG7PD9OoAFuUVTXHGGoRtJ0C9/EmCAKVLBxJGc7opWMooS5QbfCBhUmdkIK84V3FuYffo8wykmTHEGAg+XX43fC6RhNshUY5WrIwXhJBiSbUuduwXKuUcqdHELHhGzEw8cBUpbR5SwxKxSqcTCEUHVYDwvemx4UeH07TtKFSaEZgHKjTqCmFx/U6DLAq/gcs7EQaZ4cKElpgaUPk1ohw7Rhi3sIPB8Y6hTBgA7Ve6buBVgBSxXyH4RHm1RkCW4d/AeEEm1Q=") var I = java.util.zip.Inflater() I.setInput(r) I.finished() var o = ByteArray(1846) I.inflate(o) var v= String(o).split("~") Regex("(-?[0-9]+)([A-Z]+)") // Finds all the groups .findAll(v[1])// Gets the right group .filter{ x.hashCode()%2897==it.groupValues[1].toInt()} // Gets each letter and turns it into a station name .map{ it.groupValues[2].map{ v[0] .split("|")[it-'A']}}.first() } ``` ## Test ``` var v:(String)->List<String> = {x->val r=java.util.Base64.getDecoder().decode("eJw1VcluG0cU/BWfchoC/dbuPpJDkTM2EuSUnGmFgIlQYkAzBwNEvj1VrUSHkXp7S1W90v7y/XG/vD6ev15eX09/XK7XH8/5cn+9np8/nx/321+36+Vxen8up7e38/372+Xx7dNPn+bL48fzl9v98e18f3/uTn+e79fb7fn576+X6/n8nM/vj/vp+vz99BgH/7/4DYlu98vpH83i290k0vq8nzbqptuXSa3GDiurbT+JRztMKpUf0R1OJXdTtnKcX5b9pKXgpOZ6+Dxtsuf8sp/MEGWjEm3FURSmcI15O0npvmWiKofJsyx447FyR43nKvYFqyzrMmkIUieTilZHSWHOyJKdz0vFVamNJUvKih0/YKfpKN9RsnRfpm4LWqyJb6uKLBuxjtXGiqJr6YFobLeujOfliGV0Nh8dYcOCb9KEGJnmYWoNmTIISiorE5eRuzZlLLWOTQu8qK1tJ9XM8dUVNfWO5sR0JRQ1ScFGo/Xx24yoZesMJzH6tdJ5Nb3vmas3Y+Iex5nHJhUVS5XKMqtxG2svhYGA9Bdk64XMqBQj2qU3LpGtoJtNV1u4Kt53hL8lam7BYpsDMfInLEhrj/ll6sR/g1gMJmo+gkk6MloujBHRtuNKR5AUFIogNYLvPJP3ypF9xnEyD5TW2Jo0cCcZMr5g3itwlRIDDlNH6E5irTmYbN2JiIesu6lmjHLaiORVWQDYJRNDPlpMRpIsu8FVw2M0CzAhvyOCCrkikRresZFppM0r1SK8gl4Wihow7A9oFKSw4t6IC6lJPiuoRD1y7GUtB+ZTUc6DDL1H2PpBAdS8sDkOEdVbEQGBMjhrBcihgHGk0OSRnPW2Dllo16E5Slobs+3JezWSAaaGqttoRyG5WsiFilMWSUCMSsTwB+uI6ojuzZCX1eGgyKC10wZq3ZOusv43QOwoGoYfMs/BLX2ilX5cqTetQ5xaGm6COIyQVMU0SSnliBQlOelmZT+1xE1Ahz+lqw/dBFsVVaC9aYbJNAcV8B7yjWahNMekkmgYDLzEhoFRgVI+yMCoDoITvaDTMTphOoSgA7ToIFbHSAh1j9nhn70630MCtKTGMbACOsKSegHQW2KUkG7PD9OoAFuUVTXHGGoRtJ0C9/EmCAKVLBxJGc7opWMooS5QbfCBhUmdkIK84V3FuYffo8wykmTHEGAg+XX43fC6RhNshUY5WrIwXhJBiSbUuduwXKuUcqdHELHhGzEw8cBUpbR5SwxKxSqcTCEUHVYDwvemx4UeH07TtKFSaEZgHKjTqCmFx/U6DLAq/gcs7EQaZ4cKElpgaUPk1ohw7Rhi3sIPB8Y6hTBgA7Ve6buBVgBSxXyH4RHm1RkCW4d/AeEEm1Q=") var I=java.util.zip.Inflater() I.setInput(r) I.finished() var o=ByteArray(1846) I.inflate(o) var v=String(o).split("~") Regex("(-?[0-9]+)([A-Z]+)").findAll(v[1]).filter{x.hashCode()%2897==it.groupValues[1].toInt()}.map{it.groupValues[2].map{v[0].split("|")[it-'A']}}.first()} data class TestData(val name: String, val lines: List<String>) fun main(args: Array<String>) { var items = listOf( TestData("Acton Town", listOf("District", "Piccadilly")), TestData("Aldgate", listOf("Circle", "Metropolitan")), TestData("Aldgate East", listOf("District", "Hammersmith & City")), TestData("Alperton", listOf("Piccadilly")), TestData("Amersham", listOf("Metropolitan")), TestData("Angel", listOf("Northern")), TestData("Archway", listOf("Northern")), TestData("Arnos Grove", listOf("Piccadilly")), TestData("Arsenal", listOf("Piccadilly")), TestData("Baker Street", listOf("Bakerloo", "Circle", "Hammersmith & City", "Jubilee", "Metropolitan")), TestData("Balham", listOf("Northern")), TestData("Bank", listOf("Central", "Northern", "Waterloo & City")), TestData("Barbican", listOf("Circle", "Hammersmith & City", "Metropolitan")), TestData("Barking", listOf("District", "Hammersmith & City")), TestData("Barkingside", listOf("Central")), TestData("Barons Court", listOf("District", "Piccadilly")), TestData("Bayswater", listOf("Circle", "District")), TestData("Becontree", listOf("District")), TestData("Belsize Park", listOf("Northern")), TestData("Bermondsey", listOf("Jubilee")), TestData("Bethnal Green", listOf("Central")), TestData("Blackfriars", listOf("Circle", "District")), TestData("Blackhorse Road", listOf("Victoria")), TestData("Bond Street", listOf("Central", "Jubilee")), TestData("Borough", listOf("Northern")), TestData("Boston Manor", listOf("Piccadilly")), TestData("Bounds Green", listOf("Piccadilly")), TestData("Bow Road", listOf("District", "Hammersmith & City")), TestData("Brent Cross", listOf("Northern")), TestData("Brixton", listOf("Victoria")), TestData("Bromley-by-Bow", listOf("District", "Hammersmith & City")), TestData("Buckhurst Hill", listOf("Central")), TestData("Burnt Oak", listOf("Northern")), TestData("Caledonian Road", listOf("Piccadilly")), TestData("Camden Town", listOf("Northern")), TestData("Canada Water", listOf("Jubilee")), TestData("Canary Wharf", listOf("Jubilee")), TestData("Canning Town", listOf("Jubilee")), TestData("Cannon Street", listOf("Circle", "District")), TestData("Canons Park", listOf("Jubilee")), TestData("Chalfont & Latimer", listOf("Metropolitan")), TestData("Chalk Farm", listOf("Northern")), TestData("Chancery Lane", listOf("Central")), TestData("Charing Cross", listOf("Bakerloo", "Northern")), TestData("Chesham", listOf("Metropolitan")), TestData("Chigwell", listOf("Central")), TestData("Chiswick Park", listOf("District")), TestData("Chorleywood", listOf("Metropolitan")), TestData("Clapham Common", listOf("Northern")), TestData("Clapham North", listOf("Northern")), TestData("Clapham South", listOf("Northern")), TestData("Cockfosters", listOf("Piccadilly")), TestData("Colindale", listOf("Northern")), TestData("Colliers Wood", listOf("Northern")), TestData("Covent Garden", listOf("Piccadilly")), TestData("Croxley", listOf("Metropolitan")), TestData("Dagenham East", listOf("District")), TestData("Dagenham Heathway", listOf("District")), TestData("Debden", listOf("Central")), TestData("Dollis Hill", listOf("Jubilee")), TestData("Ealing Broadway", listOf("Central", "District")), TestData("Ealing Common", listOf("District", "Piccadilly")), TestData("Earl's Court", listOf("District", "Piccadilly")), TestData("East Acton", listOf("Central")), TestData("East Finchley", listOf("Northern")), TestData("East Ham", listOf("District", "Hammersmith & City")), TestData("East Putney", listOf("District")), TestData("Eastcote", listOf("Metropolitan", "Piccadilly")), TestData("Edgware", listOf("Northern")), TestData("Edgware Road", listOf("Bakerloo", "Circle", "District", "Hammersmith & City")), TestData("Elephant & Castle", listOf("Bakerloo", "Northern")), TestData("Elm Park", listOf("District")), TestData("Embankment", listOf("Bakerloo", "Circle", "District", "Northern")), TestData("Epping", listOf("Central")), TestData("Euston", listOf("Northern", "Victoria")), TestData("Euston Square", listOf("Circle", "Hammersmith & City", "Metropolitan")), TestData("Fairlop", listOf("Central")), TestData("Farringdon", listOf("Circle", "Hammersmith & City", "Metropolitan")), TestData("Finchley Central", listOf("Northern")), TestData("Finchley Road", listOf("Jubilee", "Metropolitan")), TestData("Finsbury Park", listOf("Piccadilly", "Victoria")), TestData("Fulham Broadway", listOf("District")), TestData("Gants Hill", listOf("Central")), TestData("Gloucester Road", listOf("Circle", "District", "Piccadilly")), TestData("Golders Green", listOf("Northern")), TestData("Goldhawk Road", listOf("Circle", "Hammersmith & City")), TestData("Goodge Street", listOf("Northern")), TestData("Grange Hill", listOf("Central")), TestData("Great Portland Street", listOf("Circle", "Hammersmith & City", "Metropolitan")), TestData("Greenford", listOf("Central")), TestData("Green Park", listOf("Jubilee", "Piccadilly", "Victoria")), TestData("Gunnersbury", listOf("District")), TestData("Hainault", listOf("Central")), TestData("Hammersmith", listOf("Circle", "District", "Hammersmith & City", "Piccadilly")), TestData("Hampstead", listOf("Northern")), TestData("Hanger Lane", listOf("Central")), TestData("Harlesden", listOf("Bakerloo")), TestData("Harrow & Wealdstone", listOf("Bakerloo")), TestData("Harrow-on-the-Hill", listOf("Metropolitan")), TestData("Hatton Cross", listOf("Piccadilly")), TestData("Heathrow Terminals 1, 2, 3", listOf("Piccadilly")), TestData("Heathrow Terminal 4", listOf("Piccadilly")), TestData("Heathrow Terminal 5", listOf("Piccadilly")), TestData("Hendon Central", listOf("Northern")), TestData("High Barnet", listOf("Northern")), TestData("Highbury & Islington", listOf("Victoria")), TestData("Highgate", listOf("Northern")), TestData("High Street Kensington", listOf("Circle", "District")), TestData("Hillingdon", listOf("Metropolitan", "Piccadilly")), TestData("Holborn", listOf("Central", "Piccadilly")), TestData("Holland Park", listOf("Central")), TestData("Holloway Road", listOf("Piccadilly")), TestData("Hornchurch", listOf("District")), TestData("Hounslow Central", listOf("Piccadilly")), TestData("Hounslow East", listOf("Piccadilly")), TestData("Hounslow West", listOf("Piccadilly")), TestData("Hyde Park Corner", listOf("Piccadilly")), TestData("Ickenham", listOf("Metropolitan", "Piccadilly")), TestData("Kennington", listOf("Northern")), TestData("Kensal Green", listOf("Bakerloo")), TestData("Kensington (Olympia)", listOf("District")), TestData("Kentish Town", listOf("Northern")), TestData("Kenton", listOf("Bakerloo")), TestData("Kew Gardens", listOf("District")), TestData("Kilburn", listOf("Jubilee")), TestData("Kilburn Park", listOf("Bakerloo")), TestData("Kingsbury", listOf("Jubilee")), TestData("King's Cross St. Pancras", listOf("Circle", "Hammersmith & City", "Metropolitan", "Northern", "Piccadilly", "Victoria")), TestData("Knightsbridge", listOf("Piccadilly")), TestData("Ladbroke Grove", listOf("Circle", "Hammersmith & City")), TestData("Lambeth North", listOf("Bakerloo")), TestData("Lancaster Gate", listOf("Central")), TestData("Latimer Road", listOf("Circle", "Hammersmith & City")), TestData("Leicester Square", listOf("Northern", "Piccadilly")), TestData("Leyton", listOf("Central")), TestData("Leytonstone", listOf("Central")), TestData("Liverpool Street", listOf("Central", "Circle", "Hammersmith & City", "Metropolitan")), TestData("London Bridge", listOf("Jubilee", "Northern")), TestData("Loughton", listOf("Central")), TestData("Maida Vale", listOf("Bakerloo")), TestData("Manor House", listOf("Piccadilly")), TestData("Mansion House", listOf("Circle", "District")), TestData("Marble Arch", listOf("Central")), TestData("Marylebone", listOf("Bakerloo")), TestData("Mile End", listOf("Central", "District", "Hammersmith & City")), TestData("Mill Hill East", listOf("Northern")), TestData("Monument", listOf("Circle", "District")), TestData("Moorgate", listOf("Circle", "Hammersmith & City", "Metropolitan", "Northern")), TestData("Moor Park", listOf("Metropolitan")), TestData("Morden", listOf("Northern")), TestData("Mornington Crescent", listOf("Northern")), TestData("Neasden", listOf("Jubilee")), TestData("Newbury Park", listOf("Central")), TestData("North Acton", listOf("Central")), TestData("North Ealing", listOf("Piccadilly")), TestData("North Greenwich", listOf("Jubilee")), TestData("North Harrow", listOf("Metropolitan")), TestData("North Wembley", listOf("Bakerloo")), TestData("Northfields", listOf("Piccadilly")), TestData("Northolt", listOf("Central")), TestData("Northwick Park", listOf("Metropolitan")), TestData("Northwood", listOf("Metropolitan")), TestData("Northwood Hills", listOf("Metropolitan")), TestData("Notting Hill Gate", listOf("Central", "Circle", "District")), TestData("Oakwood", listOf("Piccadilly")), TestData("Old Street", listOf("Northern")), TestData("Osterley", listOf("Piccadilly")), TestData("Oval", listOf("Northern")), TestData("Oxford Circus", listOf("Bakerloo", "Central", "Victoria")), TestData("Paddington", listOf("Bakerloo", "Circle", "District", "Hammersmith & City")), TestData("Park Royal", listOf("Piccadilly")), TestData("Parsons Green", listOf("District")), TestData("Perivale", listOf("Central")), TestData("Piccadilly Circus", listOf("Bakerloo", "Piccadilly")), TestData("Pimlico", listOf("Victoria")), TestData("Pinner", listOf("Metropolitan")), TestData("Plaistow", listOf("District", "Hammersmith & City")), TestData("Preston Road", listOf("Metropolitan")), TestData("Putney Bridge", listOf("District")), TestData("Queen's Park", listOf("Bakerloo")), TestData("Queensbury", listOf("Jubilee")), TestData("Queensway", listOf("Central")), TestData("Ravenscourt Park", listOf("District")), TestData("Rayners Lane", listOf("Metropolitan", "Piccadilly")), TestData("Redbridge", listOf("Central")), TestData("Regent's Park", listOf("Bakerloo")), TestData("Richmond", listOf("District")), TestData("Rickmansworth", listOf("Metropolitan")), TestData("Roding Valley", listOf("Central")), TestData("Royal Oak", listOf("Circle", "Hammersmith & City")), TestData("Ruislip", listOf("Metropolitan", "Piccadilly")), TestData("Ruislip Gardens", listOf("Central")), TestData("Ruislip Manor", listOf("Metropolitan", "Piccadilly")), TestData("Russell Square", listOf("Piccadilly")), TestData("St. James's Park", listOf("Circle", "District")), TestData("St. John's Wood", listOf("Jubilee")), TestData("St. Paul's", listOf("Central")), TestData("Seven Sisters", listOf("Victoria")), TestData("Shepherd's Bush", listOf("Central")), TestData("Shepherd's Bush Market", listOf("Circle", "Hammersmith & City")), TestData("Sloane Square", listOf("Circle", "District")), TestData("Snaresbrook", listOf("Central")), TestData("South Ealing", listOf("Piccadilly")), TestData("South Harrow", listOf("Piccadilly")), TestData("South Kensington", listOf("Circle", "District", "Piccadilly")), TestData("South Kenton", listOf("Bakerloo")), TestData("South Ruislip", listOf("Central")), TestData("South Wimbledon", listOf("Northern")), TestData("South Woodford", listOf("Central")), TestData("Southfields", listOf("District")), TestData("Southgate", listOf("Piccadilly")), TestData("Southwark", listOf("Jubilee")), TestData("Stamford Brook", listOf("District")), TestData("Stanmore", listOf("Jubilee")), TestData("Stepney Green", listOf("District", "Hammersmith & City")), TestData("Stockwell", listOf("Northern", "Victoria")), TestData("Stonebridge Park", listOf("Bakerloo")), TestData("Stratford", listOf("Central", "Jubilee")), TestData("Sudbury Hill", listOf("Piccadilly")), TestData("Sudbury Town", listOf("Piccadilly")), TestData("Swiss Cottage", listOf("Jubilee")), TestData("Temple", listOf("Circle", "District")), TestData("Theydon Bois", listOf("Central")), TestData("Tooting Bec", listOf("Northern")), TestData("Tooting Broadway", listOf("Northern")), TestData("Tottenham Court Road", listOf("Central", "Northern")), TestData("Tottenham Hale", listOf("Victoria")), TestData("Totteridge & Whetstone", listOf("Northern")), TestData("Tower Hill", listOf("Circle", "District")), TestData("Tufnell Park", listOf("Northern")), TestData("Turnham Green", listOf("District", "Piccadilly")), TestData("Turnpike Lane", listOf("Piccadilly")), TestData("Upminster", listOf("District")), TestData("Upminster Bridge", listOf("District")), TestData("Upney", listOf("District")), TestData("Upton Park", listOf("District", "Hammersmith & City")), TestData("Uxbridge", listOf("Metropolitan", "Piccadilly")), TestData("Vauxhall", listOf("Victoria")), TestData("Victoria", listOf("Circle", "District", "Victoria")), TestData("Walthamstow Central", listOf("Victoria")), TestData("Wanstead", listOf("Central")), TestData("Warren Street", listOf("Northern", "Victoria")), TestData("Warwick Avenue", listOf("Bakerloo")), TestData("Waterloo", listOf("Bakerloo", "Jubilee", "Northern", "Waterloo & City")), TestData("Watford", listOf("Metropolitan")), TestData("Wembley Central", listOf("Bakerloo")), TestData("Wembley Park", listOf("Jubilee", "Metropolitan")), TestData("West Acton", listOf("Central")), TestData("West Brompton", listOf("District")), TestData("West Finchley", listOf("Northern")), TestData("West Ham", listOf("District", "Hammersmith & City", "Jubilee")), TestData("West Hampstead", listOf("Jubilee")), TestData("West Harrow", listOf("Metropolitan")), TestData("West Kensington", listOf("District")), TestData("West Ruislip", listOf("Central")), TestData("Westbourne Park", listOf("Circle", "Hammersmith & City")), TestData("Westminster", listOf("Circle", "District", "Jubilee")), TestData("White City", listOf("Central")), TestData("Whitechapel", listOf("District", "Hammersmith & City")), TestData("Willesden Green", listOf("Jubilee")), TestData("Willesden Junction", listOf("Bakerloo")), TestData("Wimbledon", listOf("District")), TestData("Wimbledon Park", listOf("District")), TestData("Wood Green", listOf("Piccadilly")), TestData("Wood Lane", listOf("Circle", "Hammersmith & City")), TestData("Woodford", listOf("Central")), TestData("Woodside Park", listOf("Northern")) ) var good = 0 var bad = 0 for (item in items) { var out = v(item.name); if (item.lines == out) { good++ } else { bad++ } } println("Results: G $good B $bad") } ``` ## Edits Removed unneeded pipe separators -270 bytes Compressed with zip tools -306 bytes [Answer] # [Python 2](https://docs.python.org/2/), ~~2309~~ ~~2301~~ 2218 bytes ``` lambda I,p="Woods|Woodf|Wood L|Wo|Wimbledon |Wim|Willesden J|Wi|Whitec|Wh|Westm|Westb|West R|West K|West Har|West Hamp|West H|West F|West B|Wes|Wembley P|We|Watf|Wat|Warw|War|Wan|W|Vi|V|Ux|Upt|Upn|Upminster |U|Turnp|Tur|Tu|Tow|Totter|Tottenham H|Tot|Tooting Br|To|Th|T|Sw|Sudbury T|Su|Str|Ston|Sto|Ste|Stan|Sta|St. P|St. Jo|St|Southw|Southg|Southf|South Wo|South W|South R|South Kent|South K|South H|So|Sn|Sl|Shepherd's Bush |Sh|S|Rus|Ruislip M|Ruislip |Ru|Roy|Ro|Rick|Ri|Reg|Re|Ray|R|Queensw|Queens|Q|Pu|Pr|Pl|Pin|Pim|Pi|Pe|Pars|Par|P|Ox|Ov|Os|Ol|O|Not|Northwood |Northwo|Northw|Northo|Northf|North W|North H|North G|North E|No|New|N|Morn|Mor|Moorg|Moo|Mo|Mill|Mi|Mary|Mar|Mans|Man|M|Lou|Lo|Li|Leytons|Ley|Le|Lat|Lan|Lam|L|Kn|Kings|Kin|Kilburn |Ki|Kew|Kento|Kent|Kensi|Kens|K|I|Hy|Hounslow W|Hounslow E|Hou|Hor|Hollo|Holl|Ho|Hil|Highg|Highb|High S|Hi|Hen|Heathrow Terminals|Heathrow Terminal 5|He|Hat|Harrow-|Harr|Har|Han|Hamp|Ham|H|Gu|Greenf|Gree|Gre|Gr|Goo|Goldh|Go|Gl|G|Fu|Fins|Finchley R|Fi|Far|F|Euston |Eu|Ep|Em|Elm|El|Edgware |Ed|Eastc|East P|East H|East F|Eas|Ear|Ealing C|E|Do|De|Dagenham H|D|Cr|Cov|Coll|Col|Co|Clapham S|Clapham N|Cl|Cho|Chis|Chi|Che|Char|Chan|Chalk|Ch|Cano|Canno|Cann|Canar|Can|Cam|C|Bur|Bu|Bro|Bri|Br|Bow|Bou|Bos|Bor|Bo|Blackh|Bl|Bet|Ber|Bel|Be|Bay|Baro|Barkings|Bark|Bar|Ban|Bal|B|Ars|Arn|Ar|An|Am|Alp|Aldgate |Al|".split('|'):[j for i,j in enumerate('District|Piccadilly|Northern|Central|Circle|Metropolitan|Hammersmith & City|Jubilee|Bakerloo|Victoria|Waterloo & City'.split('|'))if[int(x,35)for x in'4 8 2A 2 1 1 7B 3N 1U 8 45 2A 8 1 W 3N 5I 4 1 8 4K 7B W 15C 7B EQ 8 EM F4 EM Y 1U 1 1 1 2 3 4 H 4 EM C 4 4 8 H 3N 2 2 3V 7B EQ 1U 3N 1 8 3N H 3N 2 1 8 4 8 7B J 2 2 8 H 2A 8 EM 2 Y 8 Y 2A 8 W 1 7B 8 Y 1 8 3N 7B 1 W 1U W EM 7D 8 1 2 9M M6 4 2 4 2 P W W W 8 2 7B W 3N 2 8 8 3N 4 4 3B W H 4 23 7B 8 H 2 7B 8 3R 3F 8 8 6 2A 8 7B 2A 2 3N I0 7B 3N 1 7B 4 1 7B 4 Y 2 2 2 2 1 2 8 A Y 4 EM H 4 4 2 2 2 2 W 7B 7B 8 4 2D 8 1 8 IC 37 8 4 2A 4 J 8 1 EO 4K 4 37 8 37 EQ 8 7W 1 7F 9M 4 Y 1 1U 4 8 3 3 9 3N 8 1 1 W 2 4 4 2 4 4 4 W 1 8 W 7F 8 4 W 3N H 3N 3N 3N 4 2 4 8 1U EM 4 1U 2 2 4 3V EM H 8 3N 4 1 H 3 8 1U 37 TL 4 E6 2 2 4 4 W 2 1U 1D 3'.split()][p.index([x for x in p if I.find(x)==0][0])]&2**i] ``` [Try it online!](https://tio.run/##ZVVhb@I4EP0r1n5Yymqv2gLdsif1AwmBtEDLQtto1euHFAzx1sSRkywgzX/vvbFDddKJfe9NxmN7PB53i2OVmbzzvrn@512nu9d1Km6@FtefEmPWJTFvHIsphBK1e9VybXLBJqC1LNcyF7ewKclUJVcQSmRZ7Ry/OhYLLxMvcWpPxq5oLC8jLwELwLsdxRwWJWm1YQLsngnIKaEnRU/0eKDHogJyYKfyspJW0CM91DYvmAF6MHugwpCXPEt32Bc2YCqVb0XAQ/SQ0QMt97Ss16@1PQp81LSsLGByJkACKX@kwDlSZL7lEVqausr2XrZeNl4EStgYjS4anci8OpmNxlBaYgtNy0wWmbTrVimCuswEHLSkRV0CqtSqELMPCwYtzBGghVq9gWghtwAtUnjpZy1lXu4bpZ80r2luaa5prnJgB9Bc0jy1JRPN6f5A93/ovqR7Tfd0h3rdGYsjcluczEa9NF8bLzis17jRcaMRlO4kJtHM2JwJMHbLDNAM/QWiWWqPTABSBtGMpqYGaKpoKo@4l5IVoCl6ZIqQabqjKU1ymuBmS2ZA40LRvBNFE@zLVTeOmUrlmCZ0Q/GRYlPnpTZ7pP9hRmwCFtDaOAZRrCBqi@tmfnUslhCKZQ6kVWYx/UFaNGeqy/@7xCV8FCN3PA4M/OWUCcAS/FBAFNO4prHF3W2cMAE0RsXGRq8zMI01jWlU0wgvgWmV8TNawKQRFhxRVJcVP@KopqigaEeRZlC03u5TKzGwpigtq5VjdLeT2MuIBbCA5lcTUkRDQ0NJw3R7elZDCi2F5g@AGoEACnVa8PDyw7qDRSE6JsxUyQRIAKuDcib9BqYwzQ1Tw0wcwyEoS0gBHnlQU2ANoAAK8N4DXFdgSoC/KdDp6i2DUCArAE7JNgV4G0HKc1P75vqFDSYgBxBFA7yIAfp0YGkA3tFAF8B6m1Yo2UDTp/Oy0Ko6a1Gr/ffzb7ExVqivv4XKhczrnbQIPGsNVVlZtarw0FardI0eP/oHIbF2iGa02C1UdqUlzWRlTWGwqG8CrFHuFN7OZxGq6ki39avSkvN/k1ajB56wsLEq5T@VztNEtv6TWlttnlVenR2@di/bnOMBGbZ6oi86A9ERF/hdBaJ7Jy4e4etdsrsPZ8K@yxvRgw3/hKMScXEZshH9hC@aiVGP@RfPvXC/juhiRiycP4TwRjEv1eGxp2Yy4nlHjEGaYbcNgIhbF80TXTJYqoNN@oD7TnzO/N0sgS/OGMsmHH01dEfoiB8zMfuOVTsOc4zyD0f3p3H79v0SnGqXnZx8p@s3iH0kAhaiO3Kh330O8Lr6YebNt1MFWXsn@eUO0XEn410G8LiyxG6v02DC0W4P@HzefXETiu6Vdw1At84d3fM19PwIyF3ClSvGiE/ac/VADbiKXfx@cFJ9dy@JK0Gv4Z4rIRfyauR2ST7uwf/zgX1eLOKFoR3nwg26EzQlu@BJPg4JPUz5gN@b0J7blDtjKLqnjmy/PBfnKl/Lw9nzQZzaURRCbcTN@QYjZ4f29fW3l@dvL@2Xz50vX9TLe2HRwGJz1hqs@A8Z/mvPW@33fwE "Python 2 – Try It Online") -6 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder). Too long...maybe it's golfable. [Answer] # PHP, ~~1785~~ ~~1780~~ 1471 bytes ``` eval(gzinflate(base64_decode('TZXLimRFEIZfZSiKoQsCyfuFpjfqQgTFlS7GQfJqF/Z0DdU1MCK+u1+0DrgpzjmZEfnfImt/eh638+X5Tbs79tNfx/Fw2Cv6IstEl2T07IOMWYp4G5OYELJsl7J0W4u0wI9zw7jAYo09Swze5iYtLheSpLWoryZZsbnS1njvvLia+Gkzy1w+irHGSuyBldFmlemCjWIX7agv0ucosounVa6GjyNXKdHw7tKyklrJUkcrUjL4bKY6lByljR0lbkPjBEQQ1iTFrixtVSu5LLqV1pPksa2MkL00t+C9GhSDnrViFpNDEZs2dRHQwTjwNPTZmdZzdsrKsBCFTR7RevGpKd1c9Ld51jqNspmAjsN4CdOkInkCPVkPxAClyIltDuACzXm4NNpuYyCc2lZJS8kw3kOfw1YqU8UvCFXBE4CCBeLCdCqdiuy3d3RXJrsiNU5otUnBSkstUjjZLT7ywTjFUiRYl/E/ssVkIx5AYmpOdO7grlbBryKRZUnTZnHZVWJSkbQW2oEXhnVvtvaxVAIqyZUnJbrScpGUsc1XBDV787F4KA1rDCvIWDONTetG9ogg1GCUZo3kMKJ0oynL4McRdajBc+xkpG9VKQXes8+cs6ZDFLCIWcYq/dmbChK7lR45b3hwBlMV+aI6Z2fE1mVxBtsg2dRtn5KeKXGhRdyvmkKZ6ESZjWY+oNl4PXOTQbcm8aqKyXjFiDnBNGoduWuLFDnCSOe9kXMuZPdwkvgaNeS10Bv934RsBs6USkAafKxJpgA8VKmFbnbquAITc+OkY8O0bFDKVvKe1va0sCpzhuFmmmSM4iUnQo+WlpSQLFzUTbknLVIXXdr6PoCZG6xWatSHzhym101ZlR86aWtbkBUYkE4I26RBJO1Yagop2ASmbuATH9oNwjZc1cHxDFOcaJZ01oPTOV9hY75vGJ97JEkdJC4w2Na83hiGCUmFu8I1hnbkQWKKStJiUik12ZOLDP2nDmOf1A+U6CpHUuV76pxni6ZyWEgxws5XDT2jUYomJIKlhaGCDRP1iisYy81juCsLEzg3zq7JAG6XQVPwgtsnLnIayErv2IZ16OY0l6GCDFKGzDDBANiGvXkXhHJdlWmeqSCVrZA5SR6lfQn5cH+cD+8OX7c/1vXpcjnI4Zv1fLu2J306X8fT4uHb88vteh43Hr9rHz6s68uH8+3xzds335xvf/Lx+0/9/LR05w/rdr18vDydb+2Z1x8v19vjuurjT+fBhXx+etKCn2l2uZ4bj7+02+vJX7q9vz+uh5dPnRPvPsyofyWCv/50f953LD0cuCMPb98e+zvznrfvDqfrun26Ph/nu/L+fl+uq43Hu/X549NlrjtOkOM4tZfjPtHgv8bHLVxDp4eH4zp9qeD7by8fQf6/Tf6klb+f1ni80P9xfZ5r3PHh/VeHX58P93//Aw=='))); ``` ## Beautified ``` eval(' // base64_decode(gzinflate()) long string into the further beautified: function a($b){ $c="fe538,e0526,cb734,cd88,3156,0447,f267,b198,a498,22c02456,95b7,54317A,a5e246,6ee34,9061,17938,03323,2963,2ad7,de35,0101,5b423,cad9,d2415,1eb7,ee38,bdc8,f8334,7907,ec79,85034,26e1,6a87,9ca8,8747,1715,4875,acf5,5f023,6245,9596,81e7,ae91,78e07,8ab6,7cf1,c473,a2e6,cea7,b407,ee57,0748,16f7,a5d7,4028,fa26,f723,ddb3,a8c1,9035,7c513,36a38,07838,0a31,9b57,70d34,5c03,4d068,7d87,6130234,85507,adc3,68e0237,1ac1,f0079,6af246,8871,6fc246,4fe7,ad456,8e389,f743,a431,24d238,bad7,3f324,8e57,f901,793246,0641,a6a589,dd23,3541,0202348,4127,cb51,a070,38e0,0976,24b8,7918,7de8,5a07,6d17,2729,3197,89823,af268,9ff18,bce1,9bb8,0523,5468,9a78,67a8,3928,0ff68,83e7,c100,6713,9717,0ab0,fc53,3415,8a10,74c5,b0e246789,0288,16a24,cf60,bf71,66424,73778,ed21,2ff1,0e01246,dba57,f5b1,b500,c318,40923,ae71,7720,19e134,0d37,6a723,3662467,5e76,5f57,f997,4735,dab1,3451,c778,ef75,2ed6,7960,b038,1631,40a6,52b6,ae26,2e9123,ffe8,de27,3678,55d7,45a019,0cb0234,8f98,0893,6a21,10608,c349,98b6,1d734,a726,05d3,fae0,70c5,1991,6ef3,8f168,8771,f790,cc83,76e6,e241,8ec24,31168,7b61,6e268,26f8,7bc23,7a75,e6a1,f4b9,8661,6e724,cc023,ef11,1878,fe78,116238,d060,6081,9f07,9f21,de83,7c48,c295,7c33,d5d5,26334,42c79,e4f0,f3a15,7b58,bbf8,24f5,10423,c0c1,68b7,2aa7,c7c17,8349,a567,36d23,dcb7,b0d38,0bd8,2cf3,bef3,6123,b6b34,18468,c1b9,c51239,38e9,d881,b5579,a4c0,ccc057A,a8d6,a870,e0856,df31,ed43,f277,287345,55e5,b476,bb93,8931,f2424,49d235,70b1,45634,f0e5,7f80,62b3,7ca3,0f18,a8624,6361,3847"; $d=["Bakerloo","Central","Circle","District","Hammersmith & City","Jubilee","Metropolitan","Northern","Piccadilly","Victoria","Waterloo & City"]; $e=substr(md5($b), 21, 3); if($e=="ddb" && $b[0] == "H") // hard-coded Heathrow Terminals 1, 2, 3 here return $d[8]; foreach(explode(",", $c) as $f) if(substr($f, 0, 3) == $e) foreach(str_split(substr($f, 3)) as $g) echo $d[hexdec($g)]."\n"; } '); ``` ## Explanation To distinguish the station name with as few as many characters, I fiddled a little and found out that if I took the 22nd, 23rd and 24th character of the MD5 hash, it would be unique except for ONE collision: `ddb` could stand for `Heathrow Terminals 1, 2, 3` as well as for `Dagenham Heathway`. To refer to the 11 tube line names, I just use a hexidecimal digit from 0 through A. Then I created a comma separated list of the MD5 hash substrings, with the corresponding tube line digits next to it. But I did leave out `Heathrow Terminals 1, 2, 3` from the list to avoid the collision. Example: `fe538` means that whatever station who's md5'd name has the characters `fe5` on the 22nd, 23rd and 24th place, runs the tube lines referred to by `3` and `8`. Meaning `Acton Town` runs tube lines `District` and `Piccadilly`. Then I wrote a simple function that checks the input. MD5 hashes it. Takes the 22nd, 23rd and 24th character. Matches it against the list that I created. And shows the corresponding tube names. With the expection of `ddb` off course, which is hardcoded to `Piccadilly`, when the given string starts with an `H`. ## Edits * Replaced `array()` with `[]` for -5 chars * Used gzdeflated and base64\_encoded my code, so I can now use `eval(gzinflate(base64_decode()))` for -309 chars [Answer] # [Cinnamon Gum](https://github.com/quartata/cinnamon-gum), 2100 bytes Hexdump: ``` 0000000: 6c95 594d 77db 3a0e fd2b 5ab9 33e7 3873 l.YMw.:..+Z.3.8s 0000010: ce7c ccaa ab3a 6d93 d797 be66 92bc 7a0d .|...:m....f..z. 0000020: 4b88 c563 8af4 8054 1ccd af1f 1066 484a K..c...T.....fHJ 0000030: 4aec 7417 5f80 e025 085c 92ca a7da 5b53 J.t._..%.\....[S 0000040: 3dd8 8359 7c56 ce93 aafd f256 d535 344a =..Y|V.....V.54J 0000050: ebe1 e327 dd6c c1e3 e252 51ad 71f9 1d3d ...'.l...RQ.q..= 0000060: d9bd d5ca 8379 b155 5fc0 f93c f81a ba0e .....y.U_..<.... 0000070: c975 cab7 1598 a6ba 543e 84d9 23f1 448b .u......T>..#.D. 0000080: 3274 706b a15b 8c83 9a2d eac5 1f96 7c8b 2tpk.[...-....|. 0000090: c43f a96e 0f30 9480 b1ae ba22 fb84 a360 .?.n.0....."...` 00000a0: e4d0 802e a115 ec90 aa7b 4f88 7e21 3fb4 .........{O.~!?. 00000b0: b5cb b890 d758 2ebf f51b a571 b2ca 1568 .....X.....q...h 00000c0: 2699 09ac c0ec 1697 683c 815e bea0 cb35 &.......h<.^...5 00000d0: 7889 9f82 b11f 6d54 0d66 7162 c6e9 4cb4 x.....mT.fqb..L. 00000e0: 5366 7b26 95d1 cba9 065f 6804 cc1a 575d Sf{&....._h...W] 00000f0: da9e 8a9d 18e5 6270 8740 f185 cd8b d3c7 ......bp.@...... 0000100: 15d6 d684 1c2d 0a48 3bf5 3fac 6e79 a662 .....-.H;.?.ny.b 0000110: dd48 9d35 8dc3 6111 f3c4 906f 0d68 de0d .H.5..a....o.h.. 0000120: 4493 c968 a877 8fa4 80dc 6c36 b1b5 961c D..h.w....l6.... 0000130: 5677 169a c54f 062d bb7e 5c71 e8b8 5729 Vw...O.-.~\q..W) 0000140: b969 1a4b b6df b605 15eb 42d1 7e07 6369 .i.K......B.~.ci 0000150: b4e3 b667 8291 ce08 3fc8 74e7 324b 3c71 ...g....?.t.2K<q 0000160: 7549 d6b9 622e 52cf 3c59 c194 6ca7 71b8 uI..b.R.<Y..l.q. 0000170: d80c 171c f75c c89e 97db 93f3 d535 33c9 .....\.......53. 0000180: 29ea 8967 fa01 457a 2f41 6363 8d02 2354 )..g..Ez/Acc..#T 0000190: 0bfa 6cea 1a8c 3d5a f81b 68a0 92ba 4b1b ..l...=Z..h...K. 00001a0: 1240 1aaa 750b f458 8286 0b46 c68f 406b [[email protected]](/cdn-cgi/l/email-protection)..@k 00001b0: 52c6 27db c456 6b9c 1440 1ed1 827e b44c R.'..Vk..@...~.L 00001c0: 7b51 dd80 57bc d651 e38a 7d57 7d05 4abd {Q..W..Q..}W}.J. 00001d0: 2298 a991 061e 6172 b532 4a81 9064 3a77 ".....ar.2J..d:w 00001e0: 6631 0a67 bac0 a0da 1eb0 c821 03ee a0ea f1.g.......!.... 00001f0: dd91 65a6 de5a d238 1cac 6d26 0134 ec39 ..e..Z.8..m&.4.9 0000200: 2a37 49d7 d994 c88c 0b30 87ef 6d3f 822d *7I......0..m?.- 0000210: d7b6 751e c98d b688 2731 0d68 2c3d b556 ..u.....'1.h,=.V 0000220: ec56 ad99 4a09 3f85 2abb 026a c645 cad9 .V..J.?.*..j.E.. 0000230: 7866 e263 d29f 618b 8669 8c35 36c3 d708 xf.c..a..i.56... 0000240: 5ef4 319b 70d3 14cd f839 b070 527d 6927 ^.1.p....9.pR}i' 0000250: bf80 0ee9 e742 8626 8c8d be79 fba3 43cc .....B.&...y..C. 0000260: d42b 7ac2 1ea4 3f9c 129c c0b7 92b3 2551 .+z...?.......%Q 0000270: 11e8 ab32 75ab b110 7481 b979 ce74 92b8 ...2u...t..y.t.. 0000280: ddf6 de60 5eac 80b5 f538 4ada 8846 b33d ...`^....8J..F.= 0000290: 0015 bb12 01e9 b1d9 a170 8681 46ae 0869 .........p..F..i 00002a0: 804b 9e57 e3bc 74d9 a79b d4e3 976e 0366 .K.W..t......n.f 00002b0: d7a1 f16f 4f97 87ef f79c f89c b1de f9a2 ...oO........... 00002c0: 5497 4983 c4c0 ddfb df1e 08df 7fc0 7c05 T.I...........|. 00002d0: c5f3 ef53 7c6e d6d0 888d 35bf 1023 6e60 ...S|n....5..#n` 00002e0: 1583 2476 d922 b98d c536 1bec 363d 0d92 ..$v."...6..6=.. 00002f0: a3a2 f8f3 cabe f6e1 b4cd b599 f278 05c6 .............x.. 0000300: bbb1 8a5e 69db d718 7a51 a6cc 2a36 2fc7 ...^i...zQ..*6/. 0000310: 2bab 1ba4 7834 24ca 02b7 70d8 c9f8 5339 +...x4$...p...S9 0000320: 604f db6c 31ea 6511 80c0 303c a645 085c `O.l1.e...0<.E.\ 0000330: aaec a221 1f6a ef4e b050 7cb4 d494 01d1 ...!.j.N.P|..... 0000340: 8cc4 78f9 5aea ae7a 6390 24bf 396d d7a0 ..x.Z..zc.$.9m.. 0000350: 0cf4 daa7 6005 81c5 7bca becc 22db f7ce ....`...{..."... 0000360: 2314 7276 1dd6 4f23 7d67 8c34 ba06 4daa #.rv..O#}g.4..M. 0000370: f800 913d 70e7 ac11 7413 8a17 a7c6 0b6b ...=p...t......k 0000380: 2e38 e685 e4b2 cc08 db3d 0f88 c745 4147 .8.......=...EAG 0000390: c42f 847d 40ea 9401 edaa bf2f ab7f 2cab ./.}@....../..,. 00003a0: 7f9e f4aa fe75 dafc efb1 d934 d6cc 8bfd .....u.....4.... 00003b0: 5a6d db6a 0564 d08f 4129 ef45 f59b 0b12 Zm.j.d..A).E.... 00003c0: 5a5e 1cc4 2a77 e991 7fac 8fea 7734 2e8e Z^..*w......w4.. 00003d0: 989e c621 23b1 4ddf d2b9 6bab 3796 92d6 ...!#.M...k.7... 00003e0: 4e4c 5287 523f d12e a03d 40ec d591 3771 [[email protected]](/cdn-cgi/l/email-protection) 00003f0: 17f7 54b7 450d d9de 3876 4f59 c8fe d916 ..T.E...8vOY.... 0000400: a4f8 55c3 1a27 86a1 4121 c3a7 0719 a4d2 ..U..'..A!...... 0000410: f65b bd93 73ed cd75 7296 4ccc 52ca 2263 .[..s..ur.L.R."c 0000420: 2e5d 4253 51e5 7c56 7ff9 a187 6eaf e0af .]BSQ.|V....n... 0000430: 7949 6cf5 cab5 e33b 95a0 7614 e310 0f6a yIl....;..v....j 0000440: 570c 559a f738 dfa4 e26f 5952 3194 e796 W.U..8...oYR1... 0000450: 56cc 7e8c 7c70 c72a e64d ff1b 0f30 3581 V.~.|p.*.M...05. 0000460: 7bb7 32a4 63e2 d5ee ffdd 7031 79b7 21c5 {.2.c.....p1y.!. 0000470: 3a55 e6f4 069a 0dd9 1dc6 37d3 89d9 d8b5 :U........7..... 0000480: db20 0332 515a 0bc3 a606 91d9 2bf0 b9cd . .2QZ......+... 0000490: e32d f0bc 76de a08a 321d 0fac f942 82d3 .-..v...2....B.. 00004a0: 505c 16e2 4f11 8a8c a927 a4bd b57a fa50 P\..O....'...z.P 00004b0: 78b7 b6de 58e9 e695 2429 8969 daff 9bf0 x...X...$).i.... 00004c0: cc28 597c 07d5 40f5 1374 a156 f2ea a8b8 .(Y|[[email protected]](/cdn-cgi/l/email-protection).... 00004d0: bc5d 99e6 003b 654d 344c 5a98 adb4 d158 .]...;eM4LZ....X 00004e0: 85d7 6c11 9c06 8d1b 6bca e08a bdbe 98a4 ..l.....k....... 00004f0: fda7 b539 b86b 397c a4fd 7221 7fb7 a697 ...9.k9|..r!.... 0000500: 2bc7 8c87 b524 1af4 cb45 2743 8f45 5eda +....$...E'C.E^. 0000510: 1996 8b6c e146 d2a1 22d8 e86a 3405 af3f ...l.F.."..j4..? 0000520: 105c 83a9 77f8 f741 f472 a44d e25d dc1d .\..w..A.r.M.].. 0000530: 3376 bc97 1659 8fb8 b4fe 41d5 6d0e 2cf8 3v...Y....A.m.,. 0000540: f160 19f1 8d96 3576 bc1f 434e bcc0 8f0a .`....5v..CN.... 0000550: 75e3 66f1 adf6 6322 f9d9 310f 3d7b 7864 u.f...c"..1.={xd 0000560: 5876 ca4d 8dde f39a c434 6aaf e574 ebf8 Xv.M.....4j..t.. 0000570: b528 b10b 763f 7433 bb91 fc08 8d16 9656 .(..v?t3.......V 0000580: fa3d 812e 3c9e c3ed a20a f1fb e2f9 15e7 .=..<........... 0000590: cd8a 720b 4d13 b5f6 d72e ca22 ee77 7628 ..r.M......".wv( 00005a0: 4f0a 419d 35f1 0a96 e5f4 1649 31bd dce5 O.A.5......I1... 00005b0: 79c8 8c62 194d 755a d576 91d9 2a63 a64f y..b.MuZ.v..*c.O 00005c0: d25b 0d3c cdd9 47fa 2d21 7bc5 77f7 3880 .[.<..G.-!{.w.8. 00005d0: bc37 a25e 64ce ffe9 11cd 0737 917c 4147 .7.^d......7.|AG 00005e0: 9a1f a1e2 8df5 f10e 9e18 a9c3 bb69 fc50 .............i.P 00005f0: 60cb 6098 9a5c a5de 3cff eeb0 890a 9f02 `.`..\..<....... 0000600: e216 8d9f 91b9 e36e e8ac 698a f85c b41d .......n..i..\.. 0000610: 301b 11f7 d132 ef6c d8e8 a073 1a33 55d9 0....2.l...s.3U. 0000620: 41f9 4871 4adc ef7a e5b4 dabf c138 d9d3 A.HqJ..z.....8.. 0000630: 399a a247 5ce4 f4c4 68e7 50eb 9783 a3b0 9..G\...h.P..... 0000640: 8413 f41b 74e8 e2d2 6752 270e b6e5 7d92 ....t...gR'...}. 0000650: 1778 da93 e3d1 dbeb 0f99 cb3d f2a6 54f7 .x.........=..T. 0000660: 4a9e f5b9 a4ee 5bdc b748 0d47 58f5 2e0b J.....[..H.GX... 0000670: f704 e725 d0ee e40d 9fd9 6a0b 06e3 32e6 ...%......j...2. 0000680: 540d a36e 43d6 eef2 24b6 7f55 f118 cfca T..nC...$..U.... 0000690: 36c5 4fdc 2297 aff9 96bd 1dd1 b82f 131e 6.O."......../.. 00006a0: 6b15 f4b2 29af 5d62 90d4 0639 29fd 9390 k...).]b...9)... 00006b0: a605 0a28 e7ce 94c5 8173 576c 0d74 a24d ...(.....sWl.t.M 00006c0: 2b49 45b1 9560 3a4b 5838 e2de e030 d192 +IE..`:KX8...0.. 00006d0: 3752 ef6d bd93 2f47 f377 34db 0c1e 1b6a 7R.m../G.w4....j 00006e0: dc3f 6c21 f0e5 c296 69ee be09 3d2e 8a5d .?l!....i...=..] 00006f0: 2c27 e172 a52c f183 72e1 4b89 f7b0 cd2b ,'.r.,..r.K....+ 0000700: 78c0 6eaf e795 f0d0 e220 3714 ab72 793e x.n...... 7..ry> 0000710: 582b 67c4 0aeb 9cfe 08e6 9772 61f1 5e6e X+g........ra.^n 0000720: d1c7 cf33 226b 6915 af78 5d83 c65c f482 ...3"ki..x]..\.. 0000730: 4b46 c26b ad45 2f77 b032 fa01 4916 3f27 KF.k.E/w.2..I.?' 0000740: df3f 1ad4 7afc dd98 5192 6926 7b95 3324 .?..z...Q.i&{.3$ 0000750: 1e7b b5c3 a3f4 1586 3ff7 9d32 a129 d3b0 .{......?..2.).. 0000760: 0c65 514e 1683 43f9 9379 0b95 33f5 f1e7 .eQN..C..y..3... 0000770: b314 c0db 9afb 13fa e716 b4ce 397a f963 ............9z.c 0000780: d663 c963 0dda f3a2 9d2f 5e4d 8531 ac20 .c.c...../^M.1. 0000790: 6f0a 0344 68a6 4779 198d e4ca f189 65aa o..Dh.Gy......e. 00007a0: 2f6e 8b2f ff74 48c8 4b91 9efa bfc4 5aea /n./.tH.K.....Z. 00007b0: 7a72 d0c5 fb50 e29a a788 86d1 d787 c9d0 zr...P.......... 00007c0: d997 3e81 b830 3bde 83bc e502 cf3f 000a ..>..0;......?.. 00007d0: 7cfe 0360 ea3f 71cf 5f22 c6f0 fcc2 2786 |..`.?q._"....'. 00007e0: ac8b 533a 13b9 1370 637b 3251 104e 88ba ..S:...pc{2Q.N.. 00007f0: f8c6 6a9c 5642 66db 2a8f e29e a610 a86e ..j.VBf.*......n 0000800: 618f fa4c 69ae 953e 7e48 89cd 9382 26fc a..Li..>~H....&. 0000810: 5b6f 6aaf 4a15 4f4a 9d62 6768 72e3 08da [oj.J.OJ.bghr... 0000820: 3dff 6789 a0d2 8927 d73e d17d 019c 6a70 =.g....'.>.}..jp 0000830: d2fd ff07 .... ``` [Try it online!](https://tio.run/##fZpp21U10oW/@yuC2k5o2JkTW6TRtgUcEFRQWtHs7ERAJhFl9q/73pV9HuDqD@@5Lg/Tc@pUqlattSrbdv327Xrrzu33fvnj1t9/L/vrfRVbCSoUv6mUtlW5unQ1NruqUNeinOtJuZycUjf191880O9rffyKdjr//soMYAjRemqqtVpVXV1VcStObakktfYYVbFrU6kum1L6qdb6/Vu86aH1Y72HsITwa86qhehUrsOrvASvTGubqsMMZRbi@OyrUp9p3fj4N3oGOXNuD@EkRO18jzdJhZEX1Rcb1JJDI4FGZmmrKqyBg5zT9/VPWv9D/yAx/vv1HsITwm1bVtmFohK5cC4OUuvY1LD8cQsuKOcli5Naf//00szhkg7@kEUgRF@7Ud3ZpLYtUhXTneo2WBVMpcRmFGU2J7XQ@k19k/eLF/RvWp/cQ0RCbGXd@DKSzi4VtZpAg0Zb1CiuqZFNVat0Sc3vf6S/5TAfyG/3EEk6UlJQra5JmVCyqnHl8N51lf1WlHXDKO/zSog/ZhD9zYdav6b/fQiRpRY2eZWWuKpqwqpyy06VajfVawuKc0SKJCHs/bu/6v8S4z0J9PQQokgW3g1VS@xqGW5RxdOW1dRO@taqsWavqosLWZzSt/UyE3mV/37eQ1Qpp98W0GA7WZigeisLHUmr8gPApG6NcmP1h1rI68l5/dexU4csVkKsoa1qzXxwSyEr29ehRjCcKySjVgGHCTEfQnw332mIvraHaISwsRS1lEo/F0BmItiOmWZkEzhNr4tqK@BQbxySuPaBvsovYQ@xESLlXFQZ2VIBEB03AL5swDqZaFWLvSjf5CAPZ4Bb3@jx26r154eDdEIEJz@@WkYqbIZvrCQVA8Hy4pk/cBFSAFpfjyd7Ij9d4@3yj3uIIdCqBQzUsimTe1DRJqqbPNAyGcBs9HNzLR2Vc72r/7X/7pV91glhwsYoxCzzCRqW6rNy62AyBvWJHcTWyJH2EO/pM/@U7j7S6x5C@GLb@EzZKFjemlPRGKOGa16VJQ6pSlZbn3xxRgetqwS6o68dZTH5wjOarfCTNaek8qhCGhsJNBcp8RpUiaYp9W@aoR9IhJvxxUGEL0Lkg7Sywjuer42cZl1TV6GBi57XTDltUeqSfPw8R/nrB3Bx@e09hPDFWiLjXD34itvgbWEyQgedlgalvgATx48ofV1/thfyI/2Xbtf3EMIXq4cg1hg5gy00tS@UczSw7YV5LbGd5CPl/EUCnIK97Gcf/LaHEL5IwRc6AltHy6AE2wafgcSaKZ6C1ATIOI364ywt1Rf1B99TDTC@hxC@2PICrBMFGwnGbBmYFJGD4oY7EJ9r5dDUHw4oD@4QQvjClg5hFQ4y6gK9hFSVHd5IBWD1bbHwDqBXb8@DfPL4xOkGk7/2zR5C@GJZB@rRiGNqbrBxqEJ3KwBnwtCRik4YYa1JnCevSG81ld1DCF8YC5hNRYpSWFY1PBOfbY7E9hB6zEN54TQlwP5jH/f/aP2vX/cQwhfULyorh28e1qeulMZL2E5TswUhq/dA6yIEri/9queM/KU/30MIX6Q1GFAO3YWE@G0xiCZkktoCzdiAia@QvHpyAUBpzfuzy8/0ucNBhC@sFd4uQGKJpjMjCeYIzvLBbGRQPFINgNWrsxX1nrbntN7ef7CHEL6I0fHpSkfWinqgwBS2r3BVhjYX1yHVhWIz/Du0eB17MSOTLzYSiKEy8Z1mbNZlxl7mfIOGmCMPJbuJi671FZ1hrje01@WVXdjlINUl5cuGIBbg2DKdXVYnvNOFB5GIbBk99U46u@eAENw6pd/bQ0y@SCvEFyhDK5khjVC/TXI4oQrbkNM10CqlD3L2ptHX3j2pL@0hhC@66HklA@q3YGsGdGfruqrFRgggepHLTQ6Cqp9jyN7R@ob@5FAL6yaDQ7/dAubNFjI3kCV/VZBGGQ@Ih0SZXvVwiEWBta7rEI/KaYUvQsfbOFNWhHVzoAqDMzL1W1FtgJc2FQvWQV3VRt@VkxR99@Kz62/uISZfiLdZOnLRk7ckQB/QZiogzDvW6pR3rR0m9SP9xrQI@uNDFtNfeNxdqs2CBmjTDQG4LSJuGAbGzCkbglDO8ceTcPbXPy7sIYQvjOlZzJ6lLXUVSVsgLIC5FrLAD3qJs2uqlZ7clyzuH9UiT2gNQRXyH3AUkDeUPQL48hWc5sy4ru5glH4WMdX5nMzqbpTs5AsoFMo2FiR2MUo0sBqRtEgqPuI0lhzLS@bg7pz2nX6t8AXKCcl1prI7salij2qiQZvwckniXUR2FSxzeR5DXrf12EOsE50V@TIolx/4ggnrkYo4Nd5ICj@NcZpZ3DmvX7z2EMIXELjMCA6reSaV0pDAMJI@spLE@6UGaahv9NmXAhy8lhW@aAGi7hSQnyTpLYpvyuDChVUMtEVn@/RaWn/99Pakb9j39u61bJ/KTgLWJ9pS8GerzFrDdCizYnpgcdSef5EQr/85jRrojiePDiJ8UR0HHZlUMJ@cO2KGV0H5Ghi9YVNWS2jxpY7I6@EhhBO@WGkoFgVfFQscvCWDFlbgWCOwhk0g53GwKFev8/YY9nwnnjiEEL5AKFaSBtspw1DWY/HoVZKpY8vAheGlhLWOy5f713dg6K931nLCF3HBEmwrDt4xJFAgFgWNXJRbsH1V@GLuFurn8/qmEfLTywfwxQ97COGLKvsIRtdgluEYRh/hYEegQfi8zUOGUP2u7Mcgmy/1V09f4MIJX@TW5AzsDKGSRe1oanQ4WWwBGl/iJuibTX0I@@rHTb@uy62jEMIXS4NyNiwzRwJB2WDe0SRWiC7ltJR4pHZYJn4W/3ww4XsI4QvrDFlYcGHYaUA5WEqbOJZGdVlF@Du@QanX9L0/cUqvPfsFCdBfHEIIX0BaCLgBQWnB1tRGOVnVZNtjX6tAFk2Ysoys39XPB22XZTf9BQKqeoS3u19xzA2q3VbBpGwCLdERb7zgIh9gBTL1J6c/3UPs@4hFbDws60X3isendMl8HfwD29JATKpkcUI/OxjfE1q/eziI8EUaOKPh@czorFhbHY3Oglh2XuosEM3r2A4A39XIv2jq9BdV2rYCiSWg4tsingT@FYQIBUI@i3CaunILVGxan35bhOgoxOQLGQ8j4LDiAbrYhCT2Ow/OlZKAvmeaegXifOfBfpIH/iiE8EURi9ci6LSO9D2cg66Jh5ThYe@UxX3bJ/XYazSTZuj0PAvhC99xQcFmFm42SrUZ2dKILtXF9ASSckms65efX9QXRUZOSlHTbl2d8IVJg097RtMHDP9WIEuXk4BM/CvH4e/MzOKbWYT85/nvn9fCC19UL@McUF9Tkc4cYWPKiZXGH6klGQjdb5O1vpWVW58@9hL9euGLEVlwV7m1SK7DeeyJ4J0K@NbkhEyLFd1Xsub@TlvvsZdd1K@2PYSd6GTx8hb6xaaE/fogjSF6RH1ir0P1hTelf/zo6wt6vzu4/TyL6S8KNj62MRd3UO4cyhSY7hSZvw6zAXVQox6dFfer/6n1n/LrjT3E9BcJGx8CK81ITMsmWxGOZahQghXjwR@ls@qy1ELm5M73F83zLMLcijhy6pi01FDSlizUFT0@ZeC85x7vAuqqLmF5n97FJwk0lnAIMfcRtig2F747um4BAkZzjE1mH8@GuCZlhYbUE23nZQ70ax7BgXsI4QtXAxWIUNciC9qCD4V8YAmX8E258Ed2VUK8/@2RiKSXmjr9xWopmHNy84J1XVYQUiNcVcQm2HUsKFyTSVXaXriyBzn@PITwRXf40rGIL4ibYBsH76wRymHWRhH/ZTfBxXt7L@zuuQ4hhC8CcseSSRn8EAmRvaaKxWNpFFWE0EdFE9RXP8iOOS@F5Gbsqz3EOn0nBVslgZDF9sWCdfXwRZbtEwYaqshp5s2B7DOvv62vv6iF8EVrlhkpCefNBsJ8AjLjMGnVgNNhRVvytGtvff907jP39aUXIYQv1gbAS@kQNTSGIAIJJ2tQqLKobCJpGAgBuGCzf@E/nzX9bg8hfJEDS0AU6i@NPuRNNjuRoi6FXTcMQ8nVH613QjgvT6rwxdiYadYgzF5GLpwcCQIAWqKzaVCpKpczalrnXwuHufdipQlzH1mbKFeWONZDGoAMQaamyQMt4eCAKOzmQIs3@OTNj/UnVw8hhC9MYYaymINusKmbhXJQUuQJ9qEq6GwdbswsborhRE9vwL6n9hDCF0ZwkV0tsDX8NRBDZIUdr3oK2y3F3poRdIILCPy0vseg/Xh0EOEL5@DJtRW5xIAs86CBq4cxvaHH@L@OmhFbOYHmZM3T@taRmgXhC1wra20ZAHPjSC7MiAY9cmJW0FjCLtRiOgMdCPTxly/KGeblAz45RkJUMfTRyc2ezCd8hUVhdZPFiab@IVe@ulEKo08@ebjtIYQvghB@g6TJQsyykysZMlCxCm0GcNpXOch3f06yQVFv6OfLREjzjg@Ar4aNP0UKTycdRhIBGmITQBpjH@eG@BaTeuq@OyBr3xCD8MWoKFcWDXNNpFGUoFoOPwxuvFu5uA1doHXycN36MjrD9BebrPiWLPyGt1mDbDiJiE3uO3tHqlO0cyu6dzgJ0Hjw51t7COELL@X2pohvH7K905YegKiJXmoqN8MNgVHnaWbYQ5x9zuBh8kVpHBlpp7Nyqx9kcZfO7sRXo/Ag7lY9ktugL/64ItT1TtPn9xDCF5tFENlQWQmFeT3eQtlNJmwV@yii7XJepiBSik/1e8eegNJ8yGLnC9b@asXG@yb8D3UZA98uiX8ohsE92LWkr25HFP70YNeC8EWpILEauJMtCGdkQHTpRq5FmrQX9hstLP@zTFw/cGcY08Y3OGaBoUpl4GoQf9FgzC73ILlQ7DIWzMHPgvAfXjT2lf0yXkTAGuEqNv5isEfdsV31LFcgkBXGlrCrN9vzLG5LChJqDyF84RaYzhiqBiwAwoA5tiwbNMWAgQBrCHL5MK/A7WS/37X79hBi3nfKgwOfcVOsx2I5EY4ehHQrm0AzovZFpOi0PvPbOVGQuTEfZTH5ojBXlf1OhdY9bIN9jBlEh6XjNFiVWN@oiip0VK74rumvXqrF3EfEsg/PaZIn/Q4mVExYC4utR6PE@Rw2xN3C/3JR5OzZIUSYjo8dcKt4re5YfiB9cRUsh028/ACe@MEhuHj4vKUnxf3tIeJ80CMePKxi7LAWYaUga/KslpscLoMV9tlVHvTMBzxan9Gffvf8IHMfSYtYIYuDXwjRPeazDFoQKx9cIpzmbN/d7z/2JG7M1uwh8tzZ@UwVNHiHT@59WFnLxPYFASs4bQNxY2fXtz/epeTbF@UUvnCRaUK9ZA@Dxqv4xRIZcfYs9ubMUmJYP5WKWINXj6px4iiE8EVcDV8mC5EtkGXYGPtCHTgDImk5kyqyMCrR0rf1j6sI49vPsxC@qHJrvVR4qcsiWHyTNRFgwhkYhk1sgvU7wN@aGfx@@Sbd/WIPMZ@PrJCTD@wRBUbHvfmVPriJEKrLYg/yBRfHz2Lif37/s@/yfs@3hxC@cAIjJmPbjbhFDFECGNN5VtSlUQYjO5NKFxExfeLTuc8cud8ofLE1qD82aGosILGJg4@lywMaufLbrDz6kOcj@tTNYztVTGztz0ei8IVtWLMud60V2y9PRdgJbDfyfBK2SXJ5Ks9G1btvQuHvCo/Pe/3jr@xP3qZdQzV3w59wamPZFsqAF3UJG8@SaWFo18Wu3d4bqrCu9x59uIcwUxD5ipiYz6XKaLYhN0HAsSQ@HQ3CEDrAU98dP7q31feqvnp7DyF8sRlcThswC5sLwYoRT8LohU1umSKsNXzeJ9W9@iuVePjjC9ZK83nqvDGXT9dN7NGgGesCf@33@7KWuSGXlZ/9B6f2yYkHYn/P6lP7ZWUSvtjEBRk@rpIsymgJCQgQYrHyKKvIYwXr5wPASVkX9PU3nmj3@h5i8kXHQayy3lUnMhiyfC0EAdvRJdmbt8la8@Jiv660IP1wkDivQCKezuBoTMxyPSpjJk9Wlz2BqS1T2fuFL@WqVC5M3dGMpOkv5AqkLfJApOIGjEMQe6ICq4gbNhQlKHNDfOlVHut9Q0xzH4lxPrFyss3w43JTVjZGPHRxPoHVqDYrB2mHpejE1S/wSmoPIXwRxRwsuG55IMJ2mjiDkVu6LjdcgLXIXT0zckfrf1/Tnz7a8@iHgwhf2AFu8srXUkOPouAVvBil0ofcg4C5edWkTtyGaO6fOTy2unIIMf1FBYTbAkuMNQi2RVZSxnNEIfSEs24F0KvH9/jkV/9jlNL0FwW6c13ui7MslCsskeX@tQfEuAlq5PmvlPNDeOKfzzu7h5jPU@dQyNPjXsXxmUYlh5VHqexCg40HUQIr6qlca536Tf/06r5d7SGEL6o8vg7OVfqJmLAQMbgOuDkbDA4dwOS8ziy@fl@W1PbEXtBfHmUx9xF8FppRWIMi22CMIMTWPKQqLIyoP4tVnLdrN/Slj4Y8Vpgm4ZX9Mbs01fDjLOpiKCr0G@CG1FGzLNtpcQwpG3xTqmr9OXP64V9nJMIbexZ58sXKij/NsmehQ1E8tkaUIKaYhb@cXCRzkP/euaHP6fPn9PrLtXtHHcl2/p8PmKKYQFBdEPUsK@qWSGUzCc9mOGGs1Eed3B8VvUljnnGou3sIN02j/I8SY2GQ/v@XfP7vvy/fubP9fp3Gf1Xv/fp/ "Cinnamon Gum – Try It Online") I have no doubt this can be golfed *much* more, the problem is Cinnamon Gum's lack of complete docs. (@quartata pls this has great chance of being amazing troll lang) I might dig into the source code to see if there's anything that can be beneficial to this. [This](https://tio.run/##nVvPU9w6Er7zV6h8yEA9SG3e7l6ylUMgCbw8SFjgZQ6pHDS2wNqRJa9kM5n957MteQBb6rYNOaQS8klu9c@vW0q9bUqjf//1y7F3LMuyvex93hjNbsxGZyz@9ZZ9zz5I11iZN9lhdinznBdSqW32Axaq4o43Il21W3giba4ELLsQjTW1UbLhureQfeSuyca/eMarSlhXyaZkr9iJbHZfroUFqTPiy5GcfoeSVxQ6EU/fCYWeqsN/MbYphe2wNi83fJvNw2rj2Kk196nOEKmtE5orcuch@pivhWXXjRUCVWn4d2UMqPTRLIhuD7PP7UoqgVntmCtCielRj7leExrsXEPoxsLhDp9WHWZL8AkvY8/Qx9yuZM5JQ4@fJT2BXUt9R6p00u92GzhZ4BZ8OFYHNdqxE9PaKR@PLbl1G6@JbOLIjzv4RSI32hs/mzhZwCon/yfYJRwmm7KjsJXRhRNbPDc8eEuANiX4K/i3ELG9Yt0onq9vreTWZfOP6BeVBqKCXRleZPGib4AzsGfAgsxEMETu1z@Asaa9K2eF8rFxPmlecG1sNh2cpgUdoppB0Zv0hM/yUgvHYyfWOFy9g4NY@ZNIpKlWramU2B6ttkcgY/YCwVqwYGtdw87gsNmoi7QWzvCVr7NpY5xwJQqjJde4ZwzVe8KrQhD1Lt1Z84KzJRaOkft7qN2yZcnt7TRUQxZBRUCg4GeoK5ORAot86sHiO9m/5OoWMgcY6Zw3suofEyuNHr9mn7itsmmzlFznAnRyzrUYTwgAtV4jmM9G1Wv4BUHVdUJ6ebcRSmUTVamDuo3M15gW44R6AlkJ4mJjTJHNEkPxGsSG2lBVceglStxhw88yNgt7bdpprIEMDElMECk4ihkQXhcQZnOi0SglYVu2TPWRYu99qjrltkBrRiSFNT@V2M429wd@J7RXCMIzYxs@Ys8EbyJGl2DFKhUXd6MPXhkOSXdpKH7kyocAJFlexIxyWLP6suxWYa40TjM@cqsWL@EnXpks9AzZ1OkD9JPUeZmaLXaFgD2jSfpkcQkbXLaNRjwktqDH5gZvXRJPShRQ3G24FbN4wg6L1nOKlk@fVAmI85C0T@Agg6gcyZYfVYXXBExB1QoYfAWmxI08Iffgs3VNce7EX1pHcZGhZg8HvKRbxq7/26ZmeX6T8IlLOFmdzZAX6qAvWwUZCs/78C5Q2MMXRvzqEYs4Vj@voF9xqxaqMlHYer4@1PKn1rd/dH7qu88peCeR9WIdnirT5sIXIpy8Ye41jMdTowpfb6jGo683jy35Zk3pbcxiYbkp7gRNxwafslwDlkz9fR1YKDrsEhYrHjcuz/ejoIdbY4ts0oEDlEgKQzci3eK01RpE8i41mXbPuNS8Vc0M/tU76cwWkdDO0FcAUoOv8WIGkTnz9rMYe0WkBQLocFIwSJcd1kKH94otBVeFz1xP2@PYI6OPQKqjoSthjOeMNz4Toq1fyqcC1fGy3ECXD5ZRjr05ZL8fsr9nc9DsH9kz9mb/HEXrwsudJj7ELPKuZMfcaqK3j7Eh2b1ifzhPlHrlJe5uPZYaZ6IydGHK/hTa9Xcm2zJvvrFqMUo6zoxaGasnqxKyLuQUatjTd2KAGsjsVG6MN7ZQglqbl9kkmzgzrXawN1XZ4p13aIK2E@ilmIPeFt3gC4gveJAdl@SPfB2aghfRRPALPfQ42p@8DxGjsyQnPPkb2/@qtlUt@UFGKB6wjXQlOWmIZBglX0MZNrumzU0m/T@lghCkPbfXAu2gpLMORPBzWLTqINvqO9/q@KwIUfsa9te55UH0Z5bXwbyarIl/asgPjVtZCWxh0ifPebGyZi2wm4EZnOScVysBP6EmBH2lQS3LeeBap0mmi7LBbhxEdi5TUgm5Y3UpLY@ofKQNsR11w76IATqsoBRU3gtbG6MQ7jZMn8/jWucmFK5jytJPBKofaud@zjxyfdUT/ILLgrNv6Ogltm6YRjNIiG7O/RKgnQTZMTxZwy64XSnB3mNpP5HcbpVYYcZJJQclsY@6yCar22RzDFupQLqR8hGnvAujW7zHHVOBMXaMJ7wsm@w2php0jOxdGDs6hhrubXfFCNKgcHn/0DH2i@CO2jjKrF/EhuolY3cIXyDmRii0m2xNs9gOHUrnRkZuGYsboB2pzmZouMMvRbXC51d9Fw7YWymA0s8IvoA2szqhACVG0aTQ6Cx6Ah@ixmXT@KbxI8cQY1EZIVJpP3y@8jUhHKanr4q8x0v89qsvN8R8GNn5nquxG@rBzj99O838edqJ64mn0/cJwSUvijEu@KIxYKCxV2bLiSHL8LyAdv5WiJqS9G10Kay8x6f9sXc@fSRVT3SySB5ZKZmbWRePl1Jr9D6ccNFLxeE0aYzPniVfQo70uZIiP8kHw9iZpgF95f67BQMs3CySG7AEy41yWwfFn6JENrvi9wDN/eQ/kSKW9opv/XgHnYJMtkBXokA5MCaTuIO/4GqJtXIFad6/SpgzyAbsugKmsyHYcWzJK@MD1RMuPOX3RfahN3JFPcGQr1rplKzn3WYlmu0Wo01YLOYOir1VmPEd5wTkeWy2nuYY31t95pVwiB1JPhUWmdKHRHJjGPl417u1auEmx8rXAnycXUvshjNOL9elqCHVFyDBcevKMWVGUFCqXT/Uphk2v1YG4mjGTcVAQRrA0Ewas55iTuHmdzZz6tA0HcLQ8bTrOYP6xx2QOhjHeIfFYwQ99FJ6lhYP1@JKvsOCn6UDcmzbEUI3MJHHEk0BockNTfQHHs@rwD2OU/MnQkAAV8aSVXuwrah9wZokA6QjNyZfE08pRm7qrn2v3pUENEEMPAAM0cy4xhi84bpui9CQYLcuiCF2aGo8FqE30vkL86bho70@QG9EVeP0aSTOb0qxDcMEI91EM3VjTODgxyKfnIE/YpGLuxTbNN0ziPAuYMB/iGebg1VnCWmMc23Adg7wii1L0fTGN6k0G2HHbhFRLba32lesOa8bb1obxJ4RBkNX8AtruRbU06Yh@q@6ktrRLzr74j9iETKZYjXxGgbDej5L3/RNRvxfP0kqN00jvvH2Z8nph1d9D3n88@zYGeaYJVcNGNXz/@S@If7WkmvqNjAOuSWUSaFnXP3G0tjQu78HOtIisdHPeA/vn7OpCfwhNldE308vyRSK09/drAO9iUvE3WGpSKPfIPirmplPiALUPzytGzPVtgbszOdGAfvi50aDmvOwFXaxHNWFHRQjXIQ5XENQLvz0RFOBKHUFCV4jj8BnsFi/nMpoVIT2lVDKRnSbTVrfQ/OS10JlL8paS8hA4WIeyfGxbR6hn1udN7Kv7sT1UbJJ2OUBS8zvBlg/hkNvAbG6EtDo84R5ZkRZMG4HgPr/9EB15/3IyrLvb94evfnx2tXgx9CJCLd/sLdn2Tu2WOztwReZZFIz93bPL7fst3dMduD9xdvFwfe//XhtvUrq/YNuJ/YbW7xa@N8PF6//Y6TeF/dc7Q8WvflxcPDailrxXOwD@pAtuC4WB37Vv@CztZW6YfbXr/8D "Python 2 – Try It Online") is the Python script I hacked together to generate the compressed string. [Answer] # [Python 2](https://docs.python.org/2/), ~~1430~~ ~~1418~~ 1416 bytes ``` n=i=0 for e in(input()+' '*26)[:26]:n=n*256+ord(e) w=bin(n)[2:] for j in'Bakerloo,Central,Circle,District,Hammersmith & City,Jubilee,Metropolitan,Northern,Piccadilly,Victoria,Waterloo & City'.split(','): for z,o in eval('eJxNVclxAzEMa4gPHdRVi8f9txEApOQ8MhNrtSQAgtjP5/Op3fq0cWw3O8dqbV/7TLfVbO8v/v/UZq3ZWrbdTsEJ7k+PR3jZbU471WpZeHvguLZyn9ZtbVpb7w7fr25joUFcOtaOebOx8ZhXHMej23gt0B2/J8/7V4dqvKxvmzVQT6udFxzYju6gbbG1o5+jZbIpxpbVvJNyLQenq9gu+RYu9IIiqCsuLNO7+bbVdQVscAGNTqdUkGZEZSdXMEFl9cUP/0EZ1UYDC3YCTr9oSIJykzWg6XioUqcmGyK2GSzYFtBGitApLMXDxaK7w47H1day0CCSTgGTIeF7wtwsTH5v0n3YXHb4EmrmmHsOEe/RK5tXFnoR8xuSHtNHnUapnSwhM6Wrt9DxS6bfylIKXTkhzA4qr0vPOWMyOxzHTsEHFfMA3GbYBn+NxOfATB/LRZZS+x9FcYlZQK54VSqswCl5hYxjpIO4B3iO2T1Ne0Jp18WEWDVymksOGi3rEG4Tj5r8VM1jHHyEzQOMMHjnFqQCmO0I7y8ZUgY3wJ/xKv7FGKC2ELJnumoSXf1NLxasSsPKLeXGRDeQxjLOcplgJbTv0IOOkqq5znoFvicVRMG8groALmftMwPJ2ncMbecAL3GWS/+iGCUGnFY02hH+hxnW0AEclIsLEtzLTRLiu8o9X6TFvuv1nXeJNdtjcljIMeQMDVeKDo1KiMAB9qVE8oTa03rlrgdlJJlgAmqpDVXpAtdieUDALxKwSaLzmm1bfw7gD9yQrYbIRAjDSWlz7nPleiyZOTTqsfIz1jAn6T91YyEx2LkiElAPVrwpwGiukhQ9q1O+X8R1OiLC7TSltkyuQELiYto7gt4YxP0G+ZiRelnEiS4+CVOJO/6FOgNI2wvNl8SuP2CYEVdUejDhuRRK8nPJTSVVfXmH2oSfHi4ZiG9W+67jYIJxaUaOYd3ATTyRRuOXIjGaFnPxcHdOLhQFChoQctYSEdBfPvFrcnaiR535vqr6JlDnmt8gD5/9kt31WZ47I6w9rE1T3fk1Zcaul01dqSb/NIFLINVif7Q5ir/bauccZuwCv93f7x8/H97i'.decode('base64').decode('zip'))[i]: if all([w[k]<'1'for k in z]+[w[k]>'0'for k in o]):print j i+=1 ``` [Try it online!](https://tio.run/##RZRJk6pYFITXXb/CVVs@jFZABSq6OgKRURAZRKGiFgwXvMjsZfzz1fVed3RvM86XmXEWWY3oXhbE11fxDt/XL3HZzMAMFq@wqFr0usDms/kPYrf4eCN2n2/Fe/GD2O6wsoleweKlfw@@L4vFB/H2@YtMv8n53n@AJivLJQcK1PjZkoNNmIHlAT5RA0O0lPw8B80zh@g@@33GQTQulTaAGQBLDaCmrMoMIr9YnsoG3UFTLM8wDP0IZtm4dL4Nygb6y6uPfqX86zD/41l9U6/z5Xzx9jL7WWZalt91ZqDzs9c5UIaTE2YDO/Gav0nOUmQ6kI4ZNPBspRu0dj81yDLYBKXn7UqvyLheh9ee1OmoDpwVZauxE@h0t@pWF68mvWsTRPaTV6gHdjbJ1AsuGwq/Vh6QuqRVvbFgPBQ4VUD1VNwQ27S8CKGOfB0E@kB795ukgZQgE7TeEyuFXlHOJqq749Dlk2PYuzYShslN210SBCJebrHvALkaqsDplNOoGqComaTFTLdlZBnW3LNVTzqFBYETGc4zZMWTXUeXh@jxnhXdNF7ImPByXq15D7@4B450ObthSktWxsd0TXY3WF7qMBfHIyFakyugvQgRW6na7TD4R6rfUBIe@eOa4yw7EW0ZCFSP@qctbbt1Qbo3KdjweZPn0lPnwco8btFNKEqTHlpLQiepuPhVYfV3bXdtEHMYrF0Qj5l8vNmP@8Ru6mbdnfWrNurDJH3/VBJijSXFwN0X2GnQY9ber1TT8yxsYITQzTzjuN04Vv3suWx7d4e0kvXNnoQ6YeMnsFYqnL7y14Mz5o@nLkKy4cWNnW4b2tHwVJJGfjJ0TZPSQqgNLtfXMjXS3iVxyV5ZDceOEsQjR/CqUrR5ad1i/KQO/tN6no8quInmARhDquphlSVKYHdrWdcfdb2dilLoYOiYmkgnTcmqeYy0/qwQRagFIGRVUrxaKwyK3EUsBHdN3CXsPhTXNcuHmfxUeTSptqnCli6Z284WurbDixtQThFKwyyVNWBoBwccDyV@hBq7Z2qHp0vbX5NN1iRRpihZwuZ1dXBuFYsiCC4HVh2OveWrU57jQdxTyYEZjcYNZJNND9Y1m6jinAE4erpt189YnvCULXY2g7sjPxDqA/IZe3aavupF2D7uBlPjOnajTVyHKkfZVoYeY2vwKnRRSSVo4w7ntYh50ARZwUNrg3GOruirnaAnJ5nou1NGW@2Z4FzeiS4gPdxb0zzSxVmxLceJb7lElFYswY0HReaK7ajUlZXBv/i6G5GsbY@m2eo3ORV9oTgPoRTp6t0QuHtphMi1@GgfnzuhCQsfmlty29XNTskORY7o5LBdMQ9E4ldvQ8m7nml43CbjB@6Ffput8ai2gtVJFlT55MCYMrawWQV@G4Ze23MdQ8bUQK8khoLzPyIQlhF4nQf@E@w288V/wgSr@WLxAT/fXn6D8czPsteP/uPx@eccn//cosfPJZo@sV/iX/P1/2L5uXirGligWfoyg9g7/vX1z4LOLNQAgOZ/Aw "Python 2 – Try It Online") **Explanation** The input is encoded as a binary representation (8-bits ASCII code for each letter of the input word) when completing the input word by spaces at right if the length of the word is less than 26. I already done the same representation for all possible inputs and find the minimal bits that differentiate the outputs. The code looks at these specific bits to decide on the output. * -12 bytes thanks to Jonathan Allan. * -2 bytes thanks to Mr. Xcoder when using lexicographical comparison. [Answer] # [Jotlin 1.0](https://github.com/jrtapsell/jotlin), 1539 bytes ## Submission ``` {x->d("eJw1VcluG0cU/BWfchoC/dbuPpJDkTM2EuSUnGmFgIlQYkAzBwNEvj1VrUSHkXp7S1W90v7y/XG/vD6ev15eX09/XK7XH8/5cn+9np8/nx/321+36+Vxen8up7e38/372+Xx7dNPn+bL48fzl9v98e18f3/uTn+e79fb7fn576+X6/n8nM/vj/vp+vz99BgH/7/4DYlu98vpH83i290k0vq8nzbqptuXSa3GDiurbT+JRztMKpUf0R1OJXdTtnKcX5b9pKXgpOZ6+Dxtsuf8sp/MEGWjEm3FURSmcI15O0npvmWiKofJsyx447FyR43nKvYFqyzrMmkIUieTilZHSWHOyJKdz0vFVamNJUvKih0/YKfpKN9RsnRfpm4LWqyJb6uKLBuxjtXGiqJr6YFobLeujOfliGV0Nh8dYcOCb9KEGJnmYWoNmTIISiorE5eRuzZlLLWOTQu8qK1tJ9XM8dUVNfWO5sR0JRQ1ScFGo/Xx24yoZesMJzH6tdJ5Nb3vmas3Y+Iex5nHJhUVS5XKMqtxG2svhYGA9Bdk64XMqBQj2qU3LpGtoJtNV1u4Kt53hL8lam7BYpsDMfInLEhrj/ll6sR/g1gMJmo+gkk6MloujBHRtuNKR5AUFIogNYLvPJP3ypF9xnEyD5TW2Jo0cCcZMr5g3itwlRIDDlNH6E5irTmYbN2JiIesu6lmjHLaiORVWQDYJRNDPlpMRpIsu8FVw2M0CzAhvyOCCrkikRresZFppM0r1SK8gl4Wihow7A9oFKSw4t6IC6lJPiuoRD1y7GUtB+ZTUc6DDL1H2PpBAdS8sDkOEdVbEQGBMjhrBcihgHGk0OSRnPW2Dllo16E5Slobs+3JezWSAaaGqttoRyG5WsiFilMWSUCMSsTwB+uI6ojuzZCX1eGgyKC10wZq3ZOusv43QOwoGoYfMs/BLX2ilX5cqTetQ5xaGm6COIyQVMU0SSnliBQlOelmZT+1xE1Ahz+lqw/dBFsVVaC9aYbJNAcV8B7yjWahNMekkmgYDLzEhoFRgVI+yMCoDoITvaDTMTphOoSgA7ToIFbHSAh1j9nhn70630MCtKTGMbACOsKSegHQW2KUkG7PD9OoAFuUVTXHGGoRtJ0C9/EmCAKVLBxJGc7opWMooS5QbfCBhUmdkIK84V3FuYffo8wykmTHEGAg+XX43fC6RhNshUY5WrIwXhJBiSbUuduwXKuUcqdHELHhGzEw8cBUpbR5SwxKxSqcTCEUHVYDwvemx4UeH07TtKFSaEZgHKjTqCmFx/U6DLAq/gcs7EQaZ4cKElpgaUPk1ohw7Rhi3sIPB8Y6hTBgA7Ve6buBVgBSxXyH4RHm1RkCW4d/AeEEm1Q=").split("~").w{v ->Regex("(-?[0-9]+)([A-Z]+)").findAll(v[1]).f{x.hashCode()%2897==b.groupValues[1].toInt()}.m{b.groupValues[2].m{v[0].split("|")[b-'A']}}.first()}} ``` ## Test code ``` var v:(String)->List<String> = {x->d("eJw1VcluG0cU/BWfchoC/dbuPpJDkTM2EuSUnGmFgIlQYkAzBwNEvj1VrUSHkXp7S1W90v7y/XG/vD6ev15eX09/XK7XH8/5cn+9np8/nx/321+36+Vxen8up7e38/372+Xx7dNPn+bL48fzl9v98e18f3/uTn+e79fb7fn576+X6/n8nM/vj/vp+vz99BgH/7/4DYlu98vpH83i290k0vq8nzbqptuXSa3GDiurbT+JRztMKpUf0R1OJXdTtnKcX5b9pKXgpOZ6+Dxtsuf8sp/MEGWjEm3FURSmcI15O0npvmWiKofJsyx447FyR43nKvYFqyzrMmkIUieTilZHSWHOyJKdz0vFVamNJUvKih0/YKfpKN9RsnRfpm4LWqyJb6uKLBuxjtXGiqJr6YFobLeujOfliGV0Nh8dYcOCb9KEGJnmYWoNmTIISiorE5eRuzZlLLWOTQu8qK1tJ9XM8dUVNfWO5sR0JRQ1ScFGo/Xx24yoZesMJzH6tdJ5Nb3vmas3Y+Iex5nHJhUVS5XKMqtxG2svhYGA9Bdk64XMqBQj2qU3LpGtoJtNV1u4Kt53hL8lam7BYpsDMfInLEhrj/ll6sR/g1gMJmo+gkk6MloujBHRtuNKR5AUFIogNYLvPJP3ypF9xnEyD5TW2Jo0cCcZMr5g3itwlRIDDlNH6E5irTmYbN2JiIesu6lmjHLaiORVWQDYJRNDPlpMRpIsu8FVw2M0CzAhvyOCCrkikRresZFppM0r1SK8gl4Wihow7A9oFKSw4t6IC6lJPiuoRD1y7GUtB+ZTUc6DDL1H2PpBAdS8sDkOEdVbEQGBMjhrBcihgHGk0OSRnPW2Dllo16E5Slobs+3JezWSAaaGqttoRyG5WsiFilMWSUCMSsTwB+uI6ojuzZCX1eGgyKC10wZq3ZOusv43QOwoGoYfMs/BLX2ilX5cqTetQ5xaGm6COIyQVMU0SSnliBQlOelmZT+1xE1Ahz+lqw/dBFsVVaC9aYbJNAcV8B7yjWahNMekkmgYDLzEhoFRgVI+yMCoDoITvaDTMTphOoSgA7ToIFbHSAh1j9nhn70630MCtKTGMbACOsKSegHQW2KUkG7PD9OoAFuUVTXHGGoRtJ0C9/EmCAKVLBxJGc7opWMooS5QbfCBhUmdkIK84V3FuYffo8wykmTHEGAg+XX43fC6RhNshUY5WrIwXhJBiSbUuduwXKuUcqdHELHhGzEw8cBUpbR5SwxKxSqcTCEUHVYDwvemx4UeH07TtKFSaEZgHKjTqCmFx/U6DLAq/gcs7EQaZ4cKElpgaUPk1ohw7Rhi3sIPB8Y6hTBgA7Ve6buBVgBSxXyH4RHm1RkCW4d/AeEEm1Q=").split("~").w{v ->Regex("(-?[0-9]+)([A-Z]+)").findAll(v[1]).f{x.hashCode()%2897==b.groupValues[1].toInt()}.m{b.groupValues[2].m{v[0].split("|")[b-'A']}}.first()}} data class Test(val input0: String, val output: List<String>) val tests = listOf<Test>( Test("""Acton Town""",listOf("""District""","""Piccadilly""")), Test("""Aldgate""",listOf("""Circle""","""Metropolitan""")), Test("""Aldgate East""",listOf("""District""","""Hammersmith & City""")), Test("""Alperton""",listOf("""Piccadilly""")), Test("""Amersham""",listOf("""Metropolitan""")), Test("""Angel""",listOf("""Northern""")), Test("""Archway""",listOf("""Northern""")), Test("""Arnos Grove""",listOf("""Piccadilly""")), Test("""Arsenal""",listOf("""Piccadilly""")), Test("""Baker Street""",listOf("""Bakerloo""","""Circle""","""Hammersmith & City""","""Jubilee""","""Metropolitan""")), Test("""Balham""",listOf("""Northern""")), Test("""Bank""",listOf("""Central""","""Northern""","""Waterloo & City""")), Test("""Barbican""",listOf("""Circle""","""Hammersmith & City""","""Metropolitan""")), Test("""Barking""",listOf("""District""","""Hammersmith & City""")), Test("""Barkingside""",listOf("""Central""")), Test("""Barons Court""",listOf("""District""","""Piccadilly""")), Test("""Bayswater""",listOf("""Circle""","""District""")), Test("""Becontree""",listOf("""District""")), Test("""Belsize Park""",listOf("""Northern""")), Test("""Bermondsey""",listOf("""Jubilee""")), Test("""Bethnal Green""",listOf("""Central""")), Test("""Blackfriars""",listOf("""Circle""","""District""")), Test("""Blackhorse Road""",listOf("""Victoria""")), Test("""Bond Street""",listOf("""Central""","""Jubilee""")), Test("""Borough""",listOf("""Northern""")), Test("""Boston Manor""",listOf("""Piccadilly""")), Test("""Bounds Green""",listOf("""Piccadilly""")), Test("""Bow Road""",listOf("""District""","""Hammersmith & City""")), Test("""Brent Cross""",listOf("""Northern""")), Test("""Brixton""",listOf("""Victoria""")), Test("""Bromley-by-Bow""",listOf("""District""","""Hammersmith & City""")), Test("""Buckhurst Hill""",listOf("""Central""")), Test("""Burnt Oak""",listOf("""Northern""")), Test("""Caledonian Road""",listOf("""Piccadilly""")), Test("""Camden Town""",listOf("""Northern""")), Test("""Canada Water""",listOf("""Jubilee""")), Test("""Canary Wharf""",listOf("""Jubilee""")), Test("""Canning Town""",listOf("""Jubilee""")), Test("""Cannon Street""",listOf("""Circle""","""District""")), Test("""Canons Park""",listOf("""Jubilee""")), Test("""Chalfont & Latimer""",listOf("""Metropolitan""")), Test("""Chalk Farm""",listOf("""Northern""")), Test("""Chancery Lane""",listOf("""Central""")), Test("""Charing Cross""",listOf("""Bakerloo""","""Northern""")), Test("""Chesham""",listOf("""Metropolitan""")), Test("""Chigwell""",listOf("""Central""")), Test("""Chiswick Park""",listOf("""District""")), Test("""Chorleywood""",listOf("""Metropolitan""")), Test("""Clapham Common""",listOf("""Northern""")), Test("""Clapham North""",listOf("""Northern""")), Test("""Clapham South""",listOf("""Northern""")), Test("""Cockfosters""",listOf("""Piccadilly""")), Test("""Colindale""",listOf("""Northern""")), Test("""Colliers Wood""",listOf("""Northern""")), Test("""Covent Garden""",listOf("""Piccadilly""")), Test("""Croxley""",listOf("""Metropolitan""")), Test("""Dagenham East""",listOf("""District""")), Test("""Dagenham Heathway""",listOf("""District""")), Test("""Debden""",listOf("""Central""")), Test("""Dollis Hill""",listOf("""Jubilee""")), Test("""Ealing Broadway""",listOf("""Central""","""District""")), Test("""Ealing Common""",listOf("""District""","""Piccadilly""")), Test("""Earl's Court""",listOf("""District""","""Piccadilly""")), Test("""East Acton""",listOf("""Central""")), Test("""East Finchley""",listOf("""Northern""")), Test("""East Ham""",listOf("""District""","""Hammersmith & City""")), Test("""East Putney""",listOf("""District""")), Test("""Eastcote""",listOf("""Metropolitan""","""Piccadilly""")), Test("""Edgware""",listOf("""Northern""")), Test("""Edgware Road""",listOf("""Bakerloo""","""Circle""","""District""","""Hammersmith & City""")), Test("""Elephant & Castle""",listOf("""Bakerloo""","""Northern""")), Test("""Elm Park""",listOf("""District""")), Test("""Embankment""",listOf("""Bakerloo""","""Circle""","""District""","""Northern""")), Test("""Epping""",listOf("""Central""")), Test("""Euston""",listOf("""Northern""","""Victoria""")), Test("""Euston Square""",listOf("""Circle""","""Hammersmith & City""","""Metropolitan""")), Test("""Fairlop""",listOf("""Central""")), Test("""Farringdon""",listOf("""Circle""","""Hammersmith & City""","""Metropolitan""")), Test("""Finchley Central""",listOf("""Northern""")), Test("""Finchley Road""",listOf("""Jubilee""","""Metropolitan""")), Test("""Finsbury Park""",listOf("""Piccadilly""","""Victoria""")), Test("""Fulham Broadway""",listOf("""District""")), Test("""Gants Hill""",listOf("""Central""")), Test("""Gloucester Road""",listOf("""Circle""","""District""","""Piccadilly""")), Test("""Golders Green""",listOf("""Northern""")), Test("""Goldhawk Road""",listOf("""Circle""","""Hammersmith & City""")), Test("""Goodge Street""",listOf("""Northern""")), Test("""Grange Hill""",listOf("""Central""")), Test("""Great Portland Street""",listOf("""Circle""","""Hammersmith & City""","""Metropolitan""")), Test("""Greenford""",listOf("""Central""")), Test("""Green Park""",listOf("""Jubilee""","""Piccadilly""","""Victoria""")), Test("""Gunnersbury""",listOf("""District""")), Test("""Hainault""",listOf("""Central""")), Test("""Hammersmith""",listOf("""Circle""","""District""","""Hammersmith & City""","""Piccadilly""")), Test("""Hampstead""",listOf("""Northern""")), Test("""Hanger Lane""",listOf("""Central""")), Test("""Harlesden""",listOf("""Bakerloo""")), Test("""Harrow & Wealdstone""",listOf("""Bakerloo""")), Test("""Harrow-on-the-Hill""",listOf("""Metropolitan""")), Test("""Hatton Cross""",listOf("""Piccadilly""")), Test("""Heathrow Terminals 1, 2, 3""",listOf("""Piccadilly""")), Test("""Heathrow Terminal 4""",listOf("""Piccadilly""")), Test("""Heathrow Terminal 5""",listOf("""Piccadilly""")), Test("""Hendon Central""",listOf("""Northern""")), Test("""High Barnet""",listOf("""Northern""")), Test("""Highbury & Islington""",listOf("""Victoria""")), Test("""Highgate""",listOf("""Northern""")), Test("""High Street Kensington""",listOf("""Circle""","""District""")), Test("""Hillingdon""",listOf("""Metropolitan""","""Piccadilly""")), Test("""Holborn""",listOf("""Central""","""Piccadilly""")), Test("""Holland Park""",listOf("""Central""")), Test("""Holloway Road""",listOf("""Piccadilly""")), Test("""Hornchurch""",listOf("""District""")), Test("""Hounslow Central""",listOf("""Piccadilly""")), Test("""Hounslow East""",listOf("""Piccadilly""")), Test("""Hounslow West""",listOf("""Piccadilly""")), Test("""Hyde Park Corner""",listOf("""Piccadilly""")), Test("""Ickenham""",listOf("""Metropolitan""","""Piccadilly""")), Test("""Kennington""",listOf("""Northern""")), Test("""Kensal Green""",listOf("""Bakerloo""")), Test("""Kensington (Olympia)""",listOf("""District""")), Test("""Kentish Town""",listOf("""Northern""")), Test("""Kenton""",listOf("""Bakerloo""")), Test("""Kew Gardens""",listOf("""District""")), Test("""Kilburn""",listOf("""Jubilee""")), Test("""Kilburn Park""",listOf("""Bakerloo""")), Test("""Kingsbury""",listOf("""Jubilee""")), Test("""King's Cross St. Pancras""",listOf("""Circle""","""Hammersmith & City""","""Metropolitan""","""Northern""","""Piccadilly""","""Victoria""")), Test("""Knightsbridge""",listOf("""Piccadilly""")), Test("""Ladbroke Grove""",listOf("""Circle""","""Hammersmith & City""")), Test("""Lambeth North""",listOf("""Bakerloo""")), Test("""Lancaster Gate""",listOf("""Central""")), Test("""Latimer Road""",listOf("""Circle""","""Hammersmith & City""")), Test("""Leicester Square""",listOf("""Northern""","""Piccadilly""")), Test("""Leyton""",listOf("""Central""")), Test("""Leytonstone""",listOf("""Central""")), Test("""Liverpool Street""",listOf("""Central""","""Circle""","""Hammersmith & City""","""Metropolitan""")), Test("""London Bridge""",listOf("""Jubilee""","""Northern""")), Test("""Loughton""",listOf("""Central""")), Test("""Maida Vale""",listOf("""Bakerloo""")), Test("""Manor House""",listOf("""Piccadilly""")), Test("""Mansion House""",listOf("""Circle""","""District""")), Test("""Marble Arch""",listOf("""Central""")), Test("""Marylebone""",listOf("""Bakerloo""")), Test("""Mile End""",listOf("""Central""","""District""","""Hammersmith & City""")), Test("""Mill Hill East""",listOf("""Northern""")), Test("""Monument""",listOf("""Circle""","""District""")), Test("""Moorgate""",listOf("""Circle""","""Hammersmith & City""","""Metropolitan""","""Northern""")), Test("""Moor Park""",listOf("""Metropolitan""")), Test("""Morden""",listOf("""Northern""")), Test("""Mornington Crescent""",listOf("""Northern""")), Test("""Neasden""",listOf("""Jubilee""")), Test("""Newbury Park""",listOf("""Central""")), Test("""North Acton""",listOf("""Central""")), Test("""North Ealing""",listOf("""Piccadilly""")), Test("""North Greenwich""",listOf("""Jubilee""")), Test("""North Harrow""",listOf("""Metropolitan""")), Test("""North Wembley""",listOf("""Bakerloo""")), Test("""Northfields""",listOf("""Piccadilly""")), Test("""Northolt""",listOf("""Central""")), Test("""Northwick Park""",listOf("""Metropolitan""")), Test("""Northwood""",listOf("""Metropolitan""")), Test("""Northwood Hills""",listOf("""Metropolitan""")), Test("""Notting Hill Gate""",listOf("""Central""","""Circle""","""District""")), Test("""Oakwood""",listOf("""Piccadilly""")), Test("""Old Street""",listOf("""Northern""")), Test("""Osterley""",listOf("""Piccadilly""")), Test("""Oval""",listOf("""Northern""")), Test("""Oxford Circus""",listOf("""Bakerloo""","""Central""","""Victoria""")), Test("""Paddington""",listOf("""Bakerloo""","""Circle""","""District""","""Hammersmith & City""")), Test("""Park Royal""",listOf("""Piccadilly""")), Test("""Parsons Green""",listOf("""District""")), Test("""Perivale""",listOf("""Central""")), Test("""Piccadilly Circus""",listOf("""Bakerloo""","""Piccadilly""")), Test("""Pimlico""",listOf("""Victoria""")), Test("""Pinner""",listOf("""Metropolitan""")), Test("""Plaistow""",listOf("""District""","""Hammersmith & City""")), Test("""Preston Road""",listOf("""Metropolitan""")), Test("""Putney Bridge""",listOf("""District""")), Test("""Queen's Park""",listOf("""Bakerloo""")), Test("""Queensbury""",listOf("""Jubilee""")), Test("""Queensway""",listOf("""Central""")), Test("""Ravenscourt Park""",listOf("""District""")), Test("""Rayners Lane""",listOf("""Metropolitan""","""Piccadilly""")), Test("""Redbridge""",listOf("""Central""")), Test("""Regent's Park""",listOf("""Bakerloo""")), Test("""Richmond""",listOf("""District""")), Test("""Rickmansworth""",listOf("""Metropolitan""")), Test("""Roding Valley""",listOf("""Central""")), Test("""Royal Oak""",listOf("""Circle""","""Hammersmith & City""")), Test("""Ruislip""",listOf("""Metropolitan""","""Piccadilly""")), Test("""Ruislip Gardens""",listOf("""Central""")), Test("""Ruislip Manor""",listOf("""Metropolitan""","""Piccadilly""")), Test("""Russell Square""",listOf("""Piccadilly""")), Test("""St. James's Park""",listOf("""Circle""","""District""")), Test("""St. John's Wood""",listOf("""Jubilee""")), Test("""St. Paul's""",listOf("""Central""")), Test("""Seven Sisters""",listOf("""Victoria""")), Test("""Shepherd's Bush""",listOf("""Central""")), Test("""Shepherd's Bush Market""",listOf("""Circle""","""Hammersmith & City""")), Test("""Sloane Square""",listOf("""Circle""","""District""")), Test("""Snaresbrook""",listOf("""Central""")), Test("""South Ealing""",listOf("""Piccadilly""")), Test("""South Harrow""",listOf("""Piccadilly""")), Test("""South Kensington""",listOf("""Circle""","""District""","""Piccadilly""")), Test("""South Kenton""",listOf("""Bakerloo""")), Test("""South Ruislip""",listOf("""Central""")), Test("""South Wimbledon""",listOf("""Northern""")), Test("""South Woodford""",listOf("""Central""")), Test("""Southfields""",listOf("""District""")), Test("""Southgate""",listOf("""Piccadilly""")), Test("""Southwark""",listOf("""Jubilee""")), Test("""Stamford Brook""",listOf("""District""")), Test("""Stanmore""",listOf("""Jubilee""")), Test("""Stepney Green""",listOf("""District""","""Hammersmith & City""")), Test("""Stockwell""",listOf("""Northern""","""Victoria""")), Test("""Stonebridge Park""",listOf("""Bakerloo""")), Test("""Stratford""",listOf("""Central""","""Jubilee""")), Test("""Sudbury Hill""",listOf("""Piccadilly""")), Test("""Sudbury Town""",listOf("""Piccadilly""")), Test("""Swiss Cottage""",listOf("""Jubilee""")), Test("""Temple""",listOf("""Circle""","""District""")), Test("""Theydon Bois""",listOf("""Central""")), Test("""Tooting Bec""",listOf("""Northern""")), Test("""Tooting Broadway""",listOf("""Northern""")), Test("""Tottenham Court Road""",listOf("""Central""","""Northern""")), Test("""Tottenham Hale""",listOf("""Victoria""")), Test("""Totteridge & Whetstone""",listOf("""Northern""")), Test("""Tower Hill""",listOf("""Circle""","""District""")), Test("""Tufnell Park""",listOf("""Northern""")), Test("""Turnham Green""",listOf("""District""","""Piccadilly""")), Test("""Turnpike Lane""",listOf("""Piccadilly""")), Test("""Upminster""",listOf("""District""")), Test("""Upminster Bridge""",listOf("""District""")), Test("""Upney""",listOf("""District""")), Test("""Upton Park""",listOf("""District""","""Hammersmith & City""")), Test("""Uxbridge""",listOf("""Metropolitan""","""Piccadilly""")), Test("""Vauxhall""",listOf("""Victoria""")), Test("""Victoria""",listOf("""Circle""","""District""","""Victoria""")), Test("""Walthamstow Central""",listOf("""Victoria""")), Test("""Wanstead""",listOf("""Central""")), Test("""Warren Street""",listOf("""Northern""","""Victoria""")), Test("""Warwick Avenue""",listOf("""Bakerloo""")), Test("""Waterloo""",listOf("""Bakerloo""","""Jubilee""","""Northern""","""Waterloo & City""")), Test("""Watford""",listOf("""Metropolitan""")), Test("""Wembley Central""",listOf("""Bakerloo""")), Test("""Wembley Park""",listOf("""Jubilee""","""Metropolitan""")), Test("""West Acton""",listOf("""Central""")), Test("""West Brompton""",listOf("""District""")), Test("""West Finchley""",listOf("""Northern""")), Test("""West Ham""",listOf("""District""","""Hammersmith & City""","""Jubilee""")), Test("""West Hampstead""",listOf("""Jubilee""")), Test("""West Harrow""",listOf("""Metropolitan""")), Test("""West Kensington""",listOf("""District""")), Test("""West Ruislip""",listOf("""Central""")), Test("""Westbourne Park""",listOf("""Circle""","""Hammersmith & City""")), Test("""Westminster""",listOf("""Circle""","""District""","""Jubilee""")), Test("""White City""",listOf("""Central""")), Test("""Whitechapel""",listOf("""District""","""Hammersmith & City""")), Test("""Willesden Green""",listOf("""Jubilee""")), Test("""Willesden Junction""",listOf("""Bakerloo""")), Test("""Wimbledon""",listOf("""District""")), Test("""Wimbledon Park""",listOf("""District""")), Test("""Wood Green""",listOf("""Piccadilly""")), Test("""Wood Lane""",listOf("""Circle""","""Hammersmith & City""")), Test("""Woodford""",listOf("""Central""")), Test("""Woodside Park""",listOf("""Northern""")) ) for (r in tests) { val result = v(r.input0) if (result != r.output) { error("Error during $r, expected ${r.output}, got $result") } else { print(jotlin.runner.TestUtils.tick) } } ``` ]
[Question] [ Write a program or function (hereafter "function") that returns or prints the source code of four new functions: Increment, decrement, undo, and peek. The initial function contains an internal integer value of `0`. Each of the returned functions contains a value based on that value, and each behaves differently: * **Increment** contains the value of the function that created it plus 1. When called, it returns or prints the source code of four new functions: Increment, decrement, undo, and peek. * **Decrement** contains the value of the function that created it minus 1. When called, it returns or prints the source code of four new functions: Increment, decrement, undo, and peek. * **Undo** returns increment, decrement, undo, and peek functions equivalent to those returned by the function that created the function that created it, i.e. its grandparent. Calling successive Undo functions will return functions earlier and earlier in the "history." *Note: Because the very first generation of Undo has no "grandparent" its behavior is undefined. It may return any value, throw an error, etc.* * **Peek** contains the value of the function that created it. When called it returns or prints that value. ## Example Suppose `yourFunction` is your initial function. It returns four strings that contain the source code of the subsequent functions. ``` [incr, decr, undo, peek] = yourFunction(); eval(peek)(); // => 0 [incrB, decrB, undoB, peekB] = eval(incr)(); eval(peekB)(); // => 1 [incrC, decrC, undoC, peekC] = eval(incrB)(); eval(peekC)(); // => 2 [incrD, decrD, undoD, peekD] = eval(incrC)(); eval(peekD)(); // => 3 [incrE, decrE, undoE, peekE] = eval(undoD)(); eval(peekE)(); // => 2 [incrF, decrF, undoF, peekF] = eval(undoE)(); eval(peekF)(); // => 1 [incrG, decrG, undoG, peekG] = eval(decrF)(); eval(peekG)(); // => 0 eval(peekF)(); // => 1 ``` ## Rules 1. This is a [code-generation](/questions/tagged/code-generation "show questions tagged 'code-generation'") challenge. With the exception of "peek," the initial function and the functions it creates (and the functions they create and so on) must return source code that can be stored (copied/pasted, saved in a file, et al) and executed in a separate session. Returning a closure, for example, is not valid. 2. The functions generated don't need to be named "increment," "decrement," etc. They're not required to be named at all. 3. The "depth" of the Undo functions, i.e. how far back you can go in their "history," should be limited only by memory or language constraints. 4. You're encouraged to include in your answer examples of the four functions generated by your initial function or its successors. 5. The output formats are flexible. Inclusive of rule (1), [standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/) apply; your initial function—and the subsequent functions—could return four programs separated by newlines; an array of four strings; an object with four string properties; four files; etc. 6. [Standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) apply and [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. 7. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Your score is the number of bytes in your initial function. Lowest number of bytes wins. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~54~~ 35 bytes ``` Hold[1~#0~##,#0[-1,##],#0@##2,+##]& ``` [Try it online!](https://tio.run/##TY5Ra4MwFIWfk18hCZQNleke21myWt0GKxvsMYSRaqRhMUqNg620f92ZWTBP9/Cdc7in5uYgam5kwYcqGZ4bVdL4gqMLxgGOaBgHGLNREYzvA3/Ui@Gtqmje68LIRi@XnWpMx@CuKXsl6EnqIonOAQSdES3VvBafzFsm3s1o@P4KApB9c9VzI@jHT71vFMUP65eKjvY6HmsApLyVhiv5K8ijag98Lwxl1AYYCxBibGFTd@SERnREgYdKMd1el429rRBf6My8xHuVnSHEroDgFjJoR5GKXoXte6v3o9SG2M5mxhsHpzNOHbydsH26dXA248zB@YTt1NzBT9CNTBqFYYiu@v/p8Ac "Wolfram Language (Mathematica) – Try It Online") Returns `Hold[incr, decr, undo, peek]`, where the expression body consists of four unevaluated expressions. When evaluated, `incr`, `decr`, and `undo` reduce to similar four-element `Hold[...]` expressions, and `peek` to an integer\*. \* Upon `undo`ing with no history, `peek` takes on the value `##2`, and subsequent `incr`/`decr` operations yield `peek=n+##2` for some integer `n`. `undo`ing that `undo` restores `peek=0`. [Answer] # JavaScript (ES6), 98 bytes ``` f=(k=0,p='' )=>[(g=n=>(0+f).replace(/\S*/,`f=(k=${k+n},p="${btoa(f)}"`))(1),g(-1),atob(p),"_=>"+k] ``` [Try it online!](https://tio.run/##jdHPb4IwFAfwO39FQ0xoB4Juyy6mJPLztotHNROxJQijBNBkMf7trPCMk0SSXWhC3/u8b9tjdI7quErLZlqIA2stC5Ui/@FpnteIiwp9yr/msVb2jYgQRTWiNnJOnLPK5JX4xjXSkaYRsxGrpkqLBGv7qGYf7xpZKFEj9uM9BrqX/nXLLiWgLac4ozOjpJqGCLXXOKEFtfFM58SsWJlHMcPWZvViGbu@dHLJ9OIq69XJpUuKObmqO0LwnBgJnspvlwWXxFC/qK3q2bZdKOu0iKulgQ6sX07FQcilZCxbbmXsoAsTi6IWOTNzkWB2jnLcbxNMyALJu5IHmykAOQA5ADkAOR3U9/WzyCjpPJLzG@kC6QLpAukOSGecdB/J1xvpAekB6QHpDUh3nPQeybcb6QPpA@kD6d/Jfs446T9LGQAZABkAGQxIf5wMnt1lCGQIZAhkeCf7ceNkOHzxf4xtfwE "JavaScript (Node.js) – Try It Online") [Answer] # [Rust](https://www.rust-lang.org), 603 bytes ``` fn f(){let m=("fn ","(){let m=",";let n=vec!",";println!(\"fn a(){{println!(\\\"","\\\")}}\");for i in [(\"b\",",",\"\"),(\"c\",",",\"\"),(\"d\",",",\"o.pop();\")]{let mut o=n.clone();o.push(i.1);","println!(\"{}{}{}{:?}{}{:?}{}{}{}{}{}{}{}{}{}{}{}\",m.0,i.0,m.1,m,m.2,o,m.3,i.1,m.4,i.1+1,m.5,i.1-1,m.6,o[o.len()-2],m.7,i.2,m.8);}}");let n=vec![0,0];println!("fn a(){{println!(\"0\")}}");for i in [("b",1,""),("c",-1,""),("d",0,"o.pop();")]{let mut o=n.clone();o.push(i.1);println!("{}{}{}{:?}{}{:?}{}{}{}{}{}{}{}{}{}{}{}",m.0,i.0,m.1,m,m.2,o,m.3,i.1,m.4,i.1+1,m.5,i.1-1,m.6,o[o.len()-2],m.7,i.2,m.8);}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rVJLboMwFJS6a07hvJWtGgvoLypCPQiwSAiolsBGBLpBnKSbLNoT9DY9TcdJE5oqiyyqJ95nZpDt0Xt7b_tNt91-9F3pLb6uktKwkouhKjpWx5wwkqQjgD5ynYlfi3zupqbVpqvMnKdOu4RymKA0JWhcEeOIFJW2ZZppwxLoVylIREqgJID8L7A-AlY1tuEiApHt79J3zMZG5ZU1BQgI-s0L1yoQEX75da1h3MXT85TPBE6qlS81vloFskYOpUW-BYZZ3bl647p713mue5A2saoqDBdemAF4BBWiLkQ0jnjv5FXiSz-b3DpjFvk7m05dohXJQJKzg3KS3qFfk_Tl0ZVLTJmOvsyQ__djv2OfeHm91JCwYXaNXYtmP8xhC78B) [Attempt this after a couple iterations](https://ato.pxeger.com/run?1=7VXdTsIwFL408hTlXLWxLKygEhbig1AuWDfikq0lsHmz9Em88UIfSp_G0w0oBoxcGKORdTs95_v6ty9f0sfnVbUun55eqnLRG71dpAtN5pTVy1Wmy1x3KQhgtoNojGielqSYUMASOIEd4orIpXrykKpuU-5WkLBZ0y8qpQQ3yPXMWgzRwqxIRjJNpjghlsAdzyUgxxFRB0jiERMszZKyCJlZe6KqJGaiA5UbnSKBA6r1Pc2CkEVuzt7Zatu08Z2PRxruVQR9nuFXBCEvMApuMA4QwzoYuv7KZdcu67nshpupCfJUU9YTMwRukRLYj1hkLf6zV2za5wTfkBPByWDmxTuiHQwa0T5qBjHwIQcnDSjgYpMmTbrV5xR5_M6nKfP9wjizqbPZfshs4RdmCz8xm_Bm6_9xsyVns_0Hs23H_gLTtbfta40SFPMMB5G6Q_DxR5uPUYXOJQqE0cNSxy0RHxCqIdwqim6SfTrZ0YmjbXuE7cX_Dg) Probably not anywhere close to optimally golfed, but I'm pretty impressed with myself for getting it to work at all. Expanded version: ``` fn f() { let m=("fn ","(){let m=",";let n=vec!",";println!(\"fn a(){{println!(\\\"","\\\")}}\");for i in [(\"b\",",",\"\"),(\"c\",",",\"\"),(\"d\",",",\"o.pop();\")]{let mut o=n.clone();o.push(i.1);","println!(\"{}{}{}{:?}{}{:?}{}{}{}{}{}{}{}{}{}{}{}\",m.0,i.0,m.1,m,m.2,o,m.3,i.1,m.4,i.1+1,m.5,i.1-1,m.6,o[o.len()-2],m.7,i.2,m.8);}}"); let n = vec![0, 0]; println!("fn a(){{println!(\"0\")}}"); for i in [("b", 1, ""), ("c", -1, ""), ("d", 0, "o.pop();")] { let mut o = n.clone(); o.push(i.1); println!( "{}{}{}{:?}{}{:?}{}{}{}{}{}{}{}{}{}{}{}", m.0, i.0, m.1, m, m.2, o, m.3, i.1, m.4, i.1 + 1, m.5, i.1 - 1, m.6, o[o.len() - 2], m.7, i.2, m.8 ); } } ``` [Answer] # [Rust](https://www.rust-lang.org), 279 bytes ``` ||{macro_rules!q{($x:tt)=>{$x(stringify!($x))}} q!((|s|move|mut v:Vec<_>,n|{let f=|m,u:&_|format!("||{{macro_rules!q{{($x:tt)=>{{$x(stringify!($x))}}}} q!({})(vec!{:?},{})}}",s,u,m);v.push(n);(f(n+1,&v),f(n-1,&v),f({v.pop();v.pop()}.unwrap(),&v),format!("||{}",n))}))(vec![0],0)} ``` This is a nullary closure that returns a 4-tuple of strings. It uses a macro to do most of the quine heavy-lifting. The state is inserted right towards the end, using a vector for the undo history. The undo history starts with a single entry so the `.unwrap()` doesn't panic, but the program outputted using it *will* panic. [Attempt This Online!](https://ato.pxeger.com/run?1=bZBBTsMwEEXFNhdg60RVZYtpVXYooeUWbCgKIbEhop6kiR2KbJ-ETRaw5zpwGtymhQqxmv9HX_-N_frW6Fb1HwKJzEqkzKy4ImL-rpWYXHydnFprZJY3VdroFW_DtaGjTawUmy_MaENb1ZT4UIqX0K8Zcy5Yh5Ta1sqq41ZqRbr4mueX6QLQ7qutBB2PUyuqRmYqpJFH_GEcQf6lDBzjGO14Hpr4yoE3zkXQggbJkm5a6_aRIkuooHh2DuOOgVeTgzI-UdV0l9xON9X43GReDYGj23wreigbYDezW5gxN_zP510SELJ9Fs3gHnIoGJkT4Wv9uvZHqxX6khLzeInGLXGJBf_VGovqx9ScP-1MBIeuJNhz-n6Y3w) ([after a few iterations](https://ato.pxeger.com/run?1=bVDBTsMwDBXXfoVbTSgR2QScUMfGX3BhaJQuGRWr27VJGUrzJVx2gDu_A1-D0xaYEFEk-1nPfs9-ea1MrffvCiFPMmTcbqQGNXszWo0vPo_WbWvzJK2KZWU2sg63lo12sdZ8NrejHat1leE6U88hlTl3LtiGjLVQQwt50UgfjIYGYriWKVzCEuYCENrABkCvE4OZpwkwxDomRguqqPJEhx2FRWThj4cDE_-66H1Yx1kj09DGV04QcC4S3ciatATkHKbQTEpTPzCkvFdTDOEEzgQ5abgAD8eH0PqWomRDc5e5icGnKqF04HWjhiX6BUgakPPA8d7TzakA-jT4_Faccdff--POu_BHYYm4F6lYcTqOYtyXS1pSbzBkUYZpvEDrFrjAlfzNDa6KH1BK-diBSHzPmgaDzn7fxy8)) Initial output: ``` // inc ||{macro_rules!q{($x:tt)=>{$x(stringify!($x))}} q!((| s | move | mut v : Vec < _ >, n | { let f = | m, u : & _ | format! ("||{{macro_rules!q{{($x:tt)=>{{$x(stringify!($x))}}}} q!({})(vec!{:?},{})}}", s, u, m) ; v.push(n) ; (f(n + 1, & v), f(n - 1, & v), f({ v.pop() ; v.pop() }.unwrap(), & v), format! ("||{}", n)) }))(vec![0, 0],1)} // dec ||{macro_rules!q{($x:tt)=>{$x(stringify!($x))}} q!((| s | move | mut v : Vec < _ >, n | { let f = | m, u : & _ | format! ("||{{macro_rules!q{{($x:tt)=>{{$x(stringify!($x))}}}} q!({})(vec!{:?},{})}}", s, u, m) ; v.push(n) ; (f(n + 1, & v), f(n - 1, & v), f({ v.pop() ; v.pop() }.unwrap(), & v), format! ("||{}", n)) }))(vec![0, 0],-1)} // undo (will panic) ||{macro_rules!q{($x:tt)=>{$x(stringify!($x))}} q!((| s | move | mut v : Vec < _ >, n | { let f = | m, u : & _ | format! ("||{{macro_rules!q{{($x:tt)=>{{$x(stringify!($x))}}}} q!({})(vec!{:?},{})}}", s, u, m) ; v.push(n) ; (f(n + 1, & v), f(n - 1, & v), f({ v.pop() ; v.pop() }.unwrap(), & v), format! ("||{}", n)) }))(vec![],0)} // peek ||0 ``` [Answer] # [Python REPL](https://www.python.org), ~~67~~ ~~61~~ 59 bytes ``` eval(s:='0,(n:="eval(s:=%r)")%("-~"+s),n%("~-"+s),n%s[2:]') ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VdHLaoNAFAZgsvUpRAg6RKF0VSxu5voQaRelUSINo3gJBEJeJBs35p3ap6n6j3CymXOG-b9zFnN_1JfuWNlhLPzM_xj7rkjeft_z89cpatMsfIkjm2bBet82LGDbKEhuwa5lsZ3aW-Ladv-afoYMI_421zrPf2K_tN9N7B_y-eztoZq2FF7dlLaL5gDzvLlwBDmSHFE-ZZfF8xMjiDsloASUgBJUccqEYxJMgkkwSZmgTDqmwBSYAlMrW2ZQphzTYBpMg2nKFGXaMQNmwAyYWdkyijLzPAOfMAyo_w) Outputs `(peek, incr, decr, undo)` # [Python](https://www.python.org), ~~89~~ ~~99~~ ~~93~~ ~~91~~ 86 bytes ``` lambda:eval(s:='(n:="lambda:eval(s:=%r)")%(s+"\'+1\'"),n%(s+"\'-1\'"),n%s[:-4],n%"0"') ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bdFPaoQwHIZhuvUUEhhMGIUWuiiCm_wxN-imdmGr0qEzGVFnoGfpxs30ML1Be5pqvkqkzUb9hbxPAr5_tG_Dy9GMlybMwuJyGprk7ut-Xx6eqjKtz-We9mkWUZNm5M_ipmOEbWi_JUW0vSkiwmLzOybL2D-kye3j9EGuScSgf1997sxzF4dVPT9PpjrGYVvXr9MFGsqCttuZgdpT5lVGGQuCueBIOBqOiE-V3TvvYP9z7nqBXqAX6MW65x5AOEACkAAkALkGhAeQDlAAFAAFQC2ART2AckAOIAeQA8jXgPIAuQM0AA1AA9ALYG0PoC3gU_FLxxHvHw) Outputs `(incr, decr, undo, peek)` +10 bytes due to an oversight (peek was a lambda and not a string which contained a lambda. [Old Answer](https://ato.pxeger.com/run?1=XdFNTsMwEAVgsc0pQjb1qAkCVihSNv49AwIWgSSionWiNEVCiIvAJptyJzgNdV5rxWzs0eh945H89d29Dc-tHfdNXMT3-93QZDc_t-ty81iVef1artk2LxbM5kXyr_l-3n9QctG0_aYciG2XyfIqodS6KjtWd3l2_UDpUV4uCA_8nn2u7FOfxlXtzp2t2jTu6vrlsEPDKOr6lR2YazCiKHJZjjBHmiPOD_lpHZegAHIvBaSAFJBiLnlIhacSVIJKUDmnIqTSUwWqQBWoOtFpXEiVpxpUg2pQPacqpNpTA2pADag50WlqSI2j4SR80Tji_gM)) [Answer] # [Kotlin 1.7.10](https://kotlinlang.org/), 494 490 bytes ``` {val q='!'+1;val h=listOf(0,0);fun p(h:List<Int>){val l=listOf("{val q='!'+1;val h=listOf(","h.joinToString()",");fun p(h:List<Int>){val l=listOf(",");print(l[0]+h.joinToString()+l[2]);for(r in l)print(q+r+q+',');println(l[3])};p(h+(h.last()+1));p(h+(h.last()-1));p(h.dropLast(1));print('{');print(h.last());print('}')}");print(l[0]+h.joinToString()+l[2]);for(r in l)print(q+r+q+',');println(l[3])};p(h+(h.last()+1));p(h+(h.last()-1));p(h.dropLast(1));print('{');print(h.last());print('}')} ``` [Try it on Kotlin Playground!](https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS43LjIwIiwicGxhdGZvcm0iOiJqYXZhIiwiYXJncyI6IiIsIm5vbmVNYXJrZXJzIjp0cnVlLCJ0aGVtZSI6ImlkZWEiLCJjb2RlIjoidmFsIGZ1bmN0aW9uID0ge3ZhbCBxPSchJysxO3ZhbCBoPWxpc3RPZigwLDApO2Z1biBwKGg6TGlzdDxJbnQ+KXt2YWwgbD1saXN0T2YoXCJ7dmFsIHE9JyEnKzE7dmFsIGg9bGlzdE9mKFwiLFwiaC5qb2luVG9TdHJpbmcoKVwiLFwiKTtmdW4gcChoOkxpc3Q8SW50Pil7dmFsIGw9bGlzdE9mKFwiLFwiKTtwcmludChsWzBdK2guam9pblRvU3RyaW5nKCkrbFsyXSk7Zm9yKHIgaW4gbClwcmludChxK3IrcSsnLCcpO3ByaW50bG4obFszXSl9O3AoaCsoaC5sYXN0KCkrMSkpO3AoaCsoaC5sYXN0KCktMSkpO3AoaC5kcm9wTGFzdCgxKSk7cHJpbnQoJ3snKTtwcmludChoLmxhc3QoKSk7cHJpbnQoJ30nKX1cIik7cHJpbnQobFswXStoLmpvaW5Ub1N0cmluZygpK2xbMl0pO2ZvcihyIGluIGwpcHJpbnQocStyK3ErJywnKTtwcmludGxuKGxbM10pfTtwKGgrKGgubGFzdCgpKzEpKTtwKGgrKGgubGFzdCgpLTEpKTtwKGguZHJvcExhc3QoMSkpO3ByaW50KCd7Jyk7cHJpbnQoaC5sYXN0KCkpO3ByaW50KCd9Jyl9XG4vLyBDYWxsIHRoZSBzb2x1dGlvbjpcbmZ1biBtYWluKCkgPSBmdW5jdGlvbigpIn0=) A function/lambda that prints the source code for four new lambdas: increment, decrement, undo and peek. Calling the first-generation undo function produces a lambda that compiles but produces invalid sources for its own undo. ## Explanation ``` { // A lambda of type () -> Unit val q = '!' + 1 // The " character to avoid backslashes val h = listOf(0, 0) // The history of numbers, initialised with two numbers // to make initial undo compilable fun p(h: List<Int>) { // Define a nested function p(h) that prints // the source code for increment/decrement/undo val l = listOf( // List of source code lines to print "{val q='!'+1;val h=listOf(", "h.joinToString()", ");fun p(h:List<Int>){val l=listOf(", ");print(l[0]+h.joinToString()+l[2]);for(r in l)print(q+r+q+',');println(l[3])};p(h+(h.last()+1));p(h+(h.last()-1));p(h.dropLast(1));print('{');print(h.last());print('}')}" ) print(l[0] + h.joinToString() + l[2]) for (r in l) print(q + r + q + ',') // Print a quoted version of the whole lambda println(l[3]) } p(h + (h.last() + 1)) // Increment p(h + (h.last() - 1)) // Decrement p(h.dropLast(1)) // Undo print('{') // Peek print(h.last()) print('}') } ``` * Increment/decrement/undo are similar lambdas with a different `h`istory * Peek is a lambda that always *returns* the last value of `h` (while the others print) ## Example outputs After one round of incrementing: * Increment/decrement/undo print the following program: ``` {val q='!'+1;val h=LIST;fun p(h:List<Int>){val l=listOf("{val q='!'+1;val h=listOf(","h.joinToString()",");fun p(h:List<Int>){val l=listOf(",");print(l[0]+h.joinToString()+l[2]);for(r in l)print(q+r+q+',');println(l[3])};p(h+(h.last()+1));p(h+(h.last()-1));p(h.dropLast(1));print('{');print(h.last());print('}')}",);print(l[0]+h.joinToString()+l[2]);for(r in l)print(q+r+q+',');println(l[3])};p(h+(h.last()+1));p(h+(h.last()-1));p(h.dropLast(1));print('{');print(h.last());print('}')} ``` where `LIST` is actually: + Increment: `listOf(0, 0, 1, 2)` + Decrement: `listOf(0, 0, 1, 0)` + Undo: `listOf(0, 0)` (the original history) * Peek prints `{1}`, a constant lambda returning the latest value in the history -4 bytes by replacing the last `println` with `print` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~64~~ 62 bytes ``` f=_=>`f=${f}+'+1'\nf=${f}+'-1'\nf=${(f+"").slice(0,-5)}\n_=>0` ``` [Try it online!](https://tio.run/##jdJRa4MwEAfwdz9FkEETrK3d2JOk0MTEDzHHKhqHmyRSu76MfnbncrYo9SFPx0H@vzuOfOWXvCtOdXsOtSlVL2lf0Q@6P1b06be6Bqtgt8r0rQlvDa4C3yebrqkLhaN1@EqumR5i0bGPvbdaF6fDGpXKlh9dmqG0Sn0f3hFFEg/BtqnP2M@0T2KvMLozjdo05hOrS95g@5RgQmK03SK6R5EHKAOUAcoAZf@ozdm5xIlnU3438hx4DjwHns945sbzKf888gnwCfAJ8MmM5258MuVfRl4AL4AXwIs7b2e68WJpewm8BF4CL2e8cOPl0u1T4FPgU@DTO29HP/DLfjr/Og479H8 "JavaScript (Node.js) – Try It Online") -2 bytes thanks to [@emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a) [Answer] # [Python 3](https://docs.python.org/3/), ~~105~~ ~~93~~ 83 bytes -12 bytes thanks to 97.100.97.109 -10 bytes thanks to Mukundan314 and xnor ``` print(*map(open(__file__).read().replace,['0']*3,['-~0','~-0','0'[2:]]),'print(0)') ``` Outputs [incr, decr, undo, peek] separated by spaces [Try it online!](https://tio.run/##bdDdboMgFAfwe5@CeAM01Jj1rslu/HyIpjFOcXNlQBTTLsv66k48dB8dXEBAzu9/UL@bFyV3c6Najh5RGIazHnppyOat1kRpLklVdb3gVUWjgdctsYsWdcPZAcf4uNkt6/YaY4avWzvH@PCwPx4pwwDFFNN5caPRDL0mNAha3iF@4U2lJqMnQ2w23QdoGZ1emviTyhA@Y@o@RuehNxwKbkeNUCO3rN2DuD5k3duorj7xyj3q4nLskEoK1dTCFX2f/xgojF5VL8kFwmzPazZDH5vNs1BPtRgJZShc9XD/K@oTSgZupkHeEoJeNgNbmrLzJFvFkOb8tET9@x3RqEVvlmetofYWhfIE6hMAEhCSO8Je9BCJM1IwUjBSMFKPkXiQ1CEZIBkgGSCZB0k9SOaQHJAckByQ/A5ZfQ@SO6QApACkAKTwILkHKRxSAlICUgJS3iFrjAcp/4DzFw) [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~68~~ 51 bytes ``` echo 'bc<<<0';sed 's/0/0+1/p;s/+/-/p;s/0..../0/' $0 ``` [Try it online!](https://tio.run/##Zc/NisIwEAfwe55ikEIUiUm6R8NCPz3uI0ibBhTdWprWi/js3TBzqZu5BP6/ZDLTNv6y2GaCb7DzOIIxvPqp@eLs5QG8tcYYxY/edcC9VFLttRyOXu6lwFMdQoWcQ6KW8JBN49yHdg6EB6GxJ2N@uF@nc5DtDl4MQmECogPRaBB3DWbbhkkg0TtIUrzy@4RN8krfahOS8@Dc7SPWGF97O37EKcad@xd/YTz33YO9V/PQzhnDvzP6ZKUZ9oecPI88Jy/Ii8gL8pK8jLzEiaAiryKvyGvyOvIaF4UT@Yl8dXf5Aw "Bash – Try It Online") -17 bytes thanks to [@Jiří](https://codegolf.stackexchange.com/users/101306/ji%c5%99%c3%ad) Outputs `[peek, incr, decr, undo]` seperated by newlines [Answer] # [C (gcc)](https://gcc.gnu.org/), 241 bytes ``` // 0 v;f;l;char*e,b[999];c(n){f=fopen(__FILE__,"r");for(l=1;fgets(b,999,f);l=0)l?v=strtol(b+3,&e,10),printf(n-80?n-85?"// %d%s":"// %s%s":"%s",n-80?n-85?n-73?v-1:v+1:"":b,n-85?b+2:e):puts(b);}main(){c(73);c(68);c(80);c(85);printf("%d\n",v);} ``` [Try it online!](https://tio.run/##RY7BSsQwFEX3foUEKol9YVLLOG1C6UpB8A9USpNJ6kBMS1LjYvDXjZkiuDlcHvdynqKTUintdtfsKgojrFDvo7/VIF/atn0TCjtyNp2ZF@3wMDw@PT8MAyCPiDCzx7arhJn0GrCE3AdDhO0YsX3swurX2WJZ1nCjoWIEFn9yq8GONqzP2Pcoa4tjERDfUthSBvxXHD3UfaQVj2XFEeIStrMs77gmfPm8mIn4/hhPDpOzwoea5J/vmwsbtnFPxJ8ZFcdXhyDmQUo/ythxCol@/QI "C (gcc) – Try It Online") ~~Creates~~ Prints the source code the following programs: * `I` increment * `D` decrement * `P` peek * `U` undo [Full Example](https://tio.run/##fVFRT8IwEH7fr2hqMC10MCQKrs69qAmJiT7okxoCXQcNpV3WMTTGv@68VYw8GG/Ll2931919X0W4FKJpBgMUBUfKCL3NJLpwVaZsf3UZWK54zdd88XQO8cLFal52NetK1i14IIih764olalysmC4I/qvmBnKbZLbQhoym91Mb69nM4ZLTLnaZ6FzB5@5Lck6GfJ8KSsHyXYCs5Svk4iuU53oVMeuKrNtQRaU1QnwymqieyN2LNkwoizfj1bMhJMoBThNMUjpZB2HY8@cZwAHLSYcj9I6HMZ1bxhjHGvm07p3Eksa58XWr6NgQ6Gtk@SXwXYHcjc1ahW3IDjY6AkKdyi0QGHi9wNn3lwlN6CCfwSbuTKEvgsyHlEuyNmkxUnk8ZTy/d9xJ3s2mKGa8iBAEKClWimH4LVGvyEwD2VyYw24Mq@UWSJl0MP0zjerHJEfVxGYitr7NJT6Yhu/CwXBR9P0B1cc7eG@hekf4KuP/8OnyPV86Zpw9wU) It is oddly satisfying running this on a machine with a spinning hdd with caching disabled. [Answer] # ARM Thumb machine code, 63 bytes (Note: offset starts at 2 for alignment) ``` 00000002: 0f a3 01 22 00 21 10 e0 0d a3 1a 78 98 5c 70 47 ...".!.....x.\pG 00000012: 0b a3 1a 78 01 3a 99 5c 07 e0 01 24 00 e0 ff 24 ...x.:.\...$...$ 00000022: 07 a3 1a 78 99 5c 21 44 01 32 36 25 5b 1b ae 18 ...x.\!D.26%[... 00000032: 81 55 01 3e 99 5d 81 55 fb d1 42 55 70 47 01 .U.>.].U..BUpG. ``` Commented assembly ``` .syntax unified .arch armv7ve .thumb .globl PEEK, INCR, DECR, UNDO .p2align 2,0 // force 4 byte misalignment. Unscored. nop .globl func .thumb_func // Input: r0: pointer to output buffer, bits[1:0] = 0b10 // Output: written to *r0 // Clobbers: r0-r6 func: // Get address of data (as main code expects) adr r3, data // Initial length movs r2, #1 // Initial value movs r1, #0 // Output the code b .Lwrite_no_len begin: // Input: none // Output: r0 // Clobbers: r0, r2, r3 peek: // Get address of data adr r3, data // Load length ldrb r2, [r3, #0] // Load data[length] ldrb r0, [r3, r2] // Return bx lr // Input: r0: pointer to output buffer, bits[1:0] = 0b10 // Output: written to *r0 // Clobbers: r0-r6 undo: // Get address of data adr r3, data // Load length ldrb r2, [r3, #0] // Decrement length subs r2, #1 // Load new value ldrb r1, [r3, r2] // Output the code b .Lwrite_no_len // Input: r0: pointer to output buffer, bits[1:0] = 0b10 // Output: written to *r0 // Clobbers: r0-r6 incr: // Value to add movs r4, #1 // Jump to the common code for incr and decr b .Lnext // Input: r0: pointer to output buffer, bits[1:0] = 0b10 // Output: written to *r0 // Clobbers: r0-r6 decr: // Value to add (I use 8-bit arith so 0xFF == -1) movs r4, #0xFF .Lnext: // Get address of length adr r3, data // Load length ldrb r2, [r3] // Load data[length] ldrb r1, [r3, r2] // Add either 1 or 0xFF to the value add r1, r4 // Increment length adds r2, #1 // func and undo jump here to skip length calc // expected state: // - r0 = out pointer // - r1 = value // - r2 = length // - r3 = address of length .Lwrite_no_len: // FIXME: awkward // Offset from beginning to data // Save in a register for later // Doesn't work in Clang movs.n r5, #data - begin // Subtract from pointer to get the beginning subs r3, r3, r5 // Add to length adds r6, r5, r2 // Store new value at the end of the stack strb r1, [r0, r6] // memcpy loop .Lloop: subs r6, r6, #1 ldrb r1, [r3, r6] strb r1, [r0, r6] bne .Lloop // Store length since it is overwritten by memcpy strb r2, [r0, r5] // Return bx lr .p2align 2,0 data: // While this value isn't important, it is still read // from in the memcpy loop. .byte 1 end: // stack of values will be added here // helpers for driver, not part of code .section .rodata .globl INCR, DECR, UNDO, PEEK, SIZE INCR: .word incr - begin DECR: .word decr - begin UNDO: .word undo - begin PEEK: .word peek - begin SIZE: .word end - func ``` Note that this assembly file **must be compiled by GAS or GCC**. Clang emits a garbage value for the label arithmetic at `movs.n`. The code must be placed at a 2 bytes aligned, 4 byte misaligned address, and so must all the output pointers. This is a doozy that can probably be optimized a lot. The main issue is that calling functions on ARM doesn't automatically make a call stack like x86, the `lr` register must be saved manually. Additionally, `bl` is a 4 byte instruction so calling a helper function has a 6 byte overhead. This generates code by writing to a pointer. Since self modifying code is pretty tricky, here is a driver for Linux: ``` #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <unistd.h> typedef volatile unsigned char vu8; extern void func(vu8*); // These are helpers in the asm file that mean I don't have to recalculate the lengths. extern const int PEEK, UNDO, INCR, DECR, SIZE; #define MAX_SIZE 4096 // Just calling the function pointer wouldn't work // because the compiler expects me to follow a // calling convention for some reason. // Note that you must compile with -march=armv7-a // (technically v5te+ will work as well) for blx. static int call(vu8 *output, const volatile void *func) { register int inout asm("r0") = (int)output; // ensure Thumb bit register int funcptr asm("r1") = 1 | (int)func; asm( "blx %1" : "+r" (inout), "+r" (funcptr) : : "r2", "r3", "r4", "r5", "r6", "r12", "lr", "cc", "memory" ); return inout; } static vu8 *get_page(void) { // Allocate a read/write page vu8 *ptr = mmap( NULL, MAX_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 ); if (ptr == MAP_FAILED || ptr == NULL) abort(); // fill with UDF #0xDE to make out of bounds jumps crash memset((void *)ptr, 0xDE, MAX_SIZE); // Misalign so the pointer is not 4 byte aligned return ptr + 2; } static void make_exec(vu8 *ptr) { // mark read/exec // No rwx here mprotect((char *)ptr - 2, MAX_SIZE, PROT_READ | PROT_EXEC); // clear instruction cache __builtin___clear_cache((char *)ptr - 2, (char *)ptr - 2 + MAX_SIZE); } static void peek(vu8 *ptr) { int val = call(NULL, ptr + PEEK); printf("%d\n", val); } static vu8 *eval(vu8 *ptr, int func_offset) { vu8 *output = get_page(); call(output, ptr + func_offset); make_exec(output); peek(output); return output; } int main(void) { printf("size: %d\n", SIZE); printf("offsets: %d %d %d %d\n", INCR, DECR, UNDO, PEEK); vu8 *A = get_page(); call(A, func); make_exec(A); peek(A); vu8 *B = eval(A, INCR); vu8 *C = eval(B, INCR); vu8 *D = eval(C, INCR); vu8 *E = eval(D, UNDO); vu8 *F = eval(E, UNDO); vu8 *G = eval(F, DECR); peek(F); } ``` The functions all use the same calling convention except for `peek` which follows AAPCS. The input is `r0`, which is a pointer that is 2 byte aligned and 4 byte misaligned. The function will be written to this pointer. The function clobbers r0-r6, which is not AAPCS compliant. The way the code works is it replicates itself by literally reading itself, followed by a length, then a stack of values. ``` code length values.... ``` Each time a new value is added, the new value is appended and the length is incremented. When undo is called, the length is decremented. The length and the values are all 8-bit integers, so this can only store up to 254 values (the stack is 1-indexed because of the length byte) Currently, the functions will be stored at the following offsets in the output buffer. When calling these, remember that the lowest bit must be set as these are Thumb functions. * `peek`: 0 * `undo`: 8 * `incr`: 18 * `decr`: 22 [Answer] # [sclin](https://github.com/molarmanful/sclin), 64 bytes ``` 0. ,`">S form"map c><"dup "["1+""1-"\pop2*`"end"].".\n"g@"++"4*# ``` [Try it here!](https://replit.com/@molarmanful/try-sclin) Returns `[ inc dec undo peek ]`. For testing/convenience purposes, the following snippet: ``` ; ."\n"++ n>< n>o ``` will output each code on separate lines for easy copy-pasting. For example, running the initial code with the snippet: ``` ; ."\n"++ n>< n>o 0. ,`">S form"map c><"dup "["1+""1-"\pop2*`"end"].".\n"g@"++"4*# ``` outputs: ``` "0"dup 1+. ,`">S form"map c><"dup "["1+""1-"\pop2*`"end"].".\n"g@"++"4*# "0"dup 1-. ,`">S form"map c><"dup "["1+""1-"\pop2*`"end"].".\n"g@"++"4*# "0"dup pop pop. ,`">S form"map c><"dup "["1+""1-"\pop2*`"end"].".\n"g@"++"4*# "0"dup end. ,`">S form"map c><"dup "["1+""1-"\pop2*`"end"].".\n"g@"++"4*# ``` Running `inc`: ``` ; ."\n"++ n>< n>o "0"dup 1+. ,`">S form"map c><"dup "["1+""1-"\pop2*`"end"].".\n"g@"++"4*# ``` outputs: ``` "0""1"dup 1+. ,`">S form"map c><"dup "["1+""1-"\pop2*`"end"].".\n"g@"++"4*# "0""1"dup 1-. ,`">S form"map c><"dup "["1+""1-"\pop2*`"end"].".\n"g@"++"4*# "0""1"dup pop pop. ,`">S form"map c><"dup "["1+""1-"\pop2*`"end"].".\n"g@"++"4*# "0""1"dup end. ,`">S form"map c><"dup "["1+""1-"\pop2*`"end"].".\n"g@"++"4*# ``` ## Explanation Somewhat prettified code: ``` 0. ,` ( >S form ) map c>< "dup " [ "1+" "1-" \pop 2*` "end" ] .".\n" g@ \++ 4*# ``` This solution takes advantage of the stack to trivialize the history functionality; for example, undo becomes a simple matter of popping the stack. * `,` ( >S form ) map c><` serializes the stack into a series of formatted number strings. This is because sclin constructs negative numbers as `1_` but string-formats numbers as `-1`; luckily, sclin can perform arithmetic on number strings. * `"dup "` is code for "new item in history" (which, in this case, is simply duplicating the top of the stack). * `[ "1+" "1-" \pop 2*` "end" ]` are the core `[ inc dec undo peek ]` codes. * `.".\n"` is code for "execute the next line." * `g@` gets the current line as a string, which allows for code generation in subsequent iterations. * `\++ 4*#` vectorized-concatenates all the code pieces to create complete `[ inc dec undo peek ]` codes. A concatenative solution in a concatenative language! ]
[Question] [ Given a word (or any sequence of letters) as input, you must interpolate between each letter such that each adjacent pair of letters in the result is also adjacent on a QWERTY keyboard, as if you typed the input by walking on a giant keyboard. For example, '**yes**' might become '**y**tr**es**', '**cat**' might become '**c**xz**a**wer**t**'. ### Rules: * This is the keyboard format you should use: ``q````w````e````r````t````y````u````i````o````p``  ``a````s````d````f````g````h````j````k````l``   ``z````x````c````v````b````n````m`` Any pair of keys which is touching in this layout is considered adjacent. For instance, 's' and 'e' are ajacent, but 's' and 'r' are not. * The input "word" will consist of any sequence of letters. It will have only letters, so you don't have do deal with special characters. * The input can be in any convenient form: stdin, a string, a list, etc. Letter case does not matter; you can take whatever is more convenient. * The output can be in any convenient form: stdout, a string, a list, etc. Letter case does not matter, and it does not need to be consistent. * Any path across the keyboard is valid, except that you cannot cross the previous letter again before getting to the next letter. For example, '**hi**' could become '**h**j**i**' or '**h**jnbgyu**i**', but not '**h**b*h*u**i**'. * A letter is not ajacent with itself, so '**poll**' cannot become '**poll**'. Instead it would need to become something like '**pol**k**l**'. * No output letters are allowed before or after the word. For example, '**was**' cannot become 'tre**was**' or '**was**dfg'. This is code golf, the shortest answer in bytes wins. [Answer] # [Python 2](https://docs.python.org/2/), 83 bytes ``` lambda s:re.findall('.*?'.join(s),'qwertyuioplkmnjhbvgfcxdsza'*len(s))[0] import re ``` [Try it online!](https://tio.run/##Tcu9DsIgFEDhvU/BdqExxDiaGB9EHWgBoV5@BLTiy6MuhvFLzom1mOB3TR/ODYWbpCB5nxTX1kuBSIGPR@BLsJ5mtoH7qlKpDxsi3pxfzPS86vkl81vAiOrXsNP2MlgXQyokqRaT9YVoClVlYMOfsyg9je0VA2LvVXzf9gE "Python 2 – Try It Online") Walks the entire keyboard until the word is written. [Answer] # [Python 2](https://docs.python.org/2/) + [NetworkX](https://networkx.org), 274 bytes (optimal solution) # ~~296~~ ~~300~~ ~~302~~ ~~308~~ ~~315~~ ~~319~~ ~~324~~ ~~327~~ ~~328~~ ~~430~~ ~~432~~ bytes -4 bytes thanks to mypetlion ``` from networkx import* i=input() M,z='qwertyuiop asdfghjkl zxcvbnm'.center(55),i[:1] G=from_edgelist([(M[e],M[e+h])for h in[-1,1,11,12,-11,-12]for e in range(44)if' '!=M[e]and' '!=M[e+h]]) for y,x in zip(i,i[1:]):z+=[shortest_path(G,y,x)[1:],list(G[y])[0]+y][x==y] print z ``` [Try it online!](https://tio.run/##NU/BbsMgDL3nK7wTsJBpidpLJM459QsQqrKGNLQJMELWwM9nMGmy/WzpPT3bNvjJ6OY4RmcW0NK/jHvuoBZrnH8vFFPabh6T4kIjQ98v6XzYlLEA/TqM9@nxnAEg7refL72gj5vUXjp8PhOqeFuLomPZ@CqHu5zV6jHHFy4FTVBOgozGwQRK86qmKVI2tEqtqhuROZk4cL2@S3w6ETUiQG8sG/R6@J@TjyBFVge6Z31UFqu0vm4FaWPJ@DqlX@Tqr7b3E@5o0pHM0r@LOh4E4Z@iDILvjAVRWKe0h3gcHFlEAW2IopiHBGhOJVOtSPwC "Python 2 – Try It Online") This solution gives the shortest possible output. The keyboard is transformed into a graph used to find the shortest path to compute the output string: ``` puzzles --> poiuhbvcxzazxcvbhjklkiuytres programming --> poiuytrtyuioijhgtresasdcvbnmkmkijnbg code --> cvbhjioijhgfde golf --> ghjiolkjhgf yes --> ytres hi --> hji poll --> polpl ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) `-g`, 23 bytes ``` ;D·ÎÔ+D·Årí)pUl)fUq".*? ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=O0S3ztQrRLfFcu0pcFVsKWZVcSIuKj8=&input=WyJQIiJPIiJMIiJMIl0KLWc=) Takes input as an array of capital letters. Very similar to the other answers otherwise. Explanation: ``` ; :Set D to the keyboard layout D·Î :Get the first row of keys Ô :Reversed + :Concat D·Å :The other two rows rí) :Interleaved p :Repeat that string Ul) : A number of times equal to the length of the input f :Get the substrings that match U : The input q".*? : joined with ".*?" :Implicitly output just one of the matches ``` [Answer] # JavaScript (ES6), 70 bytes Same strategy as TFeld. ``` s=>'qazsxdcfvgbhnjmklpoiuytrew'.repeat(s.length).match(s.join`.*?`)[0] ``` [Try it online!](https://tio.run/##dclBDsIgEADAux8BTNz4gepDmiZd6UJByiJgtX4e9a7HyXhcsejsUj1EnqiZrpXuJG74Ks9Jm9Ve5uiXa0js7lvN9BCQKRFWWSBQtHVWsGDV88eeXRxhfx5Vfxya5lg4EAS20sgeAITGKgaldj9qo/KvEofwvfYG "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes ``` ≔”&⌈″⌊5EWXVNa…-εW¶ζR”η≔⌕η§θ⁰ζFθF⊕﹪⁻⌕ηιζ²⁶«§ηζ≦⊕ζ ``` [Try it online!](https://tio.run/##TY2xDoIwGIRneIqGqU1qYhxcnFhMGEh8hdoWWi1/oS2IGJ@9IqJxuuHuvo8r5rhlJsbce10DzrqbdOHea9uaa3MBda6HiovRTyyjSJFDug6PGgRWFOWhACFH3FG0JYSiaZ5U1iHcEbRkAdzJRkKQApdW9MbiUkPvfwS9vCja7Qkh6JEmJ6ch4C9YvdsZmpSsXd1/yI/wGWNrjYmbwbwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔”&⌈″⌊5EWXVNa…-εW¶ζR”η ``` Get the string `qwertyuioplkmjnhbgvfcdxsza`. ``` ≔⌕η§θ⁰ζ ``` Find the position of the first character of the word. This index is normally one past the character just reached, but this value fakes out the first iteration of the loop to print the first character of the word. ``` Fθ ``` Loop over each character. ``` F⊕﹪⁻⌕ηιζ²⁶« ``` Compute how many characters to print to include the next character of the word and loop that many times. ``` §ηζ≦⊕ζ ``` Print the next character cyclically indexed and increment the index. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~43~~ ~~33~~ 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ü2εUžV`.ιJsRìD«Œ.ΔнÅ?XyθÅ¿}¨}JIθ« ``` Not the right language for this challenge, since it cannot use regex like the other answers did.. EDIT: proven wrong by [*@Makonede*'s 05AB1E answer using the Elixir eval builtin `.E`](https://codegolf.stackexchange.com/a/241815/52210). [Try it online](https://tio.run/##AToAxf9vc2FiaWX//8O8Ms61VcW@VmAuzrlKc1LDrETCq8WSLs6Uw4EywqNSWFF9wqh9SknOuMKr//9wb2xs) or [verify all test cases](https://tio.run/##AVUAqv9vc2FiaWX/fHZ5PyIg4oaSICI/ef/DvDLOtVXFvlZgLs65SnNSw6xEwqvFki7OlMOBMsKjUlhRfcKofUp5zrjCq/8s/2hpCnBvbGwKd2FzCmNhdAph). **Explanation:** ``` ü2 # Split the input into overlapping pairs # i.e. "poll" → ["po","ol","ll"] ε # Map each to: U # Pop and store the current pair in variable `X` žV # Push ["qwertyuiop","asdfghjkl","zxcvbnm"] ` # Pop and push all three separated to the stack .ι # Interweave the top two with each other J # Join the list of characters to a single string # → "azsxdcfvgbhnjmkl" s # Swap so "qwertyuiop" is at the top R # Reverse it to "poiuytrewq" ì # Prepend it in front of the earlier string # → "poiuytrewqazsxdcfvgbhnjmkl" D« # Duplicate it, and append it to itself # → "poiuytrewqazsxdcfvgbhnjmklpoiuytrewqazsxdcfvgbhnjmkl" Œ # Get all substrings of this strings .Δ # Find the first substring which is truthy for: Á # Rotate the current string once towards the right 2£ # Only leave the first 2 letters R # Reverse it XQ # Check if it's equal to pair `X` }¨ # After the find_first, remove the last character } # Close the map J # Join everything together Iθ« # Append the last character of the input # (after which the result is output implicitly) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~51~~ ~~39~~ 38 bytes *-1 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).* ``` gžV`.ιJsRì×s….*?ý’R޽™«.‡Ð~r/ÿ/,"ÿ"’.E ``` [Try it online!](https://tio.run/##yy9OTMpM/f8//ei@sAS9czu9ioMOrzk8vfhRwzI9LfvDex81zAw6uvfQ3kctiw6t1nvUsPDwhLoi/cP79XWUDu9XAsrquf7/H61UoKSjoJQPInIgRCwA "05AB1E – Try It Online") Takes input as a list of lowercase letters and outputs as a singleton list. This answer exists to [prove Kevin Cruijssen wrong](https://codegolf.stackexchange.com/a/177134); you *can* use regex in 05AB1E. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes ``` Lk•÷Y$Ṙp*?‛€?jẎh ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiTGvigKLDt1kk4bmYcCo/4oCb4oKsP2rhuo5oIiwiIiwieWVzXG5jYXRcbmhpXG5wb2xsXG53YXMiXQ==) ``` Lk•÷Y$Ṙp*?‛€?jẎh k• # List of rows on the keyboard: ["qwertyuiop", "asdfghjkl", "zxcvbnm"] ÷ # Push each item onto the stack Y # Interleave the top two: "azsxdcfvgbhnjmkl" $ # Swap so "qwertyuiop" is on top Ṙ # Reverse it p # Prepend it to the other string L * # Repeat it input-length number of times ?‛€?j # Join each character in the input by ".*?" Ẏh # Get the first regex match ``` [Answer] # [J-uby](https://github.com/cyoce/J-uby), 71 bytes Again lost a few bytes by having to call `Regexp.new` with a string instead of using a Regexp literal with interpolation. Same technique as [TField](https://codegolf.stackexchange.com/a/177097/11261) et al. ``` -[:+@|:*&"qazsxdcfvgbhnjmklpoiuytrew",~:join&".*?"|:new&Regexp]|:<<&:[] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWN911o620HWqstNSUChOriitSktPK0pMy8rJys3MK8jNLK0uKUsuVdOqssvIz89SU9LTslWqs8lLL1YJS01MrCmJrrGxs1KyiY6HG-RSUlhQruEVHKyUr6SgoJYKIEqXYWC64eCVIKBVEFKOIF4CE8kFEDoSIhZq5YAGEBgA) ## Explanation ``` -[ :+@ | :* & "qazsxdcfvgbhnjmklpoiuytrew", # Repeat string times size of input ~:join & ".*?" | :new&Regexp # Also make a Regexp by joining input with ".*?" ] | # then :<< & :[] # call :[] with the two values, i.e. repeated_string[regexp] ``` ]
[Question] [ Write the shortest code measured by byte count to generate an ASCII grid composed of rhombi, given the following parameters: * m - number of complete rhombi in one row * n - number of rows * s - side of the smallest rhombus * r - level of nesting - how many rhombi are there inside the "base ones" (which are fonud between the intersections of the grid) ## Examples ``` 1. Input: 5 3 1 0 Output: /\/\/\/\/\ \/\/\/\/\/ /\/\/\/\/\ \/\/\/\/\/ /\/\/\/\/\ \/\/\/\/\/ A 5x3 grid of rhombi with side 1, no nesting 2. Input: 3 2 2 0 Output: /\ /\ /\ / \/ \/ \ \ /\ /\ / \/ \/ \/ /\ /\ /\ / \/ \/ \ \ /\ /\ / \/ \/ \/ A 3x2 grid of rhombi with side 2, no nesting 3. Input: 5 2 1 2 Output: ///\\\///\\\///\\\///\\\///\\\ ///\\\///\\\///\\\///\\\///\\\ ///\\\///\\\///\\\///\\\///\\\ \\\///\\\///\\\///\\\///\\\/// \\\///\\\///\\\///\\\///\\\/// \\\///\\\///\\\///\\\///\\\/// ///\\\///\\\///\\\///\\\///\\\ ///\\\///\\\///\\\///\\\///\\\ ///\\\///\\\///\\\///\\\///\\\ \\\///\\\///\\\///\\\///\\\/// \\\///\\\///\\\///\\\///\\\/// \\\///\\\///\\\///\\\///\\\/// A 5x2 grid of rhombi with side 1 (the smallest rhombus), level of nesting is 2 4. Input: 4 2 2 1 Output: //\\ //\\ //\\ //\\ ///\\\///\\\///\\\///\\\ // \\// \\// \\// \\ \\ //\\ //\\ //\\ // \\\///\\\///\\\///\\\/// \\// \\// \\// \\// //\\ //\\ //\\ //\\ ///\\\///\\\///\\\///\\\ // \\// \\// \\// \\ \\ //\\ //\\ //\\ // \\\///\\\///\\\///\\\/// \\// \\// \\// \\// A 4x2 grid of rhombi with side 2 with level of nesting 1 5. Input: 4 2 3 3 Output: ////\\\\ ////\\\\ ////\\\\ ////\\\\ /////\\\\\ /////\\\\\ /////\\\\\ /////\\\\\ //////\\\\\\//////\\\\\\//////\\\\\\//////\\\\\\ //////\\\\\\//////\\\\\\//////\\\\\\//////\\\\\\ ///// \\\\\///// \\\\\///// \\\\\///// \\\\\ //// \\\\//// \\\\//// \\\\//// \\\\ \\\\ ////\\\\ ////\\\\ ////\\\\ //// \\\\\ /////\\\\\ /////\\\\\ /////\\\\\ ///// \\\\\\//////\\\\\\//////\\\\\\//////\\\\\\////// \\\\\\//////\\\\\\//////\\\\\\//////\\\\\\////// \\\\\///// \\\\\///// \\\\\///// \\\\\///// \\\\//// \\\\//// \\\\//// \\\\//// ////\\\\ ////\\\\ ////\\\\ ////\\\\ /////\\\\\ /////\\\\\ /////\\\\\ /////\\\\\ //////\\\\\\//////\\\\\\//////\\\\\\//////\\\\\\ //////\\\\\\//////\\\\\\//////\\\\\\//////\\\\\\ ///// \\\\\///// \\\\\///// \\\\\///// \\\\\ //// \\\\//// \\\\//// \\\\//// \\\\ \\\\ ////\\\\ ////\\\\ ////\\\\ //// \\\\\ /////\\\\\ /////\\\\\ /////\\\\\ ///// \\\\\\//////\\\\\\//////\\\\\\//////\\\\\\////// \\\\\\//////\\\\\\//////\\\\\\//////\\\\\\////// \\\\\///// \\\\\///// \\\\\///// \\\\\///// \\\\//// \\\\//// \\\\//// \\\\//// A 4x2 grid of rhombi with side 3, level of nesting 3 ``` Be sure to display the partially visible rhombi at the edges and corners where necessary. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 20 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ā.I∫e+H╚╬8}:±№╬8╬¡∙* ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTAxLkkldTIyMkJlK0gldTI1NUEldTI1NkM4JTdEJTNBJUIxJXUyMTE2JXUyNTZDOCV1MjU2QyVBMSV1MjIxOSo_,inputs=MyUwQTMlMEEyJTBBNA__) Takes the input in the reversed order of what they are in the examples - r, s, n, m. Explanation: ``` ā push an empty array - canvas .I∫ } for each in range(input) (1-indexed) e+ add the second input H decrement ╚ create a diagonal of that size ╬8 insert into the canvas : create a duplicate of the canvas ±№ reverse it vertically and horizotally ╬8 insert that into the canvas ╬¡ quad-palindromize ∙ multiply vertically by the next input * multiply horizontally by the next input ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~48~~ ~~39~~ 37 bytes ``` UO⊕Iε\F⊖IζC¹¦¹‖ML≔⊗⁺IζIεδF⊖NCδ⁰F⊖NC⁰δ ``` [Try it online!](https://tio.run/##jY07C8IwFIV3f0XodAMRWnHSSdql4AvnLm16@4A0KTeJoH8@BqEO4iB3OVy@cz451CRNrUK4NMroHkotCSfUDlvIa@sAORcsqaqE71edIQYFfhFPzjnLzfyATLAsYjfsFEp3GokMwe4YXwdrx15DYXyjYu@qvF3Kgi2eGNtfllLP3p391CDBx9UKlv4Np@/lELZsEy8L67t6AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` UO⊕Iε\ ``` Draw a square of size `r + 1`. This is a quarter of a nested diamond of size 1. ``` F⊖IζC¹¦¹ ``` Copy the square 1 square right and down `s - 1` times to get it to the right size. ``` ‖ML ``` Reflect it to become a full nested diamond. ``` ≔⊗⁺IζIεδ ``` Compute the size of this nested diamond. ``` F⊖NCδ⁰ ``` Copy the diamond to the right `m - 1` times. ``` F⊖NC⁰δ ``` Copy the diamond downwards `n - 1` times. [Answer] # [Python 2](https://docs.python.org/2/), ~~160~~ ~~159~~ 158 bytes -1 byte thanks to Jonathan Frech ``` m,n,s,r=input() l=~-s*' '+'/'*(r-~r)+~-s*' ' for x in range(n*2):print'\n'.join(m*(l[i:i+s+r]+l.replace(*'/\\')[i:i+s+r][::-1])for i in range(r+s))[::1-x%2*2] ``` [Try it online!](https://tio.run/##RcxNCoMwEEDhvafIpkx@FaOrgCdRF1JsmxLHMLFgN149baG02/fBi8/ttqLNedGok6bOY3xsXBShO0ySwEBBBZKTOUiobyouK7GdeWQ04XXmKK1wkTxuMCCU99UjXyQPvXdeJUWjCiXNMUznmUuohgHEj3rnTD2Kz9H/j6SSEG@qzX6y0o45t9rqRjcv "Python 2 – Try It Online") This uses the fact that the bottom of the rhombus is the top inverted (`[::-1]`), iterating over `range(n*2)` and using `~x%2*2-1` to control if it is the top or the bottom. For the top (and the bottom) the right side is just the left side inverted and replacing `/` with `\` -> `l.replace(*'/\\')..[::-1]` To generate the pattern / nesting `~-s*' '+'/'*(1+r*2)+~-s*' '` is used to make a string like `///` that will be iterated and chopped : ``` '| //|/ ' ' | ///| ' ' |/// | ' ' /|// |' ``` [Answer] # [Julia 0.6](http://julialang.org/), 190 bytes ``` g(n,m,s,r)=(s+=r+1;f(i,j,u=mod(i-j+r,2s),v=mod(j+i+r,2s))=(" \\/")[abs(u-r)<abs(v-r)?1+(u<=2r):1+2(v<=2r)]; for i=1:2(s-1)m println((f(i+(i-1)÷(s-1),s+j+(j-1)÷(s-1))for j=1:2(s-1)n)...)end) ``` This is a functional solution which computes for every index pair `i,j` what the symbol should be displayed. [Try it online!](https://tio.run/##RY5RDoIwEESvQvjazS6YbaIfSONBxA8MYtpAMa3lah7Ag2HBRP/ezO5kxsbBtIdluYPjkQN71BBIe5JjD4YtRz1OHZjCkmcVkOdNWzJfnd7zrGl2OZ7ba4BYeKxXmBOchCDWWnmshBTMG16O/eQzo6VSEArBMXt4456DA0iFlJoE36/txIEsgf0buEbtL@qwLEu8uQ7T/D0rFla4fAA "Julia 0.6 – Try It Online") ### Illustration Start with a grid ``` f(i,j,u=mod(i,2s),v=mod(j,2s))=(" -|*")[1+(u==0)+2(v==0)] for i=1:2(s-1)m println((f(i-1,j)for j=1:2(s-1)n)...)end ---------*---------*---- | | | | | | | | | | | | | | | | | | ---------*---------*---- | | | | | | | | | | ``` `r > 0` means thicker lines ``` f(i,j,u=mod(i+r,2s),v=mod(j+r,2s))=(" -|*")[1+(u<=2r)+2(v<=2r)] for i=1:2(s-1)m println((f(i,j)for j=1:2(s-1)n)...)end **-----*****-----*****-- **-----*****-----*****-- || ||||| ||||| || ||||| ||||| || ||||| ||||| || ||||| ||||| || ||||| ||||| **-----*****-----*****-- **-----*****-----*****-- **-----*****-----*****-- **-----*****-----*****-- **-----*****-----*****-- || ||||| ||||| || ||||| ||||| || ||||| ||||| || ||||| ||||| ``` Handle the corners by checking which line on the original grid is closest ``` f(i,j,u=mod(i+r,2s),v=mod(j+r,2s))=(" -|")[abs(u-r)<abs(v-r)?1+(u<=2r):1+2(v<=2r)] for i=1:2(s-1)m println((f(i,j)for j=1:2(s-1)n)...)end |-------|||-------|||--- ||-----|||||-----|||||-- || ||||| ||||| || ||||| ||||| || ||||| ||||| || ||||| ||||| || ||||| ||||| ||-----|||||-----|||||-- |-------|||-------|||--- ---------|---------|---- |-------|||-------|||--- ||-----|||||-----|||||-- || ||||| ||||| || ||||| ||||| || ||||| ||||| || ||||| ||||| ``` A fairy tells us to remove every `s-1` line ``` f(i,j,u=mod(i+r,2s),v=mod(j+r,2s))=(" -|")[abs(u-r)<abs(v-r)?1+(u<=2r):1+2(v<=2r)] for i=1:2(s-1)m println((f(i+(i-1)÷(s-1),s+j+(j-1)÷(s-1))for j=1:2(s-1)n)...)end ---||------||------||--- --||||----||||----||||-- |||| |||| |||| |||| |||| |||| |||| |||| |||| |||| |||| |||| --||||----||||----||||-- ---||------||------||--- ---||------||------||--- --||||----||||----||||-- |||| |||| |||| |||| |||| |||| |||| |||| |||| |||| |||| |||| --||||----||||----||||-- ---||------||------||--- ``` Traverse diagonally and done ``` f(i,j,u=mod(i-j+r,2s),v=mod(j+i+r,2s))=(" \\/")[abs(u-r)<abs(v-r)?1+(u<=2r):1+2(v<=2r)] for i=1:2(s-1)m println((f(i+(i-1)÷(s-1),s+j+(j-1)÷(s-1))for j=1:2(s-1)n)...)end ///\\\ ///\\\ ///\\\ ////\\\\////\\\\////\\\\ ////\\\\////\\\\////\\\\ /// \\\/// \\\/// \\\ \\\ ///\\\ ///\\\ /// \\\\////\\\\////\\\\//// \\\\////\\\\////\\\\//// \\\/// \\\/// \\\/// ///\\\ ///\\\ ///\\\ ////\\\\////\\\\////\\\\ ////\\\\////\\\\////\\\\ /// \\\/// \\\/// \\\ \\\ ///\\\ ///\\\ /// \\\\////\\\\////\\\\//// \\\\////\\\\////\\\\//// \\\/// \\\/// \\\/// ``` [Answer] ## JavaScript (ES6), 154 bytes ``` f= (m,n,s,r)=>[...Array((s+=r)*n*2)].map((_,i)=>[...Array(s*m*2)].map((_,j)=>i/s&1^j/s&1?`\\ `[g(j%s)]:`/ `[g(s-1-j%s)],g=j=>i%s-j>r|j-i%s>r).join``).join` ` ``` ``` <div oninput=o.textContent=f(+m.value,+n.value,+s.value,+r.value)> m: <input type=number min=0 id=m><br> n: <input type=number min=0 id=n><br> s: <input type=number min=0 id=s><br> r: <input type=number min=0 id=r></div> <pre id=o> ``` Directly calculates the character at each cell of the output. [Answer] # CJam, 44 ``` q~:R+,_ff{-zR>}{_W%:~\+"\ /"f=}%_W%Wf%+*f*N* ``` [Try it online](http://cjam.aditsu.net/#code=q%7E%3AR%2B%2C_ff%7B-zR%3E%7D%7B_W%25%3A%7E%5C%2B%22%5C%20%2F%22f%3D%7D%25_W%25Wf%25%2B*f*N*&input=4%202%203%203) **Explanation:** ``` q~ read and evaluate the input :R+ save the last number in variable R, then add the last 2 numbers (s+r) ,_ make an array [0 1 … s+r-1] and duplicate it ff{…} make a matrix, calculating for each (x,y) pair from the 2 arrays: -z abs(x-y) R> compared with R (1 if greater, 0 if not) {…}% transform each row of the matrix: _W% duplicate and reverse it :~ bitwise-NOT each element (0 → -1, 1 → -2) \+ prepend to the original row "\ /"f= replace numbers with characters from this string (by index): 0 → '\'; 1, -2 → ' '; -1 → '/' this generates the "/\" part _W% duplicate the matrix and reverse the rows Wf%+ reverse each row, then append (by rows) to the original matrix this adds the "\/" part * repeat the matrix (by rows) n times f* repeat each row m times N* join the rows with newlines ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 167 bytes ``` (c,r,s,n)=>{int w=s+n,i=0,j;var g="";for(;i<r*2*w;i++,g+="\n")for(j=0;j<c*2*w;){int y=i%w,q=(j/w+i/w+1)%2,p=~-w*q+j++%w*(1-2*q);g+=p>y+n|p<y-n?' ':"\\/"[q];}return g;} ``` [Try it online!](https://tio.run/##jY8xT8MwEIVn8iusSFHt@EKbhC44DgMSLCBVMDBQhmBCcNQ6je02ikr468GthIRYqE53y/vu6T1hItHoctwaqSr02BtbrpknVoUxaLH3jC2sFOhmq0QmlQX05xir3V@OHj6a9asUt1q@IY5GLECDAUV4vncc6rihCiSfQc12hUYV93323mjMZKbDJOyYpBQqyv2l8slBqPmM1Zk4auTo0XMZdNByXE87Kt3GJEhgw7@iLmxpTWnQhTiOkrAlzDlt8p6qz03WR@pqgiaX/nI59Z/bFzbo0m61QhUbRub9NNw1Lvl9IRUm3t47u26UaVbl@ZOWtryTqsS/GuI5pBDDjBD2H5lC4uYUcu64GJITyIujZ3wimUJ6IAdvGL8B "C# (.NET Core) – Try It Online") I'm surprised by the size I managed; I was initially expecting a longer solution. In saying this, I'm sure there are other tricks I've missed. ### DeGolfed ``` (c,r,s,n)=>{ int w=s+n, // rhombus quadrant width, and height i=0, // string row j; // string column var g=""; // go through every character row and column for(; i < r*2*w; i++, g += "\n") for(j = 0; j < c*2*w;) { int y = i % w, // vertical position in the quadrant q = ( j / w + i / w + 1) % 2, // Get the rhombus quadrant as a 0 or 1 p = ~-w * q + j++ % w * (1-2*q); // horizontal position in quadrant. the value is either ascending or descending depending on the quadrant // select which character to use at this [i,j] position g += p > y + n | p < y - n ? ' ' : "\\/"[q]; } return g; } ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~201~~ 189 bytes ``` def f(m,n,s,r):Z=range(s+r);R=[r-~min(i,s+~i+r,min(s-1,r))for i in Z];L=[m*(' '*(s+~i)+'/'*R[i]+' '*(i-r)+'\\'*R[i]+' '*(s+~i))for i in Z];print'\n'.join((L+[l[s+r:]+l[:s+r]for l in L])*n) ``` [Try it online!](https://tio.run/##VY67DoMgFED3fgUbr2tbtS4a/8DJUWRoUmlpFA24dPHXKZjYpGE5nJzce5fP@ppN5v1jUEiRCQw4sLTsans3z4E4bmnV1sIm26QN0eD4prmF@HFJGlKqZos00gZ1smpqMTGCEWYkhpTjC2at0JJjFKVObHB9/5NH@DdlsdqsuDf4/J7DHtJwMYpwSSn5KMoAMtZjrBtJmaFekQJySOFKT4rkkIW3YxEghSzibbfpgTnk1H8B "Python 2 – Try It Online") Uses the fact that the bottom is the same as the top, but shifted: ``` Top: /\/\/\ Bottom: /\/\/\ ``` Saved 22 bytes thanks to Jonathan Frech [Answer] # Perl 5, 159 + 3 (-anl) bytes ``` ($m,$n,$s,$r)=@F;$s=$"x($s+$r-1);$_="$s/\\$s"x$m;$n*=2;{$t=$_;map$t=~s, ?(\S) ?,$1x$&=~y///c,ge,1..$r;print$t;redo if s, /,/ ,g&&s,\\ , \\,g||y,/\\,\\/,&&--$n} ``` [Try It Online](https://tio.run/##DY3RCoIwGEZf5Uc@htZvS6urMeqqF@h2IFImgs6xeWFUPnrLu8OBw3GN708xphgYlhEYPtOXq0LQSOYUYQufF5lCpRMEaQxCMmNQsBtdqjcmjUoNtVthCUzn1NwyOjOKGUIvLynlnduGi90OXjnf2QmT8s1jpO5JayBZErdCBDaGmIzh9vN58TpahWQh8hz2G@ORSjrQ/je6qRttiHlt@z8) ]
[Question] [ This challenge is similar to [this old one](https://codegolf.stackexchange.com/q/3783/3808), but with some unclear parts of the spec hammered out and less strict I/O requirements. --- Given an input of a string consisting of only printable ASCII and newlines, output its various metrics (byte, word, line count). The metrics that you must output are as follows: * Byte count. Since the input string stays within ASCII, this is also the character count. * Word count. This is `wc`'s definition of a "word:" any sequence of non-whitespace. For example, `abc,def"ghi"` is one "word." * Line count. This is self-explanatory. The input will always contain a trailing newline, which means line count is synonymous with "newline count." There will never be more than a single trailing newline. The output must exactly replicate the default `wc` output (except for the file name): ``` llama@llama:~$ cat /dev/urandom | tr -cd 'A-Za-z \n' | head -90 > example.txt llama@llama:~$ wc example.txt 90 165 5501 example.txt ``` Note that the line count comes first, then word count, and finally byte count. Furthermore, each count must be left-padded with spaces such that they are all the same width. In the above example, `5501` is the "longest" number with 4 digits, so `165` is padded with one space and `90` with two. Finally, the numbers must all be joined into a single string with a space between each number. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win. (Oh, and by the way... you can't use the `wc` command in your answer. In case that wasn't obvious already.) Test cases (`\n` represents a newline; you may optionally require an extra trailing newline as well): ``` "a b c d\n" -> "1 4 8" "a b c d e f\n" -> " 1 6 12" " a b c d e f \n" -> " 1 6 16" "a\nb\nc\nd\n" -> "4 4 8" "a\n\n\nb\nc\nd\n" -> " 6 4 10" "abc123{}[]()...\n" -> " 1 1 16 "\n" -> "1 0 1" " \n" -> "1 0 4" "\n\n\n\n\n" -> "5 0 5" "\n\n\na\nb\n" -> "5 2 7" ``` [Answer] # Perl, 49 bytes Added +3 for `-an0` Input on STDIN or 1 or more filenames as arguments. Run as `perl -an0 wc.pl` `wc.pl`: ``` /\z/g;pos=~//;printf"%@+d %@+d $` ",y/ //,~~@F ``` Explanation: ``` -n0 slurps the whole input into $_ and says we will do our own printing -a tells perl to split the input on whitespace into array @F /\z/g Matches the absolute end of the input. g modifier so the position is remembered in pos which will now contain the input length pos=~// An empy regex repeats the last succesful match, so /\z/ again. After that $` will contain the the number of input characters and the array @+ will contain the length of this number printf All preparation is complete, we can go print the result "%@+d" will become e.g. %6d if the number of characters is a number of length 6, so lines and words will get printed right aligned in a field of length 6. $` $` we can directly interpolate since it won't contain a % y/\n// Count the number of newlines in $_ ~~@F The array of words @F in scalar context gives the number of words ``` [Answer] # Pyth, 21 bytes ``` jdm.[;l`lQ`ld[@bQcQ)Q ``` [Test suite](https://pyth.herokuapp.com/?code=jdm.%5B%3Bl%60lQ%60ld%5B%40bQcQ%29Q&test_suite=1&test_suite_input=%22a+b+c+d%5Cn%22%0A%22a+b+c+d+e+f%5Cn%22%0A%22++a+b+c+d+e+f++%5Cn%22%0A%22a%5Cnb%5Cnc%5Cnd%5Cn%22%0A%22a%5Cn%5Cn%5Cnb%5Cnc%5Cnd%5Cn%22%0A%22abc123%7B%7D%5B%5D%28%29...%5Cn%22%0A%22%5Cn%22%0A%22+++%5Cn%22%0A%22%5Cn%5Cn%5Cn%5Cn%5Cn%22%0A%22%5Cn%5Cn%5Cna%5Cnb%5Cn%22&debug=0) Pyth has some very nice built-ins here. We start by making a list (`[`) of the newlines in the string (`@bQ`), the words in the string (`cQ)`) and the string itself (`Q`). Then, we pad (`.[`) the length of each string (`ld`) with spaces (`;` in this context) out to the length of the number of characters (`l`lQ`). Finally, join on spaces (`jd`). [Answer] # Python 2, ~~100~~ 77 bytes This solution is a Python function that accepts a multi-line string and prints the required counts to stdout. Note that I use a format string to build a format string (which requires a `%%` to escape the first format placeholder). *Edit: Saved 23 bytes due to print optimisations by Dennis.* ``` def d(b):c=len(b);a='%%%us'%len(`c`);print a%b.count('\n'),a%len(b.split()),c ``` Before the minifier, it looks like this: ``` def wc(text) : size = len(text); numfmt = '%%%us' % len(`size`); print numfmt % text.count('\n'), numfmt % len(text.split()), size ``` [Answer] # POSIX awk, 79 75 67 65 bytes ``` {w+=NF;c+=length+1}END{d=length(c)"d %";printf"%"d d"d\n",NR,w,c} ``` Edit: saved 4 bytes since POSIX allows a bare `length`, saved 7 bytes by discounting the invocation part, and saved two bytes thanks to Doorknob's tip for adding `d %` to `d`. This was originally for GNU awk, but best I can tell, it uses only POSIX awk functionality. Better formatted: ``` gawk '{ w += NF c += length($0) + 1 # length($0) misses the newline } END { d = length(c) # GNU awk's length returns the length of string representation of number printf "%"d"d %"d"d %d\n", NR, w, c }' ``` [Answer] ## [Seriously](https://github.com/Mego/Seriously), 39 bytes ``` " "╩╜l;$l╝@╜sl' ╜ck`#╛#"{:>%d}"%f`M' j ``` [Try it online!](http://seriously.tryitonline.net/#code=IgogIuKVqeKVnGw7JGzilZ1A4pWcc2wnCuKVnGNrYCPilZsjIns6PiVkfSIlZmBNJyBq&input=ImFiYzEyM3t9W10oKS4uLlxuIg) Explanation (newlines are replaced with `\n`): ``` "\n "╩╜l;$l╝@╜sl'\n╜ck`#╛#"{:>%d}"%f`M' j "\n " push a string containing a newline and a space ╩ push input to register 0 (we'll call it s) ╜l; push two copies of len(s) (byte count) $l╝ push len(str(len(s))) to register 1 (this will serve as the field width in the output) @╜sl push word count by getting the length of the list formed by splitting s on spaces and newlines '\n╜c count newlines in input k push stack to list `#╛#"{:>%d}"%f`M map: # listify ╛# push reg 1 (field width), listify "{:>%d}" push that string % do old-style string formatting for field width f do new-style string formatting to pad the field appropriately ' j join on spaces ``` [Answer] # AppleScript, 253 bytes This assumes that AppleScript's text item delimiters are set to space (if I need to count the stuff to force that assumption, I'll add it). ``` set w to(display dialog""default answer"")'s text returned set x to b(w) set y to w's text item's number set z to w's paragraph's number a(x,z)&z&a(x,y)&y&" "&x on a(x,n) set o to" " repeat b(x)-b(n) set o to o&" " end o end on b(n) count(n as text) end ``` [Answer] # CJam, ~~31~~ 26 bytes ``` q_)/_S*S%@_]:,:s),f{Se[}S* ``` [Try it online!](http://cjam.tryitonline.net/#code=cV8pL19TKlMlQF9dOiw6cyksZntTZVt9Uyo&input=YWJjMTIze31bXSgpLi4uCg) ### How it works ``` q_ e# Read all input from STDIN and push two copies. ) e# Pop the last character (linefeed) of the second copy. / e# Split the remaining string at linefeeds. _ e# Push a copy. S* e# Join the copy, separating by spaces. S% e# Split at runs of spaces. @_ e# Rotate the original input on top and push a copy. ] e# Wrap all four items in an array. :, e# Get the length of each item. :s e# Cast the lengths (integers) to strings. ) e# Pop the last length (byte count). , e# Get the number of digits. f{Se[} e# Left-pad all three length with spaces to that length. S* e# Join, separating by spaces. ``` [Answer] # Julia, ~~112~~ 81 bytes ``` f(s,n=endof,l="$(n(s))",g=r->lpad(n(split(s,r))-1,n(l)))=g(r"\n")" "g(r"\S+")" "l ``` This is a function that accepts a string and returns a string. We save the following as function arguments: * `n = endof` function, which gets the last index of an indexable collection (in this case is the length of the string) * `l = "$(n(s))`, the length of the input converted to a string using interpolation * A lambda function `g` that accepts a regular expression and returns the length - 1 of the input split on that regex, left padded with spaces to match the length of `l`. We get the number of lines using `g(r"\n")` and the number of words using `g(r"\S+")`, then we join those together with `l` delimited by spaces. Saved 31 bytes thanks to Dennis! [Answer] # MATL, 38 bytes ``` '\n'32cZtttnGnw-wPZvPYbnqbnvvV!3Z"vX:! ``` You can [try it online!](http://matl.tryitonline.net/#code=J1xuJzMyY1p0dHRuR253LXdQWnZQWWJucWJudnZWITNaInZYOiE&input=JyAgYSBiIGMgZCBlIGYgIFxuJw) This shouldn't be so long though... Explanation, for the calculation, ``` '\n'32cZt %// Takes implicit input and replaces any \n with a space tt %// Duplicate that string twice nGnw-w %// Length of the string with \n's minus length with spaces to give number of \n's PZvPYbnq %// Take string with spaces, flip it, remove leading spaces, flip it again, %// split on spaces, find length and decrement for number of words bn %// get length of string with spaces, the number of characters ``` The last part does the output formatting ``` vvV! %// concatenate the 3 numbers to a column vector, convert to string and transpose 3Z"v %// make string ' ' and concatenate on the bottom of previous string X:! %// linearise and transpose to get correct output (impicitly printed) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` »⁶Ḳ¹ƇLṭċ⁷$;LWG ``` [Try it online!](https://tio.run/##ATcAyP9qZWxsef//wrvigbbhuLLCucaHTOG5rcSL4oG3JDtMV0f///8iICBhIGIgYyBkIGUgZiAgXG4i "Jelly – Try It Online") -1 thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis). [Answer] ## JavaScript (ES6), 115 bytes ``` s=>[/\n\/g,/\S+/g,/[^]/g].map(r=>l=(s.match(r)||[]).length).map(n=>(' '.repeat(99)+n).slice(-`${l}`.length)).join` ` ``` Does not require any input. Formatting was painful. If there was an upper limit on the amount of padding I could reduce `(' '.repeat(99)+n)` to something shorter e.g. `` ${n}``. [Answer] ## PowerShell, 140 bytes ``` param($a)$c="$((($l=($a-split"`n").Count-1),($w=($a-split"\S+").Count-1),($b=$a.length)|sort)[-1])".Length; "{0,$c} {1,$c} {2,$c}"-f$l,$w,$b ``` (newline left in for clarity :D) The first line takes input `$a`, and then the next part is all one statement. We're setting `$c` equal to *some-string's* `.length`. This will form our requisite padding. Inside the string is an immediate code block `$(...)`, so that code will be executed before evaluated into the string. In the code block, we're sending three items through the `|sort` command, and then taking the biggest one `(...)[-1]`. This is where we're ensuring to get the columns to the correct width. The three items are `$l` the line count, where we `-split` on newlines, the `$w` word count, where we `-split` on whitespace, and `$b` the length. The second line is our output using the `-f` operator (which is a pseudo-shorthand for `String.Format()`). It's another way of inserting expanded variables into strings. Here, we're saying that we want all of the output to be padded to the left so that each column is `$c` wide. The padding is done via spaces. The `0`, `1`, and `2` correspond to the `$l`, `$w`, and `$b` that are arguments to the format operator, so the line count, word count, and byte count are padded and output appropriately. Note that this either requires the string to have already-expanded newlines (e.g., doing a `Get-Content` on a text file or something, and then either piping or saving that to a variable, then calling this code on that input), or use the PowerShell-styled escape characters with backticks (meaning ``n` instead of `\n`). **Example** ``` PS C:\Tools\Scripts\golfing> .\reimplement-wc.ps1 "This line`nis broken`ninto three lines.`n" 3 7 38 ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-s`, 25 bytes ``` sX##a-#_._M[nNa`\S+`Na#a] ``` Takes the multiline string as a command-line argument. [Try it online!](https://tio.run/##K8gs@P@/OEJZOVFXOV4v3jc6zy8xISZYO8EvUTkx9v///7rF/xO5uLiSuJK5UrgA "Pip – Try It Online") *Thanks to [Dennis's CJam answer](https://codegolf.stackexchange.com/a/74227/16766) for making me realize that the longest number is always the character count.* ### Explanation ``` s is space; n is newline; a is 1st cmdline arg (implicit) [ ] Construct a list of three elements: nNa Number of newlines in a `\S+`Na Regex search: number of runs of non-whitespace characters in a #a Length of a (i.e. number of characters in a) M To each element of that list, map this function: #a Number of characters in a # Length of that number -#_ Subtract length of each element sX Construct a string of that many spaces ._ Prepend it to the element The resulting list is autoprinted, space-separated (-s flag) ``` --- Here's a 29-byte solution with flags `-rs` that takes input from stdin: ``` [#g`\S+`NST:gY#g+1]MsX#y-#_._ ``` [Try it online!](https://tio.run/##K8gs@P8/Wjk9ISZYO8EvOMQqPVI5Xdsw1rc4QrlSVzleL/7//0QuLq4krmSuFIVUrv@6RcUA "Pip – Try It Online") [Answer] # Powershell, ~~123~~ 115 bytes ``` switch -r($args|% t*y){'\s'{$a=0}'\S'{$w+=!$a;$a=1}'(?s).'{$b++}' '{$l++}}$c="$b".Length "{0,$c} {1,$c} $b"-f$l,+$w ``` Test script: ``` $f = { switch -r($args|% t*y){ # evaluate all matched cases '\s' {$a=0} # any whitespace (newline not included) '\S' {$w+=!$a;$a=1} # any not-whitespace (newline not included) '(?s).'{$b++} # any char (newline included!) '`n' {$l++} # new line char } $c="$b".Length "{0,$c} {1,$c} $b"-f$l,+$w } @( , ("a b c d`n", "1 4 8") , ("a b c d e f`n", " 1 6 12") , (" a b c d e f `n", " 1 6 16") , ("a`nb`nc`nd`n", "4 4 8") , ("a`n`n`nb`nc`nd`n", " 6 4 10") , ("abc123{}[]()...`n", " 1 1 16") , ("`n", "1 0 1") , (" `n", "1 0 4") , ("`n`n`n`n`n", "5 0 5") , ("`n`n`na`nb`n", "5 2 7") ) | % { $s,$e = $_ $r = &$f $s "$($e-eq$r): $r" } ``` Output: ``` True: 1 4 8 True: 1 6 12 True: 1 6 16 True: 4 4 8 True: 6 4 10 True: 1 1 16 True: 1 0 1 True: 1 0 4 True: 5 0 5 True: 5 2 7 ``` Explanation: * `$args|% t*y` splits arument strings into chars * `switch -r($args|% t*y)` evaluate *all matched cases* + `'\s'` case for any whitespace + `'\S'` case for any non-whitespace + `'(?s).'` case for any char (newline included) + `'\n'` case for newline char (newline represent itself) * `$c="$b".Length` calculate a length of bytes number. $b is always max($l,$w,$b) by design * `"{0,$c} {1,$c} $b"-f$l,+$w` format numbers with same length. The variable $w converts to int. It need for strings without words. Other variables formats 'as is' because 'The input will always contain a trailing newline' and $l and $b cannot be 0. [Answer] ## Pascal, 248 bytes This complete `program` requires a processor supporting “Extended Pascal” as defined by ISO standard 10206. * The variable `input` possesses the built-in data type `text`. As such any newline character (sometimes it’s CR, sometimes LF, sometimes CR+LF, or something else) is *automagically* converted into a single space character (`' '`). In order to distinguish from a space character as *payload* of a line, and a space character that resulted from this conversion, you will need to query the function `EOLn`. * A `text` variable is conceptually similar to a `file of char`. This `program` in fact counts *characters*, i. e. actually behaves like `wc ‑m`. However, since the task states that characters strictly draw from the ASCII character set, there is no difference. ``` program c(input,output);var l,w,c,z:integer value 0;p:char;begin p:=' ';while not EOF do begin c:=c+1;l:=l+ord(EOLn);w:=w+card([p]*[' ',' ']-[input^]);p:=input^;get(input)end;z:=trunc(ln(card([0..l,0..w,0..c]))/ln(10))+2;writeLn(l:z-1,w:z,c:z)end. ``` Ungolfed and annotated version: ``` { By listing a `program` parameter of the spelling `input`, there’s an implicit `reset(input)` which implies a `get(input)`. } program wordCount(input, output); var { `line`, `word` and `character` are singular, because they kind of enumerate these units as if input was a zero-based `array`. } line, word, character, width: integer value 0; previousCharacter: char; begin { This program counts “word beginnings” as words. This is the _change_ from “space character” _to_ “non-space character”. } previousCharacter := ' '; while not EOF(input) do begin character := character + 1; { As per POSIX specification a line is payload _plus_ one newline. } line := line + ord(EOLn(input)); { The second character literal is an HT (horizontal tabulator). } word := word + card([previousCharacter] * [' ', ' '] - [input^]); { Prepare `previousCharacter` for _next_ iteration. } previousCharacter := input^; { Advance “reading cursor”. } get(input); end; { To produce POSIX-compliant output write: writeLn(line:1, ' ', word:1, ' ', character:1); As per task specification we will determine a common width though. We use ⌊ln(N) / ln(10)⌋ + 1 as the base formula, where N needs to be the largest number from `line`, `word` and `character`. This can be found by the expression |[0, line] ∪ [0, word] ∪ [0, character] ∩ ℤ|. We add another +1 for the space _between_ numbers. } width := trunc(ln(card([0..line, 0..word, 0..character])) / ln(10)) + 2; writeLn(line:width-1, word:width, character:width); end. ``` [Answer] ## Ruby, 108 bytes ``` f=->s{a=[s.count($/),s.split(/\S+/).size-1,s.size].map(&:to_s) a.map{|b|" "*(a.map(&:size).max-b.size)+b}*" "} ``` [Answer] # Perl, ~~71~~ ~~62~~ 61 bytes *includes +1 for `-n`* ``` $;=length($b+=y///c);$w+=split$"}{printf"%$;d %$;d $b",$.,$w ``` Commented: ``` while (<>) { # implicit because of -n $; = length( # printf formatting: width $b += y///c # count characters ); $w += split $" # count words }{ # explicit: end while, begin END block printf "%$;d %$;d $b", $., $w # $. = $INPUT_LINE_NUMBER } # implicit because of -n ``` * Save another byte, again thanks to @TonHospel. * Save 9 bytes thanks to @TonHospel showing me a few tricks of the trade! [Answer] # Lua, ~~74~~ 66 bytes Golfed: ``` t=arg[1]_,l=t:gsub('\n','')_,w=t:gsub('%S+','')print(l,w,t:len()) ``` Ungolfed: ``` text = arg[1] _,lines = text:gsub('\n','') _,words = text:gsub('%S+','') print(lines, words, text:len()) ``` Receives input through command line arguments. We rename the first argument (`arg[1]`) to save bytes. `string.gsub` returns the number of replacements as well as the modified string, so we're using that to count first `'\n'` (newlines), then `'%S+'` (instances of one or more non-whitespace characters, as many as possible, i.e. words). We can use anything we want for the replacement string, so we use the empty string (`''`) to save bytes. Then we just use `string.len` to find the length of the string, i.e. the number of bytes. Then, finally, we print it all. [Answer] # Retina, 65 ``` ^((\S+)|(¶)|.)* $#3 $#2 $.0 +`(\b(.)+ )(?!.*\b(?<-2>.)+$) a$1 a <space> ``` [Try it Online!](http://retina.tryitonline.net/#code=XigoXFMrKXwowrYpfC4pKgokIzMgJCMyICQuMAorYChcYiguKSsgKSg_IS4qXGIoPzwtMj4uKSskKQphJDEKYQog&input=YWEKCgpiIGMgZCBlIGYgZyBoIGkgaiBrCmwKbQo) The first stage is the actual wc program, the rest of it is for padding. The `a` placeholder thing is probably unnecessary, and some of the groups can probably be simplified a bit. [Answer] # Haskell, 140 bytes ``` import Text.Printf w h=let{l=length;s=show.l;c=s h;m=s.words$h;n=s.lines$h;f=maximum$map l[c, m, n];p=printf"%*s"f}in p n++' ':p m++' ':p c ``` The ungolfed version is hereunder, with expanded variable and function names: ``` import Text.Printf wc str = let charcount = show.length $ str wordcount = show.length.words $ str linecount = show.length.lines $ str fieldwidth = maximum $ map length [charcount, wordcount, linecount] printer = printf "%*s" fieldwidth in printer linecount ++ (' ' : printer wordcount ++ (' ' : printer charcount)) ``` This is a function that accepts a string and returns a string. It just uses the `Prelude` functions `words` (resp. `lines`) to get the number of words (resp. lines) given that they seem to use the same definition as `wc`, then gets the longest value (as a string) amongst the counts and use the printf format taking the width amongst its arguments for formatting. [Answer] # C, 180 178 bytes ``` #include <stdio.h> #include <ctype.h> main(b,w,l,c,d){d=' ';b=w=l=0;while((c=fgetc(stdin))!=EOF){if(!isspace(c)&&isspace(d))w++;b++;d=c;if(c==10)l++;}printf("%d %d %d\n",l,w,b);} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~24~~ 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¨¶¡¹… S¡õK¹)€g§Zg>jJ¦ ``` `j` is currently bugged, so could have been 21 bytes without the `§` and `J`.. [Try it online](https://tio.run/##AT4Awf9vc2FiaWX//8KowrbCocK54oCmIAoJU8Khw7VLwrkp4oKsZ8KnWmc@akrCpv//IiIiYQoKCmIKYwpkCiIiIg) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W@f/QikPbDi2sfNSwTIGLM/jQwsNbvSs1HzWtST@0PCrdLsvr0LL/QDmlw/uVdP5HKyUqJCkkK6TE5CnpwNgKqQppYL6CApKIggJETUxeUkxeckxeCowLgihCScmGRsbVtdGxGpp6enpgMahxClAODMI5EFOVYgE). **Explanation:** ``` ¨ # Remove the trailing newline of the (implicit) input ¶¡ # And split it on newlines ¹… S¡ # Take the first input again, and split it on [" \n\t"] õK # Then remove all empty string items ¹ # And take the first input again as is ) # Wrap all three value of the stack to a single list €g # Take the length of each of the items § # Cast the integers to strings (should have been implicit, but `j` is bugged) Z # Take the max (always the last / amount of bytes) (without popping the list) g> # Take the length + 1 of this max j # Append leading spaces so all items or of this length J # Join them together (should have been done by the `j` already, but it's bugged) ¦ # Remove the leading space (and output implicitly to STDOUT) ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-p0`, 79 bytes Includes a trailing space in the output. ``` a=[/ /,/\S+/,/./m].map{$_.scan(_1).size} $_="%#{a.map{_1.to_s.size}.max}d "*3%a ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnm0km6BgVLsgqWlJWm6Fjf9E22j9bn0dfRjgrWBpJ5-bqxebmJBtUq8XnFyYp5GvKGmXnFmVWotl0q8rZKqcnUiWDreUK8kP74YIgUUqahNUVDSMlZNhBgLNX3BqkQuLq4krmSuFC6ICAA) ## [Ruby](https://www.ruby-lang.org/) `-p0`, 84 bytes No trailing space. ``` a=[/ /,/\S+/,/./m].map{$_.scan(_1).size} $_=["%#{a.map{_1.to_s.size}.max}d"]*3*" "%a ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnm0km6BgVLsgqWlJWm6FjdDEm2j9bn0dfRjgrWBpJ5-bqxebmJBtUq8XnFyYp5GvKGmXnFmVWotl0q8bbSSqnJ1Ilg-3lCvJD--GCIHFKmoTVGK1TLWUlJQUk2EmA21YsGqRC4uriSuZK4ULogIAA) ]
[Question] [ Related: [Calculate \$f^n(x)\$](https://codegolf.stackexchange.com/q/137527/78410), [Polynomialception](https://codegolf.stackexchange.com/q/78334/78410) ## Challenge Given a polynomial \$f(x) = a\_0 + a\_1 x + a\_2 x^2 + \cdots + a\_k x^k\$ of order \$k\$, we can compute its composition with itself \$f\left(f(x)\right) = f \circ f(x) =: f^2(x)\$, which evaluates to another polynomial of order \$k^2\$. The challenge is to reverse the process. Assuming \$f(x)\$ is an integer polynomial (\$a\_0, a\_1, \cdots, a\_k \in \mathbb{Z}\$), take the polynomial \$f^2(x)\$ and recover the polynomial \$f(x)\$. This is equivalent to finding a [functional square root](https://en.wikipedia.org/wiki/Functional_square_root) of the given polynomial. The polynomials may be input and output as a list of coefficients (highest-order term going first or last) or a built-in polynomial object. You may assume \$k \ge 1\$, i.e. \$f(x)\$ is not a constant. It is guaranteed that a solution exists. If multiple distinct \$f(x)\$s have the same \$f^2(x)\$, your program may output any nonempty subset of all solutions. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code wins. ## Test cases Coefficient list is given in highest-order-term-first order. ``` Input: x / coefficients: [1, 0] Output: x, -x, or -x + c for any integer c / coefficients: [1, 0] or [-1, c] Input: x + 20 / coefficients: [1, 20] Output: x + 10 / coefficients: [1, 10] Input: 25x - 18 / coefficients: [25, -18] Output: 5x - 3 / coefficients: [5, -3] Input: x^4 - 4x^3 + 8x^2 - 8x + 6 / [1, -4, 8, -8, 6] Output: x^2 - 2x + 3 / [1, -2, 3] Input: -x^4 - 2x^2 - 2 / [-1, 0, -2, 0, -2] Output: -x^2 - 1 / [-1, 0, -1] Input: x^9 + 6x^8 + 21x^7 + 58x^6 + 119x^5 + 194x^4 + 262x^3 + 260x^2 + 201x + 112 / [1, 6, 21, 58, 119, 194, 262, 260, 201, 112] Output: x^3 + 2x^2 + 3x + 4 / [1, 2, 3, 4] Input: x^9 + 6x^8 + 21x^7 + 54x^6 + 103x^5 + 154x^4 + 182x^3 + 160x^2 + 105x + 40 / [1, 6, 21, 54, 103, 154, 182, 160, 105, 40] Output: -x^3 - 2x^2 - 3x - 4 / [-1, -2, -3, -4] Input: x^9 / [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] Output: x^3 or -x^3 / [1, 0, 0, 0] or [-1, 0, 0, 0] ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~638~~ ~~634~~ ~~608~~ ~~603~~ ~~572~~ ~~560~~ ~~508~~ 470 bytes (without brute force as well) Tthanks to @randomdude999 for the golfing down the code by like 100 bytes as well as everyone who has helped point out smaller golfing tricks! ``` from gmpy2 import* R=range r=reduce p=lambda n,i=1:n/i and[l+[i]for l in p(n-i,i)]+p(n,i+1)or[[]][n:] e=lambda f,x:r(lambda y,z:y*x+z,f) def s(g): n=isqrt(len(g));N=n+1;t,_=iroot(abs(g[0]),N) for F in(t,-t): f=[F] for i in R(1,N):f+=[0];f[i]=(g[i]-sum(fac(n)/fac(n-len(j))/r(mul,[fac(j.count(k))for k in R(i+1)])*r(mul,[f[k]for k in j])*F**(N-len(j))for j in p(i))-(i==n)*f[1]*F**~-n)/n/F**n if n<2:f[1]=g[1]/-~F if all(e(f,e(f,i))==e(g,i)for i in R(N*N)):return f ``` [Try it online!](https://tio.run/##dVDBbuMgED3XX8GRsaE23jZKneWaow@9IrRyE@MlsbFLsNT00F/PDmlTZSNVgpnhzbw3M0zH8Hd05elk/DiQbpiOJbHDNPqQJs/SN65rEy99u503bTLJvhletg1xzEpRudySxm1VnymrzehJT6wjE3XcMgs6w4jZTMDoldJauUon7UXBsLfK06/Hkb1Xx/Qte2cGkm1ryIF2UCXESXt49YH2rUMAVrV0mVgF9kdaP46BNi9YqAoNrIaExAnWOAENjAek3xmp1hod4jZO9kwFFlYmk8hZGRxaIt1qfpgHapoNdZCfHY8NdwC5p8PcMxXB3f1mnF2ge4AouP8UjOtpSC91aq@/kzvE12lK64tazOw@f8gCcGqldJAaJXSs@@DY3eUYueTOGuJ@l1XMyQ5Nzj/WZ7Tpe9pSw@JFESlb2mFwtWKd1gCVb8PsHTGnyVsX8D@VYAQ/Krl@l/8B5SMjXCxvavgDI0t0eBfXKR71EC@/3A1tgeroHpEmxBOaJ9QpF2U0RewsYuInFtaK4heac7RElogsUeCID7dbFD8dDad/ "Python 2 – Try It Online") ## Explanation In the code, the functions * `m` computes the multinomial coefficient \$\binom{n}{k\_0,k\_1,\dots,n-\sum k}\$ * `p` list out all partitions of `n` (code from <https://codegolf.stackexchange.com/a/84192/61039> (without this code was 601 bytes)) * `e` evaluates our polynoimal * `s` does the actual functional square root The way it works is by computing the coefficients of \$f\$ (of degree \$n\$) using the \$n+1\$th highest coefficients of \$f\circ f\$, then checks if the computation is correct as multiple polynomials can lead to the same highest coefficients. The way the computation works is by considering the following series of manipulations: \begin{align\*} f(x)&=\sum\_{i=0}^na\_ix^i\\ f(f(x))&=\sum\_{i=0}^na\_i\left(\sum\_{j=0}^na\_jx^j\right)^i\\ &=\sum\_{i=0}^na\_i\sum\_{k\_0+k\_1+\dots+k\_n=i}\binom{i}{k\_0,k\_1,\dots,k\_n}\prod\_{j=0}^n a\_j^{k\_j}x^{jk\_j}\\ &=\sum\_{i=0}^na\_i\sum\_{k\_0+k\_1+\dots+k\_n=i}\binom{i}{k\_0,k\_1,\dots,k\_n}\left(\prod\_{j=0}^na\_j^{k\_j}\right)x^{\sum\_{j=0}^njk\_j}\\ &=\sum\_{k\_0+k\_1+\dots+k\_n\leq n}a\_{k\_0+k\_1+\dots+k\_n}\binom{k\_0+k\_1+\dots+k\_n}{k\_0,k\_1,\dots,k\_n}\left(\prod\_{j=0}^na\_j^{k\_j}\right)x^{\sum\_{j=0}^njk\_j}\\ &=\sum\_{i=0}^{n^2}\left(\sum\_{\sum\_{j=0}^njk\_j=i,k\_i\geq0}a\_{k\_0+k\_1+\dots+k\_n}\binom{k\_0+k\_1+\dots+k\_n}{k\_0,k\_1,\dots,k\_n}\left(\prod\_{j=0}^na\_j^{k\_j}\right)\right)x^i\\ \end{align\*} From here, if \$i>n^2-n\$, then \$k\_1+\dots+k\_n=n\$, forcing \$k\_0=0\$ since \$a\_{>n}=0\$. Furthermore, $$\sum\_{j=0}^njk\_j=n\sum\_{j=0}^nk\_j-\sum\_{j=0}^njk\_{n-j}=n^2-\sum\_{j=0}^njk\_{n-j}$$ so the coefficient of \$x^{n^2-i}\$ for \$i<n\$ simplifies to \begin{align\*} &\hphantom{=}a\_n\sum\_{\substack{\sum\_{j=1}^njk\_j=n^2-i\\k\_0=0\\k\_i\geq0}}\binom{n}{k\_0,k\_1,\dots,k\_n}\left(\prod\_{j=0}^na\_j^{k\_j}\right)\\ &=a\_n\sum\_{\substack{\sum\_{j=0}^njk\_{n-j}=i\\\sum\_{j=0}^nk\_j=n\\k\_i\geq0}}\binom{n}{k\_0,k\_1,\dots,k\_n}\left(\prod\_{j=0}^na\_j^{k\_j}\right)\\ &=a\_n\sum\_{\substack{\sum\_{j=0}^njk\_j=i\\k\_0=n-\sum\_{j=1}^nk\_j\\k\_i\geq0}}\binom{n}{k\_0,k\_1,\dots,k\_n}\left(\prod\_{j=0}^na\_{n-j}^{k\_j}\right) \end{align\*} and the \$\sum\_{j=1}^njk\_j=i\$ is really asking for partitions of \$i\$. To extend this analysis to \$i=n\$ to get \$a\_0\$, we simply notice that we need to include the case that \$1(n-1)+(n-1)n=n^2\$, i.e. we simply add \$a\_0^{n-1}a\_1\$. The reason why this helps is this expansion gives us * \$x^{n^2}\$ coefficient of \$f\circ f\$ is \$a\_n^{n+1}\$ * \$x^{n^2-i}\$ coefficient is linear in \$a\_i\$ for \$0<i<n\$ as the only term containing \$a\_i\$ is \$na\_0^na\_i\$ As all terms in the coefficient of \$x^{n^2-i}\$ in \$f\circ f\$ only depends on \$a\_{<i}\$ other than \$na\_0^na\_i\$, we can easily compute \$a\_i\$. The only issue is when \$n\$ is odd, which gives us \$2\$ solutions for \$a\_n\$. [Answer] # Python + numpy (758 bytes; non-brute force) I thought it would be interesting to give a non-brute force answer to this question. Without further ado, here is the code: ``` import numpy as np import numpy.polynomial.polynomial as Poly from math import comb def expand_bell(n_deriv, derivs, bell_arr): """Fill in the n_deriv'th diagonal of bell_arr Note that n=1 is the main diagonal, n=2 is the second diagonal etc. The result will have bell_arr[n, k] + B_(n, k)(...derivs) correct up to the n_deriv'th diagonal, where B_(n, k) is the partial bell polynomial""" for n in range(n_deriv, len(bell_arr)): k = n - n_deriv + 1 for i in range(n_deriv): bell_arr[n,k] += comb(n - 1, i) * derivs[i] * bell_arr[n-i-1,k-1] def get_nth_derivative(n, ff_derivs, bell_polys): """Get the nth derivative of f(f) in terms of the nth derivative of f given derivatives 0...n-1 of f evaluated at the fixed point For this we use the Faa di Bruno formula The return value is (m, b), coefficients such that m * f^(n)(x0) + b = ff^(n)(x0) Note that for n=1, ff'(x0) = f'(x0)^2, which is not linear; but for n>1 it is linear""" assert n >= 2 b = 0 for k in range(2, n): b += ff_derivs[k] * bell_polys[n, k] # k=1 and k=n m = ff_derivs[1] + ff_derivs[1]**n return m, b x = Poly.Polynomial([0, 1]) def get_fixed_points(f): return (f - x).roots() def poly_from_fixed_pt_and_first_deriv(ff, x0, x1): """Given the fixed point x0 of f, the first derivative x1, and ff(x) = f(f(x)) All of the other derivatives of f are forced Compute these other derivatives and return the corresponding polynomial""" f_deriv = ff.deriv(2) derivs = [x0, x1] d = round(np.sqrt(ff.degree())) bell_arr = np.zeros((d+1, d+1), dtype=complex) ar = np.arange(d+1) bell_arr[(ar, ar)] = x1 ** ar for i in range(2, d+1): m, b = get_nth_derivative(i, derivs, bell_arr) deriv = (f_deriv(x0) - b) / m derivs.append(deriv) expand_bell(i, derivs[1:], bell_arr) f_deriv = f_deriv.deriv() return get_poly_from_derivs(x0, np.array(derivs)) def get_poly_from_derivs(x0, derivs): d = len(derivs) # Factorials fact = np.concatenate(([1], np.cumprod(np.arange(1, d)))) coeffs = derivs / fact p = Poly.Polynomial(coeffs) return p(x - x0) def round_polynomial(p): return Poly.Polynomial(np.round(np.real(p.coef))) def functional_square_root(ff): if ff.degree() == 1 and ff.coef[1] == 1: # Special case because there is no fixed point for ff (or every point is a fixed point) return x + ff(0) / 2 fixed_pts = get_fixed_points(ff) ff_deriv = ff.deriv() # Guess a fixed point for x0 in fixed_pts: first_deriv_st = ff_deriv(x0)**0.5 # There are two possibilities for the first derivative for x1 in (first_deriv_st, -first_deriv_st): guess = round_polynomial(poly_from_fixed_pt_and_first_deriv(ff, x0, x1)) if (ff.has_samecoef(guess(guess))): return guess ``` Try it on repl.it: <https://replit.com/@praneethkolichala/Functional-root-of-polynomials> Golfed version: ``` import numpy as N import numpy.polynomial.polynomial as Q from math import comb P,z,C=Q.Polynomial,N.zeros,complex def G(f,x,y): D,d=f.deriv(2),round(N.sqrt(f.degree())) B,ar,s=z((d+1,d+1),dtype=C),N.arange(d+1),z(d+1,dtype=C) B[(ar,ar)],s[:2]=y**ar,[x,y] for i in range(2,d+1): m,b=s[1]+s[1]**i,sum(s[k]*B[i,k] for k in range(2, i)) s[i]=(D(x)-b)/m for n in range(i,len(B)):B[n,n-i+1]=sum(comb(n-1,l)*s[1+l]*B[n-l-1,n-i] for l in range(i)) D=D.deriv() F=N.hstack(([1],N.cumprod(N.arange(1,d+1)))) return P(s/F)(P([0,1])-x) def R(f): if f.degree()==1 and f.coef[1]==1: return P([0,1])+f(0)/2 p,D = (f-P([0,1])).roots(),f.deriv() for x in p: t=D(x)**0.5 for y in (t,-t): g=P(N.round(N.real((G(f,x,y)).coef))) if (f==g(g)):return g ``` # Explanation *(Aside):* At first, I was looking at [polynomial decomposition](https://en.wikipedia.org/wiki/Polynomial_decomposition). This *almost* solves the problem, because it decomposes a polynomial as $$h = u\_1 \circ u\_2 \circ \dots \circ u\_n$$ where \$u\_1, \dots u\_n\$ are not linear and cannot be further decomposed. Moreover, it turns out that these \$ u\_i \$'s are essentially unique up to linear factors. For example, for any linear polynomial \$\ell(x) = ax + b\$, clearly \$ u\_1 \circ u\_2 = (u\_1 \circ \ell) \circ (\ell^{-1} \circ u\_2)\$. However, sometimes \$u\_1 \circ u\_2 = v\_1 \circ v\_2\$ are distinct decompositions. For example, \$T\_m \circ T\_n = T\_n \circ T\_m\$ where \$ T\_i \$ are the [Chebyshev polynomials](https://en.wikipedia.org/wiki/Chebyshev_polynomials) or even $$ x^n \circ x^sh(x^n) = x^sh(x)^n \circ x^n = x^{sn}h(x^n)^n $$ According to [this paper](https://arxiv.org/pdf/0807.3578.pdf), those are the only two cases, and all decompositions can be generated by taking some decomposition and applying these transformations or changing a polynomial by a linear factor. I couldn't figure out how to use these decompositions and combine them in a way to make \$f\circ f\$, although it seems very possible, and I'm sure someone else with some more mathematical ability could do it. --- So how did I end up doing it? The first thing to notice was that composing a function with itself can only expand the set of fixed points, where a fixed point is an \$x\$ such that \$ f(x) = x \$. By the fundamental theorem of algebra, there exists a fixed point of \$ f(x) \$ in \$ \mathbb{C} \$. Now, suppose we had \$ f\circ f \$ and a fixed point \$x\_0\$ of \$ f \$. We can compute the derivatives of \$ f\circ f \$ using [Faà di Bruno's formula](https://en.wikipedia.org/wiki/Fa%C3%A0_di_Bruno%27s_formula). For example, we have $$ \frac{d}{dx}f(f(x)) = f'(f(x))f'(x) $$ Thus, evaluating at \$ x=x\_0 \$, we get \$ f'(x\_0)^2 \$, since \$ f(x\_0) = x\_0 \$. Since we can compute the derivative of \$ f(f(x)) \$ this gives us two possibilities for \$ f'(x\_0) \$. In fact, it turns out that for \$ n \geq 2 \$, the value of \$ \frac{d^n}{dx^n} f(f(x)) \$ evaluated at \$ x = x\_0 \$ will be a linear polynomial in \$ f^{(n)}(x\_0) \$ (here, \$ f^{(n)} \$ is the \$n\$th derivative) in the Faà di Bruno formula, assuming \$ f'(x\_0), f''(x\_0), \dots f^{(n-1)}(x\_0) \$ are known and considered constants. Only for \$ n=1 \$ is it a quadratic; thus, we can solve exactly for the rest of the derivatives. In sum, our procedure is to find the roots of \$ f(f(x)) = x \$ and iterate through them. Eventually, one of those roots will also have \$ f(x) = x \$. For each one, calculate the derivatives of \$ f(x) \$ assuming it were a fixed point of \$f(x)\$. Then, check if the polynomial with these derivatives actually matches \$ f(f(x)) \$ when it is composed with itself. In principle, this method works even if the coefficients aren't integers. You would have to remove the `round_polynomial` method, however, and change `has_samecoef` to something that checks for approximately matching coefficients, so that floating point errors don't throw everything off. [Answer] # [Haskell](https://www.haskell.org/), ~~110~~… 97 bytes * -3 bytes + a provably correct solution by shamelessly stealing the idea of trying increasing values of `b` from [Arnauld's answer](https://codegolf.stackexchange.com/a/225241/82619). ``` k#p=[q|b<-[1..],q<-mapM([-b..b]<$id)p,all((==).e p<*>e q.e q)[0..k*k]]!!0 e q x=foldl1((+).(*x))q ``` [Try it online!](https://tio.run/##XUvNjsIgEL73KTB6gO4MKY1uGlO8m6zxAQgHalGbIoL24GGffVns0Uzyzfd7Nc/ROpfSuAxSxd@uRSU41xBbvJlwoAo7zjvdroaeBTDOUSol45aEttxZEjOLTFWcj@Wo9WJRFdkgL3m@u94JSr8Yp@WLsZhuZvCyvxd5iQ9r@h@/3e6Pau8nnb3H4CcagDrrL9OVBIJEsGVgBXnvkhJQ6SJj/X71BlA0s8Y1NIANfGeFuQRYzzCH1efpv9PZmcsz4bH@Bw "Haskell – Try It Online") The relevant function is `(#)`, which takes as input the degree `k` of the polynomial and the list `p` of coefficients, highest to lowest order. ## How? ``` e q x=foldl1((+).(*x))q ``` `e` is a simple function that evaluates a polynomial `q` at point `x`. --- ``` k#p=[q|b<-[1..],q<-mapM([-b..b]<$id)p,all((==).e p<*>e q.e q)[0..k*k]]!!0 ``` `(#)` bruteforces all the polynomials `q` of degree at most `k`. We try all the possible coefficients between `-b` and `b`, starting from `b=1` and working our way up. As soon as we find a valid polynomial, we stop and return it. To check whether `q` is valid (i.e. `q(q(x))==p(x)`), instead of computing the coefficients of the composition, we try whether the equality holds for every `x` between `0` and `k*k`. Since both `q(q(x))` and `p(x)` have degree at most `k*k`, if they are equal for `k*k+1` values of `x` then they are the same polynomial. [Answer] # [J](http://jsoftware.com/), 80 67 bytes Takes in the polynomials with lowest term first. Bruteforce (in the "generate all possible answers and filter them" way) and thus runs out of memory for the bigger test cases. ``` ((-:[:+/[*1 0,+//.@:(*/)^:(]1<@-~#)~)"1#])>.@%:@#(>@,@{@#<@i:)>.&|/ ``` [Try it online!](https://tio.run/##XY/BTsMwEETv@YpRI6jdpo7XTarUlMqiEifEgWsVfECJgAsfAOqvh0kCNFTWruTZfTu7793MzFvcesyRwcIzVgaHp4f7TqmVP/plflwIbLbMcxO8WuT62atadmF1SvVJzySt9d6EKx9StQ9Z@AzpLrx5atdfeaeT5uX1Ay02iBUqxAKSjJqFQNU3jdEs8zOq8k92f3pcozzrUSq4cqysEd2UmTqNKNfv05l2vTAkSR7vDIa2gpP6QY1hi4ijucBtLIPyluNki5K@QosJR6M47ECLFgU3tiWEnFTkSnKWuxe/3M/t9vL@yyfdNw "J – Try It Online") Rather straight forward: * `>.@%:@#(>@,@{@#<@i:)>.&|/` is a maybe too verbose way to generate `square(highest exponent)`-length lists with elements in the range of `-(max (abs coefficients)) … (max (abs coefficients))`. For each polynomial `p`: * `+//.@:(*/)` multiplies two polynomials (with one side fixed to `p`) * `^:(]1<@-~#)` do this `length of list - 1` times, keeping all the results. So we get `p^1, p^2, p^3, …`. * `1 0,` prepend `p^0`: `1 + 0x + 0x^2 + 0x^3 …`. * `[*` multiply by the coefficients, `a_0*p^0, a_1*p^1, a_2*p^2, a_3*p^3, …` * `[:+/` as the `p`s are actually list, sum the rows together to get the final result. * `-: … #` keep only the lists that have the original polynomial as the final result. [Answer] # JavaScript (ES7), ~~192~~ 178 bytes Expects the coefficients from lowest to highest order and returns a list in the same format. Pretty long, but very fast for the test cases. ``` p=>eval("r=g=(p,x)=>p.reduce((s,v,i)=>s+v*x**i);for(m=0;r;)for(a=Array(-~(p.length**.5)).fill(++m);p.some((_,x)=>g(p,x)-g(a,g(a,x)))&&!a.every((v,j)=>r=v+m?a[j]--&0:a[j]=m););a") ``` [Try it online!](https://tio.run/##jVPLbsIwELzzFS4HZCd2iENA0MhUPfQrUFRZwQlBgUQOjeDSX6e7Ie6hVSmWH6v1zox3be91p9vMls1JHOutuebq2qi16XRFx1YVijb8zNS6CazZfmSG0pZ3vARP63fe2fNKluS1pQcVJjZhaGr1aq2@UPFJm6Ayx@K087xgzliQl1VFff/AkiZo6wOQvffkRS8iCqo5jjNjbDJ50oHpjL1Q2vE9BFnV@YcXvdmnQkzCZzQUMLFEj9k12YwI2UhOwpSTx9p0OgBIbclGgJmlA0n0MMtAIsMeGs05EXL5GBihGD9zqiLmZAkLjMV9ikFVRJzc0Hj68Obol7twRDuAdOILyBqWOYhLuYJpBaeJFhFOIVYEs5RIPIijNifxT3yMxYAN2VtLiJKIlyGkGvdldfJ4WDHDtB1H@Ff/lY67u2H7@wadw1X0Vo8HnoWrqHRovAgJScV9B4n/0NEgl47SUQDf4E1nO9oQtSZZfWzrygRVXdCc4keCZ90aCq@cXb8A "JavaScript (Node.js) – Try It Online") ### How? Given a polynomial \$P\$ of length \$n\$ (i.e. of degree \$n-1\$) as input, this builds all polynomials \$Q\$ of length \$\lfloor\sqrt{n}\rfloor+1\$ with integer coefficients in \$[-m\dots m]\$ such that \$Q(Q(x))=P(x)\$ for all \$x\in[0\dots n-1]\$. We start with \$m=1\$ and widen the search window until a solution is found. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 86 bytes -10 bytes thanks to @att. ``` (t=a/@(r=Range[0,Tr[1^#]^.5]))/.Solve[(p=t.#^r&)@p@x~CoefficientList~x==#,t,Integers]& ``` [Try it online!](https://tio.run/##fY9Ba4MwFMfv/RSBgCiLmpcap4cMYafBDmPbLShIia3Q2mLDCIz1q7sXW3foYaf3S97//V5yaO3OHFrbb9qpI2oKrWrTKhzVeztsjebsc9TQ0LpJZB1FafJx3H8ZHZ6UTWgzBlF1qtzl@Wi6rt/0ZrCv/dlenFKUWfYyWLM147kOprexH6ymJH4iXXUX15S5uiYBSavVt2Mr4sgDERxBSOSYQMEI3jYZcoZ1jf0Cq8BzMadzDMfXgLg1xHWm9F2shXcCwiOC9NM5AkCJJD2V2bwBU7m47RA5n2X@NTDvAfhXmy1avl60ctFCsWjhTwtcztrMfxalP9Mv "Wolfram Language (Mathematica) – Try It Online") Non-brute force. Just writes it as a equation in the coefficients, and solves it with `Solve`. Returns all solutions. [Answer] # Python/NumPy, 249 bytes ``` from numpy import* from itertools import* def f(p): l=sqrt(abs(p[0]));P=poly1d(p);t=P-[1,0];o=P-P.o*P[0]//2 for s,c in product((-l,l),combinations(t.r,int(sqrt(P.o)))):a=poly1d(int_(around((s-(P.o==1))*poly(c))))+[1,0];o=[o,a][a(a)==P] return o.c ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hVPLcpswFF10x1fcySZSImzEwyXO8AFexXsPZAiGlhmMqBAt_pZusmln-kntn3TXewHHuEmnHoOQdO455x7B1-_N0XxU9fPzt84Udvjzd6HVAeru0ByhPDRKmxtrWCpNro1SVfuyvM8LKFjD1xZUUftJG5Y-tazZOTHn99uoUdVR7nH_3kRbeyeFE98rfNou1M0WQcula0GhNLQig7KGRqt9lxnG7EpUXGTq8FTWqSlV3TKz0KKsDRtUkIDjb52eJHDnkaVadfWesdYmQBRJzm9on2UEvj3p75RI413KUh5F29gCnZtO16AW2RTAj7E9aI-t9eVjWeUgscGNeIh2-ee0QrGmM4wv2qYqDbteXvOdLePTdH05VRrnmMfQ5yN1eSXdK5Q1-ois2DN1tREF2tfpkW04Fw_cgrzP8sasx210ssCFx7IuFOO4O1kYDT__eqc3tLCGHpaQqbwoyqzMa9OuAbsGJ7YeOjMCBNh4oRe7h1vIBltpjSddm_xDrnHlbQYqwb4EZLFlvajdguu8WeDONREm34ZJ58zmBj3YIMPXQDdA1zI8Mw5I7zWQcN7MX-Ijzu8TDx2EfeLiLCQ3KywledsXEOKA12rmdwC6BPROQFfAjNgemd0JSSCKxhmBw3Cms0eUnKPk3OQdOeqTkNKUffIexwDdrig2edcnAT3c-aSJiJU79uOuHCKmE5BDwtKdzK4wfhwC7ArrBdUKqqObQ0dDwUt33vBAONJ5ROZPVNS2AP9_bv3JreNNboPJrQwnt_LkVjrBIOD8ZdanlwG15PAUorAkswhHfeciTe8cvUcvgn9KlsK3PTrWS8OjkvOv_2UQw6eReJdF59f_pWb89v4A) Not very golfed yet. But perhaps good as a readable baseline. Also, not sure this will work for every single edge case. It works by solving for fixed points of f(f(x)), i.e. roots of f(f(x))-x (the case f(f(x))=x+c is treated separately). The fixed points of f(x) are a subset. We then simply try all subsets of correct size. Here is the code again with a few comments. Note that the (deprecated) poly1d class has the very golfing friendly attributes `.c` (coefficients as array) `o` (order) and `.r` (roots). Also, note that indexing a `poly1d` starts from the **end** of the underlying array. ``` from numpy import* from itertools import* def f(p): # l: leading coefficient of f # t: fixed point equation, i.e. P-x ([1,0] is x) # o: output; first set at the appropriate value for the # no fixed-point case; will be overwritten otherwise l=sqrt(abs(p[0]));P=poly1d(p);t=P-[1,0];o=P-P.o*P[0]//2 # try: +/- and all subsets (of size sqrt of input order) # of the roots of t for s,c in product((-l,l),combinations(t.r,int(sqrt(P.o)))):a=poly1d(int_(around((s-(P.o==1))*poly(c))))+[1,0];o=[o,a][a(a)==P] return o.c ``` ]
[Question] [ Everyone's been freaking out about that stupid "Flappy Bird" game being removed. So, your task is to crate a Flappy Bird Clone game. Its really simple. Here are the guide lines: * It can use either ascii art or real images * You can make your "bird" flap with either a click or a key press * It should try to be as short as possible, hence the [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") tag. Here's an example: <http://www.reddit.com/r/learnprogramming/comments/1xiimx/i_couldnt_sleep_so_i_cloned_your_flappy_bird/> In order to be a "Flappy Bird Clone," your game needs to have the following: * A bird, or other character * The "bird" should move slightly up when a key is pressed or you click/tap * If there is no clicking/tapping/etc, the "bird" should rapidly move downwards * Pipes or other obstacles should move leftwards on the screen, creating the illusion that the bird is moving * The pipes should have a small gap for the bird to fly through. * Every time you pass through a gap between pipes, your score increases by 1. * If you hit a pipe or the ground, the game ends and your score is displayed. It doesn't really need to be a "bird" or a "pipe," it can all be ascii. Here's a very minimal example of a flappy bird screen: ``` /-----[4]-----\ | || || | | || ¯¯ | | || O> | | ¯¯ __ | | __ || | | || || | \-------------/ ``` [Answer] ## Javascript + jQuery (997) *Tested on Chrome 32, Firefox 27, IE9* Open Console (F12) from **this** page and copy/paste the following code. ``` scroll(0,0);h=1/30;p=[];r=320;n=0;w=80;f=2.5;o=80;t=setInterval;$('#question').children().hide().end().append('<p id="m"></p>').append('<p id="s"></p>').click(function(){v=100});$('#s').css({position:'relative',margin:'auto',border:'2px solid',width:200,height:r}).append('<img id="b" src="//i.imgur.com/4w6Vgud.gif"/>');$('<style>.p{width:1px;border:1px solid;position:absolute}</style>').appendTo('head');function u(){$('#m').text('score '+m+' (max '+n+')')}function i(){x=r/2;v=0;m=0;p.length=0;u()}i();t("v-=h*100;x+=h*v;if(x<0||x>r)i();$('.p').remove();for(j=0;j<p.length;j++){p[j].r+=h*w;if(p[j].r>200){p.shift();j--;m++;if(m>n)n=m;u();}else if((p[j].r>165&&p[j].r<185)&&(x<p[j].h||x>p[j].h+o))i();else{$('<div class=p></div>').appendTo('#s').css({bottom:0,right:p[j].r,height:p[j].h});$('<div class=p></div>').appendTo('#s').css({bottom:p[j].h+o,right:p[j].r,height:320-p[j].h-o})}}$('#b').css({position:'absolute',left:0,bottom:x-25})",h*1e3);t("p.push({h:Math.random()*(r-o),r:0})",f*1e3) ``` > > ![enter image description here](https://i.stack.imgur.com/Ep7vZ.jpg) > > *The game replace the question block of this page.* > > *You have to click on the game frame to make the bird fly.* > > > Ungolfed and commented version : ``` $('#question').children().hide(); $('#question').append('<div id="score"></div>'); $('#question').append('<div id="scene"></div>'); $('#scene').css({position:'relative',margin:'auto',border:'2px solid black',width:'200',height:'320'}); $('#scene').append('<img id="bird" src="http://fc01.deviantart.net/fs71/f/2014/037/d/0/pixel_art___flappy_bird_by_hipsterli-d75dkyr.gif"></img>'); $('#bird').css({display:'block',position:'absolute',left:0,'pointer-events':'none',margin:'0 auto'}); $(window).scrollTop(0); //CONFIGURATION var dt=1/30, //delta timestep (typically 30Hz) pipevel=80, //pipe velocity (in pixels per second) pipefreq=2.5, //pipe spawn frequency (in second) holesize=80, //hole size (in pixels) gravity=-100, //gravity (in pixels per square second) punchvel=100; //velocity punch when clicked (in pixels per second) var x, y, pipes=[], roof=$('#scene').height(), score, maxscore=0; function updateScore() { $('#score').text('Score : '+score+' (max : '+maxscore+')'); } function init() { x=roof/2; //position v=0; //velocity score=0; pipes.length=0; updateScore(); } function step() { //euler integration v+=dt*gravity; x+=dt*v; if (x<0 || x>roof) init(); //pipes $('.pipe').remove(); for (i=0; i<pipes.length; i++) { pipes[i].rightpos += dt*pipevel; if (pipes[i].rightpos > 200) { pipes.shift(); i--; score++; if (score>maxscore) maxscore=score; updateScore(); } else if ((pipes[i].rightpos > 165 && pipes[i].rightpos < 185) && (x < pipes[i].holepos || x > pipes[i].holepos+holesize)) { //collision init(); } else { $('#scene').append('<div class="pipe" style="background-color:#000; width:1px;border:1px solid #000; position:absolute; bottom:0; right:'+Math.floor(pipes[i].rightpos)+'px; height:'+pipes[i].holepos+'px"></div>'); $('#scene').append('<div class="pipe" style="background-color:#000; width:1px;border:1px solid #000; position:absolute; bottom:'+(pipes[i].holepos+holesize)+'; right:'+Math.floor(pipes[i].rightpos)+'px; height:'+(320-(pipes[i].holepos+holesize))+'px"></div>'); } } $('#bird').css({bottom:Math.floor(x)-25}); setTimeout(step, dt*1000); } $('#question').click(function() { v=punchvel; }); function addPipe() { pipes.push({holepos:Math.random()*(roof-holesize),rightpos:0}); setTimeout(addPipe, pipefreq*1000); } init(); setTimeout(step, dt*1000); setTimeout(addPipe, pipefreq*1000); ``` You can easily modify the configuration (gravity, pipe velocity...), have a look at commented version. [Answer] # Javascript+jQuery (ASCII Art) - ~~571~~ ~~524~~ 491 ``` l=$('#answer-23452 blockquote pre').click(function(){m=1}),o=[],d=0,e=4,m=1;setInterval(function(){t=Array(153);s=~~(d/10-0.99);d++;d%10?0:o[d+20]=~~(Math.random()*5)+1;for(i=-1;k=o[i+d],i<17;i++)if(k--)for(j=-1;c=j==k||j-k==4?'-':j-k>0&&j-k<4?0:'|',j<9;j++)i>-1?t[j*17+i]=c:0,i<16?t[j*17+i+1]=c:0;m-=.2;e-=m;if(e<0||e>10||t[~~e*17+8])e=4,m=1,d=0,o=[];t[~~e*17+8]='>';r='|-------['+s+']-------';for(i=0;z=t[i]||' ',i<153;i++)i%17?r+=z:r+='|\n|'+z;r+='|\n|-----------------|';l.html(r);},150) ``` > > #### Demo > > > Open the dev tools console (F12) and run the above code in **this page** to use the below demo (right now, go ahead!): > > > > ``` > |-------[5]-------| > | || -- | > | || | > | || | > | -- | > | -- | > | || | > | || | > | -- > || | > | || || | > |-----------------| > > ``` > > Known minor bugs: * If you get a double-digit score, it messes up the layout * It is NOT easy!!! (but the original wasn't either) * There's a tradeoff between efficiency and golfedness Feel free to comment with your highscore. Also, this is my first Code Golf post, so suggestions on compression, etc. will be welcomed [Answer] ## Floppy Dragon, JavaScript, 1024b I'm making this game for the current js1k compo ( <http://js1k.com> ) Play: <http://js1k.com/2014-dragons/demo/1704> ``` _='c.scale(, ;ontouchH=onmousedown=onkeydowif(e){ }else h=45,d=1};(Eq";Rect(0,0,^,^9Q"-k,0Q+N),0()-k,2E3980-(+3)N(+3)),Y(p="fEFf&{{~_=,;=vviJ.jfVi/.OoyizyhkhEwf74)\\n$fwwuvtU`"+(10<h?"iZ[*)yj:*im**y|Ktdww54#5Dy\\iz[Kzi[Jiijk[e@1!":"zl]LfU{\\lKtBUh{zzU66iigig5\\n&iiyz{vfwwiyDfwiiE"0"v=i-e,w=(j-=h)-eG in p)y=8>>4),z=16&15),Iv+=e?y:z,w+=e?-z:y(dW(h-=6dW!eW(k+=Q,^<kW(k-=^)!dXeX(k+280)%8X(f++,Q<lWl--if(q>jX9q<jX!((k+3)%8)W(j<qXj>2q))e=40;fff";c.font="6em Arial";dWf1,5dX"#FloppyDragon"11,5eW"score"4,4e?"reH":d?"":"H"5,6setTimeout(n,l)})()I40*o-k,a.width/()/2-30* d=e=f=h=0;g=[];G=0;Y>o;o++)=g[o+Y]=8*Math.random()|0;i=j=3;k=Q;l=qc.fill;c.beginPath(c.moveTo(Style="#G=2E3;o--;)o%Q?,a.height/Y1*g[Q*~~(k/8)+Q]+);g[o]-2*(p.charCodeAt(o)Text(00n=function(){4*):(,1*Gfor(oHstartIc.lineTo(N),-4,1*Q20W&&X||Y1E3^4E4q50';for(Y in $='q^YXWQNIHG ')with(_.split($[Y]))_=join(pop());eval(_) ``` All feedbacks and new ideas are welcome! [Answer] # Color Animation and Physics; Pure JavaScript, 457 (335) bytes This is my first post in this forum; I made this code and retrospectively found this thread to post it in. Here's the code encapsulated in HTML, ready to be copy/pasted in to an html file: ``` <body><script>A=120;B=280;d=document;y=180;x=v=n=s=0;f=140;c=d.createElement('canvas');p=c.getContext('2d');c.width=B;c.height=400;c.onclick=()=>{v-=6};p.font='50px Arial';d.body.appendChild(c);r=(h,t,k=0,i='#0f0',w=40)=>{p.fillStyle=i;p.fillRect(h,k,w,t)};b=setInterval(()=>{if(x==0){n=f;f=Math.floor(B*Math.random());x=160}x--;v+=.1;y+=v;r(0,400,0,'#08f',B);r(20,40,y,'#fc0');r(x-40,n);r(x+A,f);r(x-40,B-n,n+A);r(x+A,B-f,f+A);if(x==60)s++;p.strokeText(s,A,80);if(x>20&&x<100&&(y<n||y>n+80)){clearInterval(b);location.reload()}},15)</script><br>Made by Thomas Kaldahl</body> ``` It has pixel perfect collisions, accurate quadratic physics, and smooth color animations, all in 457 bytes worth of purely independent offline Javascript code, shown ungolfed here in greater detail and explanation: ``` <!--entire HTML shell is omitted in golf--> <body> <script> //common numbers and the document are assigned shortcut letters A = 120; B = 280; d = document; y = 180; //y position of the top of the bird x = //x position of scrolling for pipes v = //vertical velocity of bird n = //y position of the top of the nearest pipe opening s = 0; //score f = 140; //y position of the top of the farther pipe opening c = d.createElement('canvas'); //canvas p = c.getContext('2d'); //canvas context //set canvas dimensions c.width = B; c.height = 400; c.onclick = () => { v -= 6 }; //apply jump velocity to bird when clicked p.font = '50px Arial'; //font for scoring (omitted in golf) d.body.appendChild(c); //add canvas to html page //draw a rectangle on the canvas r = (h, t, k = 0, i = '#0f0', w = 40) => { p.fillStyle = i; p.fillRect(h, k, w, t) }; //main loop (not assigned to b in golf) b = setInterval( () => { if (x == 0) { //the x position is a countdown. when it hits 0: n = f; //the far pipe is now the near pipe, overwriting the old near pipe f = B * Math.random() //assign the far pipe a new vertical location x = 160; //restart the countdown back at 160 //(score increments here in golf) } x--; //count down v += .1; // apply gravity to velocity y += v; // apply velocity to bird r(0, 400, 0, '#08f', B); //draw background r(20, 40, y, '#fc0'); //draw bird (non-default color is omitted in golf) r(x - 40, n); //draw first pipe upper half r(x + A, f); //draw second pipe upper half r(x - 40, B - n, n + A); //draw first pipe lower half r(x + A, B - f, f + A); //draw second pipe lower half if (x == 60) s++; //(this is done earlier on golf) p.strokeText(s, A, 80); //draw score // if the bird is in range of the pipes horizontally, // and is not in between the pipes, if (x > 20 && x < 100 && (y < n || y > n + 80)) { clearInterval(b); location.reload() //omit interval clear in golf } }, 15) //(reduced the frame delay to 9, a 1 digit number, in golf) </script><br> Made by Thomas Kaldahl <!-- GG --> </body> ``` For fun, here's a 1066 byte version with fancier graphics: ``` <body style='margin:0'><script>var y=180,x=v=n=s=0,f=140,c=document.createElement('canvas'),p=c.getContext('2d');c.width=280;c.height=400;c.onclick=function(){v-=6};c.style='width:68vh;height:97vh';document.body.appendChild(c);p.font="50px Arial";p.shadowColor='#444';p.shadowBlur=9;p.shadowOffsetX=p.shadowOffsetY=5;function r(h,t,k=0,i='#0f0',j='#0a0',u=0,l=0,w=40){var g=p.createLinearGradient(h,l,h+40,u);g.addColorStop(0,i);g.addColorStop(1,j);p.fillStyle=g;p.fillRect(h,k,w,t);}b=setInterval(function(){if(x==0){n=f;f=Math.floor(280*Math.random());}x=x==0?159:x-1;v+=.1;y+=v;r(0,400,0,'#08c','#0cf',280,0,280);r(20,40,y,'#ff0','#fa0',y+40,y);r(x-40,n);r(x-50,20,n-20,'#0f0','#0a0',n+20,n,60);r(x+120,f);r(x+110,20,f-20,'#0f0','#0a0',f+20,f,60);r(x-40,280-n,n+120);r(x-50,20,n+120,'#0f0','#0a0',n+140,n+100,60);r(x+120,280-f,f+120);r(x+110,20,f+120,'#0f0','#0a0',f+140,f+100,60);if(x==60){s++;}p.fillStyle='#fff';p.fillText(s,120,80);if(x>20&&x<100&&(y<n||y>n+80)||y<0||y>360){clearInterval(b);location.reload();}},15);</script><br>Made by Thomas Kaldahl</body> ``` [![](https://i.stack.imgur.com/eIyVb.jpg)](https://i.stack.imgur.com/eIyVb.jpg) Also, is it cheating to use a compression system like DEFLATE? Below is the ASCII85 code for a DEFLATEd version of the code: By the way, compressed it is 335 bytes total. Gapon95\_Wi'Kf'c(i##6'h,+cM\JZeFO<h;$W'#A1',RqNigBH02C'#R$m]<i<X#6GR`2pE<Ri5mu-n%cVPrsJe:\*R^pnr9bI@[DAZnPP02A^!.$MN/@`U7l5gm!!Vr4>A;P?u[Pk8]jCnOP%dIu?`fWql>"tuO4/KbIWgK;7/iJN'f2,hnFg8e.^SO\*t\\*`,3JBn6j(f`O#],M0;5Sa35Zc@\*XaBs@N%]k\M76qa[.ie7n(^\*Z5G-lfhUZ3F#'%,X17Pj1u]L)LjpO6XbIl%N3tJhTsab8oV1T(?MC$9mT;90VMmnfBNKEY(^'UV4c?SW':X(!4,\*WCY+f;19eQ?`FK0I"(uDe:f&XV&^Rc+'SWRIbd8Lj9bG.l(MRUc1G8HoUsn#H\V(8"Y$/TT(^kATb(OreGfWH7uIf [Answer] # Objective C - ungolfed Possibly the worst code I have ever written. ![Hacky Bird Running](https://i.stack.imgur.com/pFMhc.png) You can download the binary here: [AsciiBird Download Binary](http://www.mediafire.com/download/6stxhbzr11ovty3/AsciiBird) Tap the control key frantically to keep the bird in the air! This was compiled by Xcode and run in Terminal. It has colors! Protip: Resize your terminal's window so you don't see a backlog of screen refreshes. main.m: ``` #import <Foundation/Foundation.h> #import "ABManager.h" void drawScreen(int counter) { __block struct ABPoint thisPoint; thisPoint.x = 0; thisPoint.y = 0; __block ABManager *man = [ABManager sharedManager]; [man.screen enumerateObjectsUsingBlock:^(NSString *c, NSUInteger idx, BOOL *stop) { NSString *c2 = c; NSMutableArray *newObstacles = [[NSMutableArray alloc] init]; for (NSValue *s in man.obstacles) { struct ABPoint o; [s getValue:&o]; if (thisPoint.x == o.x) { if (thisPoint.y != o.y && thisPoint.y != (o.y + 1) && thisPoint.y != (o.y - 1)) { c2 = @"\033[1;33m|\033[0m"; } else { if (counter == 0 && thisPoint.y < o.y) { o.x = o.x - 1; if (o.x < 0) { o.x = 49; o.y = (arc4random() % 11) + 1; } if (man.charPos.x == o.x) { man.score = man.score + 1; } } } } [newObstacles addObject:[NSValue valueWithBytes:&o objCType:@encode(struct ABPoint)]]; } man.obstacles = [[NSMutableArray alloc] initWithArray: newObstacles]; if (thisPoint.x == man.charPos.x && thisPoint.y == man.charPos.y) { printf("\033[1;35m>\033[0m"); if ([c2 isEqualToString:@"\033[1;33m|\033[0m"]) { man.shouldExit = TRUE; } } else { printf("%s", [c2 UTF8String]); } if (idx % 50 == 49) { printf("\n"); thisPoint.y = thisPoint.y + 1; thisPoint.x = 0; } else { thisPoint.x = thisPoint.x + 1; } }]; } int main(int argc, const char * argv[]) { @autoreleasepool { ABManager *man = [ABManager sharedManager]; int count = 0; BOOL ignoreKeypress = FALSE; while (TRUE) { if (CGEventSourceKeyState(kCGEventSourceStateCombinedSessionState,59) && !ignoreKeypress) { ignoreKeypress = TRUE; struct ABPoint p = man.charPos; p.y = p.y - 2; man.charPos = p; } else { ignoreKeypress = CGEventSourceKeyState(kCGEventSourceStateCombinedSessionState,59); if (count > 3) { count = 0; struct ABPoint p = man.charPos; p.y = p.y + 1; man.charPos = p; } else { count = count + 1; } } if (man.charPos.y < -1 || man.charPos.y > 11 || man.shouldExit) { exit(1); } printf("\n\n\n\n\n"); printf("\033[1;36m[\033[0m\033[1;30mHacky Bird\033[0m\033[1;36m]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\033[0m\n"); drawScreen(count); printf("\033[1;32m[\033[0m\033[1;31mScore: %li\033[0m\033[1;32m]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\033[0m\n", (long)man.score); [NSThread sleepForTimeInterval:0.0157]; } } } ``` ABManager.h ``` #import <Foundation/Foundation.h> #import <CoreGraphics/CoreGraphics.h> struct ABPoint { NSInteger x; NSInteger y; }; @interface ABManager : NSObject { } @property (nonatomic, readwrite) NSMutableArray *screen; @property (nonatomic, readwrite) NSMutableArray *obstacles; @property (nonatomic, readwrite) struct ABPoint charPos; @property (nonatomic, readwrite) NSInteger score; @property (nonatomic, readwrite) BOOL shouldExit;; + (id)sharedManager; @end ``` ABManager.m ``` #import "ABManager.h" @implementation ABManager + (id)sharedManager { static ABManager *sharedMyManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedMyManager = [[self alloc] init]; }); return sharedMyManager; } - (id)init { if (self = [super init]) { self.screen = [[NSMutableArray alloc] init]; for (NSUInteger i=0; i < 600; i++) { [self.screen addObject:@" "]; } self.score = 0; self.shouldExit = FALSE; struct ABPoint p; p.x = 5; p.y = 0; self.charPos = p; struct ABPoint o; o.x = 10; o.y = 5; struct ABPoint o2; o2.x = 30; o2.y = 5; self.obstacles = [[NSMutableArray alloc] initWithArray:@[[NSValue valueWithBytes:&o objCType:@encode(struct ABPoint)],[NSValue valueWithBytes:&o2 objCType:@encode(struct ABPoint)]]]; } return self; } @end ``` [Answer] # C, ~~386~~ ~~351~~ ~~347~~ 341 bytes (Windows, MinGW), 332 with a terminal emulator [![enter image description here](https://i.stack.imgur.com/3Uhxf.png)](https://i.stack.imgur.com/3Uhxf.png) Certainly not the prettiest entry, but it captures the core mechanics of flappy bird: The bird accelerates downwards, pressing a key makes him jump up, touching the pipes or the edges of the screen ends the game, score is the number of cleared pipes. ``` #import<windows.h> #define T(x)P[v*10+x]= char P[71];X,Y,W,s;main(v){srand(time(0));for(float y=1,t=0;!(v<0|v>6|(v<Y|v>=Y+W)&X>0&X<3);Sleep(99)){y+=t=kbhit()?getch(),-.9:t+.3;--X<0?X=8,Y=rand()%3+1,W=rand()%2+2:X-1||++s;memset(P,32,70);for(v=0;v<7;T(9)10,T(X)v<Y|v++>=Y+W?35:32);v=y;T(1)79;T(2)62;system("cls");printf("%s\nSCORE: %d",P,s);}} ``` It can be shortened to 333 bytes, if a POSIX terminal emulator is used (like Cmder): ``` #import<windows.h> #define T(x)P[v*10+x]= char P[71];X,Y,W,s;main(v){srand(time(0));for(float y=1,t=0;!(v<0|v>6|(v<Y|v>=Y+W)&X>0&X<3);Sleep(99)){y+=t=kbhit()?getch(),-.9:t+.3;--X<0?X=8,Y=rand()%3+1,W=rand()%2+2:X-1||++s;memset(P,32,70);for(v=0;v<7;T(9)10,T(X)v<Y|v++>=Y+W?35:32);v=y;T(1)79;T(2)62;printf("\033c%s\nSCORE: %d",P,s);}} ``` ]
[Question] [ The [Hadamard transform](https://www.mathworks.com/help/signal/examples/discrete-walsh-hadamard-transform.html) works similarly to the Fourier transform: it takes a vector and maps it to its frequency components, which are the [Walsh functions.](http://mathworld.wolfram.com/WalshFunction.html) Instead of sine waves in the Fourier transform, the Walsh functions are discrete "square waves" so to speak. This makes it easier to compute. The size of a Hadamard matrix is a power of two, `2^n x 2^n`. We can build a Hadamard matrix for a given `n` recursively. $$H\_1 = \begin{pmatrix}1&1\\1 & -1\end{pmatrix}$$ And then build block matrices in the same pattern to get $$H\_n = \begin{pmatrix}H\_{n-1}&H\_{n-1}\\H\_{n-1} & -H\_{n-1}\end{pmatrix}$$ For instance, $$H\_3 = \begin{pmatrix}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&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&1&-1\end{pmatrix} = \begin{pmatrix}H\_2&H\_2\\H\_2&-H\_2\end{pmatrix}$$ Note how the entries are always `1` or `-1` and symmetric! Easy! Then the Hadamard transform is simply multiplying `H_n` by a column vector and dividing by `2^n`. In order to apply the Hadamard transform to 2D images, we have to apply the 1D HT across every column and then every row. In short, for an input matrix X, the output will be a new matrix Y given by two matrix multiplications: $$Y = \frac{1}{2^{2n}}H\_nXH\_n$$ Another way to implement this is by first applying the HT to every column in the image separately. Then apply it to every row, pretending they were column vectors. For example, to compute the 2D HT of $$\begin{pmatrix}2 & 3\\ 2 & 5\end{pmatrix}$$ we first do $$\frac{1}{2}\begin{pmatrix}1&1\\1 & -1\end{pmatrix}\begin{pmatrix}2 \\ 2\end{pmatrix} = \begin{pmatrix}2 \\ 0\end{pmatrix} \quad\quad\quad \frac{1}{2}\begin{pmatrix}1&1\\1 & -1\end{pmatrix}\begin{pmatrix}3 \\ 5\end{pmatrix} = \begin{pmatrix}4 \\ -1\end{pmatrix} \quad\rightarrow\quad \begin{pmatrix}2&4\\0 & -1\end{pmatrix} $$ which takes care of the columns, and then we do the rows, $$\frac{1}{2}\begin{pmatrix}1&1\\1 & -1\end{pmatrix}\begin{pmatrix}2 \\ 4\end{pmatrix} = \begin{pmatrix}3 \\ -1\end{pmatrix} \quad\quad\quad \frac{1}{2}\begin{pmatrix}1&1\\1 & -1\end{pmatrix}\begin{pmatrix}0 \\ -1\end{pmatrix} = \begin{pmatrix}-0.5 \\ 0.5\end{pmatrix} \quad\rightarrow\quad \begin{pmatrix}3&-1\\-0.5 & 0.5\end{pmatrix} $$ Finally, one can also compute this recursively using the [*fast Hadamard transform*](https://en.wikipedia.org/wiki/Fast_Walsh%E2%80%93Hadamard_transform). It's up to you to find out if this is shorter or not. ## Challenge Your challenge is to perform the 2D Hadamard transform on a 2D array of arbitrary size `2^n x 2^n`, where `n > 0`. Your code must accept the array as input (2D array or a flattened 1D array). Then perform the 2D HT and output the result. In the spirit of flexibility, you have a choice for the output. Before multiplying by the prefactor `1/(2^(2n))`, the output array is all integers. You may either multiply by the prefactor and output the answer as floats (no formatting necessary), **or** you may output a string `"1/X*"` followed by the array of integers, where `X` is whatever the factor should be. The last test case shows this as an example. You may **not** import the Hadamard matrices from some convenient file that already contains them; you must build them inside the program. ## Test Cases Input: ``` 2,3 2,5 ``` Output: ``` 3,-1 -0.5,0.5 ``` Input: ``` 1,1,1,1 1,1,1,1 1,1,1,1 1,1,1,1 ``` Output: ``` 1,0,0,0 0,0,0,0 0,0,0,0 0,0,0,0 ``` Input: ``` 1,0,0,0 1,1,0,0 1,1,1,0 1,1,1,1 ``` Output: ``` 0.6250,0.1250,0.2500,0 -0.1250,0.1250,0,0 -0.2500,0,0.1250,0.1250 0,0,-0.1250,0.1250 ``` Input: ``` 0,0,0,0,0,0,0,1 0,0,0,0,0,0,2,0 0,0,0,0,0,3,0,0 0,0,0,0,4,0,0,0 0,0,0,5,0,0,0,0 0,0,6,0,0,0,0,0 0,7,0,0,0,0,0,0 8,0,0,0,0,0,0,0 ``` Output: ``` 1/64* 36,4,8,0,16,0,0,0 -4,-36,0,-8,0,-16,0,0 -8,0,-36,-4,0,0,-16,0 0,8,4,36,0,0,0,16 -16,0,0,0,-36,-4,-8,0 0,16,0,0,4,36,0,8 0,0,16,0,8,0,36,4 0,0,0,-16,0,-8,-4,-36 ``` ## Scoring This is code golf, so the smallest program in bytes wins. [Answer] ## Haskell, ~~111~~ ~~102~~ ~~97~~ 92 bytes ``` import Data.Matrix t x|n<-nrows x=h n*x*h n h 1=1 h i|m<-h$div i 2=(/2)<$>m<->m<|>(m<->(-m)) ``` This uses the `Data.Matrix` module. The input matrix has to be of type `Matrix Float` or `Matrix Double`. TIO doesn't provide `Data.Matrix`, so no link. Edit: -9 bytes thanks to @ceased to turn counterclockwis, -5 bytes thanks to @H.PWiz, -5 bytes thanks to @xnor [Answer] # JavaScript (ES6), 114 bytes This version is golfed a bit further by embedding the function \$h\$ within the callback of the deepest loop. ``` M=>(g=z=>M=M.map((r,y)=>r.map((_,x)=>r.map(v=>s+=(h=m=>m?-h(m&~-m):z?v:M[i-1][x])(i++&(z?x:y)),i=s=0)&&s/i)))(g()) ``` [Try it online!](https://tio.run/##hY7dqoJAFIXvfYquZG8cS@v0g7DHJ/AJZAjpxyaaDCfEvOjVjZpsFIrDutnrY7H2OmZVpjelvFz9c7HdtXtqE@KQU0M8oWSssgtAyW5IvDRmzeqPqYhrj@BAiriK/QMo9@4rjJq4ipJU@qFIa4EgPc@FJq6jGyKTpClA19UTiYiQA2K7Kc66OO3GpyKHPaTOaJRO2Uwwc8yFIxCdL6GQvWSC/5vfNcFTNjww4dD8rglYX@/ffTTtmiya2V8d@uuvMWje5S1c2N4OLvv/DVwNJgWv6e0D "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~161 ... 117~~ 116 bytes ``` M=>(h=m=>m?-h(m&~-m):1,g=z=>M=M.map((r,y)=>r.map((_,x)=>r.map(v=>s+=(z?v:M[i][x])*h(i++&(z?x:y)),s=i=0)&&s/i)))(g()) ``` [Try it online!](https://tio.run/##hY7NjoJAEITvPIUn0i0DC7quhqTHJ@AJyMQQV2E2DhhmQ9CDr44/Iw4kazZ16fpSqa6frMn0tpbHX7@svnfdnrqEOBSkiKu1X4ByL77COGI5nYknlAQqOwLU7ITEa2M2rH2Zhrj2CM7rJk5SKdJW4LQA6XnujbXxCZFpkhSi6@oPiYiQA2K3rUpdHXbBocphD6kzmaQzNhfMHAvhCETnj1DEHjLB/837mvAuGx6ZaGze14RsqOfvIZr1TRbN7a8efQ7XGLTo8xZ@2d4eLof/DVyNJoWP6d0V "JavaScript (Node.js) – Try It Online") ### How? Each 0-indexed cell \$(x,y)\$ of a Hadamard matrix \$H\_n\$ is equal to: $$H\_n(x,y)=\cases{ 1,&\text{if $(x\And y)$ is evil}\\ -1,&\text{otherwise} }$$ or: $$H\_n(x,y)=(-1)^{\operatorname{popcount}(x \And y)}$$ where \$\And\$ is a bitwise AND and \$\operatorname{popcount(m)}\$ is the number of bits set in \$m\$. The function \$h\$ computes \$(-1)^{\operatorname{popcount}(m)}\$ recursively: ``` h = m => m ? -h(m & ~-m) : 1 ``` (This is similar to [my answer](https://codegolf.stackexchange.com/a/169732/58563) to [Is this number evil?](https://codegolf.stackexchange.com/q/169724/58563)) The function \$g\$ computes either \$\frac{1}{2^n}H\_nM\$ or \$\frac{1}{2^n}MH\_n\$, depending on the flag \$z\$: ``` g = z => // z = flag cleared on the 1st pass, set on the 2nd M = // update M[]: M.map((r, y) => // for each row r[] at position y in M[]: r.map((_, x) => // for each cell at position x in r[]: r.map(v => // for each value v in r[]: s += // add to s: (z ? v // v = M(i, y) if z is set, : M[i][x]) * // or M(x, i) otherwise h(i++ & (z ? x // multiplied by H(x, i) if z is set, : y)), // or H(i, y) otherwise // and increment i afterwards s = i = 0 // start with s = i = 0 ) // end of inner map() over the columns && s / i // yield s divided by the width of the matrix ) // end of outer map() over the columns ) // end of map() over the rows ``` We invoke it twice to compute \$\frac{1}{2^{2n}}H\_nMH\_n\$. [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` &nKYLw/Gy,Y* ``` [Try it online!](https://tio.run/##y00syfn/Xy3PO9KnXN@9UidS6///aCMdY2sFIx3TWAA) Or [verify all test cases](https://tio.run/##y00syfmf8F8tzzvSp1zfvVInUut/rLqurnqES1RFyP9oIx1jawUjHdNYrmhDBTC0VsDJACsyAEGIEJxhiGCAFBkoIEOgfmSuEUgtgmsMMQXGNYGZD@GawiQgAmYIjSABc2SDrRUsUOwxiAUA). ### Explanation Consider input `[2,3; 2,5]` as an example. ``` &n % Input (implicit). Push number of rows and number of columns % STACK: 2, 2 KYL % Hadamard matrix of specified size % STACK: 2, [1 1; 1 -1] w/ % Swap, divide element-wise % STACK: [0.5 0.5; 0.5 -0.5] G % Push input again % STACK: [0.5 0.5; 0.5 -0.5], [2,3; 2,5] y % Duplicate from below % STACK: [0.5 0.5; 0.5 -0.5], [2,3; 2,5], [0.5 0.5; 0.5 -0.5] , % Do twice Y* % Matrix multiply % End (implicit) % STACK: [3 -1; -0.5 0.5] % Display (implicit) ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~93~~ 79 bytes ``` @(x)(r=f(f=@(f)@(x){@()[x=f(f)(x-1) x;x -x],1}{1+~x}())(log2(r=rows(x)))/r)*x*r ``` This computes \$\frac{1}{2^n}H\_nX\frac{1}{2^n}H\_n\$ [Try it online!](https://tio.run/##fY3BCsIwEETv/Yo97lYbk9SqIIX8R@lBxHgRClF0odRfj01raLzIXGbf7ux058fpefG2FkJ4g0zoaou2NmgpjL1BajggQi4UAR8ZCm7XaujV6s0DEuGtu@ox57rXfYwQbRzlnDtvsdFQZgCgoWopG2cFkwL7a@O1DIo8sSq132sJqaZvKdBzZAFlfBjBdqmbQRVXEe2W@Iz2aUVAh59O2ZL/AA "Octave – Try It Online") # [Octave](https://www.gnu.org/software/octave/), ~~47~~ 33 bytes (uses builtin) ``` @(x)(r=hadamard(r=rows(x))/r)*x*r ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0JTo8g2IzElMTexKAXILMovLwYKauoXaWpVaBX9T9OINlIw5lJQUDBSMI3V5ALyDRXAECSGlwlTbQCCMHEkpiEyE6raQAEZgk1DFjCCaEEIGMMMhAmYIKyDCJjCpGBCZgjtECFzZCtAQhYodhrEav4HAA "Octave – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 28 bytes ``` {(⍵∘⌹+.×⌹)(,⍨⍪⊢,-)⍣(2⍟≢⍵)⍪1} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1rjUe/WRx0zHvXs1NY7PB1IaWroPOpd8ah31aOuRTq6mo96F2sYPeqd/6hzEVAlkLvKsPZ/2qO2CY96@x51NR9ab/yobeKjvqnFRclAsiQjsxgkO1HDSMFYE0iYanKpq3OlKZgomDzq3WII5oCkDRUMQFATyDBEMAwRDENNuFoDBWRoqIkiYATSguAaQwyDcU1g1kC4pjB1EAEzhDkgAXNkezQ1LFCsNdAEAA "APL (Dyalog) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 23 bytes ``` {ḍ\⟨+ᵐ↰₁ᵐ-ᵐ⟩c/₂ᵐ|}ᵐ\↰₁ᵐ ``` * Input: A list of columns * Output: A list of rows ## How: It uses the Fast Hadamard Transformation. AFAIK Brachylog doesn't have matrix multiplication, nor binary operations so I doubt using the "evil numbers technique" will help shorten the code. ``` {ḍ\⟨+ᵐ↰₁ᵐ-ᵐ⟩c/₂ᵐ|}ᵐ\↰₁ᵐ # {ḍ\⟨+ᵐ↰₁ᵐ-ᵐ⟩c/₂ᵐ|}ᵐ # Fast transform: { }ᵐ # for each column: ḍ # Split in 2 | # (if this fails, return the collum. # This is the case in the final recursion step) \ # Zip, +ᵐ # and add each pair (adds the 2 subvectors) -ᵐ # and sub each pair (subs the 2 subvectors) ⟨ ↰₁ᵐ ⟩ # and apply the transformation on both results c # concat both transformed results. /₂^m # and half each element \ # Transpose ↰₁ᵐ # and apply the transformation again ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/rhjt6YR/NXaD/cOuFR24ZHTY1Ahi6IM39lsv6jpiYgs6YWSMTAZf//j4420jGK1Yk21jGNjf0fBQA "Brachylog – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` J’&þ`B§-*ðæ×⁺@÷L$⁺ ``` A monadic Link accepting a list of lists of integers (any numbers really), the square input matrix of side \$2^n\$, which yields a list of lists of floats. **[Try it online!](https://tio.run/##y0rNyan8/9/rUcNMtcP7EpwOLdfVOrzh8LLD0x817nI4vN1HBUj///8/OtpQR8EAgmJ1FEA8Q3SeITrPMDYWAA "Jelly – Try It Online")** ### How? It feels like one should be able to outer-product the dot-product of the binary representations of the 0-indexed coordinates, however to do so one would need to left-pad the binary representations with zeros which, I believe, costs too many bytes. ``` J’&þ`B§-*ðæ×⁺@÷L$⁺ - Link: list of lists of integers, M J - range of length = [1,2,...,rows(M)] ’ - decrement (vectorises) = [0,1,...,rows(M)-1] ` - use left argument as both arguments of: þ - outer-product with: & - bit-wise AND [[0&0, 0&1, ...],[1&0, 1&1, ...], ...] B - convert to binary (vectorises) § - sums (vectorises at depth 1) - i.e. bit-sums - - literal minus one * - exponentiate (vectorises) - i.e. the appropriately sized Hadamard matrix, H ð - start a new dyadic chain - i.e. f(H, M) æ× - matrix multiply - i.e. H×M @ - with swapped arguments i.e. f(H×M, H): ⁺ - repeat previous link i.e. H×M×H $ - last two links as a monad: L - length (number of rows) ÷ - divide (vectorises) ⁺ - repeat the previous link (divide by the length again) ``` [Answer] # [R](https://www.r-project.org/), ~~80~~ ~~78~~ 74 bytes ``` function(M){for(i in 1:log2(nrow(M)))T=T%x%matrix(1-2*!3:0,2)/2 T%*%M%*%T} ``` [Try it online!](https://tio.run/##PYyxCsIwFEX3fkUcAu@VV7WvcSl2dOwi8QNqNSXQJhAqrYjfHoOIwz3D4XBDNOJYiGgerp@td9Diy/gAVlgnynr0A4MLfkkeUTdarnLq5mBXKAvON1W9J8YdZ1rmsk3T72jgV/TAVBHTAROYrs/00@jz5YSY/aOSFKmvGP1yD9sk4Wa7ARSSRowf "R – Try It Online") Calculates \$\frac{1}{2^n}H\_nX\frac{1}{2^n}H\_n\$; constructs \$\frac{1}{2^n}H\_n\$ by Kronecker product `%x%`. Looks like I can still golf, recalling that `1-2*!3:0` is shorter than `c(1,1,1,-1)` as I realized in the comments to [this answer](https://codegolf.stackexchange.com/a/162303/67312). [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 51 bytes ``` a->h=1;while(#h<#a,h=matconcat([h,h;h,-h])/2);h*a*h ``` [Try it online!](https://tio.run/##dY3NCoMwEIRfJeglkQ01sX@Q6ouIh0VqV7A2iFD69GmMtdpDmcPstwwzFodW3qxrWM4cyoJyZZ7Udlce0yVGoPyOY/3oaxx5SUCGQFIldloYSjAhh9Z2L45MFswObT/6M5ogYg1HIYCVpYbMaDhU/lYQZP74HEknhdfi6ushksJWymxJ@@hKWahYaP@pnumwpAIf1w7Pp@2COf/spVUl3Bs "Pari/GP – Try It Online") ]
[Question] [ When babies open their mouths, they're not just spewing gibberish. They're actually talking in a highly advanced, adult-proof cipher... # The Baby-talk Cipher When a baby talks, it could look something like `gogooa gagooook aagaaoooy` Each single-space separated section represents a character (so the example above represents 3 characters). To decipher a section, we must count number of As and Os it contains. However, we only count those which are adjacent to another vowel. For example, the A in 'gag' would not count, but both the A and O in 'gaog' would. Counting the example above would look like this: ``` Section | Num Os | Num As gogooa | 2 | 1 gagooook | 4 | 0 aagaaoooy | 3 | 4 ``` We then use these values to convert the input into plaintext on a Polybius square. This is a 5x5 representation of the English alphabet, omitting 'J' (please note that, in baby-talk, 0-counting rules apply to the table): ``` 0 1 2 3 4 0 A B C D E 1 F G H I K 2 L M N O P 3 Q R S T U 4 V W X Y Z ``` Using the number of Os as the column, and number of As as the row, we find which character each section represents: ``` Section | Num Os | Num As | Character gogooa | 2 | 1 | (2,1) -> H gagooook | 4 | 0 | (4,0) -> E aagaaoooy | 3 | 4 | (3,4) -> Y ``` Which tells us that the baby was just saying "HEY". **Notes**: - If a section representing a character has more than 4 As or Os, ignore the extras, because 4 is the maximum value on the table. - For this task, Y is not a vowel - only A, E, I, O and U. # The Challenge Your task is to create a *full* program which takes one input, a word in baby-speak, and prints it in plaintext. * Your program must be able to take input in uppercase, lowercase, and a mix of both. * The input will only contain ASCII alphabet letters (A-Z and a-z), with single spaces to seperate the baby words. * The output text can be in any case. * You should the take the input from `STDIN` and print the plaintext on `STDOUT`. If your language does not have these, use the nearest equivalent. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins - but any solution is welcome. # Test Cases ``` 'GLOOG KAKAAOOO ARGOOO OOOOOGUGUU' -> CODE 'oaka pooopaa gaau augu' -> GOLF 'Aoao U oOOAoa oaoAoo aoAoAOa' -> NAPPY 'GUG gAGaA gOougOou' -> ALE 'OOaGOG GoGOOoGoU gAA bLAA GOUGoOUgAIGAI' -> HELLO ``` [Answer] # Perl, 82 bytes Includes +1 for `-a` Give input on STDIN: ``` perl -M5.010 baby.pl <<< "OOaGOG GoGOOoGoU gAA bLAA GOUGoOUgAIGAI" ``` `baby.pl`: ``` #!/usr/bin/perl -a say map{$A=$O=$_=uc;y/AEIOU/@/c;s/(\B.|.\B)/$$1+=$$1<4/eg;(A..I,K..Z)[5*$A+$O]}@F ``` This assumes a recent enough perl version where `-a` implies `-n`. If your perl is too old you will need to add an explicit `-n` option. It also assumes babies can't say general ASCII strings that start with digits like `1 this will not work` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 46 bytes ``` lð¡vyžNvyð:}ð¡D€g1›ÏJ©'a¢4‚W5*®'o¢4‚Ws\+A'j-è? ``` [Try it online!](http://05ab1e.tryitonline.net/#code=bMOwwqF2ecW-TnZ5w7A6fcOwwqFE4oKsZzHigLrDj0rCqSdhwqI04oCaVzUqwq4nb8KiNOKAmldzXCtBJ2otw6g_&input=T09hR09HIEdvR09Pb0dvVSBnQUEgYkxBQSBHT1VHb09VZ0FJR0FJ) **Explanation in steps** 1. split on spaces to form words 2. replace konsonants in words with spaces 3. split words on spaces to form groups of vowels 4. remove vowel groups with a length shorter than 2 5. get min of count(a) and 4, multiply by 5 6. get min of count(o) and 4 7. add counts 8. get letter at that index of alphabet (excluding "j") [Answer] # brainfuck, 656 bytes ``` +[[>>>,[>++++[<-------->-]]<]<<[>]<-[+[<+>>+<-]----[>>+<<----]>>+[<[-<]<[>]>>-]-<[[-]>+<]>[[-[->]<<+>]<->>>]<<<[>>>+<<<-]<<-]>>>>>[[<+>>+<-]----[>-<----]>--[----<]<[>]>[----<]<[>]>[------<]<[>]>[------<]<[>]><+>[[-]<->]>>]<<<[>->]<[<]>[>[<<<<<+>>>>>>+<-]<<<<]<[-]>>>>[<[>[>+<-]<-]>[-]->[<+>-]>>]<<<[-<----[>-<----]>[>+>+<<-]+>[<->[-]<]<[<]>[[<<<]<+>>>>[>>>]<<<-]>+>--------------[<->[-]]<[-<<<<[<<<]>+>>[>>>]>]<<<<]<[<+<+>>-]>++++[<<[->]>[<]>-]+<<[[-]++++<[-]>>]>[<]<<[>+<-]>>+>->[>+>+<<-]<++++[>>[-<]<[>]<-]>>[[-]++++>[-]]<<<[>]<->>>>[<+>-]<[<<<+>>>-]<<<<[>+++++<-]>[>+>+<<-]<++++++++[>>[-<]<[>]<-]>>[[-]>+<]----[>+<----]>++.[-]+>>>,[<++++[>--------<-]]>] ``` This was a pretty good way to kill a couple of hours. Requires a brainfuck interpreter that uses 8-bit wrapping cells, allows you to go left from cell 0 and returns 0 if `,` is used when stdin is empty. In my experience, these are the most common settings. This program does not consider Y a vowel, but if OP wants it to it's an easy fix. It seems like writing this would be a daunting task but if you have some familiarity with the language there's nothing surprising or new in the code. Standard brainfuck tactics: Read the input but make sure you leave a couple of empty cells between each byte, use those empty cells to store data about the input, use the data you stored to decide how to transform it and spit something out at the end. In this case it was get the input, set it all to uppercase, figure out which cells are vowels, throw that information away after using it to determine which cells are *next to* vowels, set everything that isn't next to a vowel to some value that will never be relevant so they're not in the way later, and you're basically done. From there you just have to count your `A`s and `O`s, multiply `A`s by 5 and add the number of `O`s, special case anything above 8 to avoid J and output. I did choose to handle this one word at a time, rather than taking the whole input at once, so I had to set up the part of the code that reads stdin to break at 0 or 32, but that's not too big of a problem (just wrap the subtraction by 32 in a conditional so it doesn't happen if the value is already 0, then correct for any `<` or `>` instructions you missed later). I don't know how helpful it will be because I wrote it mostly to keep my thoughts straight rather than as a real explanation, but here's the code with my comments and its original indentation: ``` +[[>>>,[>++++[<-------->-]]<]get an entire word of input each character lowered by 32 two empty cells between characters stops when reaching a space or null byte any lowercase letters have become uppercase; anything with a value below 65 used to be an uppercase character; fix it <<[>]<-[+ for each character until hitting 1: [<+>>+<-] make a backup subtract 64 from the character but stop if it hits 0 ----[>>+<<----]>>+ generate the number 64 [ 64 times: <[ if the character is not 0: - subtract 1 < go to a guaranteed 0 cell to break the loop ] we're either on the character or to the left of it; sync up <[>] >>-] -<[[-]>+<]> logical NOT of character [ if logical NOT returns true: [-[->]<<+>]<- add 32 to backup of character >>>] <<<[>>>+<<<-] move copy over to make room <<-] >>>>>[ for each character: [<+>>+<-] make copies ----[>-<----]>-- check if it's A [----<]<[>]> check if it's E [----<]<[>]> check if it's I [------<]<[>]> check if it's O [------<]<[>]> check if it's U IF YOU NEED TO ADD Y; THIS IS THE PLACE <+>[[-]<->] logical NOT to complete vowel check >>] <<<[ if the last char is a vowel; prevent a side effect >-> ] <[<]>[ for each character: >[ if it's a vowel: <<<<<+>>>>>>+<- leave a flag to the left and right to show that a ] vowel is adjacent <<<<] <[-]> clean up a side effect left behind if first char is vowel >>>[ for each char: <[ if it's adjacent to a vowel: >[>+<-]<- move it to the side ] >[-]- otherwise; destroy it >[<+>-] move backup over if it exists (subtracting 1) >>] all characters without a vowel beside them have been set to 255 all characters with a vowel beside them are set to itself minus 1 notable charaters are: 'A' minus 1 = 64 'O' minus 1 = 78 <<<[ for each character: -<----[>-<----] subtract 64 >[>+>+<<-] make a copy +>[<->[-]<]<[<]> logical NOT [[<<<]<+>>>>[>>>]<<<-] if NOT returns true; record an A >+>-------------- subtract 14 from backup [<->[-]]< logical NOT [-<<<<[<<<]>+>>[>>>]>] if NOT returns true; record an O <<<<] <[<+<+>>-] make a backup of A count >++++[<<[->]>[<]>-] subtract 4 but don't go below 0 +<<[ if the char was greater than 3: [-]++++<[-]>> put 4 there ] >[<] resynchronise <<[>+<-] if there were fewer than 4 As put the number back same thing but for the O count >>+>->[>+>+<<-] make a backup of O count <++++[>>[-<]<[>]<-] subtract 4 but don't go below 0 >>[ if the char was greater than 3: [-]++++>[-] put 4 there ] <<<[>] resynchronise <->>>>[<+>-] if there were fewer than 4 Os put the number back <[<<<+>>>-]<<<<[>+++++<-] A*5 plus B = index of character to output >[>+>+<<-] make a backup <++++++++[>>[-<]<[>]<-] subtract 8 but don't go below 0 >>[[-]>+<] if the result is nonzero it is late enough in the alphabet that it must be increased by 1 to exclude J as a possible output ----[>+<----]>++ add 65 to make it a letter .[-]+>>>, output and get new input [<++++[>--------<-]]> sub 32 if not 0 ] ``` [Answer] # JavaScript (ES6), 145 bytes ``` alert(prompt().replace(/\S+ ?/g,x=>(g=r=>(q=(x.match(/[aeiou]{2,}/gi)+"").split(r).length-1)>4?4:q,(g(/a/i)*5+g(/o/i)+10)*20/19|0).toString(36))) ``` Replaces each word (and the following space) with its corresponding letter. `s.split` `.map().join``` is 3 bytes longer: ``` alert(prompt().split` `.map(x=>(g=r=>(q=(x.match(/[aeiou]{2,}/gi)+"").split(r).length-1)>4?4:q,(g(/a/i)*5+g(/o/i)+10)*20/19|0).toString(36)).join``) ``` [Answer] # Perl, 159 +1 = 160 bytes +1 byte for -n flag. Whitespace is not part of the code and is only provided for readability. ``` for(split$",lc){ $b=0; @a=sort/([ao](?=[aeiou])|(?<=[aeiou])[ao])/g; $b++until$b>$#a||$a[$b]eq o; $c=($d=$#a-$b+1)>4?4:$d; $b=$b>4?4:$b; print+(a..i,k..z)[5*$b+$c]; } ``` The code splits the input by spaces and converts each baby word to lowercase before proceeding. The regex finds all a or o vowels that are followed by another vowel, or are preceeded by a vowel, and sorts them, a's at the start, o's at the end, then finds the index of the first 'o'. If the remaining number of matches (aka, the number of 'a's) is greater than 4, then we care about 4 a's, and if there are more than 4 o's, we care about 4 o's. Then it pulls the appropriate letter out of the matrix and prints it, then moves onto the next baby word. [Answer] ## Brainfuck, 283 bytes ``` ,[[<[>-[>>>-<<<----[----[>+<------[>-<------[<[-]>>>>[-]->>[-]<<<<<-]]]]]>[>>>>+ <<<<-]>>+<[>[>+<-]>>[>+<-]<<<-]<,<<[>>>+<<<-]>]>+[<+>[-<<]>[[-]+++++[<++++++>-]< +<]>>>]<]>>[-]>+>>+[[-]>[<+>-[<+>-[<+>-[<+>[-]]]]]<<<]>->[>+<-[[>+<-]>>+>]>[+>-- --[->]]]+[-<+]>>+++++++++++++[>+++++<-]>.,] ``` Formatted: ``` , [ [ < [ >- [ not a >>>-<<< ---- [ not e ---- [ not i >+< ------ [ not o >-< ------ [ consonant <[-]> >>>[-]->>[-]<<<<<- ] ] ] ] ] >[>>>>+<<<<-]> >+< [ prev was vowel >[>+<-]>>[>+<-]<<<- ] <,<<[>>>+<<<-] > ] >+ [ <+>[-<<] >[[-]+++++[<++++++>-]<+<] >>> ] < ] >>[-]>+>>+ [ [-] >[<+>-[<+>-[<+>-[<+>[-]]]]]< << ] >-> [ >+<- [ [>+<-] >>+> ] > [ +>----[->] ] ] +[-<+] >>+++++++++++++[>+++++<-] >., ] ``` This works with or without a trailing newline in the input. [Try it online.](http://brainfuck.tryitonline.net/#code=LFtbPFs-LVs-Pj4tPDw8LS0tLVstLS0tWz4rPC0tLS0tLVs-LTwtLS0tLS1bPFstXT4-Pj5bLV0tPj5bLV08PDw8PC1dXV1dXT5bPj4-Pis8PDw8LV0-Pis8Wz5bPis8LV0-Pls-KzwtXTw8PC1dPCw8PFs-Pj4rPDw8LV0-XT4rWzwrPlstPDxdPltbLV0rKysrK1s8KysrKysrPi1dPCs8XT4-Pl08XT4-Wy1dPis-PitbWy1dPls8Kz4tWzwrPi1bPCs-LVs8Kz5bLV1dXV1dPDw8XT4tPls-KzwtW1s-KzwtXT4-Kz5dPlsrPi0tLS1bLT5dXV0rWy08K10-PisrKysrKysrKysrKytbPisrKysrPC1dPi4sXQ&input=R0xPT0cgS0FLQUFPT08gQVJHT09PIE9PT09PR1VHVVUgb2FrYSBwb29vcGFhIGdhYXUgYXVndQ) Each character is processed mod 32 (with control flow such that the code implementing the mod operation only occurs once in the program). This enables case insensitivity, as well as collapsing the space character and EOF into a single case. A trailing newline is treated the same as `J`, which doesn't affect the output. Sketch of memory layout: `0 x C c y a A b B` where `c` is the input character, `C` is the char mod 32, `x` is whether it is a vowel, `y` is whether the previous char was a vowel, `A` and `B` are the counts of valid (next to vowels) `a` and `o` chars respectively, and `a` and `b` are their respective buffers that get copied or cleared depending on whether there is an adjacent vowel. When a space or EOF is reached, some juggling is done to reduce counts greater than 4 and to skip the letter `J`, and then the decoded character is printed. [Answer] # PHP, 163 bytes ``` <?php for(;$c=preg_replace('/(?<![AEIOU]).(?![AEIOU])/','',strtoupper($argv[++$i]));$j=min($d[79],4)+5*min($d[65],4),print range(A,Z)[$j+($j>8)])$d=count_chars($c); ``` More readable version: ``` <?php for ( ; $c = preg_replace( '/(?<![AEIOU]).(?![AEIOU])/', '', strtoupper($argv[++$i]) ); $j = min($d[79], 4) + 5 * min($d[65], 4), print range(A, Z)[$j + ($j > 8)] ) $d = count_chars($c); ``` Tests: ``` $ php babytalk.php GLOOG KAKAAOOO ARGOOO OOOOOGUGUU CODE $ php babytalk.php oaka pooopaa gaau augu GOLF $ php babytalk.php Aoao U oOOAoa oaoAoo aoAoAOa NAPPY $ php babytalk.php GUG gAGaA gOougOou ALE $ php babytalk.php OOaGOG GoGOOoGoU gAA bLAA GOUGoOUgAIGAI HELLO ``` [Answer] # Java 8, ~~272~~ ~~266~~ ~~251~~ 249 bytes ``` interface M{static void main(String[]i){String z="(?=[AEIOU])|(?<=[AEIOU])";for(String s:i[0].split(" ")){int a=s.split("(?i)A"+z+"A",-1).length-1,o=s.split("(?i)O"+z+"O",-1).length-1,t=(a>4?4:a)*5+(o>4?4:o);System.out.printf("%c",t>9?t+66:t+65);}}} ``` -6 bytes thanks to *@Joba*. -1 byte converting from Java 7 to 8, and ~~14~~ 16 additional bytes saved by changing the print-part. **Explanation:** [Try it here.](https://tio.run/##jY9NaxsxEIbv@hWDoLDyVxpIArXrLDoUYZIy0LCHYHyYbuSNkuzOstIGEte/fTN220BzqkDvzOh9RiM90DNNufXNw93jMIQm@W5LpYfvu5gohRKeOdxBTaHJblIXmmq9CWb3O4XXpc7y5dp@W2GxMb@y/Ot7oRdb7v60QJyH9efNLLZPIWUatDE7mQS0jH/PsjwYq8evY231ZHpqZk@@qdL99HTC/0J4hPADlJYZXZ7lZ3Myo/NxxseczeLmJSZfz7hPs1ZekraZ/lTqSbr8kqfxxcVc5Nws9vv9cDJS6pZ7KKmBktuXaUvSCuneA4t0kHxM4kYfYdtxLU6IQta1l58kPpLUVf17LfxcKXeN6ODKXlmLiGB/uEPAw3KFKwrF9EjQMnNLBBVRD9RXvbJMDAUwomQghWWGg1okJZ1QWUcWKuT@sBUiORnkWO5nx4X4Fn5eizgsHGNR2ZWzK6VGJ8Pwn/Ab) ``` interface M{ // Class: static void main(String[]i){ // Main method: String z="(?=[AEIOU])|(?<=[AEIOU])"; // Regex-part for look-ahead or look-behind of vowels for(String s:i[0].split(" ")){ // Loop over the program-arguments int a=s.split("(?i)A"+z+"A",-1).length-1, // The amount of A's with adjacent vowels o=s.split("(?i)O"+z+"O",-1).length-1, // The amount of O's with adjacent vowels t=(a>4?4:a) // If `a` is larger than 4, just take 4, else take `a` *5 // Multiply it by 5 +(o>4?4:o); // And add 4 if `o` is larger than 4, else take `o` System.out.printf("%c", // Print a character: t>9? // If `t` is larger than 9 (index of J) t+66 // Take character unicode (skipping J) : // Else: t+65); // Take character unicode (prior to J) } // End of loop } // End of main-method } // End of program ``` [Answer] # Python 3, ~~163~~ ~~162~~ ~~157~~ 146 bytes ``` import re for W in input().upper().split():S=''.join(re.findall("[AEIOU]{2,}",W)).count;I=min(S('A'),4)*5+min(S('O'),4);print(end=chr(65+I+(I>9))) ``` Uses regex to find all string of vowels larger than 2, counts As and Os with maximum of 4, and then prints. [Answer] ## APL, 60 ``` {⎕A[a+9<a←5⊥+/¨'ao'∊⍨¨⊂⍵/⍨0(,∨,⍨)2∧/⍵∊'aeiou']}¨' '(≠⊂⊢)819⌶ ``` Note that ⎕IO←0 and ⎕ML←3 Example: ``` fn←{⎕A[a+9<a←5⊥+/¨'ao'∊⍨¨⊂⍵/⍨0(,∨,⍨)2∧/⍵∊'aeiou']}¨' '(≠⊂⊢)819⌶ fn 'Aoao U oOOAoa oaoAoo aoAoAOa' NAPPY ``` Works in [Dyalog 15.0](http://dyalog.com/download-zone.htm), since it's the version in which 819⌶ was introduced to lowercase a string. [Answer] # Pyth, 64 bytes Can probably be golfed further. [Try it here !](https://pyth.herokuapp.com/?code=L%3F%3Cb5b4DebK%2Bds%3ArbZ%22%5Baeiou%5D%7B2%2C%7D%221J%2B%2A%2FK%5Ca5y%2FK%5CoR%40G%3F%3CJ9JhJu%2BGeHcQd%22&input=%22Aoao%20U%20oOOAoa%20oaoAoo%20aoAoAOa%22&test_suite=1&test_suite_input=%22GLOOG%20KAKAAOOO%20ARGOOO%20OOOOOGUGUU%22%0A%22oaka%20pooopaa%20gaau%20augu%22%0A%22Aoao%20U%20oOOAoa%20oaoAoo%20aoAoAOa%22%0A%22GUG%20gAGaA%20gOougOou%22%0A%22OOaGOG%20GoGOOoGoU%20gAA%20bLAA%20GOUGoOUgAIGAI%22&debug=0) ``` L?<b5b4DebK+ds:rbZ"[aeiou]{2,}"1J+*/K\a5y/K\oR@G?<J9JhJu+GeHcQd" ``` [Answer] ## R, 261 bytes I think I spent way too much time just to get this working and I believe this is an unnecessarily complicated solution, although it works. Takes input from stdin, it's important that the string is enclosed in quotes. ``` x=el(strsplit(toupper(scan(,""))," ")) cat(apply(sapply(c("A","O"),function(y)sapply(sapply(regmatches(x,gregexpr("[AEIOU]{2,}",x,)),paste,collapse=""),function(s)min(sum(el(strsplit(s,""))%in%y),4)))+1,1,function(z)t(matrix(LETTERS[-10],5))[z[1],z[2]]),sep="") ``` The use of four nested `apply`-family could theoretically be reduced to only two by making use of `mapply` instead. But because inputs to `mapply` will not be of the same length, the shorter one is recycled which complicates things and I couldn't figure out a working solution. If anyone is interested I'll add an ungolfed explanation later. [Try all the test cases on R-fiddle](http://www.r-fiddle.org/#/fiddle?id=KBUGzWIv&version=3) Please note that this version takes input as a function argument instead from stdin because `scan` doesn't work on R-fiddle. Furthermore, added a newline to make it easier to read. [Answer] # Python 3, 262 bytes ``` import re;f,b,v,n,r,l,t,g,a,o=re.findall,input().lower(),'aeiou',list(range(26)),'[aeiou]','abcdefghiklmnopqrstuvwxyz','',len,'a','o';del n[9], for w in b.split(): O,A=g(f(o+r,w))+g(f(r+o,w)),g(f(a+r,w))+g(f(r+a,w)) if O>4:O=4 if A>4:A=4 t+=l[A*5+O] print(t) ``` Less Golfed (The comments are the variables in the shortened code): ``` import re findAll = re.findall #f babyTalk = input('Baby Talk: ').lower() #b vowels = 'aeiou' #v numbers = list(range(26)) #n del numbers[9] letters = 'abcdefghiklmnopqrstuvwxyz' #l finalText = '' #t length = len #g regex = '[aeiou]' #r o = 'o' #o a = 'a' #a for word in babyTalk.split(): #w in b Os = len(findAll('o[aeiou]', word)) + len(findAll('[aeiou]o', word)) #O As = len(findAll('a[aeiou]', word)) + len(findAll('[aeiou]a', word)) #A if Os > 4: Os = 4 if As > 4: As = 4 print(As, Os) finalText += letters[As*5+Os] print(finalText) ``` [Try it online!](https://repl.it/EMOV/0) [Answer] ## [Kotlin](https://kotlinlang.org), ~~221~~ 209 bytes Now *much* more ugly and slow, all in the name of **11 bytes** ``` readLine()!!.toLowerCase().split(" ").map{fun c(c:Char)=Regex("([aeiou]{2,})").findAll(it).fold(0){a,b->a+b.value.count{it==c}}.let{if(it>4)4 else it} (('A'..'I')+('K'..'Z'))[c('a')*5+c('o')]}.forEach(::print) ``` Save it to a file (ex. `BabyTalk.kts`) to run as a script. Or, the above code can be prepended with `fun main(z:Array<String>)=` and compiled normally for a cost of 26 more bytes. [Try it online!](https://tio.run/##FY9NawIxEIbv/oroJTPVhlLsZekuBClLUViweKl4GNe4BmOyZJN@Lfvbt/G9zDPwMMN7dcFoO56jZTfSFv4y6T39vn4Er21TYD56RaeNtgpwOhXBbdy38ivq0i661ugAMzZDcaO2T0cmNdTZ6kIe861q1A/MYE9Ku3jonxcDJvGs7UkaAzokduYET9jT4vhY0PwovshEJWoXbeh1yPN6GIRRic/JL5a4ZMp0iukwTAC45ELwd45z4Os7fnLEfQ2cOD68zBM4jochffFvVF8gy9rUKeA4lpuqKtlarqWsqorJbXkf1T3lrtztmKMrsdY51xKxhigyik38Bw "Kotlin – Try It Online") Indented: ``` readLine()!! .toLowerCase() .split(" ") .map { fun c(c: Char) = Regex("([aeiou]{2,})") .findAll(it) .fold(0) { a, b -> a + b.value.count { it == c } } .let { if (it > 4) 4 else it } (('A'..'I') + ('K'..'Z'))[c('a') * 5 + c('o')] } .forEach(::print) ``` [Answer] # PHP, ~~124 129 121 120~~ 125 bytes ``` for(;$s=$argv[++$i];print chr((8<$O+=5*$A)+$O+65))for($k=$A=$O=0;$c=_&$s[$k++];$p=$c)$$c+=$$c<4&!trim($p.$s[$k]&__,AEIOU)[1]; ``` Takes input from command line arguments. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/1058dbd09688885ffee8a17473b9dcfe025b25ed). **breakdown** ``` for(;$s=$argv[++$i]; # loop $s through arguments print chr((8<$O+=5*$A)+$O+65) # 3. map A and O counts to letter, print ) for($k=$A=$O=0; # 1. reset A and O counters $c=$s[$k++]&_; # 2. loop $c through characters: $p=$c) # 2. remember current character as previous $$c+= # 1. increment counter for $c, if ... $$c<4& # it is < 4 and ... !trim($p.$s[$k]&__,AEIOU)[1]; # ... previous or next char is vowel ``` [Answer] # [J](http://jsoftware.com/), 109 bytes ``` echo{&(u:97+i.26)(+8<[)5#.4<.'AO'+/@e."1 0/~(;@#~1<#@>)@(</.~0+/\@,}.~:&(e.&'AEOUI')}:);._1' ',toupper 1!:1]3 ``` [Try it online!](https://tio.run/##DcRNC8IgGADgv2INpuLQ2XdOQg8hg@A9eaqICll1cUQ7xfzr1nN4XjmH@yN@SzKo7Zo9@WxFCdvoI10WfKE5toCZMIFPJapFIo0pEpK6MDtqiBY81UycTDXypEoSeIntHnyL6ahowy8SI1x94tD34Y3kRMnzPGeAqwOHXHQA0UWPOmvR7fDPgXcRfGdbZ9sf "J – Try It Online") ]
[Question] [ Given an integer **1 ≤ N ≤ 1,000,000** as input, output the last non-zero digit of **N!**, where **!** is the factorial (the product of all numbers from **1** to **N**, inclusive). This is OEIS sequence [A008904](//oeis.org/A008904). Your program needs finish within 10 seconds on a reasonable machine for any valid input. # Test Cases ``` 1 => 1 2 => 2 3 => 6 4 => 4 5 => 2 6 => 2 7 => 4 8 => 2 9 => 8 10 => 8 100 => 4 1000 => 2 10000 => 8 100000 => 6 1000000 => 4 ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins! [Answer] ## Mathematica, ~~45~~ 36 bytes ``` Last@Select[IntegerDigits[#!],#>0&]& ``` Very readable for a winning answer. :) (Then again, there's no GolfScript & Co. submission yet.) This handles input 1,000,000 in about 5 seconds on my machine. [Answer] # Ruby - 63 chars ``` f=->n{n<2?1:6*[1,1,2,6,4,4,4,8,4,6][n%10]*3**(n/5%4)*f[n/5]%10} ``` Source - <http://oeis.org/A008904> Handles f upto a thousand digits under a second. # Test ``` irb(main):014:0> for n in 2..6 irb(main):015:1> puts f[10**n] irb(main):016:1> end 4 2 8 6 4 ``` [Answer] ## Python - 75 ``` n=input() g=1 while n: g*=n while g%10<1:g/=10 g%=10**9 n-=1 print g%10 ``` [Answer] ## PARI/GP - 27 bytes This trades speed for size -- the testcase takes a long time (~6 seconds). ``` n->n!/10^valuation(n!,5)%10 ``` This version is much faster (~15 microseconds) but takes 81 bytes: ``` n->r=1;while(n,r*=Mod(4,10)^(n\10%2)*[1,2,6,4,2,2,4,2,8][max(n%10,1)];n\=5);lift(r) ``` You can use this (non-golfed) code to test either: ``` [%(10^n) | n <- [1..6]] ``` [Answer] # JavaScript, 59 bytes Based on [this answer](https://math.stackexchange.com/a/130389/1156907) ``` f=n=>n>9?'6248'[(a=n/5|0)%4]*f(a)*f(n%5)%10:'1126422428'[n] ``` Try it: ``` f=n=>n>9?'6248'[(a=n/5|0)%4]*f(a)*f(n%5)%10:'1126422428'[n] ;[ 0, // 1 1, // 1 2, // 2 3, // 6 4, // 4 5, // 2 6, // 2 7, // 4 8, // 2 9, // 8 10, // 8 20, // 4 100, // 4 1000, // 2 10000, // 8 100000, // 6 1000000, // 4 ].forEach(n=>console.log(n, f(n))) ``` Modified formula is: $$ D(0) = 1 \\ D(1) = 1 \\ D(2) = 2 \\ D(3) = 6 \\ D(4) = 4 \\ D(5) = 2 \\ D(6) = 2 \\ D(7) = 4 \\ D(8) = 2 \\ D(9) = 8 \\ D(n) = (LastDigitOf(2^{\lfloor n/5 \rfloor}) \* D(\lfloor n/5 \rfloor) \* D(n \mod 5)) \mod 10, \;where \;n > 9 $$ ## How? The original formula is \$D(n) = (2^{[n/5]} \* D([n/5]) \* D(n \mod 5)) \mod 10\$ But there is a problem: we need to calculate \$2^{[n/5]}\$. For example if \$n = 10 000 \$ then we need to calculate \$2^{2000}\$ which is already too hard (in JS it will output `Infinity`). But I discovered that we don't need to calculate it instead of this we just need to calculate the last digit of \$2^{[n/5]}\$. Why? Because each time we just need to calculate the last digit of \$2^{[n/5]} \* D([n/5]) \* D(n \mod 5)\$ ### Theorem The last digit of multiplication is the last digit of multiplication of last digits of each multiplier ### Proof Let's say we have two numbers \$a\$ and \$b\$. We can represent each of them to the power of `10`: $$ a = x\_n \* 10^n + x\_{n - 1} \* 10^{n - 1} + \ldots + x\_1 \* 10^1 + x\_0 \\ b = y\_n \* 10^m + y\_{m - 1} \* 10^{m - 1} + \ldots + y\_1 \* 10^1 + y\_0 $$ or $$ a = (x\_n \* 10^{n - 1} + x\_{n - 1} \* 10^{n - 2} + \ldots + x\_1) \* 10 + x\_0 \\ b = (y\_n \* 10^{m - 1} + y\_{m - 1} \* 10^{m - 2} + \ldots + y\_1) \* 10 + y\_0 $$ When we multiply them we will get: $$ a \* b = (...) \* 10 + x\_0 \* y\_0 $$ Now it is clear that the last digit of multiplication is the last digit of \$x\_0 \* y\_0\$, where the \$x\_0\$ and \$y\_0\$ are the last digits of \$a\$ and \$b\$ respectively. So we proved the theorem Now we need to find the last digits of powers of `2`. Let's write some of them: $$ 2^0 = 1 \\ 2^1 = 2 \\ 2^2 = 4 \\ 2^3 = 8 \\ 2^4 = 16 \\ 2^5 = 32 \\ 2^6 = 64 \\ 2^7 = 128 \\ 2^8 = 256 $$ Now we can see the pattern `1 (2 4 8 6) (2 4 8 6)` and can write it \$(k = [n / 5])\$: ``` if (k == 0) return 1; else return [6, 4, 8, 7][k % 4]; ``` We can ignore the first case when `k == 0` and here is why: `k % 4 == 0` when `k is one of [0, 4, 8, 12, 16, ...]` but we need to consider cases when `k is one of [0, 4, 8]` because for bigger values we will run recursion. The second multiplier in our formula is \$D(k)\$ and for `k is on of [0, 4, 8]` we get `[1, 4, 2]` respectively. We had to multiply these values by `1` but instead of this we will multiply them by `6` so we will get `[1, 24, 12]`, the last digits of these values are `[1, 4, 2]`. Now we can see that it doesn't matter to multiply them by `1` or `6` the last digits will be the same The last thing we need it is to prove that \$[n / 5] = \lfloor n / 5 \rfloor\$ for \$n \ge 0\$. I think it is obvious [Answer] # Perl, 53 ~~58~~ ~~61~~ characters All whitespace can be removed, but I left it in for "readability". Note: not using some silly explicit formula from Sloane. ``` sub f { $_ = $1 * ++$n || 1, /(.{1,7}?)0*$/ while $n < $_[0]; $1 % 10 } ``` Calculates f(10^6) in 8.7 seconds on my machine. **Update**: OP wanted it to be a whole program: ``` $_ = $1 * ++$n || 1, /(.{1,7}?)0*$/ while $n < $ARGV[0]; print $1 % 10 ``` That makes it 55 characters. [Answer] # CJam - 28 ``` 1ri{I)*_AbW%{}#A\#/1e7%}fIA% ``` You can try it at <http://cjam.aditsu.net/> for values up to 10000 or so; for larger numbers you should use the [java interpreter](https://sourceforge.net/projects/cjam/). 1000000 runs in about 3 seconds on my laptop. **Explanation:** Unfortunately the straightforward solution is too slow, so I'm keeping only the last 7 digits (before the trailing zeros) after each multiplication. ``` 1 push 1 on the stack ri read a token and convert to integer { loop (for I from 0 to N - 1) I) push I and increment * multiply with the previous value (initially 1) _Ab duplicate and convert to array of digits W% reverse array {}# find the position of the first non-zero digit A\# raise 10 to that power / divide, thus removing all trailing zeros 1e7% keep the remainder modulo 10000000 }fI end for loop A% get the last digit ``` **Note:** this language is a lot newer than the question. [Answer] # Mathematica, 34 bytes ``` Mod[#!/10^IntegerExponent[#!],10]& ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 62 bytes ``` n->{long f=n;for(;n>1||f%10==0;)f=n>1?f*--n:f/10;return f%10;} ``` [Try it online!](https://tio.run/##LU9BboNADLz3FValSNAYipO0abNa@oKecolU9bAlbLQpMQiWKBXh7dSQSLalGdnjmaM5m6iscj7uf4esME0Dn8Zx9wDg2Oe1NVkOuxECFCUfIAuEBw6VUL20VOONdxns4AIaBo7Sbtq0mpUt60BxSternVGidaJCoVP6sE9RxBv7TImqc9/WDOOC6gd106zan0I079Ln0u3hJL6Cra8dH76@wYQ3U6MbL1hDR7jAJa7wBV9xjW/4jpQgEdICaYm06tV4MF2JL5iCuI0PJ2b71/j8FJetjyt54QsOHMzhEXQqYw6XWJKH99j98A8 "Java (OpenJDK 8) – Try It Online") Similar to @Kevin Cruijssen but saves 5 bytes by combining the loops. [Answer] # C, ~~150~~ ~~140~~ 135 bytes ``` r,d;f(k,x){r=x<5?3:f(k+1,x/5);return(d=x%5)?r*"33436"[d]*(1<<d*k%4)%5:r;}main(int c,char**v){c=atoi(*++v);printf("%d",c<2?1:2*f(0,c));} ``` This is the version for ASCII systems; replace the string `33436` with `11214` for an EBCDIC system, or with `\1\1\2\1\4` for a portable program. C solutions are a bit hampered by the requirement to provide a full program; however, this does answer the question fully. Try it online (requires Javascript): * [1000000 only](https://tio.run/##HcnRCoIwFIDhV4nB4Jy5yLnWhZv4INGFnGWJZHEwGYjPvqT/7uOn44MoZ9bR9zDqhCs3KbjW1jsLo9PJoef7/OUJYpOkw5aVsPZsL@IabwpMCFGN8ozS1ey3VzdMMEzzgTQ9O1ZqwZWabn4PoIpiQf/h/fYgZBSaQtWaulI9lJoQ/ZZzNuW/Hw "C (gcc) – Try It Online") * [Loop with all testcases](https://tio.run/##VUztboMwDPzPU1hMSEnINsJHt0EoD9L1B0tKG7ULU0YnpIpn9wLtVM2yffbd2epxrxSi47rqyJGP9OLqURZNVvo1Fnx8LmjldsPZWaLrMSpo41iYZXm2Cjd6y4iQUrNjlNOoKF014YOx6nTWO5Dfgzb902Ed/KNO5mPmPltjibEDtG6vOKhD6xiblx8aXALw0fUOFoeBGkQFHuXi9mMcGwpX2xKzzdbt0Bsyv9iYLa3u6pfzekfCSEO9hki/25CD9SnTRpQp60jCLb1dTMGEKDDFDHMscIUv@IpvKBKfS13brf9B8gs "C (gcc) – Try It Online") ## Explanation It's based on the algorithm outlined in [Least Significant Non-Zero Digit of n!](http://www.mathpages.com/home/kmath489.htm), turned around so that we recurse in to find the highest power of five, and do the calculation on the way out. The tables of constants were too big, so I reduced them by finding a relationship between the previous residue `r`, the current digit `d` and the recursion depth `k`: | r | d=0 | d=1 | d=2 | d=3 | d=4 | | --- | --- | --- | --- | --- | --- | | 0 | 0 | 3×2^k | 1×2^2k | 3×2^3k | 2 | | 1 | 1 | 1×2^k | 2×2^2k | 1×2^3k | 4 | | 2 | 2 | 2×2^k | 4×2^2k | 2×2^3k | 3 | | 3 | 3 | 3×2^k | 3×2^2k | 3×2^3k | 2 | | 4 | 4 | 4×2^k | 4×2^2k | 4×2^3k | 1 | For `r>0`, this resolves to a constant times `r` times `2^dk` (mod 5); the constants are in `a[]` below (inlined in the golfed code). We also observe that `(2^4)%5` is 1, so we can reduce the exponent to avoid overflowing the range of `int`. ``` const int a[] = { 1, 1, 2, 1, 4 }; int f(int k, int x) { int r = x<5 ? 3 : f(k+1,x/5); /* residue - from recursing to higher-order quinary digits */ int d = x%5; if (!d) return r; return r * a[d] * (1 << d*k%4) % 5; } int main(int c, char **v) { c = atoi(*++v); printf("%d", c<2 ? 1 /* special-case 0 & 1 */ : 2*f(0,c)); /* otherwise, it's 2 times r */ } ``` ## Tests: ``` $ for i in 100 1000 10000 100000; do echo $i: `./694 $i`; done 100: 4 1000: 2 10000: 8 100000: 6 1000000: 4 ``` Performance is respectable, too. Here's a maximum input for a system with 32-bit `int`: ``` $ time ./694 2147483647 8 real 0m0.001s user 0m0.000s sys 0m0.000s ``` I got the same timings with a maximal 64-bit `int`, too. [Answer] # PHP - 105 ``` <?foreach(explode("\n",`cat`)as$n)if($n){$f=rtrim(gmp_strval(gmp_fact($n)),'0');echo substr($f,-1)."\n";} ``` Runs under 10 seconds with the given testcase. [Answer] ## Python3 **239 Chars** Can do [10000](http://www.ideone.com/xLq4n) in ~3.2 seconds (Ideone cuts me off at 8 seconds, i'm sure it'll take longer than 10secs though :( ) ``` from functools import * N=100 r=range s=(p for p in r(2,N)if all(p%n>0for n in r(2,p))) f=lambda n,x:n//x+(n//x>0and f(n//x,x)or 0) e=list([p,f(N,p)]for p in s) e[0][1]-=e[2][1] e[2][1]=0 print(reduce(lambda x,y:x*y,map(lambda x:x[0]**x[1],e))%10) ``` ## Python2.6 **299 Chars** (a bit faster) ``` from itertools import * N=100000 r=xrange def s(c=count(2)): while 1:p=c.next();c=ifilter(p.__rmod__,c);yield p f=lambda n,x:n//x+(n//x>0and f(n//x,x)or 0) e=[[p,f(N,p)]for p in takewhile(lambda x:x<N,s())] e[0][1]-=e[2][1] e[2][1]=0 print(reduce(lambda x,y:x*y,map(lambda x:pow(x[0],x[1],10),e))%10) ``` [Answer] ## Haskell, 78 characters ``` f n=head$dropWhile(=='0')$reverse$show$product[1..n] main=interact(show.f.read) ``` (Would probably need to be compiled to compute 1,000,000! in 10 secs). [Answer] ## J – ~~42~~ 40 characters A whole program. Save this program in a file and run with `jconsole script.ijs 1234`. Notice that this program does not exit the interpreter after printing a result. Type `^D` or `exit]0` to exit the interpreter. ``` echo([:{:@(#~*)10&#.inv@*)/1+i.".>{:ARGV ``` Here is an explanation: * `x #. y` interprets the integer vector `y` as a base `x` number; for example, `10 #. 1 2 3 4` yields `1234`. * `u inv` yields the *inverse* of a verb `u`. In particular, `x #. inv y` represents `y` as a base `x` number; for example, `10 #. 1234` yields `1 2 3 4`. Notice that `inv` is defined as `^:_1`, that is, `u` applied -1 time. * `x * y` is the *product* of `x` and `y`, thus `x 10&#.inv@* y` yields a base-10 representation of the product of `x` and `y`. * `x # y` copies the *n*-th item of `y` as often as the *n*-th item of `x`; when `x` is a vector of booleans, `x` selects which items of `y` to take. For instance, `1 0 1 0 # 1 2 3 4` yields `1 3`. * `* y` yields the *signum* of `y`. * `x u~ y` is the *reflexive* of `u`, that is, the same as `y u x`. * Thus, `y #~ * y` yields a vector of all items of `y` that are positive. In tacit notation, this can written with a *hook* as `(#~ *)`. * `{: y` yields the last item in `y`. * assembled together, we get the tacit phrase `([:{:@(#~*)10&#.inv@*)`. * `u/ y` is the *reduction* of `y`, that is, the dyadic verb `u` inserted between elements of `y`. For instance, `+/1 2 3 4` is like `1 + 2 + 3 + 4` and yields `10`. * Thus, the phrase `([:{:@(#~*)10&#.inv@*)/ y` yields the last digit of the product of the items of `y`. * `ARGV` is a boxed vector of the command line arguments. * `".>{:ARGV` is the last argument unboxed and interpreted as a number. * `i. y` computes natural numbers from `0` to `y - 1`. * Thus, `1+i. y` yields natural numbers from `1` to `y`. I could have also used `>:` *increment* here, but `1+` is clearer at the same cost of characters. * The entire program just applies `1+i.".>{:ARGV` (the vector of `1` to the number in the last command line argument) to the verb `([:{:@(#~*)10&#.inv@*)/` and prints the result with `echo`. [Answer] # [Perl 6](https://perl6.org), ~~26~~ 35 bytes ``` {[*](1..$_)~~/.*<(<-[0]>/} ``` [Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszZVbqaCWnJ@SqmD7vzpaK1bDUE9PJV6zrk5fT8tGw0Y32iDWTr/2f1p@kQJQxtBEoZpLQaE4sVJBSSVewdZOQSVeD6xdQ1OJq/Y/AA "Perl 6 – Try It Online") --- As a full program: ``` put [*](1..@*ARGS[0])~~/.*<(<-[0]>/ ``` [Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszcVVXJqkkJyfkqqgoaDtoOUY5B6soKlQzaWgAJIoKC1R0FCJBwqoxNf@B/GitWI1DPX0ICqjDWI16@r09bRsNGx0gRw7/f@1XGn5RQpAFYYmYFNAepRU4hVs7RRU4vXUQDZpaCpx1f4HAA "Perl 6 – Try It Online") ## Expanded: ``` { [*]( 1..$_ ) # reduce using &infix:« * » ~~ # match with / .* # any number of values (so it matches from the end) <( # only capture the following <-[0]> # any value but 0 (negated character class) / } ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 72 bytes (function) ``` f(n,d)long long n,d;{for(d=1;n;d%=10000)for(d*=n--;d%10<1;d/=10);d%=10;} ``` [Try it online!](https://tio.run/##VY7PCsIwDMbP9inKoNDKiqv/pdYn8SILK4OayRAvY89es@XgzCG/L19CktrGus650ViCSR1GOSeq/NB0vYbgPHpQwVUUZrbWAa0lz1VX52FDLcMTfsyfrgUZ9WKTEYNYvfoW340uVEogw00quGNR0hlJl43xYhTi@WhRz9NRO7IIW8aOsWccGEfGiXFmXBjTR8yfWKil/NNTMeYv "C (gcc) – Try It Online") # [C (gcc)](https://gcc.gnu.org/), ~~101~~ 99 bytes (whole program) ``` main(){long long n,d=1;for(scanf("%lld",&n);n;d%=10000)for(d*=n--;d%10<1;d/=10);printf("%d",d%10);} ``` [Try it online!](https://tio.run/##HYtBCoAgEEWvEoHhhJKuJw8jDkVgY1i76Oym/sVb/McLeg@hlNMfLOGNifehgxU5i1vK8g6eNzmKGGlUEwMyknDW1EHzNDvWun7WrBZpqQrwygc/rapNM4BfKb0x5gc "C (gcc) – Try It Online") This question is just shy of 8 years old so "reasonable machine" is not the same as back then, but I'm getting times of ~.01 seconds on my computer when doing all test cases together, so unless computers have increased in speed by a factor of 1000 this last decade, it should be fine. [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 64 bytes ``` {k.=Floor[_/5]If[_<2,1,6*Digits@$`U1sTny@(_%10)*3^(k%4)*$@k%10]} ``` [Try it online!](https://tio.run/##SywpSUzOSP2fqGBl@786W8/WLSc/vyg6Xt801jMtOt7GSMdQx0zLJTM9s6TYQSUh1LA4JK/SQSNe1dBAU8s4TiNb1URTS8UhG8iPrf3vl5qaUhytUlCQnB7LFVCUmVcSklpc4pxYnFocnaijYGhlqaCuoGFoEGdoZaYZ@x8A "Attache – Try It Online") Simple implementation of the OEIS formula. `Digits@$`U1sTny` compresses the hardcoded dictionary using Attache's compressed number feature. `$` refers to the function itself within this answer. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~47~~ 57 bytes ``` {for(p=$1;--$1;p=(p*$1)%1e4)while(!(p%10))p/=10;$0=p%10}1 ``` [Try it online!](https://tio.run/##bYzBCsIwEETv@YoKKSRCcSeNaaXEf/FQURQMXnqQfnvssgtevOybmR3msjxq/Vxfb1eyxdR12ynZlb2FbzFHv9zuz9ntXGlB3pdDBk2WMtsVtaLJ5wYmMILpGclERjRHCZNgkHAUd2KMBqSEMsgCevXxf51I1jZB0mD1@6pOqrX9BQ "AWK – Try It Online") Original solution did not handle "large" input values very well. Could add `-M` to force it to work, but that also requires a lot more processing time. [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 56 bytes ``` ($s=1).."$args"|%{$s=+("$(($s%1e5)*$_)".Trim(48))} $s%10 ``` [Try it online!](https://tio.run/##XZFBb4JAEIXP7q/YkNWwLRKwaq2JCUlrj7Yp3owxFEelgULZNbRRfjudXSqhzmnem2/eJLtZWkAuDhDH/TDNoWK72akymZi53LYNFuR7YZy7JzRuTYOZOOm6MOI3bMMNe5lHiTmccF4S5TtVSQjb0xk9kQ4TBTYr/0dISOynKNh/pkJGobB9mWZFIMPDejr1ZZDLBRQmJ6TTYzvqqYtEr2sQB7qfx0EmYEvwAvFMQrEsz3Qt6vKLGFh00Ig7i44bMbTosBGjNjZui/s2NmlPHiw6aYTr/FdOew2l095U@prXzvjKqVM4PdPnNJ8H4aH/8v4BocS3VByTIKRFGXxnaMIW35Zt6kkO4hirmYwSQL@HX6BxPV69@o9HIdOkjlt7dZ4q/xiGIISKamL78HVJbLglZimoyVT1phll/9EdY4n3DQ1io8GSlNUv "PowerShell Core – Try It Online") Naive implementation, takes under 5 seconds on my local, 25 seconds on TIO I'll rework it when I get a chance ]
[Question] [ Well... there are 59 (now 60) questions tagged [sorting](/questions/tagged/sorting "show questions tagged 'sorting'"), but no simple quicksorts. That must be fixed. For those unfamiliar with [quicksort](https://en.wikipedia.org/wiki/Quicksort), here is a breakdown, courtesy of Wikipedia- 1. Pick an element, called a **pivot**, from the array. 2. Reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation. 3. Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values. # Rules The rules are simple: * Implement a numerical quicksort in the programming language of your choice. * The pivot should be chosen at random *or* with median of three (1st, last, and middle element). * Your program can be a complete program or function. * You can get the input using STDIN, command line args, or function parameters. If using a string input, the input is space separated. * The input may contain decimal and negative values. However, there will be no duplicates. * You may output to STDOUT or by returning from the function. * No built-in sorting (or sorting related) functions or standard loopholes. * The list may be an arbitrary length. Bonus #1: On lists or sub-lists of length <= 5, use [insertion sort](https://en.wikipedia.org/wiki/Insertion_sort) to speed things up a bit. Reward: -15%. Bonus #2: If your language supports concurrency, sort the list in parallel. If you are using an insertion sort on sub-lists, the final insertion sort doesn't need to be in parallel. Built in thread pools/ thread scheduling are allowed. Reward: -15%. Note: Median of three was confusing some people, so here is an explanation, courtesy of (again) Wikipedia: > > choosing the median of the first, middle and last element of the partition for the pivot > > > # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Base score is in bytes. If you got one bonus, take 15% off that number. If you got both, take 30% off. That really sounds like a sales pitch. This isn't about finding the shortest answer overall, but rather the shortest in each language. And now, a shameless copy of the leaderboard snippet. # The Leaderboard The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. 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 snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` /* Configuration */ var QUESTION_ID = 62476; // Obtain this from the url // It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 41505; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+(?:.\d+)?)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1; if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } 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="language-list"> <h2>Shortest Solution 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> <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> <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] ## C++, 440.3 ~~405~~ 388 bytes 518 bytes - 15% bonus for insertion sort = 440.3 bytes ~~477 bytes - 15% bonus for insertion sort = 405.45 bytes~~ ~~474 bytes - 15% bonus for insertion sort = 402.9 bytes~~ ``` 456 bytes - 15% bonus for insertion sort = 387.6 bytes ``` Thanks to @Luke for saving 3 bytes (2 really). Thanks to @Dúthomhas for saving 18 (15 really) bytes. Note that I am new here and this is my first post. This is a `.h` (header) file. Compressed Code: ``` #include<iostream> #include<ctime> #include<cstdlib> void s(int a[],int i,int j){int t=a[i];a[i]=a[j];a[j]=t;}int z(int a[],int b,int e){int p=a[(rand()%(e-b+1))+b];b--;while(b<e){do{b++;}while(a[b]<p);do{e--;}while(a[e]>p);if(b<e){s(a, b, e)}}return b;}void q(int a[],int b,int e){if(e-b<=5){for(int i=b;i<e;i++){for(int j=i;j>0;j--){if(a[j]<a[j-1]){s(a,j,j-1);}else{break;}}}return;}int x=z(a,b,e);q(a,b,x);q(a,x,e);}void q(int a[],int l){q(a,0,l);} ``` Full Code: ``` #include <iostream> #include <ctime> #include <cstdlib> void swapElements(int toSort[], int i, int j) { int temp = toSort[i]; toSort[i] = toSort[j]; toSort[j] = temp; } int partitionElements(int toSort[], int beginPtr, int endPtr) { int pivot = toSort[(rand() % endPtr - beginPtr + 1) + beginPtr]; beginPtr--; while (beginPtr < endPtr) { do { beginPtr++; } while (toSort[beginPtr] < pivot); do { endPtr--; } while (toSort[endPtr] > pivot); if (beginPtr < endPtr) { // Make sure they haven't crossed yet swapElements(toSort, beginPtr, endPtr); } } return beginPtr; } void quickSort(int toSort[], int beginPtr, int endPtr) { if (endPtr - beginPtr <= 5) { // Less than 5: insertion sort for (int i = beginPtr; i < endPtr; i++) { for (int j = i; j > 0; j--) { if (toSort[j] < toSort[j - 1]) { swapElements(toSort, j, j - 1); } else { break; } } } return; } int splitIndex = partitionElements(toSort, beginPtr, endPtr); quickSort(toSort, beginPtr, splitIndex ); quickSort(toSort, splitIndex, endPtr); } void quickSort(int toSort[], int length) { quickSort(toSort, 0, length); } ``` [Answer] # APL, ~~49~~ 42 bytes ``` {1≥⍴⍵:⍵⋄(∇⍵/⍨⍵<p),(⍵/⍨⍵=p),∇⍵/⍨⍵>p←⍵[?⍴⍵]} ``` This creates an unnamed recursive monadic function that accepts an array on the right. It does not qualify for the bonus. Explanation: ``` {1≥⍴⍵:⍵⋄ ⍝ If length(⍵) ≤ 1, return ⍵ p←⍵[?⍴⍵]} ⍝ Choose a random pivot ∇⍵/⍨⍵> ⍝ Recurse on >p (⍵/⍨⍵=p), ⍝ Concatenate with =p (∇⍵/⍨⍵<p), ⍝ Recurse on <p ``` [Try it online](http://tryapl.org/?a=%7B1%u2265%u2374%u2375%3A%u2375%u22C4%28%u2207%u2375/%u2368%u2375%3Cp%29%2C%28%u2375/%u2368%u2375%3Dp%29%2C%u2207%u2375/%u2368%u2375%3Ep%u2190%u2375%5B%3F%u2374%u2375%5D%7D3%201%204%201%205%209%202%206%205%202%205&run) Fixed an issue (at the cost of 8 bytes) thanks to marinus and saved 7 bytes thanks to Thomas Kwa! [Answer] # C++17, ~~254~~ ~~199~~ 195 bytes ``` #include<vector> #include<cstdlib> #define P push_back(y) using V=std::vector<int>;V q(V a){int p=a.size();if(p<2)return a;p=rand()%p;V l,r;for(y:a)(y<a[p]?l:r).P;l=q(l);for(y:q(r))l.P;return l;} ``` With whitespace: ``` V q(V a) { int p = a.size(); if (p < 2) return a; p = rand() % p; V l,r; for (y : a) (y < a[p] ? l : r).P; l=q(l); for (y : q(r)) l.P; return l; } ``` [Answer] # Pyth, 25 bytes ``` L?tbsyMa_,]JObf<TJbf>TJbb ``` This defines a function `y`, that takes a list of numbers as input. Try it online: [Demonstration](http://pyth.herokuapp.com/?code=L%3FtbsyMa_%2C%5DJObf%3CTJbf%3ETJbb%0Ay%5B9%200%205%203%201%208%204%207%206%202%29%0Ay%5B1%202%203%29%0Ay%5B_1%20_99%202%20_100%29%0Ay%5B.1%20_.1%20.09%29) ### Explanation ``` L?tbsyMa_,]JObf<TJbf>TJbb L define function y(b), that returns: ?tb if t[1:] (if the list has more than one element): Ob choose a random element of b J save it in J ] put J in a list , f<TJb create a pair, that contains ^ and a list of all numbers smaller than J: [[J], [smaller than J]] _ reverse this list: [[smaller than J], [J]] a f>TJb append a list with all elements bigger than J: [[smaller than J], [J], [bigger than J]] yM call y recursively for each sublist s combine the results and return it b else: simply return b ``` # Pyth, 21 bytes (probably invalid) I use the "group-by" method, which internally uses a sort. I use it to split the original list into three sublists (all element smaller than the pivot, the pivot, and all elements bigger than the pivot). Without the sort in "group-by", it could return these 3 lists in a different order. As said, this is probably invalid. Nevertheless I'll keep it here, because it's an interesting solution. ``` L?tb&]JObsyM.g._-kJbb ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=L%3Ftb%26%5DJObsyM.g._-kJbb%0Ay%5B9%200%205%203%201%208%204%207%206%202%29%0Ay%5B1%202%203%29%0Ay%5B_1%20_99%202%20_100%29%0Ay%5B.1%20_.1%20.09%29) ### Explanation ``` L?tb&]JObsyM.g._-kJbb L def y(b): return ?tb if t[1:] (if the list has more than one element): Ob choose a random element of b J save it in J &] put it in an array and call "and" (hack which allows to call 2 functions in one statement) .g b group the elements in b by: ._-kJ the sign of (k - J) this generates three lists - all the elements smaller than J - J - all the elements bigger than J yM call y recursively for all three lists s and combine them b else: return b ``` [Answer] # ><> (Fish), ~~313~~ 309 bytes ``` !;00l[l2-[b1. >:0)?v~$:@&vl2,$:&${:}$ ^-1@{< ]]. >055[3[5b. ?v~~@~ v:}@:}@:}:}@:}@}}}(}(}({{:@= .>=$~?$>~]] .001-}}d6.{$}1+}d6 ?v:{:}@{(?v08.}:01-= >{$~~{09.>95.v-1@{< v-1}$< .:@}:@{=${::&@>:0)?^~}&>:0)?^~+}d6 1-:0a.{{$&l&1+-: >:0)?v~:1)?!v62fb. >:0)?v~:}:1)?v~69.^@{-1<>.!]]~< ^@{-1<:}@@73.>69@@:3+[{[b1. ``` This took me very long to write. [You can try it here](http://fishlanguage.com/playground/FQZ4jECrxN4dB98mZ), just put the list that has to be sorted into the initial stack, seperated with commas, before running the program. ## How it works The program grabs the first, middle and last element in the initial stack and calculates the median of these three. It then changes the stack to: [list 1] element [list 2] where everything in list 1 is smaller or equal to the element and everything in list 2 is bigger. It recursively repeats this process on list 1 and list 2 untill the whole list is sorted. [Answer] # CJam, 40 bytes ``` {_1>{_mR:P-PaL@{_P<{+}{@\+\}?}/J\J+}&}:J ``` This is a named function that expects an array on the stack and pushes one in return. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%0A%20%20%7B_1%3E%7B_mR%3AP-PaL%40%7B_P%3C%7B%2B%7D%7B%40%5C%2B%5C%7D%3F%7D%2FJ%5CJ%2B%7D%26%7D%3AJ%0A~p&input=%5B8%204%205%201%207%206%203%202%5D). The above code follows the spec as closely as possible. If that's not required, 12 bytes can be saved: ``` {_1>{_mR:P;_{P<},J_@^J+}&}:J ``` [Answer] # Python 3, ~~123~~, 122. Saved 1 byte thanks to Aaron. This is the first time I've actually bothered to write a sorting algorithm. It's actually a little easier than I thought it would be. ``` from random import* def q(s): if len(s)<2:return s p=choice(s);return q([d for d in s if d<=p])+q([d for d in s if d>p]) ``` Ungolfed: ``` from random import choice def quick_sort(seq): if len(seq) < 2: return seq low = [] high = [] pivot = choice(seq) for digit in seq: if digit > pivot: high += [digit] else: low += [digit] return quick_sort(low) + quick_sort(high) ``` [Answer] # Javascript (ES2015), 112 ``` q=l=>{let p=l[(Math.random()*l.length)|0];return l.length<2?l:q(l.filter(x=>x<=p)).concat(q(l.filter(x=>x>p)));} ``` ### Explanation ``` //Define lambda function q for quicksort q=l=>{ //Evaluate the pivot let p=l[(Math.random()*l.length)|0]; //return the list if the length is less than 2 return l.length < 2 ? l: //else return the sorted list of the elements less or equal than the pivot concatenated with the sorted list of the elements greater than the pivot q(l.filter(x=>x<=p)).concat(q(l.filter(x=>x>p))); } ``` [Answer] # Ruby, ~~87~~ 60 bytes ``` q=->a,p=a.sample{a[1]?(l,r=a.partition{|e|e<p};q[l]+q[r]):a} ``` Ungolfed: ``` def quicksort(a, pivot=a.sample) if a.size > 1 l,r = a.partition { |e| e < pivot} quicksort(l) + quicksort(r) else a end end ``` Test: ``` q[[9, 18, 8, 5, 13, 20, 7, 14, 16, 15, 10, 11, 2, 4, 3, 1, 12, 17, 6, 19]] => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] ``` [Answer] # Octave, ~~76~~ 75 bytes ``` function u=q(u)n=numel(u);if n>1 k=u(randi(n));u=[q(u(u<k)),q(u(u>=k))];end ``` Multi-line version: ``` function u=q(u) n=numel(u); if n>1 k=u(randi(n)); u=[q(u(u<k)),q(u(u>=k))]; end ``` [Answer] # Julia, 83 bytes ``` Q(x)=endof(x)<2?x:(p=rand(x);[Q((f=filter)(i->i<p,x));f(i->i==p,x);Q(f(i->i>p,x))]) ``` This creates a recursive function `Q` that accepts an array and returns an array. It does not conditionally use insertion sort, so no bonus applies. Ungolfed: ``` function Q(x::AbstractArray) if endof(x) ≤ 1 # Return on empty or 1-element arrays x else # Select a random pivot p = rand(x) # Return the function applied to the elements less than # the pivot concatenated with those equal to the pivot # and the function applied to those greater than the pivot [Q(filter(i -> i < p, x)); filter(i -> i == p, x); Q(filter(i -> i > p, x))] end end ``` Fixed an issue and saved some bytes thanks to Glen O! [Answer] # R, 78 bytes ``` Q=function(x)if(length(x)>1)c(Q(x[x<(p=sample(x,1))]),x[x==p],Q(x[x>p]))else x ``` This creates a recursive function `Q` that accepts a vector and returns a vector. It does not conditionally apply insertion sort, so no bonus. Ungolfed: ``` Q <- function(x) { # Check length if (length(x) > 1) { # Select a random pivot p <- sample(x, 1) # Recurse on the subarrays consisting of # elements greater than and less than p, # concatenate with those equal to p c(Q(x[x < p]), x[x == p], Q(x[x > p])) } else { x } } ``` [Try it online](http://www.r-fiddle.org/#/fiddle?id=hEYxcvvu) Saved 4 bytes thanks to flodel! [Answer] # K, 41 bytes ``` s:{$[#x;(s@x@&x<p),p,s@x@&x>p:x@*1?#x;x]} ``` TAKE THAT, APL!!! Doesn't do any of the bonuses. [Answer] # Haskell, ~~137~~136 bytes ``` f=filter m a b c=max(min a b)(min(max a b)c) q[]=[] q l=let{n=m(head l)(head$drop(length l`div`2)l)(last l)}in(q$f(<n)l)++(n:(q$f(>n)l)) ``` The ungolfed version is hereunder, with expanded variable and function names and some intermediate results added: ``` median a b c = max (min a b) (min (max a b) c) quicksort [] = [] quicksort l = let mid = median (head l) (middle l) (last l) lesser = filter (< mid) l greater = filter (> mid) l middle l = head $ drop (length l `div` 2) l in (quicksort lesser) ++ (mid : (quicksort greater)) ``` I'm taking advantage of the fact that there's no duplicates to use two strict comparisons. I'll have to check if `Data.List.partition` doesn't makes things shorter though, even considering I would have to add an import statement. I'm not taking the insertion sort bonus because I consider `Data.List.insert` as a sorting-related function — thus forbidden — and if not using it, adding the insertion sort pushes the code to 246 bytes, 209.1 with the bonus, so it's not worth it. *Edit :* Thanks to RobAu for their suggestion to create an alias to use `f=filter`. It may save only one byte but everything helps. [Answer] ## Tcl, 138 bytes ``` proc q v {if {$v eq {}} return lassign {} a b foreach x [lassign $v p] {if {$x<$p} {lappend a $x} {lappend b $x}} concat [q $a] $p [q $b]} ``` This is an exceedingly standard quicksort. The pivot is simply the first element of each subarray (I contend that this is a random number. <https://xkcd.com/221/>) It isn't particularly efficient in terms of memory usage, though it could be improved some with `tailcall` on the second recursion and a base case of n<1 elements. Here's the readable version: ``` proc quicksort xs { if {![llength $xs]} return set lhs [list] set rhs [list] foreach x [lassign $xs pivot] { if {$x < $pivot} \ then {lappend lhs $x} \ else {lappend rhs $x} } concat [quicksort $lhs] $pivot [quicksort $rhs] } ``` Works on all input and permits duplicates. Oh, it's also *stable*. You can test it with something simple, like: ``` while 1 { puts -nonewline {xs? } flush stdout gets stdin xs if {$xs eq {}} exit puts [q $xs] ;# or [quicksort $xs] puts {} } ``` Enjoy! :O) [Answer] # JavaScript (ES6), 191 ``` Q=(a,l=0,h=a.length-1)=>l<h&&(p=((a,i,j,p=a[i+(0|Math.random()*(j-i))])=>{for(--i,++j;;[a[i],a[j]]=[a[j],a[i]]){while(a[--j]>p);while(a[++i]<p);if(i>=j)return j}})(a,l,h),Q(a,l,p),Q(a,p+1,h)) ``` ``` // More readable U=(a,l=0,h=a.length-1)=>l<h && (p=( // start of partition function (a,i,j,p=a[i+(0|Math.random()*(j-i))])=> { for(--i,++j;;[a[i],a[j]]=[a[j],a[i]]) { while(a[--j]>p); while(a[++i]<p); if(i>=j)return j } } // end of partition function )(a,l,h),U(a,l,p),U(a,p+1,h)) // This is the shortest insertion sort that I could code, it's 72 bytes // The bonus is worth ~30 bytes - so no bonus I=a=>{for(i=0;++i<a.length;a[j]=x)for(x=a[j=i];j&&a[j-1]>x;)a[j]=a[--j]} // TEST z=Array(10000).fill().map(_=>Math.random()*10000|0) Q(z) O.innerHTML=z.join(' ') ``` ``` <div id=O></div> ``` [Answer] # Ceylon (JVM only), ~~183~~ 170 No bonuses apply. ``` import ceylon.math.float{r=random}{Float*}q({Float*}l)=>if(exists p=l.getFromFirst((r()*l.size).integer))then q(l.filter((e)=>e<p)).chain{p,*q(l.filter((e)=>p<e))}else[]; ``` It seems there is no cross-platform way to produce a random number in Ceylon, so this is JVM-only. (At the end I have a non-random version which works in JS too, and is smaller.) This defines a function which takes an iterable of floats, and returns a sorted version thereof. ``` import ceylon.math.float { r=random } {Float*} q({Float*} l) { if (exists p = l.getFromFirst((r() * l.size).integer)) { return q(l.filter((e) => e < p)).chain { p, *q(l.filter((e) => p < e)) }; } else { return []; } } ``` If (against the specification) duplicate entries are passed, those will be filtered out. This are 183 bytes: `import ceylon.math.float{r=random}{Float*}q({Float*}l){if(exists p=l.getFromFirst((r()*l.size).integer)){return q(l.filter((e)=>e<p)).chain{p,*q(l.filter((e)=>p<e))};}else{return[];}}` We can improve a bit by using the new (Ceylon 1.2) `if` expression: ``` import ceylon.math.float { r=random } {Float*} q({Float*} l) => if (exists p = l.getFromFirst((r() * l.size).integer)) then q(l.filter((e) => e < p)).chain { p, *q(l.filter((e) => p < e)) } else []; ``` This is 170 bytes: `import ceylon.math.float{r=random}{Float*}q({Float*}l)=>if(exists p=l.getFromFirst((r()*l.size).integer))then q(l.filter((e)=>e<p)).chain{p,*q(l.filter((e)=>p<e))}else[];` --- Here is a non-random version: ``` {Float*} r({Float*} l) => if (exists p = l.first) then r(l.filter((e) => e < p)).chain { p, *r(l.filter((e) => p < e)) } else []; ``` Without spaces this would be 107 bytes: `{Float*}r({Float*}l)=>if(exists p=l.first)then r(l.filter((e)=>e<p)).chain{p,*r(l.filter((e)=>p<e))}else[];` [Answer] ## [AutoIt](http://autoitscript.com/forum), ~~320.45~~ 304.3 bytes This is plenty fast (for AutoIt anyway). Qualifies for insertion sort bonus. Will add explanation after final golfing occurred. Input is `q(Array, StartingElement, EndingElement)`. ``` Func q(ByRef $1,$2,$3) $5=$3 $L=$2 $6=$1[($2+$3)/2] If $3-$2<6 Then For $i=$2+1 To $3 $4=$1[$i] For $j=$i-1 To $2 Step -1 $5=$1[$j] ExitLoop $4>=$5 $1[$j+1]=$5 Next $1[$j+1]=$4 Next Else Do While $1[$L]<$6 $L+=1 WEnd While $1[$5]>$6 $5-=1 WEnd ContinueLoop $L>$5 $4=$1[$L] $1[$L]=$1[$5] $1[$5]=$4 $L+=1 $5-=1 Until $L>$5 q($1,$2,$5) q($1,$L,$3) EndIf EndFunc ``` Random test input + output: ``` 862, 543, 765, 577, 325, 664, 503, 524, 192, 904, 143, 483, 146, 794, 201, 511, 199, 876, 918, 416 143, 146, 192, 199, 201, 325, 416, 483, 503, 511, 524, 543, 577, 664, 765, 794, 862, 876, 904, 918 ``` [Answer] ## Java, 346 bytes ``` 407 bytes - 15% bonus for insertion sort = 345.95 bytes ``` Compressed Code: ``` class z{Random r=new Random();void q(int[] a){q(a,0,a.length);}void q(int[] a,int b,int e){if(e-b<6){for(int i=b;i<e;i++){for(int j=i;j>0&a[j]<a[j-1];j--){s(a,j,j-1);}}return;}int s=p(a,b,e);q(a,b,s);q(a,s,e);}int p(int[] a,int b,int e){int p=a[r.nextInt(e-b)+b--];while(b<e){do{b++;}while(a[b]<p);do{e--;}while(a[e]>p);if(b<e){s(a,b,e);}}return b;}void s(int[] a,int b,int e){int t=a[b];a[b]=a[e];a[e]=t;}} ``` Full Code: ``` public class QuickSort { private static final Random RANDOM = new Random(); public static void quickSort(int[] array) { quickSort(array, 0, array.length); } private static void quickSort(int[] array, int begin, int end) { if (end - begin <= 5) { for (int i = begin; i < end; i++) { for (int j = i; j > 0 && array[j] < array[j - 1]; j--) { swap(array, j, j - 1); } } return; } int splitIndex = partition(array, begin, end); quickSort(array, begin, splitIndex); quickSort(array, splitIndex, end); } private static int partition(int[] array, int begin, int end) { int pivot = array[RANDOM.nextInt(end - begin) + begin]; begin--; while (begin < end) { do { begin++; } while (array[begin] < pivot); do { end--; } while (array[end] > pivot); if (begin < end) { // Make sure they haven't crossed yet swap(array, begin, end); } } return begin; } private static void swap(int[] array, int begin, int end) { int temp = array[begin]; array[begin] = array[end]; array[end] = temp; } } ``` [Answer] ## Mathematica, ~~93~~ 90 bytes ``` If[Length@#>1,pv=RandomChoice@#;Join[qs2[#~Select~(#<pv&)],{pv},qs2[#~Select~(#>pv&)]],#]& ``` No bonus, haven't got a minimal way to do insertion sort yet. When I was learning C++ recently, I did a comparison of various sorting algorithms [here](https://codereview.stackexchange.com/q/87085/69254). [Answer] ## Python2, 120 bytes ``` def p(a): if[]==a[1:]:return a b,c,m=[],[],__import__("random").choice(a) for x in a:[b,c][x>m]+=[x];return p(b)+p(c) ``` `if[]==a[1:]` is exactly as long as `if len(a)>2` but looks more golfed. [Answer] # Lua, 242 Bytes ``` function f(t,p)if(#t>0)then local P,l,r,i=math.random(#t),{},{},table.insert p=t[P]for k,v in ipairs(t)do if(k~=P)then i(v<p and l or r,v)end end t={}for k,v in pairs(f(l))do i(t,v)end i(t,p)for k,v in pairs(f(r))do i(t,v)end end return t end ``` ## Ungolfed & Explination ``` function f(t,p) # Assign 'p' here, which saves two bytes, because we can't assign it to t[P] IN the local group. if(#t>0)then # Just return 0 length lists... local P,l,r,i=math.random(#t),{},{},table.insert # Using local here actually makes the a,b=1,2 method more efficient here. Which is unnormal for Lua p = t[P] # P is the index of the pivot, p is the value of the pivot, l and r are the sub-lists around the pivot, and i is table.insert to save bytes. for k,v in ipairs(t) do # We use a completely random pivot, because it's cheaper on the bytes. if(k~=P)then # Avoid 'sorting' the pivot. i(v<p and l or r,v) # If the value is less than the pivot value, push it to the left list, otherwise, push it to the right list. end # end # t = {} # We can re-use t here, because we don't need it anymore, and it's already a local value. Saving bytes! for k,v in pairs(f(l)) do # Quick sort the left list, then append it to the new output list. i(t,v) # end # i(t,p) # Append the pivot value. for k,v in pairs(f(r)) do # Ditto the right list. i(t,v) # end # end # return t # Return... end # ``` [Answer] ## Racket 121 bytes ``` (λ(l)(if(null? l)l(let((h(car l))(t(cdr l)))(append(qs (filter(λ(x)(< x h))t))(list h)(qs (filter(λ(x)(>= x h))t)))))) ``` Ungolfed (l=list, h=head (first element), t=tail (rest or remaining elements)): ``` (define qs (λ(l) (if (null? l) l (let ((h (first l)) (t (rest l))) (append (qs (filter (λ(x) (< x h) ) t)) (list h) (qs (filter (λ(x) (>= x h)) t)) ))))) ``` Testing: ``` (qs (list 5 8 6 8 9 1 2 4 9 3 5 7 2 5)) ``` Output: ``` '(1 2 2 3 4 5 5 5 6 7 8 8 9 9) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 23 bytes Each bonus would need to be three bytes or less to pay off in the total score, so I didn't take any bonuses. ``` Z=Uö;Ê<2?U:ßUf<Z)cßUf¨Z Z=Uö; // Take a random element from the input for partitioning. Ê<2 // If the input is shorter than two elements, ?U // return it. : // Otherwise ß ß // recursively run again Uf<Z // with both items that are smaller than the partition Uf¨Z // and those that are larger or equal, )c // returning the combined result. ``` [Try it online!](https://tio.run/##y0osKPn/P8o29PA268NdNkb2oVaH54em2URpJoPoQyui/v@PNtMx1DHSMdcx0THVMY4FAA "Japt – Try It Online") ]
[Question] [ Tomorrow, November 23rd, is [Thanksgiving Day](https://en.wikipedia.org/wiki/Thanksgiving) in the United States. To prepare, you need to cook up some ASCII turkeys. However, since you're late in planning, you need a program (or function) to help you with how many birds you need to prepare. ``` .---. _ .' './ ) / _ _/ /\ =(_____) (__/_/== =================== ``` The turkeys you found are rather on the small side, so you've figured out the following ratios -- one turkey will feed: * four people who only like [white meat](https://en.wikipedia.org/wiki/White_meat) and three people who only like dark meat * or seven people who don't care either way * or a combination thereof. Meaning, there are a total of 4 servings of white meat and 3 servings of dark meat in any given turkey. Further, you can't purchase and cook a partial turkey. For example, for 3 people who only like white meat, 6 people who only like dark meat, and 3 people who don't care, you'll need two turkeys. That gives 8 servings of white and 6 servings of dark, which is enough to satisfy everyone and have some leftover white meat: ``` .---. _ .---. _ .' './ ) .' './ ) / _ _/ /\ / _ _/ /\ =(_____) (__/_/== =(_____) (__/_/== ===================================== ``` For 20 people who don't care, you'll need three turkeys, and have either a little bit of white or dark leftover: ``` .---. _ .---. _ .---. _ .' './ ) .' './ ) .' './ ) / _ _/ /\ / _ _/ /\ / _ _/ /\ =(_____) (__/_/== =(_____) (__/_/== =(_____) (__/_/== ======================================================= ``` And so on. ### Rules * The three inputs can be in any order you choose, and in [any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). Please indicate in your answer how the input is taken. * There will never be a requirement for more than 25 turkeys (so a maximum of 175 people to feed). * Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * Output can be to the console, returned as a list of strings, returned as a single string, etc. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # Befunge-93, ~~231~~ 224 bytes ``` p&:10p3+4/:&:20p2+3/\-:v v<0-1:+*`0:-\/7+++&g02<0 >" _ .---. "vg` >" ) /.' '. "v0* >" \/ /_ _ / "v1+ >"==/_/__( )_____(= "v6: v^0-1 _$"v"000g1+:>v v^< :#,_$:^1,+55:p+1p00< >>> _$$99+*"=":>,#:\:#->#1_@ ``` [Try it online!](http://befunge.tryitonline.net/#code=cCY6MTBwMys0LzomOjIwcDIrMy9cLTp2CnY8MC0xOisqYDA6LVwvNysrKyZnMDI8MAo+IiAgIF8gICAuLS0tLiAgICAgICJ2Z2AKPiIgICkgLy4nICAgICAnLiAgICAidjAqCj4iICBcLyAvXyAgIF8gICAvICAgInYxKwo+Ij09L18vX18oIClfX19fXyg9ICJ2NjoKdl4wLTEgXyQidiIwMDBnMSs6PnYgdl48CjojLF8kOl4xLCs1NTpwKzFwMDA8ID4+PgpfJCQ5OSsqIj0iOj4sIzpcOiMtPiMxX0A&input=MyA2IDM) The three values are read from stdin in the order: white meat, dark meat, don't care. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~120~~ ~~118~~ 104 bytes *14 bytes saved thanks to @Adám* ``` {,/(⌈⌈/4 3 7÷⍨⍵,⍺++/⍵)/⊂'='⍪⍨' .-_''/)\=('[4 19⍴10 10⊤¯35+⎕UCS'###(##-:77-&(#F*####+,&0N&&)#,N0Z&d++#']} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OAZLWOvsajng4g0jdRMFYwP7z9Ue@KR71bdR717tLW1geyNPUfdTWp26o/6l0FlFJX0NONV1fX14yx1VCPNlEwtHzUu8XQQMHQ4FHXkkPrjU21geaHOgerKysraygr61qZm@uqaSi7aQH5yto6agZ@amqayjp@BlFqKdrayuqxtf//GyqkAa025jIG02ZcRgZAhoGCAZcFkDY0VLAEAA) The picky white and dark are on the right, the non picky on the left. Too bad most of the byte count is taken by the string currently. **How?** `⍵,⍺++/⍵` - creates array of whity, darky and sum of them all plus non pickys `4 3 7÷⍨` - divide by how many of them gets their wishes from one chicken `⌈/` - take the highest estimate of the three - so if we have extremely high amount of dark meat seekers, they won't be left aside `⌈` - ceiling, in case only a half-chicken is in demand Then we create a string, enclose it with `⊂`, then repeat the eclosed matrix the calculated chickens times with `/`, and finally concatenate all chickens with `,/`. [Answer] # [Python 2](https://docs.python.org/2/), 142 bytes ``` lambda w,d,n:[min(e)+-min(-w/3,-d/4,-(w+d+n)/7)*e.center(18)for e in" .---. _"," .' './ )","/ _ _/ /\\","=(_____) (__/_/==","="*18] ``` [Try it online!](https://tio.run/##FY5RCoMwEESvsuTHrCZZWksrBU9iRGyNNKWuIinS06fJwPCY9zXbL7xWPse5tfEzLo9phENNiu/d4lk6rHSmPqhWeqKL0vKopoqRblg683Qc3C5PDc7rDg48CwCjtTYAMAglwBSQUxgCTJuyzyUga5No5ZCDkEgDtW12ojw1fdx2z6GwXJj3mj7MsvS8fYNExNjVCq4K6v4P "Python 2 – Try It Online") -16 bytes thanks to Lynn -4 bytes thanks to Mr. Xcoder and back to a lambda xD [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 65 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` N∫4*κ:F3*.-:h+.-¹χ∆>?F"Ωeχ&i[A⁄╔■§‼╗╝│¼ο≠≈⁹,Ρ⁴žγūž℮3zl3βΜ%G‘'³n*← ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=TiV1MjIyQjQqJXUwM0JBJTNBRjMqLi0lM0FoKy4tJUI5JXUwM0M3JXUyMjA2JTNFJTNGRiUyMiV1MDNBOWUldTAzQzclMjZpJTVCQSV1MjA0NCV1MjU1NCV1MjVBMCVBNyV1MjAzQyV1MjU1NyV1MjU1RCV1MjUwMiVCQyV1MDNCRiV1MjI2MCV1MjI0OCV1MjA3OSUyQyV1MDNBMSV1MjA3NCV1MDE3RSV1MDNCMyV1MDE2QiV1MDE3RSV1MjEyRTN6bDMldTAzQjIldTAzOUMlMjVHJXUyMDE4JTI3JUIzbioldTIxOTA_,inputs=MyUwQTYlMEEz) Order of inputs is `white`, `dark`, and then `either`. [Answer] # [Python 2](https://docs.python.org/2/), ~~197~~ ~~189~~ 174 bytes thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) for -12 bytes thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) for -1 byte ``` a,b,c=input() for i in range(5):print'='[i<4:]+(' '+" = ( /_ . _ ' _. _- __- )- . ( '__ ./_ / /_ /_ )\\/ = ="[i::4],'='*18)[i>3]*max((6+c+a+b)/7,a+3>>2,(b+2)/3) ``` [Try it online!](https://tio.run/##LYxJCsIwGIX3nuLRTRITm44qwfYibQlpccjCtJQKevr4C8L7Nm9aPttjDkWMTo1qanxYXhsXu9u8wsMHrC7cr7wWZll92FjDOn@pzCA5A5MJgIbggLZIYcFgU8AeYAkIgmzKmaWcOvpXJIm@1/9xk3TemGpQdL7Pz6LzbTnsn@7N@VFO0slR6JNysmzbQvFRFkKXIsZaZSrPvg "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 76 bytes ``` ”{‴∨➙×95;{;C.ÞgF⁷J*←λ|⁸KK][§X⎚¦»Z◧↘gⅉ✳⟧F⎇≧h”×=¹⁹NθNηF⊖⌈⌈⟦∕θ³∕η⁴∕⁺⁺θηN⁷⟧C¹⁸¦⁰ ``` [Try it online!](https://tio.run/##XY3BaoNAEIbvPsXgJTOwukpbkhA8mUsOKTn0VosYs4kL7mo2Gtqn346m0NIfdn@@b4fZuqlc3VWt9wen7YAhzImjKIq5y8LOuJjtIpZAs5HT23QkyKJglWE5hYBbljLLChvSJngsfdNG3TDMQgHpmljvbD8Or6M5KofXf9wwnzsHuFW1U0bZQZ0wV7rV9oL76lOb0eD7Vt/1SeFVwBMJ@KFGwPMvHdrx9rh4qmH/9xdiXtIHcSDv@i9MVwIS2nifJsFLkPjo3n4D "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ”{‴∨➙×95;{;C.ÞgF⁷J*←λ|⁸KK][§X⎚¦»Z◧↘gⅉ✳⟧F⎇≧h” ``` Print a 1-space-indented turkey. ``` ×=¹⁹ ``` Print the table. ``` NθNη ``` Input the number of dark and white meat eaters. ``` F⊖⌈⌈⟦∕θ³∕η⁴∕⁺⁺θηN⁷⟧ ``` Repeat one less than the ceiling of the maximum of a) one third of the number of dark meat eaters b) one quarter of the number of white meat eaters c) one seventh of the number of diners. ``` C¹⁸¦⁰ ``` Make a copy of the turkey. [Answer] # Excel VBA, ~~222~~ ~~219~~ ~~211~~ 198 Bytes Anonymous VBE immediate window function that takes input from range `[A1:C1]` with order of white meat, dark meat, and indifferent in that order and outputs to the range `[D1]`. ``` [D1]=[Int(Max((A1+3)/4,(B1+2)/5,Sum(1:1,6)/7))]:For Each s In Split(" .---.  _ 1 .' './ ) 1 / _ _/ /\ 1 =(_____) (__/_/==1",1):[E1]=s:?[Rept(E1,D1)]:Next:?[Rept("=",18*D1+1)] ``` Initially the solution finds the correct number of turkeys and then it repeats the turkey pattern that many times. Ideally this would then be directly outputted onto the VBE immediate window as shown by the function below ``` [D1]=[Int(Max((A1+3)/4,(B1+2)/5,Sum(1:1,6)/7))]:For Each s In Split(" .---. _ 1 .' './ ) 1 / _ _/ /\ 1 =(_____) (__/_/==1",1):[E1]=s:?[Rept(E1,D1)]:Next:?[Rept("=",18*D1+1)] ``` This version does initially produce the correct response, however, it is immediately autoformatted by the compiler, as `_` is the line continutation character, and is thus moved to have only one (space) character to its left, breaking the pattern. Example shown below for clarity ``` [A1:C1]=Array(0,0,20):[D1].Clear [D1]=[Int(Max((A1+3)/4,(B1+2)/5,Sum(1:1,6)/7))]:For Each s In Split(" .---. _ 1 .' './ ) 1 / _ _/ /\ 1 =(_____) (__/_/==1",1):[E1]=s:?[Rept(E1,D1)]:Next:?[Rept("=",18*D1+1)] '' Note that the `_` to the right has moved V .---. _ .---. _ .---. _ .' './ ) .' './ ) .' './ ) / _ _/ /\ / _ _/ /\ / _ _/ /\ =(_____) (__/_/== =(_____) (__/_/== =(_____) (__/_/== ======================================================= ``` To correct this the last space character (, char 32) before the `_` in line one of the output is replaced with a non-breaking space (, char 160, `Alt + 255`) ``` .---. _ .---. _ .---. _ .' './ ) .' './ ) .' './ ) / _ _/ /\ / _ _/ /\ / _ _/ /\ =(_____) (__/_/== =(_____) (__/_/== =(_____) (__/_/== ======================================================= ``` -3 bytes for use of `1` delimited split statement -8 bytes for use moving `=`'s into the split and using string addition over concatenation -13 bytes for use of a non-breaking space to prevent autoformatting of the output [Answer] # [Kotlin](https://kotlinlang.org), ~~207~~ 198 bytes thanks to [Taylor Scott](https://codegolf.stackexchange.com/users/61846/taylor-scott) for -7 bytes ``` {a,b,c->val n=maxOf((a+3)/4,(b+2)/3,(6+c+a+b)/7);arrayOf(" .---. _ "," .' './ ) "," / _ _/ /\\ "," =(_____) (__/_/==").map{println(it.repeat(n))};println("=".repeat(n*18+1))} ``` ~~This does not work on [TIO](https://tio.run/##PY7NS8NAEMXv/SuGvXTG/WqtX7RuwKMnD@KtECalKYvJGtZVlNC/PW6icWDmwe@9gff6lhofhk9uoN7iY0gK5kOgC3gJPoEbelaVOuhizAXX8tdTjchyQ/ZKYSUvyW4U3siDZFmRvaUdx8jfOSRgGqO1NlnLvEJN0CwnZ2ks0AztX6S0YPf7X@qwHIcgqy2tc4JMy13fRR9SE9AnE4/dkRMGovNuxsKJf36xvpPrbA71R4CWfUCOp/ctPIwl759TfjkVBP1iLFTjtVqpFS3Oww8 "Kotlin – Try It Online") yet, as it requires *Kotlin 1.1*~~ [Try it online!](https://tio.run/##PY7NS8NAEMXv/SuGvXTG/WqtX7RuwKMnD@KtECalKYvJGtZVlNC/PW6icWDmwe@9gff6lhofhk9uoN7iY0gK5kOgC3gJPoEbelaVOuhizAXX8tdTjchyQ/ZKYSUvyW4U3siDZFmRvaUdx8jfOSRgGqO1NlnLvEJN0CwnZ2ks0AztX6S0YPf7X@qwHIcgqy2tc4JMy13fRR9SE9AnE4/dkRMGovNuxsKJf36xvpPrbA71R4CWfUCOp/ctPIwl759TfjkVBP1iLFTjtVqpFS3Oww8 "Kotlin – Try It Online") [Answer] # JavaScript (ES6), ~~180~~ 179 bytes Outputs an array of strings. ``` (a,b,c)=>[...` .---. _ .' './ ) / _ _/ /\\ =(_____) (__/_/==`.split` `.map(l=>l.repeat(n=Math.max((6+c+a+b)/7,a+3>>4,(b+2)/3)|0)),'='.repeat(18*n+1)] ``` ``` f= (a,b,c)=>[...` .---. _ .' './ ) / _ _/ /\\ =(_____) (__/_/==`.split` `.map(l=>l.repeat(n=Math.max((6+c+a+b)/7,a+3>>4,(b+2)/3)|0)),'='.repeat(18*n+1)] console.log(f(3, 2, 3)) console.log(f(0, 0, 20)) ``` --- # JavaScript (ES6), ~~182~~ 181 bytes Outputs a single string. ``` (a,b,c)=>` .---. _ .' './ ) / _ _/ /\\ =(_____) (__/_/== ${'='.repeat(18)}`.split` `.map(l=>l.repeat(Math.max((6+c+a+b)/7,a+3>>4,(b+2)/3))).join` `+'=' ``` ``` f= (a,b,c)=>` .---. _ .' './ ) / _ _/ /\\ =(_____) (__/_/== ${'='.repeat(18)}`.split` `.map(l=>l.repeat(Math.max((6+c+a+b)/7,a+3>>4,(b+2)/3))).join` `+'=' console.log(f(3, 2, 3)) console.log(f(0, 0, 20)) ``` *-1 byte (Arnauld): `a+3>>4` instead of `(a+3)/4)`* ]
[Question] [ It is the year 87,539,319 and solitary space-walking is now commonplace, many people travel into space by themselves, propelled by nothing but a jetpack on their backs, programming their course with a personal computer and keyboard as they go. You are one such person; you were out on a lovely, peaceful spacewalk, when, all of a sudden, you were ensnared by the gravity of a black hole! As you plummet towards this black hole, spiraling ever faster inwards, you realise your one chance of survival is to broadcast a distress message, and hope a nearby ship comes to rescue you. So, you break out your keyboard, and begin typing away a program. Your program can be in any language, and must print `HELP!` to stdout (your PC broadcasts all stdout far into the depths of space.) However, as you are near a blackhole, your keyboard is slowly being ripped to shreds! Assume you are using a QWERTY keyboard like the one below, and that the blackhole is to your left; ![QWERTY KEYBOARD LAYOUT](https://i.stack.imgur.com/OLr0K.png) [Remember, left and right shift are two different keys.](https://codegolf.stackexchange.com/questions/49167/quick-escape-the-black-hole#comment-116110) after every keypress, the left-most row of your keyboard (keys covered by left-most red line) is ripped off and flung into the black hole! So, your first keypress could be any key on the keyboard, but from then onwards none of the *leftmost* `Tab`, `Caps`, `Shift`, `Ctrl` or ``` keys may be used, *at all*. (r-shift and r-ctrl can still be used) After the next keypress, the keys `1`, `Q`, `A`,`Z` and `Alt` are flung into the abyss, and may not be used thereafter. After that, you lose `Space`, `X`, `S`, `W`, `2` and so forth. Obviously, you want to complete your program as quickly as possible, so that rescue-time is increased; therefore, this is code-golf, and the shortest program *in key presses* wins! Each answer should provide a list of keypresses, so, if my answer was this program (in the language squardibblyack) ``` !HELP\. ``` a keylist could look like: `Shift``!``H``E``L``P` release shift `\``.` length: 8 I'm worried this challenge might be too difficult, but I'd love to see the kinds of answers submitted! [Answer] # CJam, 11 keystrokes The code is ``` "HELP*")9- ``` and the keylist is `Shift``"``H``E``L``P``\*``"``)` release shift `9``-` and here is a demonstration of how it looks: ![enter image description here](https://i.stack.imgur.com/cCxpQ.gif) and here is how the code works: ``` "HELP*" "This puts the string HELP* on stack"; ) "This takes out the last character of the string and puts it on the stack as a character"; 9- "This simply reduces 9 from the ASCII code of * character present on the stack which makes it an !"; "CJam automatically prints everything that is on stack"; ``` [Try the code here](http://cjam.aditsu.net/#code=%22HELP*%22)9-) [Answer] # [rs](https://github.com/kirbyfan64/rs), 10 keystrokes (assumes the user is using Nano) Or equivalent editor where `Shift` doesn't select text. This isn't really a programming language, but if `sed` can be used on Code Golf, then `rs` can be used. `Right Shift` `!` `Left` `E` `Left` `H` `Right` `L` `P` `Enter` ``` HELP! ``` It just replaces the empty string with "HELP!", effectively printing it to the screen. Roughly equivalent to the sed script: ``` s/^/HELP!/ ``` The cool part is that `rs` automatically puts `^/` in front of a replacement pattern where the delimiter (`/`) is not found. Handy for indenting code. ]
[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/3652/edit) Your job, should you choose to not refuse it, is to write a program that will "golf" a piece of given code in your language of choice. Basic functionality: * Remove extraneous whitespace * Remove comments 'Advanced' functionality: * Combine declarations (`int x; int y; int z;` to `int x, y, z;`) * Use shorter variations of basic control structures (`while(1)` is replaced with `for(;;)`) * Move code around (`i = 0; while(i < 10) { /* ... */ ++i; }` to `for(i = 0; i < 10; ++i) { /* ... */ }`) * Etc [Answer] # Python with Python Does a bunch of stuff including renaming of variables, getting rid of unnecessary whitespace and comments, and putting as much as it can on one line. Doesn't always completely work with fancier python syntax and I'll will be continuing to update with any fixes. Code: ``` import string import keyword import pkgutil builtins = __builtins__.__dict__.keys() vars = {} #imported = builtins+string.__dict__.keys()+['append','extend','count','index','insert','pop','remove','reverse','sort'] multiline = '' ml_last = '' strings = [] defined = [] undefined = [] def get_name(name): if name.startswith('__'): vars[name] = name return name if name in vars: return vars[name] for c in string.letters+'_': if c not in vars.values(): vars[name] = c return c for c0 in string.letters+'_': for c1 in string.letters+string.digits+'_': if c0+c1 not in vars.values(): if c0+c1 in keyword.kwlist: continue vars[name] = c0+c1 return c0+c1 def replace_names(expr,defining=False,prefix = '',assign=True): if ';' in expr: ns = '' for e in expr.split(';'): ns += replace_names(e,assign=assign)+';' return ns[:-1] global multiline expr = expr.strip() if expr in ['']+keyword.kwlist: return expr if expr == '""': return '"'+strings.pop(0)+'"' if expr == "''": return "'"+strings.pop(0)+"'" if '=' in expr and assign: e = expr[:] vals = [''] while '=' in e: i = e.index('=') if e != '' and e[0] == '=': vals[-1] += '=' e = e[1:] continue if e[i-1] not in '!<>*/+-%' and e[i+1] != '=' and (vals[-1]+e[:i]).count('(') == (vals[-1]+e[:i]).count(')'): vals[-1] += e[:i] e = e[i+1:] vals.append('') else: vals[-1] += e[:i+1] e = e[i+1:] if len(vals) > 1: vals[-1] += e ns = '' left,val = vals[:-1],vals[-1] for l in left: rs = replace_names(l,True,assign=assign) ns += rs+'=' ns += replace_names(val,assign=assign) return ns if expr[0] in ['(','[','{']: try: delimit = expr[0] i = 0; level = 1 while level > 0: i += 1 char = expr[i] if char in '([{': level += 1 if char in ')]}': level -= 1 inner = expr[1:i] rest = expr[i+1:] return expr[0]+replace_names(inner,defining,assign=False)+expr[i]+replace_names(rest,defining,assign=assign) except IndexError: multiline = expr return '' if expr.startswith('for') and not expr.endswith('in'): varname = '' curword = '' for i,char in enumerate(expr): if char in string.letters+string.digits+'_': curword += char else: if curword == 'in': break curword = '' varname += char rest = expr[i:] dpart = replace_names(varname[3:-2],True,assign=assign) rpart = replace_names(rest,assign=assign) return 'for' + ' '*(dpart[0] in string.letters+string.digits+'_') + dpart + ' '*(dpart[-1] in string.letters+string.digits+'_') + 'in' + ' '*(rpart[0] in string.letters+string.digits+'_') + rpart if expr.startswith('lambda'): args = expr.split('lambda',1)[1].split(':')[0] replace_names(args,True,assign=assign) poses = ['' if e == -1 else e for e in (expr.find(char) for char in ['(','[','{'])] pos = min(poses) if pos != '': delimit = '([{'[poses.index(pos)] first,rest = expr.split(delimit,1) return replace_names(first,defining,assign=assign)+replace_names(delimit+rest,defining,assign=assign) multiline = '' if ' ' in expr: ns = '' for sub in expr.split(' '): rs = replace_names(sub,defining,assign=assign) if rs == '': continue if ns != '' and (ns[-1] in string.letters+string.digits+'_' and rs[0] in string.letters+string.digits+'_'): ns += ' '+rs else: ns += rs return ns for cmp in ['**=','//=','==','!=','<>','<=','>=','+=','-=','*=','/=','%=','//','**','<<','>>','<','>','+','-','*','/','%','&','|','^','~',':',',','.']: if cmp in expr: ns = '' for sub in expr.split(cmp): rs = replace_names(sub,defining,prefix,assign=assign)+cmp ns += rs if cmp == '.': prefix += rs return ns[:-len(cmp)] if expr[0] in string.digits: return expr if not defining and expr not in defined: #print '---',prefix+expr if prefix+expr not in undefined and (prefix == '' or prefix[0] != '.') : undefined.append(prefix+expr) return expr if defining: if prefix+expr in undefined: undefined.remove(prefix+expr) if expr not in defined: defined.append(expr) return get_name(expr) def fix_names(line): for cmp in ['**=','//=','==','!=','<>','<=','>=','+=','-=','*=','/=','%=','//','**','<<','>>','<','>','+','-','*','/','%','&','|','^','~',':',',','.','=','(',')','[',']','{','}']: if cmp in line: ns = '' for sub in line.split(cmp): ns += fix_names(sub)+cmp return ns[:-len(cmp)] if line in defined and line not in vars.values(): return vars[line] return line def first_pass(file): lines_firstpass = [] for line in file: if line.strip() == '': continue indent = 0 for char in line: if not char in string.whitespace: break indent += 1 if multiline != '': line_string = ml_last else: line_string = '' #line_string = '\t'*indent line = multiline + line.strip() newline = '' while line: char = line[0] if char in ['"',"'"]: limit=char; i=0 inside = '' escape = False while True: i+=1; char = line[i] if escape: escape = False inside += char continue if char == '\\': escape = True elif char == limit: break inside += char strings.append(inside) newline += limit*2 line = line[i+1:] else: if char == '#': break newline += char line = line[1:] line = newline if line == '': continue if ' ' not in line: first = '' else: first,line = line.split(' ',1) if first in ['class','def']: name = line.split('(')[0].split(':')[0].strip() line_string += first+' ' defined.append(name) line_string += get_name(name) if '(' in line: line_string += '(' inner = line.split('(',1)[1] inner = ')'.join(inner.split(')')[:-1]) part = '' for char in inner: if char == ',' and part.count('(') == part.count(')'): line_string += replace_names(part,True)+',' part = '' else: part += char line_string += replace_names(part,True)+')' line_string += ':' to_import = '' importing = [] if first == 'from': module,rest = line.split('import') module = module.strip() #imported.append(module) first,line = 'import',rest to_import += 'from '+module+' ' if first == 'import': to_import += 'import ' for module in line.split(','): module = module.strip() #imported.append(module) to_import += module+',' to_import = to_import[:-1] line_string += to_import if line_string.strip() == '': r = replace_names(first+' '+line) if multiline != '': ml_last = line_string + r continue line_string += r ml_last = '' lines_firstpass.append((indent,line_string)) #print '\t'*indent+line_string for i,(indent,line) in enumerate(lines_firstpass): lines_firstpass[i] = (indent,fix_names(line)) return lines_firstpass def second_pass(firstpass): lines = [] current_line = '' current_line_indent = 0 last_indent = 0 for i,(indent,line) in enumerate(firstpass): for kw in keyword.kwlist: if line[:len(kw)] == kw: first = kw line = line[len(kw):] break else: first = '' limit=';' for kw in ['import','global']: if first == kw and current_line.startswith(kw): first = '' line = line.strip() limit=',' if first not in ['if','elif','else','while','for','def','class','try','except','finally'] and indent == last_indent: current_line += limit*(current_line != '') + first + line else: lines.append((current_line_indent,current_line)) current_line = first + line current_line_indent = indent last_indent = indent lines.append((current_line_indent,current_line)) new_lines = [] i = 0 while i < len(lines): indent,line = lines[i] if i != len(lines)-1 and lines[i+1][0] == indent + 1 and (i == len(lines)-2 or lines[i+2][0] <= indent): new_lines.append((indent,line+lines[i+1][1])) i += 1 else: new_lines.append((indent,line)) i += 1 return new_lines def third_pass(lines): new_definitions = '' for u in sorted(undefined,key=lambda s:-s.count('.')): #print u parts = u.split('.') if parts[0] in vars.values(): continue c = 0 for indent,line in lines: if line.startswith('import'): continue c += line.count(u) if c > 1: new_definitions += ';'*(new_definitions!='')+get_name(u)+'='+u for ind,(indent,line) in enumerate(lines): if line.startswith('import'): continue nline = '' cur_word = '' i = 0 while i < len(line): char = line[i] if char not in string.letters+string.digits+'_.': if cur_word == u: nline += get_name(u) else: nline += cur_word cur_word = '' nline += char i += 1 continue if char in '"\'': nline += char limit = char escape = False while True: i += 1 char = line[i] nline += char if escape: escape = False continue if char == '\\': escape = True if char == limit: break i += 1 continue cur_word += char i += 1 lines[ind] = (indent,nline+cur_word) return [lines[0]]+[(0,new_definitions)]+lines[1:] def golf(filename): file = open(filename) write_file = open('golfed.py','w') for indent,line in third_pass(second_pass(first_pass(file))): write_file.write('\t'*(indent/2)+' '*(indent%2)+line+'\n') file.close() write_file.close() #print first_pass(["for u in sorted(undefined,key=lambda s:-s.count('.')):"]) golf('golfer.py') ``` Tested on an old fractal drawing program I had (**4672** to **1889**): Original: ``` import pygame import math import os import colorsys from decimal import * #two = Decimal(2) #half = Decimal(0.5) def fractal_check_point(function,x,y): #n = (Decimal(0),Decimal(0)) n = (0,0) i = 0 last_dist = 0 while n[0]**2 + n[1]**2 <= 16 and i < max_iter: nr,ni = function(n) n = (nr+x,ni+y) i+=1 if i == max_iter: return False #extra = math.log(math.log( (n[0]**two + n[1]**two)**half )/math.log(300),2) extra = math.log(math.log( (n[0]**2 + n[1]**2)**0.5 )/math.log(300),2) #prev = math.sqrt(last_dist) #final = math.sqrt(n.real**2+n.imag**2) return i - extra def f((r,i)): return (r**2 - i**2, 2*r*i) screen_size = (500,500) try: screen = pygame.display.set_mode(screen_size) except pygame.error: print 'Too large to draw to window...' screen = pygame.Surface(screen_size) #pixels = pygame.PixelArray(screen) #xmin = Decimal(- 2.2) #xmax = Decimal(.8) # #ymin = Decimal(- 1.5) #ymax = Decimal(1.5) max_iter = 50 xmin = -2.2 xmax = 0.8 ymin = -1.5 ymax = 1.5 def draw_fractal(): print repr(xmin),repr(xmax) print repr(ymin),repr(ymax) print xlist = [] ylist = [] for x in range(screen_size[0]): #xlist.append(Decimal(x)*(xmax-xmin)/Decimal(screen_size[0])+xmin) xlist.append(x*(xmax-xmin)/screen_size[0]+xmin) for y in range(screen_size[1]): #ylist.append(Decimal(y)*(ymax-ymin)/Decimal(screen_size[1])+ymin) ylist.append(y*(ymax-ymin)/screen_size[1]+ymin) xi = 0 for x in xlist: yi = 0 for y in ylist: val = fractal_check_point(f,x,y) if val == False: screen.set_at((xi,yi),(0,0,0)) #pixels[xi][yi] = (0,0,0) else: r,g,b = colorsys.hsv_to_rgb(val/10.0 % 1, 1, 1) screen.set_at((xi,yi),(r*255,g*255,b*255)) ##screen.set_at((xi,yi),(0,(val/300.0)**.25*255,(val/300.0)**.25*255)) #pixels[xi][yi] = (0,(val/300.0)**.25*255,(val/300.0)**.25*255) yi += 1 xi += 1 pygame.event.get() pygame.display.update((xi-1,0,1,screen_size[1])) save_surface('F:\FractalZoom\\') def save_surface(dirname): i = 0 name = '%05d.bmp' % i while name in os.listdir(dirname): i += 1 name = '%05d.bmp' % i pygame.image.save(screen,dirname+name) print 'saved' x_min_step = 0 x_max_step = 0 y_min_step = 0 y_max_step = 0 savefail = 0 def zoom(xmin_target,xmax_target,ymin_target,ymax_target,steps): global xmin global xmax global ymin global ymax xc = (xmax_target + xmin_target)/2 yc = (ymax_target + ymin_target)/2 d_xmin = ((xc-xmin_target)/(xc-xmin))**(1.0/steps) d_xmax = ((xc-xmax_target)/(xc-xmax))**(1.0/steps) d_ymin = ((yc-ymin_target)/(yc-ymin))**(1.0/steps) d_ymax = ((yc-ymax_target)/(yc-ymax))**(1.0/steps) for s in range(steps): xmin = xc-(xc-xmin)*d_xmin xmax = xc-(xc-xmax)*d_xmax ymin = yc-(yc-ymin)*d_ymin ymax = yc-(yc-ymax)*d_ymax draw_fractal() save_dir = 'D:\FractalZoom\\' global savefail if not savefail: try: save_surface(save_dir) except: print 'Warning: Cannot save in given directory '+save_dir+', will not save images.' savefail = 1 #zoom(.5,.6,.5,.6,10) #zoom(-1.07996839017,-1.07996839014,-0.27125861927,-0.27125861923,100) #n = 1 #while 1: # pygame.display.update() # pygame.event.get() # # def f(x): # if x == 0: # return 0 # else: # return x**n # draw_fractal() # n += .0001 draw_fractal() zooming = 0 #firstx = Decimal(0) #firsty = Decimal(0) firstx = firsty = 0 clicking = 0 while 1: pygame.display.update() pygame.event.get() mx, my = pygame.mouse.get_pos() rx, ry = pygame.mouse.get_rel() # mx = Decimal(mx) # my = Decimal(my) # sx = Decimal(screen_size[0]) # sy = Decimal(screen_size[1]) sx = screen_size[0] sy = screen_size[1] if pygame.mouse.get_pressed()[0]: if clicking == 0: clicking = 1 if zooming and clicking == 1: secondx = mx*(xmax-xmin)/sx+xmin secondy = my*(ymax-ymin)/sy+ymin firstx = firstx*(xmax-xmin)/sx+xmin firsty = firsty*(ymax-ymin)/sy+ymin if secondx < firstx: xmin = secondx xmax = firstx else: xmin = firstx xmax = secondx if secondy < firsty: ymin = secondy ymax = firsty else: ymin = firsty ymax = secondy screen.fill((0,0,0)) screen.lock() draw_fractal() screen.unlock() zooming = 0 elif clicking == 1: firstx = mx firsty = my zooming = 1 screen.set_at((firstx,firsty),(255,255,255)) if clicking: clicking = 2 else: clicking = 0 ``` Golfed: ``` import pygame,math,os,colorsys;from decimal import * ai=pygame.event.get;aj=pygame.display.update;ak=math.log;al=pygame.mouse;am=False;an=pygame;ao=repr;ap=range;aq=os def a(b,c,d): e=(0,0);f=0;g=0 while e[0]**2+e[1]**2<=16 and f<o:h,i=b(e);e=(h+c,i+d);f+=1 if f==o:return False j=ak(ak((e[0]**2+e[1]**2)**0.5)/ak(300),2);return f-j def k((l,f)):return(l**2-f**2,2*l*f) m=(500,500) try:n=pygame.display.set_mode(m) except pygame.error:print'Too large to draw to window...';n=pygame.Surface(m) o=50;p=-2.2;q=0.8;r=-1.5;s=1.5 def t(): print ao(p),ao(q);print ao(r),ao(s);print;u=[];v=[] for c in ap(m[0]):u.append(c*(q-p)/m[0]+p) for d in ap(m[1]):v.append(d*(s-r)/m[1]+r) w=0 for c in u: x=0 for d in v: y=a(k,c,d) if y==am:n.set_at((w,x),(0,0,0)) else:l,z,A=colorsys.hsv_to_rgb(y/10.0%1,1,1);n.set_at((w,x),(l*255,z*255,A*255)) x+=1 w+=1;ai();aj((w-1,0,1,m[1])) B('F:\FractalZoom\\') def B(C): f=0;D='%05d.bmp'%f while D in os.listdir(C):f+=1;D='%05d.bmp'%f pygame.image.save(n,C+D);print'saved' E=0;F=0;G=0;H=0;I=0 def J(K,L,M,N,O): global p,q,r,s;P=(L+K)/2;Q=(N+M)/2;R=((P-K)/(P-p))**(1.0/O);S=((P-L)/(P-q))**(1.0/O);T=((Q-M)/(Q-r))**(1.0/O);U=((Q-N)/(Q-s))**(1.0/O) for V in ap(O): p=P-(P-p)*R;q=P-(P-q)*S;r=Q-(Q-r)*T;s=Q-(Q-s)*U;t();W='D:\FractalZoom\\';global I if not I: try:B(W) except:print'Warning: Cannot save in given directory '+W+', will not save images.';I=1 t();X=0;Y=Z=0;_=0 while 1: aj();ai();aa,ab=pygame.mouse.get_pos();ac,ad=pygame.mouse.get_rel();ae=m[0];af=m[1] if pygame.mouse.get_pressed()[0]: if _==0:_=1 if X and _==1: ag=aa*(q-p)/ae+p;ah=ab*(s-r)/af+r;Y=Y*(q-p)/ae+p;Z=Z*(s-r)/af+r if ag<Y:p=ag;q=Y else:p=Y;q=ag if ah<Z:r=ah;s=Z else:r=Z;s=ah n.fill((0,0,0));n.lock();t();n.unlock();X=0 elif _==1:Y=aa;Z=ab;X=1;n.set_at((Y,Z),(255,255,255)) if _:_=2 else:_=0 ``` Run on itself (creating a very long quine) (**9951** to **5323**): ``` import string,keyword,pkgutil;a=__builtins__.__dict__.keys();b={};c='';d='';e=[];f=[];g=[] aw=string.letters;ax=string.digits;ay=keyword.kwlist;az=False;aA=True;aB=len;aC=enumerate;aD=open def h(i): if i.startswith('__'):b[i]=i;return i if i in b:return b[i] for j in aw+'_': if j not in b.values():b[i]=j;return j for k in aw+'_': for l in aw+ax+'_': if k+l not in b.values(): if k+l in ay:continue b[i]=k+l;return k+l def m(n,o=az,p='',q=aA): if';'in n: r='' for s in n.split(';'):r+=m(s,q=q)+';' return r[:-1] global c;n=n.strip() if n in['']+ay:return n if n=='""':return'"'+e.pop(0)+'"' if n=="''":return"'"+e.pop(0)+"'" if'='in n and q: s=n[:];t=[''] while'='in s: u=s.index('=') if s!=''and s[0]=='=':t[-1]+='=';s=s[1:];continue if s[u-1]not in'!<>*/+-%'and s[u+1]!='='and(t[-1]+s[:u]).count('(')==(t[-1]+s[:u]).count(')'):t[-1]+=s[:u];s=s[u+1:];t.append('') else:t[-1]+=s[:u+1];s=s[u+1:] if aB(t)>1: t[-1]+=s;r='';v,w=t[:-1],t[-1] for x in v:y=m(x,aA,q=q);r+=y+'=' r+=m(w,q=q);return r if n[0]in['(','[','{']: try: z=n[0];u=0;A=1 while A>0: u+=1;B=n[u] if B in'([{':A+=1 if B in')]}':A-=1 C=n[1:u];D=n[u+1:];return n[0]+m(C,o,q=az)+n[u]+m(D,o,q=q) except IndexError:c=n;return'' if n.startswith('for')and not n.endswith('in'): E='';F='' for u,B in aC(n): if B in aw+ax+'_':F+=B else: if F=='in':break F='' E+=B D=n[u:];G=m(E[3:-2],aA,q=q);H=m(D,q=q);return'for'+' '*(G[0]in aw+ax+'_')+G+' '*(G[-1]in aw+ax+'_')+'in'+' '*(H[0]in aw+ax+'_')+H if n.startswith('lambda'):I=n.split('lambda',1)[1].split(':')[0];m(I,aA,q=q) J=[''if s==-1 else s for s in(n.find(B)for B in['(','[','{'])];K=min(J) if K!='':z='([{'[J.index(K)];L,D=n.split(z,1);return m(L,o,q=q)+m(z+D,o,q=q) c='' if' 'in n: r='' for M in n.split(' '): y=m(M,o,q=q) if y=='':continue if r!=''and(r[-1]in aw+ax+'_'and y[0]in aw+ax+'_'):r+=' '+y else:r+=y return r for N in['**=','//=','==','!=','<>','<=','>=','+=','-=','*=','/=','%=','//','**','<<','>>','<','>','+','-','*','/','%','&','|','^','~',':',',','.']: if N in n: r='' for M in n.split(N): y=m(M,o,p,q=q)+N;r+=y if N=='.':p+=y return r[:-aB(N)] if n[0]in ax:return n if not o and n not in f: if p+n not in g and(p==''or p[0]!='.'):g.append(p+n) return n if o: if p+n in g:g.remove(p+n) if n not in f:f.append(n) return h(n) def O(P): for N in['**=','//=','==','!=','<>','<=','>=','+=','-=','*=','/=','%=','//','**','<<','>>','<','>','+','-','*','/','%','&','|','^','~',':',',','.','=','(',')','[',']','{','}']: if N in P: r='' for M in P.split(N):r+=O(M)+N return r[:-aB(N)] if P in f and P not in b.values():return b[P] return P def Q(R): S=[] for P in R: if P.strip()=='':continue T=0 for B in P: if not B in string.whitespace:break T+=1 if c!='':U=d else:U='' P=c+P.strip();V='' while P: B=P[0] if B in['"',"'"]: W=B;u=0;X='';Y=False while aA: u+=1;B=P[u] if Y:Y=az;X+=B;continue if B=='\\':Y=True elif B==W:break X+=B e.append(X);V+=W*2;P=P[u+1:] else: if B=='#':break V+=B;P=P[1:] P=V if P=='':continue if' 'not in P:L='' else:L,P=P.split(' ',1) if L in['class','def']: i=P.split('(')[0].split(':')[0].strip();U+=L+' ';f.append(i);U+=h(i) if'('in P: U+='(';C=P.split('(',1)[1];C=')'.join(C.split(')')[:-1]);Z='' for B in C: if B==','and Z.count('(')==Z.count(')'):U+=m(Z,aA)+',';Z='' else:Z+=B U+=m(Z,aA)+')' U+=':' _='';aa=[] if L=='from':ab,D=P.split('import');ab=ab.strip();L,P='import',D;_+='from '+ab+' ' if L=='import': _+='import ' for ab in P.split(','):ab=ab.strip();_+=ab+',' _=_[:-1];U+=_ if U.strip()=='': ac=m(L+' '+P) if c!='':d=U+ac;continue U+=ac;d='' S.append((T,U)) for u,(T,P)in aC(S):S[u]=(T,O(P)) return S def ad(ae): af=[];ag='';ah=0;ai=0 for u,(T,P)in aC(ae): for aj in ay: if P[:aB(aj)]==aj:L=aj;P=P[aB(aj):];break else:L='' W=';' for aj in['import','global']: if L==aj and ag.startswith(aj):L='';P=P.strip();W=',' if L not in['if','elif','else','while','for','def','class','try','except','finally']and T==ai:ag+=W*(ag!='')+L+P else:af.append((ah,ag));ag=L+P;ah=T ai=T af.append((ah,ag));ak=[];u=0 while u<aB(af): T,P=af[u] if u!=aB(af)-1 and af[u+1][0]==T+1 and(u==aB(af)-2 or af[u+2][0]<=T):ak.append((T,P+af[u+1][1]));u+=1 else:ak.append((T,P)) u+=1 return ak def al(af): am='' for an in sorted(g,key=lambda s:-s.count('.')): ao=an.split('.') if ao[0]in b.values():continue j=0 for T,P in af: if P.startswith('import'):continue j+=P.count(an) if j>1: am+=';'*(am!='')+h(an)+'='+an for ap,(T,P)in aC(af): if P.startswith('import'):continue aq='';ar='';u=0 while u<aB(P): B=P[u] if B not in aw+ax+'_.': if ar==an:aq+=h(an) else:aq+=ar ar='';aq+=B;u+=1;continue if B in'"\'': aq+=B;W=B;Y=False while aA: u+=1;B=P[u];aq+=B if Y:Y=az;continue if B=='\\':Y=True if B==W:break u+=1;continue ar+=B;u+=1 af[ap]=(T,aq+ar) return[af[0]]+[(0,am)]+af[1:] def at(au): R=aD(au);av=aD('golfed.py','w') for T,P in al(ad(Q(R))):av.write('\t'*(T/2)+' '*(T%2)+P+'\n') R.close();av.close() at('golfer.py') ``` [Answer] ## BrainFuck - 489 Characters Removes all non executable characters. Respects comments from # to end of line. ``` ,[>--[<++>+++++++]<+[>+>+<<-]>[<+>-]+>[<->[-]]<[[,----------]]<>>--[>+ <++++++]<<--------[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>+<<<-[>+>+<<-]> [<+>-]+>[<->[-]]<[->>.<<]>>+<<<-[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>+ <<<-[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>++++++++++++++<<<------------ --[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>++<<<--[>+>+<<-]>[<+>-]+>[<->[- ]]<[->>.<<]>++++[>+++++++<-]>+<<++++[<------->-]<-[>+>+<<-]>[<+>-]+>[< ->[-]]<[->>.<<]>>++<<<--[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>[-]<<<,] ``` Naturally run through itself from this source: ``` ,[ #subtract # >--[<++>+++++++]<+ #strip comments [>+>+<<-]>[<+>-]+>[<->[-]]<[[,----------]]< #put '+' in 4th cell >>--[>+<++++++]<< #+ -------- [>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>+<<< #, - [>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>+<<< #- - [>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>+<<< #. - [>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>++++++++++++++<<< #< -------------- [>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>++<<< #> -- [>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>++++[>+++++++<-]>+<< #[ ++++[<------->-]<- [>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>++<<< #] -- [>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>[-]<<< ,] ``` [Answer] # Brainfuck golfer in Bash (v3) This is a work in progress, I will keep updating it if I can. Reads from a file (the filename should be the first command-line argument). For now all it does is * Remove any characters that are not `<>+-.,[]` * Remove two-character strings that do nothing useful, e.g. `<>`, `><`, `+-`, `-+` * When it is done, it repeats the entire procedure, so `>>>><<<<<` gets reduced to `<` ## Code ``` #!/bin/bash #if the file exists, take input from it if [ -f $1 ]; then input=`cat $1` else #complain to STDERR and exit echo "File not found. Exiting with status 1.">&2 exit 1 fi original=$input #save the original input code=$input #save original input to another variable which we will be golfing code=`echo $code|grep -o "[][<>.,+-]"|tr -d " \n"` #remove non-executable chars output=$code; #this will be output hits=-1; #Count the number of golfing operations carried out every time the code loops. When this is 0, the code will be completely golfed. until [ $hits = 0 ]; do hits=0 #we will be processing the optimised version from last time code=$output output="" #Keep taking characters off from $code until it is empty until [ m$code = m ]; do #examine the first two chars c1=${code:0:1} code=`echo $code|cut -c2-` c2=${code:0:1} #if this is 1, the two characters now being read will be removed ignore=0 if [ $c1$c2 = "<>" ] ; then #set the second character to be taken off as well and not saved to output ignore=1 elif [ $c1$c2 = "><" ] ; then ignore=1 elif [ $c1$c2 = "+-" ] ; then ignore=1 elif [ $c1$c2 = "-+" ] ; then ignore=1 else #save the char we took off to output, we aren't removing it output=$output$c1; fi if [ $ignore = 1 ]; then #ignore the second character and save no chars to output code=`echo $code|cut -c2-` #another hit hits=`expr $hits + 1` fi #end inner until loop done #end main loop done #done, print output echo $output; exit 0; ``` ## How it works After removing all non-executable characters, it does the following. The hits counter is set to `-1` at the start - it counts how many golfing operations were carried out each time the outer loop runs. 1. If the code being golfed is empty, go to step 5. 2. Read the first two chars from the code, and remove the first char. 3. If they are `<>`, `><`, `+-` or `-+`, add 1 to the `hits` counter and go back to step 1. 4. If not, save the first character to output and go to step 1. 5. If the hits counter is 0, print output and exit. 6. If not, reset the hits counter to 0, set the code being golfed to be the output variable, reset output to the empty string, and go to step 1. [Answer] # HQ9+ golfer in Bash (v3) I know HQ9+ is useless, but I might as well submit a five-liner for it. It reads from ~~standard input~~ a file. The path to the file should be the first command-line argument. ## Features * Removes all comment characters (anything except `HhQq9+`) * Removes `+` (it increments a number but there is no way to print that number) * Converts `hq` to uppercase (not golfing) ## Code ``` #!/bin/bash if [ -f $1 ]; then input=`cat $1` else exit 1; fi echo $input|tr "[[:lower:]]" "[[:upper:]]"|grep -o "[HQ9]"|tr -d ' \n' exit 0 ``` [Answer] # Java with Java Takes the file name as a command line argument, and edits the file in place. * Removes comments * Shortens identifiers (including classes, methods, variables, method parameters, and lambda expression parameters) * Trims spaces * Shortens imports * Removes unnecessary braces around one-line statements * Converts `while(true)` to `for(;;)` * Removes unneeded modifiers, such as `private` and `final` When the program is run on itself, its size is reduced from 7792 to 4366. ``` import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Golfer { public static void main(String[] args) throws IOException { Path path = new File(args[0]).toPath(); String program = Files.readAllLines(path).stream().collect(Collectors.joining("\n")); Golfer golfer = new Golfer(program); System.out.println(golfer.toString().length() + " characters"); System.out.println(golfer.toString().getBytes().length + " bytes"); golfer.golf(); String str = golfer.toString(); Files.write(path, Arrays.asList(str)); System.out.println(golfer); System.out.println(golfer.toString().length() + " characters"); System.out.println(golfer.toString().getBytes().length + " bytes"); } private String program; public Golfer(String program) { this.program = program; } public void golf() { doUnicodeSubstitutions(); protectStrings(); removeComments(); removeDuplicateSpaces(); removeExcessSpaces(); removeUnnecessaryModifiers(); simplifyImports(); shortenIdentifiers(); improveControlStructures(); unprotectStrings(); } void removeDuplicateSpaces() { program = program.replaceAll("\\s+", " "); } void removeExcessSpaces() { program = program.trim(); program = program.replaceAll("([.,;:?!@%^&*()\\[\\]{}=|/<>~]) ", "$1"); program = program.replaceAll(" ([.,;:?!@%^&*()\\[\\]{}=|/<>~])", "$1"); program = program.replaceAll("([^+]) \\+", "$1+").replaceAll("\\+\\+ \\+", "+++").replaceAll("\\+ ([^+])", "+$1"); program = program.replaceAll("([^-]) -", "$1-").replaceAll("-- -", "---").replaceAll("- ([^-])", "-$1"); } void removeUnnecessaryModifiers() { program = program.replaceAll("private |final |@Override ", ""); } void simplifyImports() { int startImports = program.indexOf("import "); List<String> imports = new ArrayList(); Matcher importMatcher = Pattern.compile("import [A-Za-z0-9$_.*]*;").matcher(program); while (importMatcher.find()) { imports.add(importMatcher.group()); } for (int i = 0; i < imports.size(); i++) { if (!imports.get(i).endsWith("*;")) { imports.set(i, imports.get(i).replaceFirst("\\.[A-Za-z0-9$_]*;", "\\.*;")); } imports = imports.stream().distinct().collect(Collectors.toList()); program = program.replaceAll("import [A-Za-z0-9$_.*]*;", ""); program = program.substring(0, startImports) + String.join("", imports) + program.substring(startImports); } } private List<Character> unusedCharacters; void shortenIdentifiers() { unusedCharacters = IntStream.concat(IntStream.rangeClosed('a', 'z'), IntStream.rangeClosed('A', 'Z')) .mapToObj(i -> (char) i) .filter(c -> !Pattern.compile("[^A-Za-z0-9$_']" + c + "[^A-Za-z0-9$_]").matcher(program).find()) .collect(Collectors.toList()); shortenIdentifiers("(class|interface|enum) ([A-Za-z0-9$_]{2,})( extends [A-Za-z0-9$_]+)?( implements [A-Za-z0-9$_,]+)?\\{", 2, "[^A-Za-z0-9$_]", "[^A-Za-z0-9$_]"); shortenIdentifiers("([A-Za-z0-9$_]+(\\[+\\]+| )|<[A-Za-z0-9$_,]+>+\\[+\\]+)(?<!implements |else |package |import |return )([A-Za-z0-9$_]{2,})(?<!null)[=,;)]", 3, "[^A-Za-z0-9$_]", "[^A-Za-z0-9$_(]"); shortenIdentifiers("([A-Za-z0-9$_]+ |<[A-Za-z0-9$_,]+>+)(?<!new |else )([A-Za-z0-9$_]{2,})(?<!main|toString|compareTo|equals|hashCode|paint|repaint)\\(", 2, "[^A-Za-z0-9$_]", "\\(", "::", "[^A-Za-z0-9$_]"); shortenIdentifiers("[^A-Za-z0-9$_]([A-Za-z0-9$_]{2,})(,[A-Za-z0-9$_]+)*\\)?->", 1, "[^A-Za-z0-9$_]", "[^A-Za-z0-9$_(]"); } void shortenIdentifiers(String pattern, int groupNumber, String... afficesForReplacement) { Pattern compiledPattern = Pattern.compile(pattern); Matcher matcher; while ((matcher = compiledPattern.matcher(program)).find()) { String identifer = matcher.group(groupNumber); char newIdentifier; if (unusedCharacters.remove((Character) identifer.charAt(0))) { newIdentifier = identifer.charAt(0); } else if (Character.isUpperCase(identifer.charAt(0)) && unusedCharacters.remove((Character) Character.toLowerCase(identifer.charAt(0)))) { newIdentifier = Character.toLowerCase(identifer.charAt(0)); } else if (Character.isLowerCase(identifer.charAt(0)) && unusedCharacters.remove((Character) Character.toUpperCase(identifer.charAt(0)))) { newIdentifier = Character.toUpperCase(identifer.charAt(0)); } else if (unusedCharacters.size() > 0) { newIdentifier = unusedCharacters.remove(0); } else { System.err.println("out of identifiers"); break; } for (int i = 0; i < afficesForReplacement.length; i += 2) { program = program.replaceAll('(' + afficesForReplacement[i] + ')' + identifer + "(?=" + afficesForReplacement[i + 1] + ')', "$1" + newIdentifier); } } } void improveControlStructures() { program = program.replaceAll("while\\(([^()]+)\\)\\{", "for(;$1;){"); program = program.replaceAll("for\\(([^()]*);true;([^()]*)\\)", "for($1;;$2)"); while (!program.equals(removeBrackets(program))) { program = removeBrackets(program); } } String removeBrackets(String string) { return string.replaceAll("((if|while|do)\\([^{;]*\\))\\{([^;}]*;)\\}", "$1$3") .replaceAll("else\\{([^;}]*;)\\}", "else $1") .replaceAll("(for\\([^{;]*;[^{;]*;[^{;]*\\))\\{([^;}]*;)\\}", "$1$2"); } void protectStrings() { adjustStrings(1000); } void unprotectStrings() { adjustStrings(-1000); } void adjustStrings(int n) { char[] chars = new char[program.length()]; for (int i = 0; i < program.length(); i++) { chars[i] = program.charAt(i); if (chars[i] == '"' && chars[i - 1] != '\'') { for (i++; chars.length > i + 1 && program.charAt(i) != '"'; i++) { chars[i] = (char) (program.charAt(i) + n); } chars[i] = program.charAt(i); } } program = new String(chars); } void removeComments() { program = program.replaceAll("(?s)/\\*.*\\*/", ""); program = program.replaceAll("//.*\n", ""); } void doUnicodeSubstitutions() { List<Character> chars = new ArrayList(); for (int i = 0; i < program.length(); i++) { if (program.charAt(i) != '\\' || program.charAt(i + 1) != 'u') { chars.add(program.charAt(i)); } else { chars.add((char) Integer.parseInt(program.substring(i + 2, i + 6), 16)); i += 5; } } char[] charArray = new char[chars.size()]; for (int i = 0; i < charArray.length; i++) { charArray[i] = chars.get(i); } program = new String(charArray); } @Override public String toString() { return program; } } ``` [Answer] ## Perl, Parts 1 - 2 (removes comments and ignores `#` characters inside double quotes) (removes all whitespace after brackets and `=` signs) I did not try to golf this code. Maybe, when it is done, it could golf itself. ``` $/="\n\n"; chomp($prog = <>); for(1..length($prog)){ $rev.=chop $prog; } #print$rev; for(1..length($rev)){ $temp = chop$rev; if ($temp eq '"'){ if($quote == 0){$quote = 1} else{$quote = 0} } if($temp eq '#' && $quote == 0){$comment = 1} if($temp eq "\n"){ $comment = 0; } if($comment != 1){ $prog.=$temp; } } for(1..length($prog)){ $rev.=chop $prog; } for(1..length($rev)){ $temp = chop$rev; if ($temp eq ";" || $temp eq "}" || $temp eq ")" || $temp eq "=" || $temp eq "{"){ $ws = 2; } if(($temp eq "\n" || $temp eq " ") && $ws != 0){$ws = 1}elsif($ws==1){$ws=0} if($ws != 1){ $prog.=$temp; } } print$prog; ``` Example input ``` for(1..10) { print "Hello, World!";#prints hello world print ($n = <>); #prints "#" } ``` Output ``` for(1..10){print "Hello, World!";print ($n =<>);} ``` Next, it will eliminate spaces between symbols and alphanumeric characters. [Answer] # Java golfer in Perl WIP at the moment, although it gets pretty nice code right now. Features: * Removes all comments * Removes unnecessary whitespace * Removes package declarations (it's single-file anyway!) ## Code ``` #!/usr/bin/env perl use strict; use warnings; my $string_re = qr/"(?:\\[btnfr"'\\]|\\(?:[0-3][0-7][0-7]|[0-7]{1,2})|\\u+[0-9a-fA-F]{4}|[^\r\n\\"])*"/; my @lines = <>; my @strings = (); # First, replace strings with placeholders. Strings suck REALLY hard when replacing. map { while (m/$string_re/) { s//"\032".@strings."\032"/e; push @strings, $&; } } @lines; # Remove comments my $in_comment = 0; my $partial_line; sub remove_comments { my $line = $_[0]; start: if ($in_comment) { if ((my $mulc_end_index = index $line, '*/') != -1) { $line = $partial_line . substr $line, $mulc_end_index + 2; $in_comment = 0; goto no_comment; } return 0; } no_comment: my $eolc_idx = index $line, '//'; my $mulc_idx = index $line, '/*'; if ($mulc_idx == -1 || ($eolc_idx != -1 && $eolc_idx < $mulc_idx)) { $line =~ s;//.*$;;; } elsif ($mulc_idx != -1) { $in_comment = 1; $partial_line = substr $line, 0, $mulc_idx; goto start; } $_ = $line; return 1 } @lines = grep {&remove_comments($_)} @lines; # Remove empty lines, remove line ends @lines = grep(!/^\s*$/, @lines); map {chomp;s/^\s*//;s/\s*$//} @lines; # Remove unnecessary whitespace map {s/\s*([][(){}><|&~,;=!+-])\s*/$1/g} @lines; # Remove unnecessary package declaration $lines[0] =~ s/^package [^;]+;//; # Finally, put strings back. map {s/\032(\d+?)\032/$strings[$1]/g} @lines; print @lines; ``` ]
[Question] [ This is my first challenge! ### Background [Perfect number](https://en.wikipedia.org/wiki/Perfect_number) is a positive integer, that is equal to the sum of all its divisors, except itself. So `6` is perfect number, since `1 + 2 + 3 = 6`. On the other hand `12` is not, because `1 + 2 + 3 + 4 + 6 = 16 != 12`. ### Task Your task is simple, write a program, which will, for given `n`, print one of these messages: > > I am a perfect number, because `d1 + d2 + ... + dm = s == n` > > I am not a perfect number, because `d1 + d2 + ... + dm = s [<>] n` > > > Where `d1, ... dm` are all divisors of `n` except for `n`. `s` is the sum of all divisors `d1, ..., dm` (again, without `n`). `[<>]` is either `<` (if `s < n`) or `>` (if `s > n`). ### Examples For `n` being `6`: "I am a perfect number, because 1 + 2 + 3 = 6 == 6" For `n` being `12`: "I am not a perfect number, because 1 + 2 + 3 + 4 + 6 = 16 > 12" For `n` being `13`: "I am not a perfect number, because 1 = 1 < 13" ### Rules * `n` is not bigger than your language's standard `int`. * You can read `n` from standard input, from command line arguments or from a file. * Output message has to be printed on standard output and no additional characters can appear in the output (it may have trailing whitespace or newline) * You may not use any built-ins or library functions which would solve the task (or its main part) for you. No `GetDivisors()` or something like that. * All other [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. ### Winner This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in **bytes** wins! [Answer] # Java, ~~255~~ 270 bytes (Still FF in base 17) ``` class C{public static void main(String[]a){int i=new Integer(a[0]),k=0,l=0;a[0]=" ";for(;++k<i;)if(i%k<1){l+=k;a[0]+=k+" ";}}System.out.print("I am "+(l==i?"":"not ")+"a perfect number, because "+a[0].trim().replace(" "," + ")+" = "+l+(l==i?" == ":l<i?" < ":" > ")+i);}} ``` And a more readable version: ``` class C { public static void main(String[] a) { int i = new Integer(a[0]), k = 0, l = 0; a[0] = " "; for(; ++k<i ;){ if (i % k == 0) { l += k; a[0] += k + " "; } } System.out.print("I am " + (l == i ? "" : "not ") + "a perfect number, because " + a[0].trim().replace(" "," + ") + " = " + l + (l == i ? " == " : l < i ? " < " : " > ") + i); } } ``` Previously didn't work for odd numbers, so I had to tweak a few things. At least I got lucky with the byte count again. :) [Answer] # R, ~~158~~ ~~163~~ ~~157~~ ~~153~~ ~~143~~ 141 bytes Still room to golf this I think. **Edit:** Replaced `if(b<n)'<'else if(b>n)'>'else'=='` with `c('<'[b<n],'>'[b>n],'=='[b==n])`. The `paste(...)` is replaced with an `rbind(...)[-1]`. Thanks @plannapus for a couple more bytes. ``` n=scan();a=2:n-1;b=sum(w<-a[!n%%a]);cat('I am','not'[b!=n],'a perfect number, because',rbind('+',w)[-1],'=',b,c('<'[b<n],'>'[b>n],'==')[1],n) ``` Ungolfed ``` n<-scan() # get number from stdin w<-which(!n%%1:(n-1)) # build vector of divisors b=sum(w) # sum divisors cat('I am', # output to STDOUT with a space separator 'not'[b!=n], # include not if b!=n 'a perfect number, because', rbind('+',w)[-1], # create a matrix with the top row as '+', remove the first element of the vector '=', b, # the summed value c( # creates a vector that contains only the required symbol and == '<'[b<n], # include < if b<n '>'[b>n], # include > if b>n '==' )[1], # take the first element n # the original number ) ``` Test run ``` > n=scan();b=sum(w<-which(!n%%1:(n-1)));cat('I am','not'[b!=n],'a perfect number, because',rbind('+',w)[-1],'=',b,c('<'[b<n],'>'[b>n],'==')[1],n) 1: 6 2: Read 1 item I am a perfect number, because 1 + 2 + 3 = 6 == 6 > n=scan();b=sum(w<-which(!n%%1:(n-1)));cat('I am','not'[b!=n],'a perfect number, because',rbind('+',w)[-1],'=',b,c('<'[b<n],'>'[b>n],'==')[1],n) 1: 12 2: Read 1 item I am not a perfect number, because 1 + 2 + 3 + 4 + 6 = 16 > 12 > n=scan();b=sum(w<-which(!n%%1:(n-1)));cat('I am','not'[b!=n],'a perfect number, because',rbind('+',w)[-1],'=',b,c('<'[b<n],'>'[b>n],'==')[1],n) 1: 13 2: Read 1 item I am not a perfect number, because 1 = 1 < 13 > ``` [Answer] # Python 2, ~~183~~ ~~173~~ 170 bytes ``` b=input();c=[i for i in range(1,b)if b%i<1];d=sum(c);print'I am %sa perfect number because %s = %d %s %d'%('not '*(d!=b),' + '.join(map(str,c)),d,'=<>='[cmp(b,d)%3::3],b) ``` Examples: ``` $ python perfect_number.py <<< 6 I am a perfect number because 1 + 2 + 3 = 6 == 6 $ python perfect_number.py <<< 12 I am not a perfect number because 1 + 2 + 3 + 4 + 6 = 16 > 12 $ python perfect_number.py <<< 13 I am not a perfect number because 1 = 1 < 13 $ python perfect_number.py <<< 100 I am not a perfect number because 1 + 2 + 4 + 5 + 10 + 20 + 25 + 50 = 117 > 100 $ python perfect_number.py <<< 8128 I am a perfect number because 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064 = 8128 == 8128 ``` Thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for saving 13 bytes! [Answer] # Pyth, 81 bytes ``` jd[+WK-QsJf!%QTStQ"I am"" not""a perfect number, because"j" + "J\=sJ@c3"==<>"._KQ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=jd[%2BWK-QsJf!%25QTStQ%22I%20am%22%22%20not%22%22a%20perfect%20number%2C%20because%22j%22%20%2B%20%22J%5C%3DsJ%40c3%22%3D%3D%3C%3E%22._KQ&input=6&test_suite_input=24%0A26%0A28&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=jd[%2BWK-QsJf!%25QTStQ%22I%20am%22%22%20not%22%22a%20perfect%20number%2C%20because%22j%22%20%2B%20%22J%5C%3DsJ%40c3%22%3D%3D%3C%3E%22._KQ&input=6&test_suite=1&test_suite_input=24%0A26%0A28&debug=0) ### Explanation: ``` implicit: Q = input number StQ the range of numbers [1, 2, ..., Q-1] f filter for numbers T, which satisfy: !%QT Q mod T != 0 J save this list of divisors in J -QsJ difference between Q and sum of J K save the difference in K jd[ put all of the following items in a list and print them joined by spaces: "I am" * "I am" +WK " not" + "not" if K != 0 "a perfect number, because" * "a perfect ..." j" + "J * the divisors J joined by " + " \= * "=" sJ * sum of J c3"==<>" * split the string "==<>" in 3 pieces: ["==", "<", ">"] @ ._K and take the (sign of K)th one (modulo 3) Q * Q ``` [Answer] # Julia, ~~161~~ 157 bytes ``` n=int(ARGS[1]) d=filter(i->n%i<1,1:n-1) s=sum(d) print("I am ",s!=n?"not ":"","a perfect number, because ",join(d," + ")," = $s ",s<n?"<":s>n?">":"=="," $n") ``` Ungolfed: ``` # Read n as the first command line argument n = int(ARGS[1]) # Get the divisors of n and their sum d = filter(i -> n % i == 0, 1:n-1) s = sum(d) # Print to STDOUT print("I am ", s != n ? "not " : "", "a perfect number, because ", join(d, " + "), " = $s ", s < n ? "<" : s > n ? ">" : "==", " $n") ``` [Answer] # CJam, 90 bytes ``` "I am"rd:R{R\%!},:D:+R-g:Cz" not"*" a perfect number, because "D'+*'=+D:++'=C+_'=a&+a+R+S* ``` For comparison, printing a single `=` could be achieved in 83 bytes. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22I%20am%22rd%3AR%7BR%5C%25!%7D%2C%3AD%3A%2BR-g%3ACz%22%20not%22*%22%20a%20perfect%20number%2C%20because%20%22D'%2B*'%3D%2BD%3A%2B%2B'%3DC%2B_'%3Da%26%2Ba%2BR%2BS*&input=6). ### How it works ``` "I am" e# Push that string. rd:R e# Read a Double from STDIN and save it in R. { e# Filter; for each I in [0 ... R-1]: R\%! e# Push the logical NOT of (R % I). }, e# Keep the elements such that R % I == 0. :D e# Save the array of divisors in D. :+R-g e# Add the divisors, subtract R and compute the sign of the difference. :Cz e# Save the sign in C and apply absolute value. "not "* e# Repeat the string "not " that many times. " a perfect number, because " D'+* e# Join the divisors, separating by plus signs. '=+D:++ e# Append a '=' and the sum of the divisors. '=C+ e# Add the sign to '=', pushing '<', '=' or '>'. _'=a& e# Intersect a copy with ['=']. +a+ e# Concatenate, wrap in array and concatenate. e# This appends "<", "==" or ">". R+ e# Append the input number. S* e# Join, separating by spaces. ``` [Answer] # Perl, 148 Bytes ``` $a=<>;$_=join' + ',grep{$a%$_==0}1..$a-1;$s=eval;print"I am ".($s==$a?'':'not ')."a perfect number because $_ = $s ".(('==','>','<')[$s<=>$a])." $a" ``` With line breaks: ``` $a=<>; $_=join' + ',grep{$a%$_==0}1..$a-1; $s=eval; print"I am ".($s==$a?'':'not ')."a perfect number because $_ = $s ".(('==','>','<')[$s<=>$a])." $a" ``` [Answer] # Lua, ~~244~~ 231 bytes Golfed: ``` n=io.read("*n")d={}s="1"t=1 for i=2,n-1 do if n%i==0 then table.insert(d,i)s=s.." + "..i t=t+i end end print(("I am%s a perfect number, because %s = %s"):format(t==n and""or" not", s, t..(t==n and" == "or(t>n and" > "or" < "))..n)) ``` Ungolfed: ``` n=io.read("*n") divisors={} sequence="1" sum=1 for i=2,n-1 do if n%i==0 then table.insert(divisors,i) sequence=sequence.." + "..i sum=sum+i end end print(("I am%s a perfect number, because %s = %s"):format(sum==n and""or" not", sequence, sum..(sum==n and" == "or(sum>n and" > "or" < "))..n)) ``` [Answer] # JavaScript (ES6), 146 Using template strings, it works in Firefox and latest Chrome. ``` for(n=prompt(),o=t=i=1;++i<n;)n%i||(t+=i,o+=' + '+i) alert(`I am ${t-n?'not ':''}a perfect number because ${o} = ${t} ${t<n?'<':t>n?'>':'=='} `+n) ``` [Answer] ## Ruby, ~~174~~ ~~160~~ ~~155~~ ~~136~~ ~~134~~ ~~128~~ 122 Bytes ``` n=6;a=[*1...n].reject{|t|n%t>0};b=a.inject(:+)<=>n;print"I am#{" not"*b.abs} a perfect number, because ",a*?+,"<=>"[b+1],n ``` Saved another 6 Bytes :) Thanks to [Tips for golfing in Ruby](https://codegolf.stackexchange.com/questions/363/tips-for-golfing-in-ruby) [Answer] # C#, 252 bytes ``` class A{static void Main(string[]a){int i=int.Parse(a[0]);var j=Enumerable.Range(1,i-1).Where(o=>i%o==0);int k=j.Sum();Console.Write("I am "+(i!=k?"not ":"")+"a perfect number, because "+string.Join(" + ",j)+" = "+k+(k>i?" > ":k<i?" < ":" == ")+i);}} ``` [Answer] # MATLAB, 238 Never going to be the shortest of all languages, but here's my attempt with MATLAB: ``` n=input('');x=1:n-1;f=x(~rem(n,x));s=sum(f);a='not ';b=strjoin(strtrim(cellstr(num2str(f')))',' + ');if(s>n) c=' > ';elseif(s<n) c=' < ';else c=' == ';a='';end;disp(['I am ' a 'a perfect number, because ' b ' = ' num2str(s) c num2str(n)]) ``` And this is in a slightly more readable form: ``` n=input(); %Read in the number using the input() function x=1:n-1; %All integers from 1 to n-1 f=x(~rem(n,x)); %Determine which of those numbers are divisors s=sum(f); %Sum all the divisors a='not '; %We start by assuming it is not perfect (to save some bytes) b=strjoin(strtrim(cellstr(num2str(f')))',' + '); %Also convert the list of divisors into a string %where they are all separated by ' + ' signs. %Next check if the number is >, < or == to the sum of its divisors if(s>n) c=' > '; %If greater than, we add a ' > ' to the output string elseif(s<n) c=' < '; %If less than, we add a ' < ' to the output string else c=' == '; %If equal, we add a ' == ' to the output string a=''; %If it is equal, then it is a perfect number, so clear the 'not' string end %Finally concatenate the output string and display the result disp(['I am ' a 'a perfect number, because ' b ' = ' num2str(s) c num2str(n)]) ``` I've managed to save 2 more bytes by not using a function. Instead you run the line of code and it requests the number as an input. Once run it displays the output at the end. [Answer] ## [Perl 6](http://perl6.org), 138 bytes ``` $_=get; my$c=$_ <=>my$s=[+] my@d=grep $_%%*,^$_; say "I am { 'not 'x?$c }a perfect number, because { join ' + ',@d } = $s { «> == <»[1+$c] } $_" ``` ( The count ignores the newlines, and indents, because they aren't needed ) `@d` is the array holding the divisors. `$s` holds the sum of the divisors. `$c` is the value of the comparison between the input, and the sum of the divisors. ( effectively `$c` is one of `-1`,`0`,`1`, but is really one of `Order::Less`, `Order::Same`, or `Order::More` ) In `'not 'x?$c`, `?$c` in this case is effectively the same as `abs $c`, and `x` is the string repetition operator. `«> == <»` is short for `( '>', '==', '<' )`. Since `$c` has one of `-1,0,1`, we have to shift it up by one to be able to use it to index into a list. Technically this will work for numbers well above 2⁶⁴, but takes an inordinate amount of time for numbers above 2¹⁶. [Answer] # [Hassium](https://github.com/HassiumTeam/Hassium), 285 Bytes Disclaimer: Works with only the latest version of Hassium due to issues with command line args. ``` func main(){n=Convert.toNumber(args[0]);s=1;l="1";foreach(x in range(2,n-3)){if(n%x==0){l+=" + "+x;s+=x;}}if(s==n)println("I am a perfect number, because "+l+" = "+s+" == "+s);else {print("I am not a perfect number, because "+l+" = "+s);if(s>n)println(" > "+n);else println(" < "+n);}} ``` More readable version: ``` func main() { n = Convert.toNumber(args[0]); s = 1; l = "1"; foreach(x in range(2, n - 3)) { if (n % x== 0) { l += " + " + x; s += x; } } if (s == n) println("I am a perfect number, because " + l + " = " + s + " == " + s); else { print("I am not a perfect number, because " + l + " = " + s); if (s > n) println(" > " + n); else println(" < " + n); } } ``` [Answer] # Pyth, 84 bytes ``` jd+,+"I am"*.aK._-QsJf!%QTtUQ" not""a perfect number, because"+.iJm\+tJ[\=sJ@"=<>"KQ ``` Invalid answer, because I refuse to implement `=` and `==` in the same equation. [Answer] # Ruby, 164 Bytes ``` ->i{t=(1...i).select{|j|i%j==0};s=t.inject &:+;r=['==','>','<'][s<=>i];puts "I am #{'not ' if r!='=='}a perfect number, because #{t.join(' + ')} = #{s} #{r} #{i}"} ``` # Test ``` irb(main):185:0> ->i{t=(1...i).select{|j|i%j==0};s=t.inject &:+;r=['==','>','<'][s<=>i];puts "I am #{'not ' if r!='=='}a perfect number, because #{t.join(' + ')} = #{s} #{r} #{i}"}.call 6 I am a perfect number, because 1 + 2 + 3 = 6 == 6 irb(main):186:0> ->i{t=(1...i).select{|j|i%j==0};s=t.inject &:+;r=['==','>','<'][s<=>i];puts "I am #{'not ' if r!='=='}a perfect number, because #{t.join(' + ')} = #{s} #{r} #{i}"}.call 12 I am not a perfect number, because 1 + 2 + 3 + 4 + 6 = 16 > 12 irb(main):187:0> ->i{t=(1...i).select{|j|i%j==0};s=t.inject &:+;r=['==','>','<'][s<=>i];puts "I am #{'not ' if r!='=='}a perfect number, because #{t.join(' + ')} = #{s} #{r} #{i}"}.call 13 I am not a perfect number, because 1 = 1 < 13 ``` [Answer] # Emacs Lisp, 302 Bytes ``` (defun p(n)(let((l(remove-if-not'(lambda(x)(=(% n x)0))(number-sequence 1(- n 1)))))(setf s(apply'+ l))(format"I am%s a perfect number, because %s%s = %s %s %s"(if(= s n)""" not")(car l)(apply#'concat(mapcar'(lambda(x)(concat" + "(number-to-string x)))(cdr l)))s(if(= sum n)"=="(if(> sum n)">""<"))n))) ``` Ungolfed version: ``` (defun perfect (n) (let ((l (remove-if-not '(lambda (x) (= (% n x) 0)) (number-sequence 1 (- n 1))))) (setf sum (apply '+ l)) (format "I am%s a perfect number, because %s%s = %s %s %s" (if (= sum n)"" " not") (car l) (apply #'concat (mapcar '(lambda (x) (concat " + " (number-to-string x))) (cdr l))) sum (if(= sum n) "==" (if(> sum n) ">" "<")) n))) ``` [Answer] # Powershell, 164 bytes ``` $a=$args[0] $b=(1..($a-1)|?{!($a%$_)})-join" + " $c=iex $b $d=$a.compareto($c) "I am $("not "*!!$d)a perfect number, because $b = $c $(("==","<",">")[$d]) $a" ``` A few of the common and not so common PoSh tricks; * Create the sum, then evaluate it with iex * Compareto to index the gt, lt, eq array * !!$d will evaluate to true == 1 for $d = 1 or -1, and false == 0 for $d = 0 [Answer] # awk, 150 ``` n=$0{for(p=i=s=n>1;++i<n;)for(;n%i<1;p+=i++)s=s" + "i;printf"I am%s a perfect number, because "s" = "p" %s "n RS,(k=p==n)?_:" not",k?"==":p<n?"<":">"} ``` Wasted some bytes on making this correct for input `1`. I'm not sure if that is expected. ``` n=$0{ for(p=i=s=n>1;++i<n;) for(;n%i<1;p+=i++)s=s" + "i; printf "I am%s a perfect number, because "s" = "p" %s "n RS, (k=p==n)?_:" not",k?"==":p<n?"<":">" } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 58 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „I€ÜIѨ©OIÊi'€–}“€…íÀ‚³,ƒ«“®vy'+}\'=®ODI.S"==><"211S£sèIðý ``` [Try it online](https://tio.run/##yy9OTMpM/f//UcM8z0dNaw7P8Tw88dCKQyv9PQ93ZaoDRR41TK591DAHzFp2eO3hhkcNsw5t1jk26dBqoPChdWWV6tq1Meq2h9b5u3jqBSvZ2trZKBkZGgYfWlx8eIXn4Q2H9/7/bwYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W6RJqr6TwqG2SgpL9/0cN8zwfNa05PCfi8MRDKw6t9I843JWpDhR51DC59lHDHDBr2eG1hxseNcw6tFnn2KRDq4HCh9aVVapr18ao2x5a5@8SoResZGtrZ6NkZGgYfGhx8eEVEYc3HN77X@d/tJmOoZGOoXEsAA). **Explanation:** ``` „I€Ü # Push dictionary string "I am" IѨ # Push the divisors of the input-integer, with itself removed © # Store it in the register (without popping) O # Get the sum of these divisors IÊi } # If it's not equal to the input-integer: '€– '# Push dictionary string "not" “€…íÀ‚³,ƒ«“ # Push dictionary string "a perfect number, because" ®v } # Loop `y` over the divisors: y'+ '# Push the divisor `y`, and the string "+" to the stack \ # Discard the final "+" '= '# And push the string "=" ®O # Get the sum of the divisors again D # Duplicate it I.S # Compare it to the input-integer (-1 if smaller; 0 if equal; 1 if larger) "==><" # Push string "==><" 211S£ # Split into parts of size [2,1,1]: ["==",">","<"] sè # Index into it (where the -1 will wrap around to the last item) I # Push the input-integer again ðý # Join everything on the stack by spaces # (and output the result implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `„I€Ü` is `"I am"`, `'€–` is `"not"`, and `“€…íÀ‚³,ƒ«“` is `"a perfect number, because"`. ]
[Question] [ The next revolution in typing on laptops was released on the [first of April, 2014 by SwiftKey](http://www.youtube.com/watch?v=-QfhTWJIDCM). However, I want to be the first person to write a swiping nano clone, but, as I can't find a good swipe-text to real-text library, and I can't wait for them, I'm asking here. ## Task Write a program that takes in swipe-text and outputs the real-text equivalent. Example: ``` Input: hgrerhjklo Output: hello ``` When the user does: ![enter image description here](https://raw.githubusercontent.com/matsjoyce/codegolf-swipe-type/master/kbd_hello.png) Other examples: ``` Input: wertyuioiuytrtjklkjhgfd Output: world Input: poiuytrtyuioiugrewsasdfgbhnmkijnbg Output: programming Input: poiuygfdzxcvhjklkjhgres Output: puzzles Input: cvhjioiugfde Output: code Input: ghiolkjhgf Output: golf ``` ## Rules * The program will take one swiped 'word' in on stdin or argv * The first and last letter of the swiped input will equate to the first and last letter of the real word * You can assume the user will make reasonably straight lines, but you can use the sample data to verify this (I made the sample data, and I will make the final test data) * For ambiguous input, you can make select either output, but I will try to eradicate all ambiguousness from the test data * This word will be in [this](https://github.com/matsjoyce/codegolf-swipe-type/blob/master/wordlist) word list (but swiped). The word list will be in the current directory, and can be read (newline separated, will be named `wordlist`, no extension). * The swipe will only contain lowercase alphabetic characters * The swipe may contain duplicated characters, if the user pauses on a key * The program must output on stdout (case does not matter) * The program must return `0` as the return code * You must provide the run command, compile command (if needed), name and which input path to use * Standard loopholes apply (they might not help, though) * No non-builtin libraries allowed * Deterministic, non golfed / obfuscated solutions preferred * No file writing, networking, etc. * Your code must run in one second or less (your code is run once per word) * The scoring runs are run on a Intel i7 Haswell processor, with 4 virtual code (2 real ones), so you can use threads if you have to * Maximum code length of 5000 bytes * The language you use must have a free (non trial) version available for Linux (Arch Linux, if that matters) ## Winning Criterion * The winner is the most accurate solution (scored by the [control program](https://github.com/matsjoyce/codegolf-swipe-type/blob/master/control.py), using the provided test list) * Popularity is the tie breaker * The scoring table will be updated every few days * Time-outs and crashes count as fails * This challenge will run for two weeks or more, depending on popularity * The final scoring will use a different, randomly selected list of words (same length, from same word list) ## Other * You can use the control program to test your program * If you are impatient, and want your program updated / added quickly, start an issue or pull request at <https://github.com/matsjoyce/codegolf-swipe-type/blob/master> * Entries are maintained at <https://github.com/matsjoyce/codegolf-swipe-type/blob/master/entries> * Logs of each program run are maintained at <https://github.com/matsjoyce/codegolf-swipe-type/blob/master/logs> * Main log at <https://github.com/matsjoyce/codegolf-swipe-type/blob/master/log.log> * The position of each key will be provided as a csv file in the current directory called `keypos.csv`, with the x and y values given as relative to `Q` (see <https://github.com/matsjoyce/codegolf-swipe-type/blob/master/keypos.csv>) * Each key is 1.5 x 1.5 cm (same unit as in keypos.csv) ## Current Score Boards [testlist](https://github.com/matsjoyce/codegolf-swipe-type/blob/master/testlist) ([logs](https://github.com/matsjoyce/codegolf-swipe-type/tree/master/logs-testlist)): ``` Three Pass Optimizer:Errors: 0/250 Fails: 7/250 Passes: 243/250 Timeouts: 0/250 Corner Sim: Errors: 0/250 Fails: 9/250 Passes: 241/250 Timeouts: 0/250 Discrete Fréchet Distance:Errors: 0/250 Fails: 17/250 Passes: 233/250 Timeouts: 0/250 Turnaround: Errors: 0/250 Fails: 18/250 Passes: 232/250 Timeouts: 0/250 Direction Checker: Errors: 0/250 Fails: 19/250 Passes: 231/250 Timeouts: 0/250 Regex Solver: Errors: 0/250 Fails: 63/250 Passes: 187/250 Timeouts: 0/250 ``` [testlist2](https://github.com/matsjoyce/codegolf-swipe-type/blob/master/testlist2) ([logs](https://github.com/matsjoyce/codegolf-swipe-type/tree/master/logs-testlist2)): ``` Corner Sim: Errors: 0/250 Fails: 10/250 Passes: 240/250 Timeouts: 0/250 Three Pass Optimizer:Errors: 2/250 Fails: 14/250 Passes: 234/250 Timeouts: 0/250 Turnaround: Errors: 0/250 Fails: 16/250 Passes: 234/250 Timeouts: 0/250 Direction Checker: Errors: 0/250 Fails: 17/250 Passes: 233/250 Timeouts: 0/250 Discrete Fréchet Distance:Errors: 0/250 Fails: 18/250 Passes: 232/250 Timeouts: 0/250 Regex Solver: Errors: 0/250 Fails: 67/250 Passes: 183/250 Timeouts: 0/250 ``` # Final Run [testlist](https://github.com/matsjoyce/codegolf-swipe-type/blob/master/testlist3) ([logs](https://github.com/matsjoyce/codegolf-swipe-type/tree/master/logs-testlist3)): ``` Corner Sim: Errors: 0/250 Fails: 14/250 Passes: 236/250 Timeouts: 0/250 Three Pass Optimizer:Errors: 0/250 Fails: 18/250 Passes: 232/250 Timeouts: 0/250 Direction Checker: Errors: 0/250 Fails: 20/250 Passes: 230/250 Timeouts: 0/250 Turnaround: Errors: 0/250 Fails: 23/250 Passes: 227/250 Timeouts: 0/250 Discrete Fréchet Distance:Errors: 0/250 Fails: 30/250 Passes: 220/250 Timeouts: 0/250 Regex Solver: Errors: 0/250 Fails: 55/250 Passes: 195/250 Timeouts: 0/250 ``` Well done to everybody and hgfdsasdertyuiopoiuy swertyuiopoijnhg! [Answer] ## JavaScript, ES6, Three Pass Optimizer, ~~112 187 235 240 241~~ 243 and ~~231~~ 234 passes A three pass filter which first figures out critical keys in the keystroke sequence and then passes the sequence through the three filters: 1. A loosely formed RegEx out of the critical keys and helping keys. This gives correct result for majority of the keys (around 150) 2. A strict RegEx made out of just critical keys. This gives correct result for an extra 85 sequences 3. A third filter to figure out ambiguity amongst close answers. This works for 40% ambiguous cases. **Code** ``` keyboard = { x: {}, y: [' q w e r t y u i o p', ' a s d f g h j k l', ' z x c v b n m'], }; for (var i in keyboard.y) for (var y of keyboard.y[i]) keyboard.x[y] = +i*7; p = C => (x=keyboard.x[C],{x, y: keyboard.y[x/7].indexOf(C)}) angle = (L, C, R) => ( p0 = p(L), p1 = p(C), p2 = p(R), a = Math.pow(p1.x-p0.x,2) + Math.pow(p1.y-p0.y,2), b = Math.pow(p1.x-p2.x,2) + Math.pow(p1.y-p2.y,2), c = Math.pow(p2.x-p0.x,2) + Math.pow(p2.y-p0.y,2), Math.acos((a+b-c) / Math.sqrt(4*a*b))/Math.PI*180 ) corner = (L, C, R, N, W) => { if (skip) { skip = false; return []; } ngl = angle(L, C, R); if (ngl < 80) return [C + "{1,3}"] if (ngl < 115 && p(L).x != p(R).x && p(L).x != p(C) && p(R).x != p(C).x && Math.abs(p(L).y - p(R).y) < 5) return [C + "{0,3}"] if (ngl < 138) { if (N && Math.abs(ngl - angle(C, R, N)) < 6) { skip = true; return [L + "{0,3}", "([" + C + "]{0,3}|[" + R + "]{0,3})?", N + "{0,3}"] } return [C + "{0,3}"] } return ["([" + L + "]{0,3}|[" + C + "]{0,3}|[" + R + "]{0,3})?"] } f = S => { for (W = [S[0] + "{1,2}"],i = 1; i < S.length - 1; i++) W.push(...corner(S[i - 1], S[i], S[i + 1], S[i + 2], W)) return [ new RegExp("^" + W.join("") + S[S.length - 1] + "{1,3}$"), new RegExp("^" + W.filter(C=>!~C.indexOf("[")).join("") + S[S.length - 1] + "{1,3}$") ] } thirdPass = (F, C) => { if (!F[0]) return null F = F.filter((s,i)=>!F[i - 1] || F[i - 1] != s) FF = F.map(T=>[...T].filter((c,i)=>!T[i - 1] || T[i - 1] != c).join("")) if (FF.length == 1) return F[0]; if (FF.length < 6 && FF[0][2] && FF[1][2] && FF[0][0] == FF[1][0] && FF[0][1] == FF[1][1]) if (Math.abs(F[0].length - F[1].length) < 1) for (i=0;i<Math.min(F[0].length, FF[1].length);i++) { if (C.indexOf(FF[0][i]) < C.indexOf(FF[1][i])) return F[0] else if (C.indexOf(FF[0][i]) > C.indexOf(FF[1][i])) return F[1] } return F[0] } var skip = false; SwiftKey = C => ( C = [...C].filter((c,i)=>!C[i - 1] || C[i - 1] != c).join(""), skip = false, matched = [], secondPass = [], L = C.length, reg = f(C), words.forEach(W=>W.match(reg[0])&&matched.push(W)), words.forEach(W=>W.match(reg[1])&&secondPass.push(W)), matched = matched.sort((a,b)=>Math.abs(L-a.length)>Math.abs(L-b.length)), secondPass = secondPass.sort((a,b)=>Math.abs(L-a.length)>Math.abs(L-b.length)), first = matched[0], second = secondPass[0], third = thirdPass(secondPass.length? secondPass: matched, C), second && second.length >= first.length - 1? first != third ? third: second: third.length >= first.length ? third: first ) // For use by js shell of latest firefox print(SwiftKey(readline())); ``` The code assumes a variable called `words` is present which is an array of all the words from [this page](https://github.com/matsjoyce/codegolf-swipe-type/blob/master/wordlist) [See the code in action here](http://jsfiddle.net/ht2kf4u2/11/) [See the test cases in action here](http://jsfiddle.net/vuL51f2j/15/) Both the above link work only on a latest Firefox (33 and above) (due to ES6). [Answer] ## Ruby, Regex Solver - ~~30 140 176 180 182~~ 187 and ~~179~~ 183 passes I'll figure out the score later. Here is very naive solution that doesn't take the keyboard layout into account: ``` words = File.readlines('wordlist').map(&:chomp) swipe = ARGV.shift puts words.select {|word| word[0] == swipe[0] && word[-1] == swipe[-1]} .select {|word| chars = [word[0]] (1..word.size-1).each {|i| chars << word[i] if word[i] != word[i-1]} swipe[Regexp.new('^'+chars.join('.*')+'$')] }.sort_by {|word| word.size}[-1] ``` It takes input from ARGV and prints the result. I'm just filtering the word list by first and last letter, and them I'm trying all of the remaining words against the input (eliminating duplicate letters and using a regex like `^g.*u.*e.*s$` for "guess") and return the first of those if there are multiple solutions. Run it like ``` ruby regex-solver.rb cvhjioiugfde ``` Anyone else, feel free to reuse this step as a first filter - I believe it won't throw out any correct words, so this preliminary check can greatly reduce the search space for better algorithms. **Edit:** Following the OPs suggestion, I'm now selecting the longest of the candidates, which seems to be a decent heuristic. Also thanks to es1024 for reminding me about duplicate letters. [Answer] # C++, Discrete Fréchet Distance - ~~201~~ ~~220~~ ~~222~~ 232 and 232 passes To me, the problem very much called for the [Fréchet Distance](https://en.wikipedia.org/wiki/Fr%C3%A9chet_distance) which unfortunately is very hard to compute. Just for fun, I've tried to approach the problem by implementing a discrete approximation described by Thomas Eiter and Heikki Mannila in [Computing Discrete Fréchet Distance](http://www.kr.tuwien.ac.at/staff/eiter/et-archive/cdtr9464.pdf) (1994). At first, I'm using the same approach as the others for filtering all words in the list which are subsequences of the input (also accounting for multiple sequential occurances of the same character). Then, I'm filling the polygon curve from letter to letter of every word with intermediate points and match it against the input curve. Finally, I divide every distance by the length of the word and take the minimum score. So far, the method doesn't work as well as I had hoped (It recognizes the code example as "chide"), but this could just be the result of bugs I haven't found yet. Else, another idea would be to use other variations of the fréchet distance ("average" instead of "maximum dog leash length"). **Edit:** Now, I'm using an approximation to the "average dog leash length". This means that I'm finding an ordered mapping between both paths which minimizes the sum of all distances and later divide it by the number of distances. If the same character appears twice or more often in the dictionary word, I only put one node in the path. ``` #include<iostream> #include<fstream> #include<vector> #include<map> #include<algorithm> #include<utility> #include<cmath> using namespace std; const double RESOLUTION = 3.2; double dist(const pair<double, double>& a, const pair<double, double>& b) { return sqrt((a.first - b.first) * (a.first - b.first) + (a.second - b.second) * (a.second - b.second)); } double helper(const vector<pair<double, double> >& a, const vector<pair<double, double> >& b, vector<vector<double> >& dp, int i, int j) { if (dp[i][j] > -1) return dp[i][j]; else if (i == 0 && j == 0) dp[i][j] = dist(a[0], b[0]); else if (i > 0 && j == 0) dp[i][j] = helper(a, b, dp, i - 1, 0) + dist(a[i], b[0]); else if (i == 0 && j > 0) dp[i][j] = helper(a, b, dp, 0, j - 1) + dist(a[0], b[j]); else if (i > 0 && j > 0) dp[i][j] = min(min(helper(a, b, dp, i - 1, j), helper(a, b, dp, i - 1, j - 1)), helper(a, b, dp, i, j - 1)) + dist(a[i], b[j]); return dp[i][j]; } double discretefrechet(const vector<pair<double, double> >& a, const vector<pair<double, double> >& b) { vector<vector<double> > dp = vector<vector<double> >(a.size(), vector<double>(b.size(), -1.)); return helper(a, b, dp, a.size() - 1, b.size() - 1); } bool issubsequence(string& a, string& b) { // Accounts for repetitions of the same character: hallo subsequence of halo int i = 0, j = 0; while (i != a.size() && j != b.size()) { while (a[i] == b[j]) ++i; ++j; } return (i == a.size()); } int main() { string swipedword; cin >> swipedword; ifstream fin; fin.open("wordlist"); map<string, double> candidatedistance = map<string, double>(); string readword; while (fin >> readword) { if (issubsequence(readword, swipedword) && readword[0] == swipedword[0] && readword[readword.size() - 1] == swipedword[swipedword.size() - 1]) { candidatedistance[readword] = -1.; } } fin.close(); ifstream fin2; fin2.open("keypos.csv"); map<char, pair<double, double> > keypositions = map<char, pair<double, double> >(); char rc, comma; double rx, ry; while (fin2 >> rc >> comma >> rx >> comma >> ry) { keypositions[rc] = pair<double, double>(rx, ry); } fin2.close(); vector<pair<double, double> > swipedpath = vector<pair<double, double> >(); for (int i = 0; i != swipedword.size(); ++i) { swipedpath.push_back(keypositions[swipedword[i]]); } for (map<string, double>::iterator thispair = candidatedistance.begin(); thispair != candidatedistance.end(); ++thispair) { string thisword = thispair->first; vector<pair<double, double> > thispath = vector<pair<double, double> >(); for (int i = 0; i != thisword.size() - 1; ++i) { pair<double, double> linestart = keypositions[thisword[i]]; pair<double, double> lineend = keypositions[thisword[i + 1]]; double linelength = dist(linestart, lineend); if (thispath.empty() || linestart.first != thispath[thispath.size() - 1].first || linestart.second != thispath[thispath.size() - 1].second) thispath.push_back(linestart); int segmentnumber = linelength / RESOLUTION; for (int j = 1; j < segmentnumber; ++j) { thispath.push_back(pair<double, double>(linestart.first + (lineend.first - linestart.first) * ((double)j) / ((double)segmentnumber), linestart.second + (lineend.second - lineend.second) * ((double)j) / ((double)segmentnumber))); } } pair<double, double> lastpoint = keypositions[thisword[thisword.size() - 1]]; if (thispath.empty() || lastpoint.first != thispath[thispath.size() - 1].first || lastpoint.second != thispath[thispath.size() - 1].second) thispath.push_back(lastpoint); thispair->second = discretefrechet(thispath, swipedpath) / (double)(thispath.size()); } double bestscore = 1e9; string bestword = ""; for (map<string, double>::iterator thispair = candidatedistance.begin(); thispair != candidatedistance.end(); ++thispair) { double score = thispair->second; if (score < bestscore) { bestscore = score; bestword = thispair->first; } // cout << thispair->first << ": " << score << endl; } cout << bestword << endl; return 0; } ``` I've compiled the code with clang, but `g++ ./thiscode.cpp -o ./thiscode` should also work fine. [Answer] # Python 2, Turnarounds, ~~224 226 230~~ 232 and ~~230~~ 234 passes This is quite a straight forward approach: * Find the points where the flow of letters changes direction (plus start and end). * Output the longest word that includes all these turning points. ``` import sys, csv, re wordlistfile = open('wordlist', 'r') wordlist = wordlistfile.read().split('\n') layout = 'qwertyuiop asdfghjkl zxcvbnm' keypos = dict((l, (2*(i%11)+i/11, i/11)) for i,l in enumerate(layout)) #read input from command line argument input = sys.argv[1] #remove repeated letters input = ''.join(x for i,x in enumerate(input) if i==0 or x!=input[i-1]) #find positions of letters on keyboard xpos = map(lambda l: keypos[l][0], input) ypos = map(lambda l: keypos[l][1], input) #check where the direction changes (neglect slight changes in x, e.g. 'edx') xpivot = [(t-p)*(n-t)<-1.1 for p,t,n in zip(xpos[:-2], xpos[1:-1], xpos[2:])] ypivot = [(t-p)*(n-t)<0 for p,t,n in zip(ypos[:-2], ypos[1:-1], ypos[2:])] pivot = [xp or yp for xp,yp in zip(xpivot, ypivot)] #the first and last letters are always pivots pivot = [True] + pivot + [True] #build regex regex = ''.join(x + ('+' if p else '*') for x,p in zip(input, pivot)) regexobj = re.compile(regex + '$') #find all words that match the regex and output the longest one words = [w for w in wordlist if regexobj.match(w)] output = max(words, key=len) if words else input print output ``` Run as ``` python turnarounds.py tyuytrghn ``` The solution is not very robust. A single wrong keystroke would make it fail. However, since the set of test cases has very little no misspellings it performs quite well, only getting confused in some cases where it picks too long words. *Edit:* I changed it a bit to not use the provided key position file but a simplified layout. This makes it easier for my algorithm because in the file the keys are not evenly spaced. I can achieve even slightly better results by including some ad-hoc tiebreakers for ambiguous cases, but that would be over-optimizing for this particular test set. Some fails remain that are not actually ambiguous but that I don't catch with my simple algorithm because it only considers direction changes of more than 90 degrees. [Answer] # PHP, Direction Checker, ~~203 213 216 229~~ 231 and ~~229~~ 233 passes This begins with a simple pass through the dictionary to obtain a list of words whose letters are all present in the input (what Martin did [here](https://codegolf.stackexchange.com/a/39742/29611)), and also only checking for `l.*` instead of `l.*l.*` when `l` is duplicated. The longest word here is then saved in a variable. Another check is then done, based on the keys at the points where the swipe changes direction (+/0 to - or -/0 to +, in either x or y). The list of possible words is checked against this list of characters, and words that do not match are eliminated. This approach relies on sharp turns in swiping to be accurate. The longest remaining word is outputted, or if no words are left, the longest word from earlier is outputted instead. **Edit:** Added all characters in a horizontal line leading up to a change in direction as possible values to check for. PHP 5.4 is required (or replace all `[..]` with `array(..)`). ``` <?php function get_dir($a, $b){ $c = [0, 0]; if($a[0] - $b[0] < -1.4) $c[0] = 1; else if($a[0] - $b[0] > 1.4) $c[0] = -1; if($a[1] < $b[1]) $c[1] = 1; else if($a[1] > $b[1]) $c[1] = -1; return $c; } function load_dict(){ return explode(PHP_EOL, file_get_contents('wordlist')); } $coord = []; $f = fopen('keypos.csv', 'r'); while(fscanf($f, "%c, %f, %f", $c, $x, $y)){ $coord[$c] = [$x, $y]; } fclose($f); $dict = load_dict(); $in = $argv[1]; $possib = []; foreach($dict as $c){ if($c[0] == $in[0]){ $q = strlen($c); $r = strlen($in); $last = ''; $fail = false; $i = $j = 0; for($i = 0; $i < $q; ++$i){ if($last == $c[$i]) continue; if($j >= $r){ $fail = true; break; } while($c[$i] != $in[$j++]) if($j >= $r){ $fail = true; break; } if($fail) break; $last = $c[$i]; } if(!$fail) $possib[] = $c; } } $longest = ''; foreach($possib as $p){ if(strlen($p) > strlen($longest)) $longest = $p; } $dir = [[0, 0]]; $cdir = [0, 0]; $check = '/^' . $in[0] . '.*?'; $olst = []; $p = 1; $len = strlen($in); for($i = 1; $i < $len; ++$i){ $dir[$i] = get_dir($coord[$in[$i - 1]], $coord[$in[$i]]); $olddir = $cdir; $newdir = $dir[$i]; $xc = $olddir[0] && $newdir[0] && $newdir[0] != $olddir[0]; $yc = $olddir[1] && $newdir[1] && $newdir[1] != $olddir[1]; if($xc || $yc){ // separate dir from current dir if($yc && !$xc && $dir[$i - 1][1] == 0){ $tmp = ''; for($j = $i - 1; $j >= 0 && $dir[$j][1] == 0; --$j){ $tmp = '(' . $in[$j-1] . '.*?)?' . $tmp; } $olst[] = range($p, $p + (($i - 1) - $j)); $p += ($i - 1) - $j + 1; $check .= $tmp . '(' . $in[$i - 1] . '.*?)?'; }else{ $check .= $in[$i - 1] . '.*?'; } $cdir = $dir[$i]; }else{ if(!$cdir[0]) $cdir[0] = $dir[$i][0]; if(!$cdir[1]) $cdir[1] = $dir[$i][1]; } } $check .= substr($in, -1) . '$/'; $olstc = count($olst); $res = []; foreach($possib as $p){ if(preg_match($check, $p, $match)){ if($olstc){ $chk = array_fill(0, $olstc, 0); for($i = 0; $i < $olstc; ++$i){ foreach($olst[$i] as $j){ if(isset($match[$j]) && $match[$j]){ ++$chk[$i]; } } // give extra weight to the last element of a horizontal run if(@$match[$olst[$i][count($olst[$i])-1]]) $chk[$i] += 0.5; } if(!in_array(0, $chk)){ $res[$p] = array_sum($chk); } }else{ $res[$p] = 1; } } } $possib = array_keys($res, @max($res)); $newlong = ''; foreach($possib as $p){ if(strlen($p) > strlen($newlong)) $newlong = $p; } if(strlen($newlong) == 0) echo $longest; else echo $newlong; ``` [Answer] # Python 3, Corner Simulator, 241 and 240 passes Algorithm: * Deduplicate (remove consecutive runs of the same character) the input and all the words in the word list (using a dictionary to get the original words back) * Remove all words that do not start and end with the start and end of the swipe (first pass) * Make a regex out of all the corners greater than 80 degrees, then remove all words which do not match this (second pass) * Regex each word (like Regex Solver) against the swipe, then split the swipe into a series of theoretically straight lines, and check if they are straight and could have been produced by a finger moving along that line (`significant_letter` function) (third pass) * Sort the words by closeness to the straight lines * Then use length as a tie breaker (longer is better) * Then use Levenshtein distance as the final tie breaker * Output word! Code: ``` # Corner Sim from math import atan, degrees, pi, factorial, cos, radians import csv import re import sys keys = {} key_size = 1.5 for line in open("keypos.csv"): k, x, y = map(str.strip, line.split(",")) keys[k] = float(x), float(y) def deduplicate(s): return s[0] + "".join(s[i + 1] for i in range(len(s) - 1) if s[i + 1] != s[i]) def angle(coord1, coord2): x1, y1, x2, y2 = coord1 + coord2 dx, dy = x2 - x1, y1 - y2 t = abs(atan(dx/dy)) if dy else pi / 2 if dx >= 0 and dy >= 0: a = t elif dx >= 0 and dy < 0: a = pi - t elif dx < 0 and dy >= 0: a = 2 * pi - t else: a = t + pi return degrees(a) def significant_letter(swipe): if len(swipe) <= 2: return 0 x1, y1, x2, y2 = keys[swipe[0]] + keys[swipe[-1]] m = 0 if x2 == x1 else (y2 - y1) / (x2 - x1) y = lambda x: m * (x - x1) + y1 def sim_fun(x2, y2): try: return (x2 / m + y2 - y1 + x1 * m) / (m + 1 / m) except ZeroDivisionError: return x2 dists = [] for i, key in enumerate(swipe[1:-1]): sx, bx = min(x1, x2), max(x1, x2) pos_x = max(min(sim_fun(*keys[key]), bx), sx) sy, by = min(y1, y2), max(y1, y2) pos_y = max(min(y(pos_x), by), sy) keyx, keyy = keys[key] dist = ((keyx - pos_x) ** 2 + (keyy - pos_y) ** 2) ** 0.5 a = angle((keyx, keyy), (pos_x, pos_y)) if 90 <= a <= 180: a = 180 - a elif 180 <= a <= 270: a = a - 180 elif 270 <= a <= 360: a = 360 - a if a > 45: a = 90 - a h = key_size / 2 / cos(radians(a)) dists.append((max(dist - h, 0), i + 1, key)) return sorted(dists, reverse=True)[0][0] def closeness2(s, t): # https://en.wikipedia.org/wiki/Levenshtein_distance if s == t: return 0 if not len(s): return len(t) if not len(t): return len(s) v0 = list(range(len(t) + 1)) v1 = list(range(len(t) + 1)) for i in range(len(s)): v1[0] = i + 1 for j in range(len(t)): cost = 0 if s[i] == t[j] else 1 v1[j + 1] = min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost) for j in range(len(v0)): v0[j] = v1[j] return v1[len(t)] / len(t) def possible(swipe, w, s=False): m = re.match("^" + "(.*)".join("({})".format(i) for i in w) + "$", swipe) if not m or s: return bool(m) return closeness1(swipe, w) < 0.8 def closeness1(swipe, w): m = re.match("^" + "(.*)".join("({})".format(i) for i in w) + "$", swipe) unsigpatches = [] groups = m.groups() for i in range(1, len(groups), 2): unsigpatches.append(groups[i - 1] + groups[i] + groups[i + 1]) if debug: print(unsigpatches) sig = max(map(significant_letter, unsigpatches)) if debug: print(sig) return sig def find_closest(swipes): level1, level2, level3, level4 = swipes if debug: print("Loading words...") words = {deduplicate(i.lower()): i.lower() for i in open("wordlist").read().split("\n") if i[0] == level1[0] and i[-1] == level1[-1]} if debug: print("Done first filter (start and end):", words) r = re.compile("^" + ".*".join(level4) + "$") pos_words2 = list(filter(lambda x: bool(r.match(x)), words)) if debug: print("Done second filter (sharpest points):", pos_words2) pos_words = pos_words2 or words pos_words = list(filter(lambda x: possible(level1, x), pos_words)) or list(filter(lambda x: possible(level1, x, s=True), pos_words)) if debug: print("Done third filter (word regex):", pos_words) sorted_pos_words = sorted((closeness1(level1, x), -len(x), closeness2(level1, x), x) for x in pos_words) if debug: print("Closeness matching (to", level2 + "):", sorted_pos_words) return words[sorted_pos_words[0][3]] def get_corners(swipe): corners = [[swipe[0]] for i in range(4)] last_dir = last_char = None for i in range(len(swipe) - 1): dir = angle(keys[swipe[i]], keys[swipe[i + 1]]) if last_dir is not None: d = abs(last_dir - dir) a_diff = min(360 - d, d) corners[0].append(last_char) if debug: print(swipe[i], dir, last_dir, a_diff, end=" ") if a_diff >= 55: if debug: print("C", end=" ") corners[1].append(last_char) if a_diff >= 65: if debug: print("M", end=" ") corners[2].append(last_char) if a_diff >= 80: if debug: print("S", end=" ") corners[3].append(last_char) if debug: print() last_dir, last_char = dir, swipe[i + 1] tostr = lambda x: deduplicate("".join(x + [swipe[-1]]).lower()) return list(map(tostr, corners)) if __name__ == "__main__": debug = "-d" in sys.argv if debug: sys.argv.remove("-d") swipe = deduplicate(sys.argv[1] if len(sys.argv) > 1 else input()).lower() corners = get_corners(swipe) if debug: print(corners) print(find_closest(corners)) ``` Run with `python3 entries/corner_sim.py` ]
[Question] [ ## Introduction: I saw there was only [one other badminton related challenge right now](https://codegolf.stackexchange.com/questions/44900/confused-badminton-players). Since I play badminton myself (for the past 13 years now), I figured I'd add some badminton-related challenges. Here the first one: ## Challenge: **Input:** Two integers **Output:** One of three distinct and unique outputs of your own choice. One indicating that the input is a valid badminton score AND the set has ended with a winner; one indicating that the input is a valid badminton score AND the set is still in play; one indicating the input is not a valid badminton score. With badminton, both (pairs of) players start with 0 points, and you stop when one of the two (pairs of) players has reached a score of 21, with at least 2 points difference, up to a maximum of 30-29. So these are all possible input-pairs (in either order) indicating it's a valid badminton score AND the set has ended: ``` [[0,21],[1,21],[2,21],[3,21],[4,21],[5,21],[6,21],[7,21],[8,21],[9,21],[10,21],[11,21],[12,21],[13,21],[14,21],[15,21],[16,21],[17,21],[18,21],[19,21],[20,22],[21,23],[22,24],[23,25],[24,26],[25,27],[26,28],[27,29],[28,30],[29,30]] ``` And these are all possible input-pairs (in either order) indicating it's a valid badminton score BUT the set is still in play: ``` [[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[0,9],[0,10],[0,11],[0,12],[0,13],[0,14],[0,15],[0,16],[0,17],[0,18],[0,19],[0,20],[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7],[1,8],[1,9],[1,10],[1,11],[1,12],[1,13],[1,14],[1,15],[1,16],[1,17],[1,18],[1,19],[1,20],[2,2],[2,3],[2,4],[2,5],[2,6],[2,7],[2,8],[2,9],[2,10],[2,11],[2,12],[2,13],[2,14],[2,15],[2,16],[2,17],[2,18],[2,19],[2,20],[3,3],[3,4],[3,5],[3,6],[3,7],[3,8],[3,9],[3,10],[3,11],[3,12],[3,13],[3,14],[3,15],[3,16],[3,17],[3,18],[3,19],[3,20],[4,4],[4,5],[4,6],[4,7],[4,8],[4,9],[4,10],[4,11],[4,12],[4,13],[4,14],[4,15],[4,16],[4,17],[4,18],[4,19],[4,20],[5,5],[5,6],[5,7],[5,8],[5,9],[5,10],[5,11],[5,12],[5,13],[5,14],[5,15],[5,16],[5,17],[5,18],[5,19],[5,20],[6,6],[6,7],[6,8],[6,9],[6,10],[6,11],[6,12],[6,13],[6,14],[6,15],[6,16],[6,17],[6,18],[6,19],[6,20],[7,7],[7,8],[7,9],[7,10],[7,11],[7,12],[7,13],[7,14],[7,15],[7,16],[7,17],[7,18],[7,19],[7,20],[8,8],[8,9],[8,10],[8,11],[8,12],[8,13],[8,14],[8,15],[8,16],[8,17],[8,18],[8,19],[8,20],[9,9],[9,10],[9,11],[9,12],[9,13],[9,14],[9,15],[9,16],[9,17],[9,18],[9,19],[9,20],[10,10],[10,11],[10,12],[10,13],[10,14],[10,15],[10,16],[10,17],[10,18],[10,19],[10,20],[11,11],[11,12],[11,13],[11,14],[11,15],[11,16],[11,17],[11,18],[11,19],[11,20],[12,12],[12,13],[12,14],[12,15],[12,16],[12,17],[12,18],[12,19],[12,20],[13,13],[13,14],[13,15],[13,16],[13,17],[13,18],[13,19],[13,20],[14,14],[14,15],[14,16],[14,17],[14,18],[14,19],[14,20],[15,15],[15,16],[15,17],[15,18],[15,19],[15,20],[16,16],[16,17],[16,18],[16,19],[16,20],[17,17],[17,18],[17,19],[17,20],[18,18],[18,19],[18,20],[19,19],[19,20],[20,20],[20,21],[21,21],[21,22],[22,22],[22,23],[23,23],[23,24],[24,24],[24,25],[25,25],[25,26],[26,26],[26,27],[27,27],[27,28],[28,28],[28,29],[29,29]] ``` Any other pair of integer would be an invalid badminton score. ## Challenge rules: * I/O is flexible, so: + You can take the input as a list of two numbers; two separated numbers through STDIN or function parameters; two strings; etc. + Output will be three distinct and unique values of your own choice. Can be integers (i.e. `[0,1,2]`, `[1,2,3]`, `[-1,0,1]`, etc.); can be Booleans (i.e. `[true,false,undefined/null/empty]`); can be characters/strings (i.e. `["valid & ended","valid","invalid"]`); etc. + **Please specify the I/O you've used in your answer!** * **You are allowed to take the input-integers pre-ordered from lowest to highest or vice-versa.** * The input integers can be negative, in which case they are of course invalid. ## 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: These test cases are valid, and the set has ended: ``` 0 21 12 21 21 23 28 30 29 30 ``` These test cases are valid, but the set is still in play: ``` 0 0 0 20 12 12 21 21 21 22 ``` These test cases are invalid: ``` -21 19 -19 21 -1 1 12 22 29 31 30 30 42 43 1021 1021 ``` [Answer] # [Python 2](https://docs.python.org/2/), 47 bytes ``` lambda a,b:[61>60-a>b<3+max(19,a)for b in-~b,b] ``` [Try it online!](https://tio.run/##jZZPb9tGFMTv/hS8WUYlgLP/N6gDBEgOBYoee3F9oGBJFeDIhqsUzaVf3ZXezJoUkwC9PPnR2vk9UjvDff56/PPp4F63t3@8Pg6f1w9DNyzX7@4S3qd@Nbxf/@x/@jz8s0BdDjfbp5du3e0Pq3/Xy/X969Xzy/5w7K7/Hh73D93m8LB5eHeti9tF1y87h5u3Hu6ydzj1ftKXZef7SV/ZX1L2h@75cfg643STdcbtL7lwM@58Djdy9gcjTQir81dQxyWr09O40OhW52/M7tXN7mXyf99f3ms4fT9MngV6Q/ZnBi9e/f7h118@3t7d9cv@fnmqsOqseqvBarSarGarxWrlKi3manA5uB4UABVACVADFAFVHFXcWQVLVmfVWw1Wo9VkNVstVitX9fyQBpeD60EBUAGUADVAEVDFUcUmcTaDsxmczeBsBmczOJvB2QzOZnCcwXEGxxkcZ3CcwXEGxxkcZ3CcwXEGxxkcZ/BG90b3RvdG90b3RvdG96R70j3pnnRPuifdk@5J96R70j3pnvRg3GDcYNxg3GDcYNxAbiA3kBvIDeQGcgO5gdxAbiA3kBvIjUaMRoxGjEaMRowkRhIjiZHESGIkMZIYSYwkRhIjiZHEZKxkrGSsZKxEViIrkZXISmQlshJZiaxEViIrkZXIykbJRslGyaRkUjIpmZRMSiYlk5JJyaRkUjIpmZRi@sX0C/UL9Qv1C/UL9Qv1C/UL9Qv1C/UL9Qv1qylXKlcqVypXKlcqVypXKlcqVypXKlcqVyWAYgXKFShYoGSBogXKFihcoHSB4gXKFyhg0BKmpUSLiZYTLShaUrSoaFnRwqKlRYsL5QVkecjzkOkh10O2h3wPGR9yPmR9yPuQeyH7Qv6FDAw5GLIw5GHIxJCLIRtCPoSMCDkRsiLkRciMkBshN0F2gvwEGQpyFGQpyFOQJSBPQKaAXAHZAvIFtKuhbQ3ta2hjQzsb2pbQvoQ2JrQzoV0FbStoXzntA9ePvUV0y3uMvWW2U@/G3kLcq/djb6ke1Iext5iP6uPYW@4n9Wns7UWQ1eextzdDUV/eem/3U9XXc39/dfXpt4@f@GrXG7W9zjCNdiWt4k/JpOiQw5sdm23aNm/bs22vtk3az95@zvZztZ/lm8c@f6zzxzZ/LLPb5u3ubicHzeOX58fNYrs4/X0zO@u9ncD@2hwXO/vG@QB6@jyfAu081E5M15eHz@8usKf8tmD3tD/s/geh22@7u9OF@@7wdJzI/Oi0OFM6r3gZDrvNYhVPZ7P@pmtnaF0e7OIcwpt7/Q8 "Python 2 – Try It Online") Outputs a list of two Booleans. Thanks to [TFeld](https://codegolf.stackexchange.com/users/38592/tfeld) for writing a test suite in [their answer](https://codegolf.stackexchange.com/a/182248/20260) that made it easy to check my solution. ``` ended: [False, True] going: [True, True] invalid: [False, False] ``` The key insight is that a valid score ends the game exactly if increasing the higher value `b` makes the score invalid. So, we just code up the validity condition, and check it for `(a,b+1)` in addition to `(a,b)` to see if the game has ended. Validity is checked via three conditions that are chained together: * `b<3+max(19,a)`: Checks that the higher score `b` isn't past winning, with either `b<=21` or `b<=a+2` (win by two) * `60-a>b`: Equivalent to `a+b<=59`, ensuring the score isn't above `(29,30)` * `61>60-a`: Equivalent to `a>=0`, ensures the lower score is non-negative --- # [Python 2](https://docs.python.org/2/), 44 bytes ``` lambda a,b:[b-61<~a<a>b/22*b-3for b in-~b,b] ``` [Try it online!](https://tio.run/##jZbNbhtHEITveoq9iQpIZKvnb8ewAgSwDwaCHHORdSAhkiGgUILCBPDFry6TXTVacu0AuTTVK059vcup2nn@cvjzaW@vm9vPr4/Lv1YPy245X727Wy0y3n9dvl/@svrZ7KfVImyeXrpVt9svvq7mq/vXq@eX3f7QXf@7fNw9dOv9w/rh3bUubmZdP@8MN2897LI3HPtw1g/zLvRnfWV/Sdntu@fH5ZcJpztb59z@kgubcKdz2MjZ7Z10RlicvoI6LlmgXmp0i9M3Jvdqk3s5@3/oL@81Hr8fz54Fekf2JwYvXv3x62@fPtze3fXz/n5@rPBqXoPX6DV5zV6L18Fr5Sot5mpwObgeFAAVQAlQAxQBVYwqdlLBnNW8Bq/Ra/KavRavg9fKVT0/pMHl4HpQAFQAJUANUARUMar4JOYzmM9gPoP5DOYzmM9gPoP5DMYZjDMYZzDOYJzBOINxBuMMxhmMMxhnMM4QnB6cHpwenB6cHpwenB5ID6QH0gPpgfRAeiA9kB5ID6QH0gPp0bnRudG50bnRudG5kdxIbiQ3khvJjeRGciO5kdxIbiQ3kpucmJyYnJicmJyYSEwkJhITiYnERGIiMZGYSEwkJhITidlZ2VnZWdlZmaxMViYrk5XJymRlsjJZmaxMViYrk1WcUpxSnFJIKaQUUgophZRCSiGlkFJIKaQUUgopg@sPrj9Qf6D@QP2B@gP1B@oP1B@oP1B/oP5A/YH61ZUrlSuVK5UrlSuVK5UrlSuVK5UrlSuVqxJAsQLlChQsULJA0QJlCxQuULpA8QLlCxQwaAnTUqLFRMuJFhQtKVpUtKxoYdHSosWF8gKyPOR5yPSQ6yHbQ76HjA85H7I@5H3IvZB9If9CBoYcDFkY8jBkYsjFkA0hH0JGhJwIWRHyImRGyI2QmyA7QX6CDAU5CrIU5CnIEpAnIFNAroBsAfkC2tXQtob2NbSxoZ0NbUtoX0IbE9qZ0K6CthW0r0z7wPqx94hueY@x98w29Tb2HuJBfRh7T/WoPo69x3xSn8becz@rz2PvL4Kivoy9vxkG9cNbH/x@qvp66u@vrj7@/uEjX@16o7bXGc6jXUmr@FMyKTrk8GbHZpu2zdv2bNurbZP2s7efs/1c7Wf57rFPH@v0sU0fy@S2ebvb27NT5uGf58f1bDM7/n0zOeu9ncD@Xh9mW//G6QB6/DydAv081E5M15eHzx8u8Kf8tmD7tNtv/weh2226u@OF@27/dDiT@a/T4kTptOJlud@uZ4t0PJv1N107Q@vy0i9OIby5128 "Python 2 – Try It Online") An improved validity check by TFeld saves 3 bytes. The main idea is to branch on "overtime" `b>21` with `b/22*b` which effectively sets below-21 scores to zero, whereas I'd branched on `a>19` with the longer `max(19,a)`. --- # [Python 2](https://docs.python.org/2/), 43 bytes ``` lambda a,b:a>>99|cmp(2+max(19,a)%30-a/29,b) ``` [Try it online!](https://tio.run/##jZZPayNHFMTv/hRzCZaJTKZe/5nuBS8Edg@BkGMujg/jtaUV2LJxTMhCvrujeVXtkSYJ5PLEk6br92bUVdPP316/Pu3tbXP129vD@Hh7N3bj@vbD@PFjrX99eXxe2feP458r1PV48V3oL8cfrK5vL97Onl92@9fu/I/xYXfX3e/v7u8@nOvLzarr153h4r2HnfaGQx@O@rLuQn/UV/anlN2@e34Yvy043dE65/anXNiCu5zDZs5u76QjwuV0Ceq85PLwKE40usvpisW92uJejn4P/em9xsP18ehZoHdkPzH45dmvP/7806er6@t@3d@sDxVezWvwGr0mr9nr4LV4rVylxVwNLgfXgwKgAigBaoAioIpRxSYVrFnNa/AavSav2evgtXitXNXzQxpcDq4HBUAFUALUAEVAFaOKT2I@g/kM5jOYz2A@g/kM5jOYz2CcwTiDcQbjDMYZjDMYZzDOYJzBOINxBuMMwenB6cHpwenB6cHpwemB9EB6ID2QHkgPpAfSA@mB9EB6ID2QHp0bnRudG50bnRudG8mN5EZyI7mR3EhuJDeSG8mN5EZyI7nJicmJyYnJicmJicREYiIxkZhITCQmEhOJicREYiIxkZidlZ2VnZWdlcnKZGWyMlmZrExWJiuTlcnKZGWyMlmDUwanDE4ZSBlIGUgZSBlIGUgZSBlIGUgZSBlIGUgprl9cv1C/UL9Qv1C/UL9Qv1C/UL9Qv1C/UL9Qv7pypXKlcqVypXKlcqVypXKlcqVypXKlclUCKFagXIGCBUoWKFqgbIHCBUoXKF6gfIECBi1hWkq0mGg50YKiJUWLipYVLSxaWrS4UF5Aloc8D5kecj1ke8j3kPEh50PWh7wPuReyL@RfyMCQgyELQx6GTAy5GLIh5EPIiJATIStCXoTMCLkRchNkJ8hPkKEgR0GWgjwFWQLyBGQKyBWQLSBfQLsa2tbQvoY2NrSzoW0J7UtoY0I7E9pV0LaC9pVpH1g/9x7RLe8x957Zpt7m3kM8qA9z76ke1ce595hP6tPce@5n9Xnu/UUwqB/m3t8MRX1574PfT1Vfp/7m7OzzL58@89WuN2p7neE42pW0ij8lk6JDDm92bLZp27xtz7a92jZpf3v7O9vf1f6Wfzz25WNdPrblY1ncNm93e3V0yNysDnVxyHs/ev1@/7ra@gWbp5fp8un45wehdlQ6Pz11/usCf7zvC7ZPu/32fxC63aa7Pnxx0@2fXo9k/uuYuFCaVryM@@394fTYTxu5v@imH27nH0Z@u@Tw/t7@Bg "Python 2 – Try It Online") Outputs: ``` ended: 0 going: -1 invalid: 1 ``` Assumes that the inputs are not below \$-2^{99}\$. [Answer] # [Python 2](https://docs.python.org/2/), ~~97~~ ~~95~~ ~~75~~ ~~72~~ ~~71~~ ~~70~~ ~~69~~ ~~64~~ ~~55~~ ~~54~~ ~~52~~ ~~51~~ ~~50~~ 48 bytes ``` lambda a,b:(b-61<~a<a>b/22*b-3)*~(19<b-(b<30)>a) ``` [Try it online!](https://tio.run/##jZbNbuNGEITvegreLC0khNXzx1l4FwiwewgQ5JiL4wMFW44ARzYcI8Be9tUdqavGlJgEyGWMpjX1Ncmu4jx/e/396WBvu0@/vT2Of2zvxm5cbz8ut5uM6@/j9fh5@4PZh@0mrD58X6JebzfL7XXoV5/H1dvzy/7w2l39NT7u77r7w9393cerBS/ull2/7gyr9xp2WRuOdTirh3V31J3qynpxQdkfuufH8duM053tc25/yYXNuPM@bOLsD046I2xOP0GdtmxQLzW6zekXs3u12b2c/T/0l/caj7@PZ88CvSP7E4MXF7/@@PNPXz7d3PTr/nZ9XOGr@Rp8jb4mX7OvxdfB18pd2szd4HZwPygAKoASoAYoAqoYVeykgjVX8zX4Gn1NvmZfi6@Dr5W7ev6RBreD@0EBUAGUADVAEVDFqOKdmPdg3oN5D@Y9mPdg3oN5D@Y9GHsw9mDswdiDsQdjD8YejD0YezD2YOzB2ENwenB6cHpwenB6cHpweiA9kB5ID6QH0gPpgfRAeiA9kB5ID6RH50bnRudG50bnRudGciO5kdxIbiQ3khvJjeRGciO5kdxIbnJicmJyYnJicmIiMZGYSEwkJhITiYnERGIiMZGYSEwkZmdlZ2VnZWdlsjJZmaxMViYrk5XJymRlsjJZmaxMVnFKcUpxSiGlkFJIKaQUUgophZRCSiGlkFJIKaQMrj@4/kD9gfoD9QfqD9QfqD9Qf6D@QP2B@gP1B@pXV65UrlSuVK5UrlSuVK5UrlSuVK5UrlSuSgDFCpQrULBAyQJFC5QtULhA6QLFC5QvUMCgJUxLiRYTLSdaULSkaFHRsqKFRUuLFhfKC8jykOch00Ouh2wP@R4yPuR8yPqQ9yH3QvaF/AsZGHIwZGHIw5CJIRdDNoR8CBkRciJkRciLkBkhN0JuguwE@QkyFOQoyFKQpyBLQJ6ATAG5ArIF5AtoqqGxhuYaGmxosqGxhOYSGkxoMqGpgsYKmivTHFg/1R7RLe8x1Z7Zptqm2kM8qA5T7akeVcep9phPqtNUe@5n1Xmq/UNQVJep9i/DoHp4r4PfT1VdT/XtYvH1ly9f@WnXF7V9znAe7UpaxZ@SSdEhhzc7Ntu0MW/j2carjUl77e11ttfVXss/Hvv8sc4f2/yxzG6bt3t@nns/Zf15/7rcLY9Hz9Xu6eV0BD2d9PzM005FV5cHzH/d4E/yfcPD0/7w8D8I3X7X3Rwv3HaHp9czmf86Ec6UTjtexsPD/XKTjuevftWdLm@ny6NfnEN4c29/Aw "Python 2 – Try It Online") Takes input as pre-ordered `a,b`. Returns `-2`, `-1`, `0` for `ended`, `in play`, `invalid`. -1 byte, thanks to Kevin Cruijssen --- Left part (`b-61<~a<a>b/22*b-3`) is a validity-check, and right part (`19<b-(b<30)>a`) is a check for game ended. [Answer] # JavaScript (ES6), ~~55 53~~ 48 bytes *Thanks to @KevinCruijssen for noticing that I was not fully assuming \$a\le b\$ (saving 5 bytes)* Takes input as `(a)(b)` with \$a\le b\$. Returns \$0\$ (valid), \$1\$ (ended) or \$2\$ (invalid). ``` a=>b=>a<0|a>29|b>30|b>21&b-a>2?2:b>20&b-a>1|b>29 ``` [Try it online!](https://tio.run/##dZFNDsIgEEb3nmJWFhY1MHRhja1noX8GQ2hjjYlJ714HdKGCCyaZ92WGR7jou57bq5luuRu7fh2qVVd1U9X6KBZdY7k0tRJUUG6bnMAJD9SI0EjPy7Ud3TzafmfHM8t61/VdxjefcGAgOEPJf7HEJCbEUMV4z5kSMS7f@Itnd21NB2y@GWvBOJisfvCkGMQ7g69I@tJJ@v55BkZixgW1WCX3AwCyjHVyghQlLgHKfASpyPvSFCYiDAtVakoJ/qpxVISFRfw3Unj5UPn6BA "JavaScript (Node.js) – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~53~~ 52 bytes ``` a=>b=>b<0|a-b>2&a>21|b>29|a>30?3:a>20&a-b>1|a>29?1:2 ``` Called as `f(max)(min)`. Returns 3 for invalid, 1 for finished, 2 for ongoing. Saved 1 byte thanks to Kevin Cruijjsen [Try it online!](https://tio.run/##dZGxCsIwEIZ3n0IcpAGDuYuDqW2KoGJBuog6t6VCHCrYuvXdYyIotYkhw/H9cPlyVza0bJTePesyUnU7@xb34laVrZTXWOexLMyNWJfTQuI0lwidKUSXS84SHhrApjYDQ1AkEKJejS4P1VYHVVfBZJdm6XG/3YzpGCakH10DBBIw4oGADuXEJgPKmaFLLxWWzn9OX@uU9cRwKMZ8Xj5oRH2y4JNF/ND/Wml2Xh9S68SHTiBIQD1dzVsUhCNmqc/AteXwGddwiNz578KsYeF0APZeGnvb6Rc "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` »19«28‘<‘×+2>ɗʋ⁹×,%Ƒ“œþ‘ɗ ``` [Try it online!](https://tio.run/##y0rNyan8///QbkPLQ6uNLB41zLAB4sPTtY3sTk4/1f2ocefh6TqqxyY@aphzdPLhfUC5k9P///9vaP7fyAgA "Jelly – Try It Online") Left argument: minimum. Right argument: maximum. Invalid: `0`. Ongoing: `1`. Ended: `2`. Mathematically, this works as below (the left argument is \$x\$, the right is \$y\$): $$[a]=\cases{a\colon1\\\lnot a\colon0}\\\otimes(a,b)=(a\bmod30,b\bmod31)\\x,y\in\mathbb Z\\X:=\min(\max(x+1,20),29)\\p:=(x,y)\\([X<y]+1)[X+2>y][p=\otimes p]$$ Explanation: ``` »19«28‘<‘×+2>ɗʋ⁹×,%Ƒ“œþ‘ɗ Left argument: x, Right argument: y »19«28‘ X := Bound x + 1 in [20, 29]: »19 X := max(x, 19). «28 X := min(X, 28). ‘ X := X + 1. <‘×+2>ɗʋ⁹ X := If X + 2 <= y, then 0, else if X < y, then 2, else 1: < t := If X < y, then 1, else 0. ‘ t := t + 1. +2>ɗ u := Check if X + 2 > y: +2 u := X + 2. > u := If u > y, then 1, else 0. × X := t * u. ,%Ƒ“œþ‘ɗ z := If x mod 30 = x and y mod 31 = y, then 1, else 0: , z := (x, y). % “œþ‘ m := z mod (30, 31) = (x mod 30, y mod 31). Ƒ z := If z = m, then 1, else 0. × X * z. ``` [Answer] # [VDM-SL](https://raw.githubusercontent.com/overturetool/documentation/master/documentation/VDM10LangMan/VDM10_lang_man.pdf), 80 bytes ``` f(i,j)==if(j-i>2and j>21)or(i<0or i=30or j>30)then{}else{(j>20and j-i>1or j=30)} ``` This function takes the scores ordered in ascending order and returns the empty set if the score is invalid or the set containing whether the set is complete (so {true} if the set is complete and valid and {false} if the set is incomplete and valid) A full program to run might look like this: ``` functions f:int*int+>set of bool f(i,j)==if(j-i>2and j>21)or(i<0or i=30or j>30)then{}else{(j>20and j-i>1or j=30)} ``` ### Explanation: ``` if(j-i>2 and j>21) /*if scores are too far apart*/ or(i<0 or i=30 or j>30) /*or scores not in a valid range*/ then {} /*return the empty set*/ else{ } /*else return the set containing...*/ (j>20 and j-i>1 or j=30) /*if the set is complete*/ ``` [Answer] # [Java (JDK)](http://jdk.java.net/), ~~59~~ 48 bytes ``` a->b->b<0|b>29|a>b+2&a>21|a>30?0:a<21|a<30&a<b+2 ``` [Try it online!](https://tio.run/##jZhdb@JGFIbv@RVupI2gIchnxp8FU63UjRqpHxeRepPuhUNM4pQABZNtlOW3pwMhH@cZtNkoAh/7YJ/3GXvOO74p78rjm8t/Huvb@WzRBDcu7q2aetIbr6ajpp5Nez/2W/W0qRbjclQFJw@tZVM29Shw@84/n38O/vr42@kvQRE8TKsvTzsfwm647r4NRYdGh1aHkQ5jHSY6THWY6TBHGSwLdQkKE1QmKE1Qm6A4QXWC8gT1GdRnVH3SRWh0aHUY6TDWYaLDVIeZDnOUESJmmShMUJmgNEFtguIE1QnKE9RnUJ/GaDQ3o7kZzc1obkZzM5qb0dyM5mbAzYCbATcDbgbcDLgZcDPgZsDNgJsBNwNuVoOyGpTVoKwGZTUoq0FZDcoClAUoC1AWoCxAWYCyAGUBygKUBSgLUBagIk0m0mQiTSbSZCJNJtJkIpCJQCYCmQhkIpCJQCYCmQhkIpCJQCYCmQhkYo0i1ihijSLWKGKNIgaKGChioIiBIgaKGChioIiBIgaKGChioIiBItHaE6090doTrT2B9gTaE2hPoD2B9gTaE2hPoD2B9gTaE2hPoD3VYlMtNtViU4hNITaF2BRiU4hNITaF2BRiU4hNITaF2BRiM60u0@oyqMugLoO6DOoyqMugLoO6DOoyqMugLoO6DOpyLSeHnBxycsjJISeHnBxycsjJISeHnBxycsjJabHoEYUmUegShTZR6BOFRlHoFIVWUegVhWZR6BbFs4ueMfOcmWfNPG/mmTPPnXn2zPNnnkHzHBotmtALCc2Q0A0J7ZDQDwkNkdARCS2R0BMJTZHQfAjdh9B@CP2H0IAIHYjQggg9iNCECHu9sNkLu72w3Qv7vbDhCzu@sOULG6uwswpbq7C3CpursLsK26uwhwmbmLCLCduYsI8JG5mwWQi7hbBdCPuFsGEI52ThpCyclYXTsnDiE858wqnPcEIx4Z4MvULxllayJ0MvYgwzzJ4Mvc6xzLB7MvRSKGJGtCdDr5ZiZsR7MvSCKmFGsidDr7lSZqR7MvSyLGNG5mdYPXI5M/JNxrrfaj2/tDk5/eP07NdP3nsbvnHwls7y7ZUP/T5NL40gvRLdhdeevR7ndQ5vgvYmRm@G8uYO7zH3HlHvefuOZ@X9@/z9e/T9@@vde2N3K@xe493N6svgtqyn7bNmUU@v3M1RLq6WnYfTaXOyewU4eLv958VNNWqGw2BcPJbHwwv3Pwi/XgxN/rUcXhyZw3JoxG3a8Ofwp3Kw2R7Y8LAcuGOPT7dgMC7ryWpRLYuw3xrPFu3NvsnsS3Ech333PSjc99GR2@o8tAL395xzXV9dF253f7Oxy9ps7tK2qfW0nATb5GJzqP9mz2T725fUJyVB9d/cfVWX3XLUrMrJ6/F6HLRf34d@XCzK@2Vv2Syq8rb9/AB1euX0/veyGV23746Hd@fh56KYHB7enYvbuO50nk9ejMvJsno9d@Wib15g@1r1u8/eLFY8@cuxUCv64flAr/rXyV22n2QX4145n0/u21ueu@3NCHQ6wSvdLeHd4B0d9dX@s/tlU932ZqumN3d3UjNuH3zaXSr4cLkZQzcI81UTtD/Yy27gPjrd4GrWuIN/Tw@6L8OwKaDrrrwbj87rVdatp891a8@13CWaWeNGeldfe9k56L4U686yXj/@Dw "Java (JDK) – Try It Online") Returns an `Object`, which is the `Integer` `0` for invalid games and the `Boolean`s `true` and `false` for valid ongoing games and for valid finished games respectively. Takes the score ordered (and curried), with the higher score first. `-2 bytes` by inverting the end-of-match check. `-11 bytes` by currying, using bitwise operators, and some return type autoboxing trickery - thanks to @KevinCruijssen ## Ungolfed ``` a-> // Curried: Target type IntFunction<IntFunction<Object>> b-> // Target type IntFunction<Object> // Invalid if: b<0 // Any score is negative | b > 29 // Both scores above 29 | a > b + 2 // Lead too big & a > 21 // and leader has at least 21 points | a > 30 // Anyone has 31 points ? 0 // If invalid, return 0 (autoboxed to Integer) // If valid, return whether the game is ongoing (autoboxed to Boolean) // Ongoing if: : a < 21 // Nobody has 21 points | a < 30 // Leader has fewer than 30 points & a < b + 2 // and lead is small ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 35 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Infix tacit function where ended is 2, ongoing is 1, invalid is 0, smaller and larger scores are left. ``` (,≡30 31|,)×(⊢<2+X)×1+⊢>X←29⌊20⌈1+⊣ ``` [Try it online!](https://tio.run/##fY4xTgMxEEV7n2K6BGWR7HEKFiEaGlIhkRRpDXZYS9YSYYMUiQ4pglWIoEDUwAFyh@QmvsgyG2/oQuP/58vz36ipO9Qz5W5v6rqbxZcvyUGKx@xg89mN1fcJ9sZkRY/86TjO3zCPiwp5XDw32U89oSy@LuPyY3ARq6f1Ssb5O03DyzN6R@eDYd0ZFcYbCMYHuFbeeFB3Bh6UszoDVWoIhQFvAhTKgym10ccdxmECKJjApCgalQyPSCVnmCf9t/vqPvx1Ww8@WOfAljB1atYieALxBBLYgnZA3AOw5RZBJevV9qfIyYk87ZJrovZ4bI8VTPJ0dL/J@5IJnnZJfgE "APL (Dyalog Unicode) – Try It Online") Implements [Erik the Outgolfer's mathematical formulas](https://codegolf.stackexchange.com/a/182258/43319) combined into $$X:=\min(\max(x+1,20),29)\\\ ([X< y]+1)[X+2>y][(x,y)=(x\bmod30,y\bmod31)]$$ rearranged (as if traditional mathematical notation had vectorisation and inline assignments) to $$[(x,y)=(x,y)\bmod(30,31)]×[y<2+X]×(1+[y< (X:=\min(29,\max(20,1+x)))])$$ and translated directly to APL (which is strictly right-associative, so we avoid some parentheses): $$((x,y)≡30\ 31​|​x,y)×(y<2+X)×1+y>X←29​⌊​20​⌈​1 +x$$ This can be converted into a tacit function simply by substituting \$⊣\$ for \$x\$ and \$⊢\$ for \$y\$, symbolising the left and right arguments rather than the two variables: $$((⊣​,⊢)≡30\ 31​|⊣​,⊢)×(⊣​<2+X)×1​+⊢​>X←29​⌊​20​⌈​1​+⊣$$ Now \$⊣⎕⊢\$ is equivalent to \$⎕\$ for any infix function \$⎕\$, so we can simplify to $$(,​≡30\ 31​|​,)×(⊣​<2+X)×1​+⊢​>X←29​⌊​20​⌈​1​+⊣$$ which is our solution; `(,≡30 31|,)×(⊢<2+X)×1+⊢>X←29⌊20⌈1+⊣`: `⊣` the left argument; \$x\$ `1+` one plus that; \$1+x\$ `20⌈` maximum of 20 and that; \$\max(20,…)\$ `29⌊` minimum of 29 and that; \$\min(29,…)\$ `X←` assign that to `X`; \$X:=…\$ `⊢>` is the right argument greater (0/1)?; \$[y>…]\$ `1+` add one; \$1+…\$ `(`…`)×` multiply the following by that; \$(…)×…\$  `2+X` two plus `X`; \$2+X\$  `⊢<` is the right argument less than that (0/1); \$[y<…]\$ `(`…`)×` multiply the following by that; \$(…)×…\$  `,` concatenate the arguments; \$(x,y)\$  `30 31|` remainders when divided by these numbers; \$…\mod(30,31)\$  `,≡` are the concatenated arguments identical to that (0/1)?; \$[(x,y)=…]\$ [Answer] # x86 Assembly, 42 Bytes Takes input in `ECX` and `EDX` registers. Note that `ECX` must be greater than `EDX`. Outputs into `EAX`, where `0` means the game's still on, `1` representing the game being over and `-1` (aka `FFFFFFFF`) representing an invalid score. ``` 31 C0 83 F9 1E 77 1F 83 FA 1D 77 1A 83 F9 15 7C 18 83 F9 1E 74 12 89 CB 29 D3 83 FB 02 74 09 7C 08 83 F9 15 74 02 48 C3 40 C3 ``` Or, more readable in Intel Syntax: ``` check: XOR EAX, EAX CMP ECX, 30 ; check i_1 against 30 JA .invalid ; if >, invalid. CMP EDX, 29 ; check i_2 against 29 JA .invalid ; if >, invalid. CMP ECX, 21 ; check i_1 against 21 JL .runi ; if <, running. CMP ECX, 30 ; check i_1 against 30 JE .over ; if ==, over. MOV EBX, ECX SUB EBX, EDX ; EBX = i_1 - i_2 CMP EBX, 2 ; check EBX against 2 JE .over ; if ==, over. JL .runi ; if <, running. ; if >, keep executing! CMP ECX, 21 ; check i_1 against 21 JE .over ; if ==, over. ; otherwise, it's invalid. ; fallthrough! .invalid: DEC EAX ; EAX = -1 RETN .over: INC EAX ; EAX = 1 ; fallthrough! .runi: RETN ; EAX = 0 or 1 ``` Fun fact: this function *almost* follows the C Calling Convention's rules on which registers to preserve, except I had to clobber `EBX` to save some bytes on stack usage. --- ### Optional (not included in byte-count) By adding the following 6 bytes directly before start of the code above, you can pass `ECX` and `EDX` unordered: ``` 39 D1 7D 02 87 CA ``` Which is the following in readable Intel Syntax: ``` CMP ECX, EDX JGE check XCHG ECX, EDX ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 92 bytes ``` \d+ $* ^(1{0,19},1{21}|(1{20,28}),11\2|1{29},1{30})$|^(1*,1{0,20}|(1{0,28}),1?\4)$|.+ $#1$#3 ``` [Try it online!](https://tio.run/##NYyxDsJADEP3/EaL1EKKYl@H3sTIT1QIJBhYGBBb228/kkMMceT4Oe/H5/m6lV13vpb5fpB2L5cOiynypliIbXVLU05br8DM1W3Nkm19uzq91yjQKvonT/Po6dE/NmibVIoHEDCUUCbhpMmEOdQ0hhYAWIEfRhl8IcuAHLfBTf3C2oQki/5IHZPAgnX5Ag "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input in ascending order. Explanation: The first stage simply converts from decimal to unary so that the scores can be properly compared. The second stage contains six alternate patterns, grouped into three groups so that three distinct values can be output, which are `10` for win, `01` for ongoing and `00` for illegal. The patterns are: * Against 0-19, a score of 21 is a win * Against 20-28, a score of +2 is a win * Against 29, a score of 30 is a win * Against any (lower) score, a score of 0-20 is ongoing * Against a score of up to 28, a score of +1 is ongoing * Anything else (including negative scores) is illegal [Answer] # [Stax](https://github.com/tomtheisen/stax), 20 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ÇåπßéD╩¬7▼ß▌ΣU¬í╡S┤╘ ``` [Run and debug it](https://staxlang.xyz/#p=8086e3e18244caaa371fe1dde455aaa1b553b4d4&i=0+21%0A12+21%0A21+23%0A28+30%0A29+30%0A0+0%0A0+20%0A12+12%0A21+21%0A21+22%0A-21+19%0A-19+21%0A-1+1%0A12+22%0A29+31%0A30+30%0A42+43%0A1021+1021%0A&a=1&m=2) It takes input in the same format as the examples. `0` means there's a valid winner. `1` means the game is in progress. `-1` means invalid score. In pseudo-code, with ordered inputs `x` and `y`, the algorithm is ``` sign(clamp(x + 2, 21, 30) - y) | (x < 0 || x >= 30 ? 0 : -1) ``` * `sign` means numeric sign (`-1`, `0`, or `1`) * `clamp` forces its first argument into the specified half-open interval [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~33~~ 32 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") ``` {h⍵+1 0}+h←(⊢≡31 30|⊢)×21 2∨.≥-\ ``` [Try it online!](https://tio.run/##fY@/SkMxGMX3PsXZqtRK/nTwurrYSbAdXaI3NYFwW0wUijoJxRZadBBnBcGtky9Q3yQvcv1yU5zE5ZyTL8n58amJ65ZT5caXdVy92HGcPbH61sTlV4eD3XcMDXbi4j3O3ySHZHeUd79fBYeIj5/7cf7RPatH9CguV1TQP4mLh81axtkznQanR6TD4/6gbg@N9hpB@4AL5bWHutK4Uc6We1BViWA0vA4wykNXpS4P260RiMOycZFcUiSXDOJg60Xr3@7z6/DbbT18sM7BVpg4NW0QDBnBGuNiS@KZJETyvwm2ahhNCy8AbNb5D28yL9IcOecq5HKZpqLIC4CEUk9S6qVbztK6JD8 "APL (Dyalog Unicode) – Try It Online") in: a pair in descending order out: 2=ongoing, 1=ended, 0=invalid tests stolen from [Adám's answer](https://codegolf.stackexchange.com/questions/182245/valid-badminton-score/182370#182370) [Answer] # [Bash](https://www.gnu.org/software/bash/) 4+, ~~97~~ ~~89~~ ~~91~~ 88 bytes Assume that inputs are ascending. Used concepts from [VDM-SL](https://codegolf.stackexchange.com/a/182261/15940) answer. [Try it Online](https://tio.run/##VY4/b4NADMX3fAoLnRAMSLbJ0IsCHTJEmbtmoeSigAJEDcpAyGenvj@p1OWefX7@@X1X98tyTtInmPoyQNYbiBQdR8XHMVqaQhG0hWKYClwlSZs1JcdtyTQ3W5yl0XNb5vg5FbzBNBXLtKU4EQfG1kwyZp3KnNzcHVHT8vJVtBu629WM5gT7qjP3TbQ6AwKTCHFQ7ZUJOLf6ATla1VY95tDXAfSPg56GnkYcKG@a6zmoXNF/tEd1bU7wVQ8/gZWJn7Qt3nEy@Qgpw35O7pwLt2ZY27CEdlGe5Rc) `z==0` - game in progress `z==1` - game completed `z==2` - invalid ***-8** by bracket cleanup from `(( & | ))` conditions* ***+2** fixing a bug, thanks to Kevin Cruijssen* ***-3** logic improvements by Kevin Cruijssen* ``` i=$1 j=$2 z=0 ((j-i>2&j>21|i<0|i>29|j>30?z=2:0)) ((z<1&(j>20&j-i>1|j>29)?z=1:0)) echo $z ``` ]
[Question] [ In set theory, the natural numbers \$\mathbb{N} = \{0, 1, 2, 3, ...\}\$ are usually encoded as [pure sets](https://en.wikipedia.org/wiki/Hereditary_set), that is sets which only contain the empty set or other sets that are pure. However, not all pure sets represent natural numbers. This challenge is about deciding whether a given pure set represents an encoding of natural number or not. The encoding of natural numbers works in the following way1: * Zero is the empty set: \$ \text{Set}(0) = \{\} \$ * For a number \$n > 0\$: \$ \text{Set}(n) = \text{Set}(n-1) \cup \{\text{Set}(n-1)\}\$ Thus, the encodings of the first few natural numbers are * \$ 0 \leadsto \{\}\$ * \$ 1 \leadsto \{0\} \leadsto \{\{\}\}\$ * \$ 2 \leadsto \{0,1\} \leadsto \{\{\},\{\{\}\}\}\$ * \$ 3 \leadsto \{0,1,2\} \leadsto \{\{\},\{\{\}\},\{\{\},\{\{\}\}\}\}\$ * \$ 4 \leadsto \{0,1,2,3\} \leadsto \{\{\},\{\{\}\},\{\{\},\{\{\}\}\},\{\{\},\{\{\}\},\{\{\},\{\{\}\}\}\}\}\$ ## The Task * Given a string representing a pure set, determine whether this set encodes a natural number according to the above construction. * Note, however, that the elements of a set are not ordered, so \$\{\{\},\{\{\}\},\{\{\},\{\{\}\}\}\}\$ is not the only valid representation of \$3\$ as e.g. \$\{\{\{\}\},\{\},\{\{\{\}\},\{\}\}\}\$ represents the same set. * You may use `[]`, `()` or `<>` instead of `{}`. * You may assume the sets are given without the `,` as separator. * You can assume there won't be any duplicate elements in the input, e.g. `{{},{}}` is not a valid input, and that the input is well-formed, e.g. no `{{},`, `{,{}}` or similar. ## Test Cases True: ``` {} {{}} {{},{{}}} {{{}},{}} {{},{{}},{{},{{}}}} {{{},{{}}},{},{{}}} {{{{}},{}},{{}},{}} {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}} {{{{{}},{}},{{}},{}},{{}},{},{{},{{}}}} {{},{{}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}},{{{}},{}},{{},{{}},{{},{{}}}}} {{{{{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}} ``` False: ``` {{{}}} {{{{}}}} {{{{}},{}}} {{},{{}},{{{}}}} {{{},{{}}},{{}}} {{{{{}}},{}},{{}},{}} {{},{{}},{{},{{}}},{{},{{}},{{{}}}}} {{{{{}},{}},{{{}}},{}},{{}},{},{{},{{}}}} {{{{{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{{}},{}},{{}},{}},{{{}},{}},{{}}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}} ``` --- Related: [Natural Construction](https://codegolf.stackexchange.com/q/95035/56433) (Output the set encoding of a given natural number.) 1 See <https://en.wikipedia.org/wiki/Set-theoretic_definition_of_natural_numbers> [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~53~~ ~~48~~ 44 bytes ``` f=a=>(a=eval(a)).every(e=>a[e.length]&&f(e)) ``` [Try it online!](https://tio.run/##7VO9DoIwGNx5EGiTyhuUxEEnJ3@mytBgQQ1pDRASn76WiEZqaUt0cHBr7r7eXb7cd6YtrbPqdGlmXByYlDmmOAEUs5aWgEIYs5ZVV8BwQgmLS8aL5piGYQ4YhDITvBalgkUBIrJd7xZpBIPgFc4VoUD4BpJ0BEYdZeYUgez/0FNgTOHOIrtPb4QmOSJDiDF93eDxcOXXDBzmaGDknc0YzwT5jn1b7mfjdRsdrDTac7KcrzbmwyC2pvaSjh74VJ1Ye/hh0z1rrhs5D/VfQ21uQgflDQ "JavaScript (Node.js) – Try It Online") Test cases mostly shamelessly stolen from @Arnauld's answer. Explanation: If a set represents a natural number, then the natural number it represents must be equal to the size of the set, and (given that the elements are guaranteed distinct) the elements must be the representations of the natural numbers less than it, and these must therefore have shorter lengths. This is trivially true of the empty set of course. Edit: Saved 5 bytes thanks to @Arnauld. Saved 4 bytes thanks to @Cowsquack. [Answer] # [Python 3](https://docs.python.org/3/), ~~69~~ ~~58~~ 44 bytes 11 bytes thanks to Erik the Outgolfer. 14 bytes thanks to Mr. Xcoder. ``` f=lambda s:all(len(e)<len(s)*f(e)for e in s) ``` [Try it online!](https://tio.run/##7VSxDsIgFNz5CkYwbG5N@yXIgAqxCdKmj8Wvx2JpI4haEwcHF7g83t0jeZfrL@7U2a33ujHyvD9KDJU0hhhliaJ1uIBu9Ih1N2CFW4uBeqfAHSQoaPgOccEQ52I6WUA3GCpJlS3P8T32JqSZ9YrOCoqR/UCPIJud0d9JJ7rPJheHl0pr274t97vfm9ySGCBdU8E0/H7nn3mmbJhcJrfrf8NZ31otgVDIDgjZsQRH1Q@tdUSP6UL9FQ "Python 3 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~60~~ 59 bytes ``` E!=(If[Sort@#===Range[t=Tr[1^#]]-1,t,E]&//@ToExpression@#)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d9V0VbDMy06OL@oxEHZ1tY2KDEvPTW6xDakKNowTjk2VtdQp0THNVZNX98hJN@1oqAotbg4Mz/PQVlT7b@CvoNCtYJSda2SDpCsrtUB4looB8jSqUZwIFJoCmqVFGpj/wMA "Wolfram Language (Mathematica) – Try It Online") The core of this solution is the function ``` If[Sort@#===Range[t=Tr[1^#]]-1,t,E]& ``` which converts a list of the form `{0,1,2,...,n-1}` in any order into the output `n` (in particular, it converts `{}` to `0`), and converts anything else into the real number `E`. Call this function `f`. Given an input such as `"{{{}},{}}"`, we do the following: 1. Convert the string into a Mathematica expression. 2. Apply `f` at every level, getting `f[{f[{f[{}]}], f[{}]}]`. 3. Evaluating all the `f`'s will produce a natural number for an input representing it. For example, `f[{f[{f[{}]}], f[{}]}]` = `f[{f[{0}], 0}]` = `f[{1, 0}]` = `2`. Anything else will produce `E`. 4. We test if the result is a natural number by checking if it's not `E`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (v2), 9 bytes ``` ↰ᵐo.t~k|Ė ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HbhodbJ@TrldRl1xyZ9v9/dHR0bKwOkABhECs2FgA "Brachylog – Try It Online") As usual for a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'"), this is a full program. Input from standard input, using square brackets. Output to standard output as `true.` versus `false.`. ## Explanation Although I said above that this is a full program, it's actually more interesting than that; it's *both* a full program and a function. When used as a full program, it prints `true.` if the set is a natural number, or `false.` if it isn't. When used as a function, it "normalizes" a natural number (i.e. normalizes all its elements and sorts them into order by value; this program uses lists internally, not sets), or "throws an exception" (actually a failure, as this is Prolog) if the input isn't a natural number. The full program behaviour is easy enough to explain: it's purely implicit in Brachylog's treatment of full programs that don't contain I/O instructions. The behaviour in question is "run the function, taking its input from standard input, and asserting that its output matches the description given by the first command-line argument; if the assertion fails or the program throws an exception, print `false.`, otherwise print `true.`". In this case, the command-line argument is missing (i.e. "anything goes"), so the exception/no-exception behaviour of the function gives the output. As for the function behaviour: ``` ↰ᵐo.t~k|Ė ↰ᵐ Map a recursive call to this function over the list o Sort the list . | Assert that the following operation need not change the list: t Take the last (i.e. greatest) element of the list ~k Append an arbitrary element to the resulting list . | Output the unchanged list | Exception handler: if the above threw an exception, Ė Assert that the input is empty, and output an empty list ``` A natural number is defined as containing two parts: the elements of the natural number below, unioned with the number itself. Thus, all its elements are also natural numbers. We can recognise a natural number by a) verifying that all its elements are natural numbers, b) verifying that the set's largest element is identical to the set without its largest element. When we're using lists rather than sets (thus the square brackets), we need to put them into a consistent order for equality comparisons to work (in this case, sorted by "value"). Brachylog's default sort order will sort a prefix of a list before the list itself, which conveniently means that it'll sort natural numbers by numerical value. So we can just recursively sort all our numbers to get them into a consistent order. In fact, via the function we're defining recursively, we can achieve both results at the same time: recursively sorting the number's elements, and verifying that it's a natural number. The function thus has four main parts. `↰ᵐ` is the recursive call, ensuring that each element is a natural number, and converting it each element to a normalized form. `o` the normalizes the number itself (its elements are already normalized, so all we have to do is to sort it). Then `.t~k|` ensures we have the structure we want by checking that the largest element and other elements are the same. An empty list (i.e. 0) doesn't have a last element, so will get an assertion failure with `t`; the `|Ė` handles this case, via giving an explicit fallback in the case where the input list is empty. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ߀Ṣ ÇṖƤƑ ``` Since the input has to be a string, this submission is only valid as a full program. [Try it online!](https://tio.run/##y0rNyan8///w/EdNax7uXMR1uP3hzmnHlhyb@P///2goiI3VAWMEA5sQscqobdygdR4A "Jelly – Try It Online") or [verify all test cases](https://tio.run/##y0rNyan8///w/EdNax7uXMR1uP3hzmnHlhyb@P9wO1AIiBTc///X0OBSUIiO1QGR0bEwWgfEhnJAomgyOnAlcDVQHWhaYXrxG6KDxVy4CRhGQBkYbkAzgpDxKCbjth2rA7AJEauM2sYNXudxaepowFIQWoJAjzKsSSkaNRWQmpJwJSN0ozAT82iso6kjIco1AQ "Jelly – Try It Online") ### How it works ``` ߀Ṣ Helper link. Argument: A (array) ߀ Recursively map the helper link over A. Ṣ Sort the result. ``` This yields a canonical representation of the input, consisting solely of sorted arrays. ``` ÇṖƤƑ Main link. Argument: A (array) Ç Call the helper link to canonicalize the array. Ƒ Fixed; call the link to the left and test if it returns its argument unchanged. ṖƤ Pop prefix; for each non-empty prefix of the result, remove its last element. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` Ẉ<La߀Ạ ``` This is a port of [Leaky Nun's Python answer](https://codegolf.stackexchange.com/a/177874/12012). Since the input has to be a string, this submission is only valid as a full program. [Try it online!](https://tio.run/##y0rNyan8///hrg4bn8TD8x81rXm4a8H///@joSA2VgeMEQxsQsQqo7Zxg9Z5AA "Jelly – Try It Online") or [verify all test cases](https://tio.run/##y0rNyan8///hrg4bn8TD8x81rXm4a8H/w@1ABhApuP//r6HBpaAQHasDIqNjYbQOiA3lgETRZHTgSuBqoDrQtML04jdEB4u5cBMwjIAyMNyAZgQh41FMxm07VgdgEyJWGbWNG7zO49LU0YClILQEgR5lWJNSNGoqIDUl4UpG6EZhJubRWEdTR0KUawIA "Jelly – Try It Online") ### How it works ``` Ẉ<La߀Ạ Main link. Argument: A (array) Ẉ Width; compute the length of A's elements. L Yield the length of A. < Compare them, yielding an array of Booleans. ߀ Recursively map the main link over A. a Take the logical AND of the Booleans and the results of the map. Ạ All; yield 1 if and only if all ANDs yielded 1. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~36~~ 40 bytes ``` (Sort//@#//.{a__,{a__}}:>{a})!={}!={{}}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyM4v6hEX99BWV9frzoxPl4HRNTWWtlVJ9ZqKtpW1wJxdW2t2v/A0szUEoeAosy8kmhlXbs0B@VYtbrg5MS8umqu6lodLpAqMKkDYoGZIBEUUR24NFQeqhZFE0wXPu06WEyE6sbQDmWg2Y2mnZDRKObishmr5diEiFVGbeMGr/O4IMkFngJQ0wJqjGFJP9XI0U9a8sGedtCNQU@5o5GNpo5Ys7hq/wMA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~26~~ ~~24~~ 27 bytes ``` {{o'!x}[#x]~{x@<x:o'x}x}`j? ``` [Try it online!](https://ngn.bitbucket.io/k#eJy1lMsKgzAURPf5CmsLtpBFu00K7X+EgN0IfYCgLiIhfnu1akx84CO3rkQuJ+Nk7kREyjjYCcX2ghdS3K+CxIFQQoWvG0IZkQeWFwmJPEHD+E2PYfR4fqigOU1OXKGM+Yz7HuRDL/yHZRwU3GFxhYZia2zJxHCSe2qxlu12gKG2xmEQOzps4wIGsWPSBDziy/KjDLV9ue3LFr+n1M7IxpaK4V9V2JTUakcFj32aGfNRiomvhwGgNdEcdqXWxP6wC7Qh2vksryzdls4lAYPrmQp77m0ZDFtjdfjce8ZSa6QfEtv2F0jZDE0Y2dmVPTNQ2wXWsWwqLHAn2MsBAW0qAbATjJJZ0QnriP8phPK+viWXHTQ=) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ẈṢ‘⁼Jȧ@ßƇƑ ``` [Try it online!](https://tio.run/##y0rNyan8///hro6HOxc9apjxqHGP14nlDofnH2s/NvH////RUBAbqwPGCAY2IWKVUdu4Qes8AA "Jelly – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 bytes Port of [Neil's JS solution](https://codegolf.stackexchange.com/a/177882/58974). Please upvote that if you're upvoting this. ``` e@Ê>XÊ©ßX ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=ZUDKPljKqd9Y&input=W10=) or [run all test cases](https://tio.run/##y0osKPn/P9XhcJddxOGuQysPz4/4/z@aiyskKNSVKzqWKzo6FkzogBggFpDSQRbTgUtCZCFsHWQdUC06ePTqYDEOohddM4yBai@aZgIG66AYi8NerFZjEyJWGbWNG7TO4@Jyc/QJdoUkFuQUgBJTmEkmGinOSUoxWJMLuiFoCXU0gtHUER@7sVy6uUEA) ``` :Implicit input of array U e :Does every element in U return true @ :When passed through the following function as X Ê :Length of U > :Greater than XÊ :Length of X © :Logical AND with ßX :A recursive call of the programme with X passed as the new value of U ``` [Answer] # [Red](http://www.red-lang.org), 81 bytes ``` func[a][p: 1 foreach e to-block a[p: p *(pick[1 0](length? e)< length? a)* f e]p] ``` [Try it online!](https://tio.run/##3ZJBCoMwEEX3nmJwpUKhbqXQO3Q7zCKNkyqKBrHnT7Ui1TQaSheFrpL5mbwJ@b/j3Fw4RwpUZtS9kSgIdQYpqLZjIQtg6NvDtW5lBWI80ZBEupQVpnCkqObm1hdn4PgE817ECShg0mR0Vzb9UIRIYfAqkKxyVNbSIDi75ma7@yk6QRPJC7T5NmWFmRb3W5aYTfiCtz/1bbBd@o6/vf678fNXhHYwnAY7TdhOCjod/iwpuzlZ0TZS@8f2es01Dw "Red – Try It Online") Similar to Leaky Nun's Python 3 answer [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes ``` If[Max[#0/@#]<(l=2Length@#),l]&@*ToExpression/*EvenQ ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfMy3aN7EiWtlA30E51kYjx9bIJzUvvSTDQVlTJydWzUErJN@1oqAotbg4Mz9PX8u1LDUv8H9AUWZeSbSygq6dQlq0cmysgpqCvoNCcAlQOD24ICezJFqpuparuroWTOiAGCAWkNJBFtOBS0JkIWwdZB1QLTp49OpgMQ6iF10zjIFqL5pmAgbroBiLw16sVmMTIlYZtY0btM6DpBJY1KOkAZS4wkw01UixTlKawZpg0A1BS6qjUYymjlizlGL/AwA "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ The gambler's fallacy is a cognitive bias where we mistakenly expect things that have occurred often to be less likely to occur in the future and things that have not occurred in a while to be more likely to happen soon. Your task is to implement a specific version of this. ## Challenge Explanation Write a function that returns a random integer between 1 and 6, inclusive. The catch: the first time the function is run, the outcome should be uniform (within 1%), however, each subsequent call will be skewed in favor of values that have been rolled fewer times previously. The specific details are as follows: * The die remembers counts of numbers generated so far. * Each outcome is weighted with the following formula: \$count\_{max} - count\_{die} + 1\$ + For instance, if the roll counts so far are \$[1, 0, 3, 2, 1, 0]\$, the weights will be \$[3, 4, 1, 2, 3, 4]\$, that is to say that you will be 4 times more likely to roll a \$2\$ than a \$3\$. + Note that the formula means that a roll outcome of \$[a, b, c, d, e, f]\$ is weighted the same as \$[a + n, b + n, c + n, d + n, e + n, f + n]\$ ## Rules and Assumptions * Standard I/O rules and banned loopholes apply * Die rolls should not be deterministic. (i.e. use a PRNG seeded from a volatile source, as is typically available as a builtin.) * Your random source must have a period of at least 65535 or be true randomness. * Distributions must be within 1% for weights up to 255 + 16-bit RNGs are good enough to meet both the above requirements. Most built-in RNGs are sufficient. * You may pass in the current distribution as long as that distribution is either mutated by the call or the post-roll distribution is returned alongside the die roll. Updating the distribution/counts *is a part of this challenge*. * You may use weights instead of counts. When doing so, whenever a weight drops to 0, all weights should increase by 1 to achieve the same effect as storing counts. + You may use these weights as repetitions of elements in an array. Good luck. May the bytes be ever in your favor. [Answer] # [R](https://www.r-project.org/), 59 bytes ``` function(){T[o]<<-T[o<-sample(6,1,,max(T)-T+1)]+1 o} T=!1:6 ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T0OzOiQ6P9bGRhdI2egWJ@YW5KRqmOkY6ujkJlZohGjqhmgbasZqG3Ll13KF2CoaWpn9L0otyMlMTixJ1TA0MNBJ09DU/A8A "R – Try It Online") Keeps the counts in `T`, which is then transformed to be used as the `weights` argument to `sample` (which then most likely normalizes them to sum to `1`). The `[<<-` operator is used to assign a value to `T` in one of the parent environments (in this case, the only parent environment is `.GlobalEnv`). [Answer] # [Python 3](https://docs.python.org/3/), ~~112~~ 99 bytes ``` from random import* def f(C=[0]*6):c=choices(range(6),[1-a+max(C)for a in C])[0];C[c]+=1;print(c+1) ``` [Try it online!](https://tio.run/##DcsxDsMgDEDRvadgxKGVgiJlaMTEMRADcqBhACOHoT09ZfrL@@3XL6rbGImpCA71nMmlEfflccYkkrTGrX7Z4Y0GL8oYbzndJ8odnk6/girhKy0kYhFErsJ6mMNhHXpl9NE41y5RaRjjDw "Python 3 – Try It Online") **Explanation** ``` # we only need the "choice" function from random import* # C, the array that holds previous choices, is created once when the function is defined # and is persisted afterwards unless the function is called with a replacement (i.e. f(C=[0,1,2,3,4,5]) instead of f() ) C=[0]*6 # named function def f(.......): # generate weights [1-a+max(C)for a in C] # take the first item generated using built-in method c=choices(range(6),......................)[0] # increment the counter for this choice C[c]+=1 # since the array is 0-indexed, increase the number by 1 for printing print(c+1) ``` Edit: Saved 13 bytes. Thanks, [attinat](https://codegolf.stackexchange.com/users/81203/attinat)! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` Z>αāDrÅΓΩ=Q+= ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/yu7cxiONLkWHW89NPrfSNlDb9v//aEMdAx1jHSMdIB0LAA "05AB1E – Try It Online") Takes the list of counts as input. Outputs the roll and the new counts. Explanation: ``` Z # maximum > # plus 1 α # absolute difference (vectorizes) # the stack now has the list of weights ā # range(1, length(top of stack)), in this case [1..6] D # duplicate r # reverse the entire stack ÅΓ # run-length decode, using the weights as the run lengths Ω # pick a random element # the stack is now: counts, [1..6], random roll = # output the roll without popping Q # test for equality, vectorizing + # add to the counts = # output the new counts ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 32 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") -4 bytes using replicate instead of interval index. ``` {1∘+@(⎕←(?∘≢⌷⊢)(1+⍵-⍨⌈/⍵)/⍳6)⊢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9rwUccMbQeNR31TH7VN0LAH8h51LnrUs/1R1yJNDUPtR71bdR/1rnjU06EPZGoCic1mmkA5IKf2fxpQy6PePqBeT/9HXc2H1hs/apsI5AUHOQPJEA/PYKCS3sWGBgZAHWaPercYcCH4BjqmQBEgG0UMaBdUGAA "APL (Dyalog Unicode) – Try It Online") Defined as a function that takes the current distribution as an argument, prints the resulting die roll, and returns the updated distribution. First run on TIO is 100 invocations starting with `[0,0,0,0,0,0]`, second run is heavily biased towards 1 with `[0,100,100,100,100,100]`, and the last run is heavily biased towards 6 in the same manner. [Answer] # JavaScript (ES8), 111 bytes ``` _=>++C[C.map((v,i)=>s+=''.padEnd(Math.max(...C)-v+1,i),s=''),n=s[Math.random()*s.length|0]]&&++n;[,...C]=1e6+'' ``` [Try it online!](https://tio.run/##PY4xb8QgDIX3/gpLlQ6oCYKlQ1OyRDd26ZqiCl3I3VU5iAKKTmr721MnQ8Vg3vf8bH/5xefTfJ1KFVMf1sGun7ZBbLtW3fzE@SKvwjYZLWNq8v0x9vzNlwuZd66UakW1oKEemalDyGhzt/uzj326cfGU1RjiuVx@tHOHA2KsO7kFnTXhGRlbhzTzXHwBC52W/89JmAmZmsorGK01/RAFfD8AzCGTN3BRk9jC3UYqMA5xQ6cUcxqDGtOZs/c0jvDIAGkSAoOqamBXFCH9Ufb1@WWH@yVEBaPZv@sf "JavaScript (Node.js) – Try It Online") ### How? This is a rather naive and most probably suboptimal implementation that performs the simulation as described. We keep track of the counts in \$C\$. At each roll, we build a string \$s\$ consisting of each die \$i\$ repeated \$max(C)-C\_i+1\$ times and pick a random entry in there with a uniform distribution. [Answer] # [Perl 6](http://perl6.org/), 31 bytes ``` {--.{$/=.pick}||++«.{1..6};$/} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WldXr1pF31avIDM5u7amRlv70Gq9akM9PbNaaxX9WpA6lZTM4hIFWwWnxHSPxOIMDZCkprVCcWKlQpoGWFJTR0HdWkFdB6o0Lb9IIc7IwPo/AA "Perl 6 – Try It Online") Accepts the current weight distribution as a BagHash, starting with one where all weights are 1. The distribution is mutated in-place. The BagHash `pick` method selects a key at random using the associated weights; the weight of that key is then decremented by one. If that weight is thereby made zero, `++«.{1..6}` increments the weights of all numbers 1-6. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 91 bytes ``` w=1~Table~6 F:=Module[{g},g=RandomChoice[w->Range@6];w[[g]]++;w=Array[Max@w-w[[#]]+1&,6];g] ``` [Try it online!](https://tio.run/##VY49C8IwEIb3/opSwaUpNEsHS6QidCuIuB0Zoj3SQD@gRk4p7V@Pqbp43HDv8z7Ddco22Clrbso5Eny5qGuLSxaUO1EN9aNFmPTMtDirvh66YzOYGwIle581FpnMCUBLGcc5icM4qhdU6llQ4vHGY75l3tHSnUbTW4hqg@E6hEY39h7J4FescOIs/NvZ95@H4GuVbPUiRpLxNJX@Dpx7Aw "Wolfram Language (Mathematica) – Try It Online") [Answer] ## Javascript (ES6+), 97 bytes ``` d=[1,2,3,4,5,6] w=[...d] r=x=>(i=~~(Math.random()*w.length),k=w[i],w.concat(d.filter(x=>x!=k)),k) ``` ### Explanation ``` d=[1,2,3,4,5,6] // basic die w=[...d] // weighted die r=x=>( // x is meaningless, just saves 1 byte vs () i=~~(Math.random()*w.length), // pick a random face of w k=w[i], // get the value of that face w.concat(d.filter(x=>x!=k)), // add the faces of the basic die that aren't the value // we just picked to the weighted die k // return the value we picked ) ``` Note this will eventually blow up if `w` exceeds a length of 232-1, which is the max array length in js, but you'll probably hit a memory limit before then, considering a 32-bit int array 232-1 long is 16GiB, and some (most?) browsers won't let you use more than 4GiB. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 49 bytes ``` {($!=roll (1..6 X=>1+max 0,|.{*})∖$_:),$_⊎$!} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkNF0bYoPydHQcNQT89MIcLWzlA7N7FCwUCnRq9aq1bzUcc0lXgrTR2V@EddfSqKtf@tuYB6VVIUbBWSEtM1NK250vKLFOKMDBSquThBMkXWXJwaKkU6QDWaQEVpGkAaKFScCJLTUVCKKVECyVlz1f4HAA "Perl 6 – Try It Online") Takes the previous rolls as a Bag (multiset). Returns the new roll and the new distribution. ### Explanation ``` { } # Anon block taking # distribution in $_ max 0,|.{*} # Maximum count 1+ # plus one 1..6 X=> # Pair with numbers 1-6 ( )∖$_ # Baggy subtract previous counts roll : # Pick random element from Bag ($!= ) # Store in $! and return ,$_⊎$! # Return dist with new roll ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~22~~ 20 bytes ``` Xt hOs.e*]kh-eSQbQQ1 ``` [Try it online!](https://tio.run/##K6gsyfj/P6KEK8O/WC9VKzY7Qzc1ODApMNDw//9oQx0DHWMdIx0gHQsA "Pyth – Try It Online") Input is the previous frequencies as a list, outputs the next roll and the updated frequencies separated by a newline. ``` Xt¶hOs.e*]kh-eSQbQQ1 Implicit: Q=eval(input()) Newline replaced with ¶ .e Q Map elements of Q, as b with index k, using: eSQ Max element of Q (end of sorted Q) - b Subtract b from the above h Increment *]k Repeat k the above number of times Result of the above is nested weighted list e.g. [1,0,3,2,1,0] -> [[0, 0, 0], [1, 1, 1, 1], [2], [3, 3], [4, 4, 4], [5, 5, 5, 5]] s Flatten O Choose random element h Increment ¶ Output with newline t Decrement X Q1 In Q, add 1 to the element with the above index Implicit print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ’ạṀJx$X,Ṭ+¥¥ ``` [Try it online!](https://tio.run/##ATEAzv9qZWxsef//4oCZ4bqh4bmASngkWCzhuawrwqXCpf8weDbDh@G5hOG5qsaKMTAwwqH/ "Jelly – Try It Online") A monadic link which takes a single argument, the current count list, and returns a list of the number chosen and the updated count list. # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` 0x6+ɼṀ_®‘Jx$XṬ+ɼṛƊ ``` [Try it online!](https://tio.run/##y0rNyan8/9@gwkz75J6HOxviD6171DDDq0Il4uHONWCh2ce6/h9a9HBni4qhgcGhhf8B "Jelly – Try It Online") As an alternative, here’s a niladic link which returns the number chosen and keeps track of the count list in the register. ]
[Question] [ # It was a warm summer evening... when my stupid car decided to break down in the middle of the road on my way back from the supermarket. I pushed it to the sideline and decided to walk home. I opened the trunk to take out the grocery and remaining stuff. It was then that I noticed the items were not evenly bagged. Some bags had more heavy items while others had few lighter stuff - some even had a mix of such items. To make it easy for me to carry, I decided to group everything in to two bags and make their weights as close to each other as possible. ![Making my way downtown](https://i.stack.imgur.com/hXUhq.png) # Your goal is to help me rearrange the items in to two shopping bags in such a way that the difference between both bags is close to zero as possible. **Mathematically:** > > **WEIGHT LEFT HAND — WEIGHT RIGHT HAND ≈ 0** > > > # Example If I had only 2 items, Bread and Peanut butter, and the weight of bread is 250 grams and peanut butter is 150 grams, the best way is to carry them separately in two hands. > > **WLH - WRH = W(BREAD) - W(P.BUTTER) > > 250 - 150 = 100** > > > The other possibility is : > > **W(BREAD, P.BUTTER) - W(empty hand) = (250 + 150) - 0 = 400** > > > This is not better than our first case, so you should go with the first one. # Your code should 1. take inputs of numbers indicating weights of items in the shopping bag. Units are not important, but they should be the same (ideally kilograms or grams). Input can be done one by one or all at once. You may restrict the total count to 20 items max, if you want. 2. The input format/type is up to you to choose, but nothing else should be present other than the weights. 3. Any language is allowed, but stick to standard libraries. 4. Display output. Again, you're free to choose the format, but explain the format in your post. ie, how can we tell which ones are left hand items and which ones are right hand items. # Points 1. Shortest code wins. # Hint > > The two possible algorithms that I could think of are differentiation (faster) and permutations/combinations (slower). You may use these or any other algorithm that does the job. > > > [Answer] # Pyth, 9 bytes ``` ehc2osNyQ ``` Input, output formats: ``` Input: [1, 2, 3, 4, 5] Output: [1, 2, 4] ``` [Demonstration.](https://pyth.herokuapp.com/?code=ehc2osNyQ&input=%5B1%2C+2%2C+3%2C+4%2C+5%5D&debug=0) ``` ehc2osNyQ Q = eval(input()) yQ Take all subsets of Q. osN Order those element lists by their sums. c2 Cut the list in half. eh Take the last element of the first half. ``` This works because `y` returns the subsets in such an order that each subset and its complement are equidistant fom the center. Since the sum of a subset and the sum of its complement will always be equidistant from the center, the list after `osNyQ` will also have this property. Thus, the center two elements of `osNyQ` are complements, and must have an optimal split. We extract the first of those two elements and print it. [Answer] # Pyth, 16 ``` ho.a-FsMNs./M.pQ ``` This takes the inputs as a pythonic list on STDIN. The output is a list of 2 lists with the first list being the items in one bag, and the second list representing the items in the second bag. This brute forces all combinations, so it will run very slowly (or run out of memory) for large inputs. [Try it online here](https://pyth.herokuapp.com/?code=ho.a-FsMNs.%2FM.pQ&input=%5B20%2C+10%2C+5%2C+4%2C+6%2C+2%5D&debug=0) To support the handling of just one input, this goes up to 17: ``` hho.a-FsMNs./M.pQ ``` This will print the values that go in one hand. [Answer] # CJam, ~~19~~ 18 bytes ``` {S+m!{S/1fb:*}$W=} ``` This is an anonymous function that pops an array of integers from the stack and returns an array of integers separated by a space. *Thanks to @jimmy23013 for his ingenious `:*` trick, which saved 1 byte.* Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%5B1%202%203%204%5D%20%20%20%20%20%20%20%20%20%20e%23%20Input%0A%7BS%2Bm!%7BS%2F1fb%3A*%7D%24W%3D%7D%20e%23%20Function%0A~p%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Call%20and%20print.). ### How it works ``` S+ e# Append a space to the array of integers. m! e# Push the array of all possible permutations. { e# Sort the array by the following: S/ e# Split the array at the space. 1fb e# Add the integers in each chunk (using base 1 conversion). :* e# Push the product of both sums. }$ e# Permutations with a higher product will come last. W= e# Select the last permutation. ``` Denote the total weight of the shopping bags with **W**. Then, if the bags in one of the hands weigh **W/2 - D/2**, those in the other hand must weigh and **W - (W/2 - D/2) = W/2 + D/2**. We are trying to minimize the difference **D**. But **(W/2 - D/2)(W/2 + D/2) = W^2/4 - D^2/4**, which becomes larger as **D** becomes smaller. Thus, the maximal product corresponds to the minimal difference. [Answer] # Python 2.7, 161, 160 ## code ``` from itertools import* m=input();h=sum(m)/2.;d=h for r in(c for o in range(len(m)+1) for c in combinations(m,o)): t=abs(h-sum(r)) if t<=d:d=t;a=r print a ``` # Algorithm > > **2 x Wone hand = Total weight > > Wone hand ~ Total weight / 2** > > > Check if each combination is getting closer to half of total weight. Iterate and find the best one. ## input ``` >>>[1,2,3,4] ``` ## output ``` (2, 3) ``` The displayed tuple goes in one hand, the ones that are not displayed goes in the other (it is not against the rules). [Answer] # JavaScript (*ES6*) 117 Using a bit mask to try every possible split, so it is limited to 31 items (ok with the rules). Like the ref answer it outputs just one hand. Note: i look for the minimum difference >=0 to avoid Math.abs, as for each min < 0 there is another > 0, just swapping hands. To test: run the snippet in Firefox, input a list of numbers comma or space separated. ``` f=(l,n)=>{ // the unused parameter n is inited to 'undefined' for(i=0;++i<1<<l.length;t<0|t>=n||(r=a,n=t)) l.map(v=>(t+=i&m?(a.push(v),v):-v,m+=m),m=1,t=0,a=[]); alert(r) } // Test // Redefine alert to avoid that annoying popup when testing alert=x=>O.innerHTML+=x+'\n'; go=_=>{ var list=I.value.match(/\d+/g).map(x=>+x); // get input and convert to numbers O.innerHTML += list+' -> '; f(list); } ``` ``` #I { width: 300px } ``` ``` <input id=I value='7 7 7 10 11'><button onclick='go()'>-></button> <pre id=O></pre> ``` [Answer] # Haskell, 73 bytes ``` import Data.List f l=snd$minimum[(abs$sum l-2*sum s,s)|s<-subsequences l] ``` Outputs a list of items in one hand. The missing elements go to the other hand. Usage: `f [7,7,7,10,11]` -> `[7,7,7]` For all subsequences `s` of the input list `l` calculate the absolute value of the weight difference between `s` and the missing elements of `l`. Find the minimum. [Answer] ## Haskell, 51 bytes ``` f l=snd$minimum$((,)=<<abs.sum)<$>mapM(\x->[x,-x])l ``` Output format is that left-hand weights are positive and right-hand weights are negative. ``` >> f [2,1,5,4,7] [-2,-1,5,4,-7] ``` To generate every possible split, we use `mapM(\x->[x,-x])l` to negate every possible subset of elements. Then, `((,)=<<abs.sum)` labels each one with its absolute sum and `snd$minimum$((,)=<<abs.sum)` take the smallest-labeled element. I couldn't get it point-free because of type-checking issues. [Answer] # Axiom, 292 bytes ``` R==>reduce;F(b,c)==>for i in 1..#b repeat c;p(a)==(#a=0=>[a];w:=a.1;s:=p delete(a,1);v:=copy s;F(s,s.i:=concat([w],s.i));concat(v,s));m(a)==(#a=0=>[[0],a];#a=1=>[a,a];b:=p(a);r:=[a.1];v:=R(+,a)quo 2;m:=abs(v-a.1);F(b,(b.i=[]=>1;d:=abs(v-R(+,b.i));d<m=>(m:=d;r:=copy b.i);m=0=>break));[[m],r]) ``` A brute force application. This would minimize the set ``` A={abs(reduce(+,a)quo 2-reduce(+,x))|x in powerSet(a)} ``` because if is minimum ``` y=min(A)=abs(reduce(+,a)quo 2-reduce(+,r)) ``` it would be minimum too ``` 2*y=abs(reduce(+,a)-2*reduce(+,r))=abs((reduce(+,a)-reduce(+,r))-reduce(+,r)) ``` where (reduce(+,a)-reduce(+,r)) and reduce(+,r) are the 2 weight of two bags.( But that last formula not find to me the minimum, in the application). Ungolf and results ``` -- Return the PowerSet or the Powerlist of a powerSet(a)== #a=0=>[a] p:=a.1;s:=powerSet delete(a,1);v:=copy s for i in 1..#s repeat s.i:=concat([p],s.i) concat(v,s) -- Return one [[m], r] where -- r is one set or list with reduce(+,r)=min{abs(reduce(+,a)quo 2-reudece(+,x))|x in powerSet(a)} -- and m=abs(reduce(+,a) quo 2-reduce(+,r)) -- because each of two part, has to have the same weight MinDiff(a)== #a=0=>[[0],a] #a=1=>[ a ,a] b:=powerSet(a) r:=[a.1];v:=reduce(+,a) quo 2;m:=abs(v-a.1) for i in 1..#b repeat b.i=[]=>1 k:=reduce(+,b.i) d:=abs(v-k) d<m=>(m:=d;r:=copy b.i) m=0=>break [[m],r] --Lista random di n elmenti, casuali compresi tra "a" e "b" randList(n:PI,a:INT,b:INT):List INT== r:List INT:=[] a>b =>r d:=1+b-a for i in 1..n repeat r:=concat(r,a+random(d)$INT) r (5) -> a:=randList(12,1,10000) (5) [8723,1014,2085,5498,2855,1121,9834,326,7416,6025,4852,7905] Type: List Integer (6) -> m(a) (6) [[1],[1014,2085,5498,1121,326,6025,4852,7905]] Type: List List Integer (7) -> x:=reduce(+,m(a).2);[x,reduce(+,a)-x] (7) [28826,28828] Type: List PositiveInteger (8) -> m([1,2,3,4]) (8) [[0],[2,3]] Type: List List Integer (9) -> m([10,1,2,3,4]) (9) [[0],[10]] Type: List List Integer (10) -> m([40,20,80,50,100,33,2]) (10) [[0],[40,20,100,2]] Type: List List Integer (11) -> m([7,7,7,10,11]) (11) [[0],[10,11]] Type: List List Integer ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ṗµ∑;Iht ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZfCteKIkTtJaHQiLCIiLCJbMSwgMiwgMywgNCwgNSwgNl0iXQ==) Port of [isaacg's Pyth answer](https://codegolf.stackexchange.com/a/51478/100664), go upvote that ``` ṗ # Subsets µ∑; # Sorted by sum I # Cut in half ht # Get the second element of the first half ``` [Answer] # R (234) a longer and slower solution with R. Function: ``` function(p){m=sum(p)/2;n=100;L=length(p);a=matrix(0,n,L+2);for(i in 1:n){idx=sample(1:L,L);a[i,1:L]=idx;j=1;while(sum(p[idx[1:j]])<=m){a[i,L+1]=abs(sum(p[idx[1:j]])-m);a[i,L+2]=j;j=j+1}};b=which.min(a[,L+1]);print(p[a[b,1:a[b,L+2]]])} ``` Expected input - vector with the weights. Expected output - vector with the weights for one hand. Example ``` > Weight(c(1,2,3,4)) [1] 3 2 > Weight(c(10,1,2,3,4)) [1] 10 > Weight(c(40,20,80,50,100,33,2)) [1] 100 40 20 2 > Weight(c(7,7,7,10,11)) [1] 7 7 7 ``` Human readable code version: ``` weight <- function(input) { mid <- sum(input)/2 n <- 100 input_Length <- length(input) answers <- matrix(0, n, input_Length+2) for(i in 1:n){ idx <- sample(1:input_Length, input_Length) answers[i, 1:input_Length ] <- idx j <- 1 while(sum(input[idx[1:j]]) <= mid){ answers[i, input_Length+1] <- abs(sum(input[idx[1:j]]) - mid) answers[i, input_Length+2] <- j j <- j + 1 } } best_line <- which.min(answers[, input_Length+1]) print(paste("weight diference: ", answers[best_line, input_Length+1])) print(input[answers[best_line, 1:answers[best_line, input_Length+2]]]) } ``` ]
[Question] [ I can have a large `if/else` condition for each 30 minutes but I'm looking for more math and Unicode based solution. Here are clock emojis: 🕐🕑🕒🕓🕔🕕🕖🕗🕘🕙🕚🕛🕜🕝🕞🕟🕠🕡🕢🕣🕤🕥🕦🕧. If you lack proper rendering support, you can see them below (they're not in the same order and they may look different to what you see) or at [the Unicode chart](http://www.unicode.org/charts/PDF/U1F300.pdf), page 4. They correspond to Unicode codepoints U+1F550 (CLOCK FACE ONE OCLOCK) through U+1F567 (CLOCK FACE TWELVE-THIRTY). Your challenge is to write a program that outputs to STDOUT the closest clock face emoji to the current system time (AM and PM should be treated the same). For example if the time `t` is [5:15 ≤ t < 5:45), you would display the 5:30 emoji 🕠. This is code-golf, so shortest code in bytes wins. You may want to include a way to easily specify the time to test your code. # Edge test cases ``` Time Output Written ---------------------- 11:48 🕛 12:00 3:15 🕞 3:30 9:45 🕙 10:00 ``` ![enter image description here](https://i.stack.imgur.com/aka7v.png) [Answer] # Ruby — ~~61~~ 54 bytes # ~~Python 3 — 79 77 75 74 bytes~~ **edit:** Turns out this is much shorter in Ruby, because `Time` doesn't need to be imported and integer division is the default. ``` a=(Time.now.to_i/900-3)/2%24 puts""<<128336+a/2+a%2*12 ``` Arithmetic: * `Time.now.to_i`: Seconds since epoch. * `/900`: Combine time into 15-minute segments. * `-3`: `-4` because characters start at 1 o'clock, `+1` so that rounding is done to nearest half hour, rather than downwards. * `/2`: Combine into half-hour segments. * `%24`: Get current half-hour segment out of 12 hours. * `a/2 + a%2*12`: Account for the fact that whole-hour characters come in a block before half-hour characters. **Local time version, 69 bytes:** ``` n=Time.now a=((n.to_i+n.gmtoff)/900-3)/2%24 puts""<<128336+a/2+a%2*12 ``` **Original Python 3 version:** ``` import time a=int((time.time()/900-3)/2%24) print(chr(128336+a//2+a%2*12)) ``` Prints the current time UTC. Python 2's `chr` only accepts 0-255, and `unichr` only 0-65535. In Python 3, `/` is always floating-point division and `//` is always integer division. [Answer] # Bash + Coreutils, 60 47 ``` date +%I\ 60*%M+45-30/24%%2~C*+16iF09F9590+P|dc ``` [Try it online!](https://tio.run/##S0oszvj/PyWxJFVBW9UzRsHMQEvVV9vEVNfYQN/IRFXVqM5ZS9vQLNPNwNLN0tTSQDugJiX5/38A "Bash – Try It Online") Emojis render fine on the OSX terminal, but for Linux (Ubuntu 14.04) you'll have to `sudo apt-get install ttf-ancient-fonts` For testing different times, insert `-d $time` into the date command. e.g for testing 12:59: ``` date -d 12:59 +%I\ 60*%M+45-30/24%%2~C*+16iF09F9590+P|dc ``` [Answer] # CJam, 31 bytes ``` "🕐")et5<60b675+30/24%2mdC*++ ``` You can change the time in the following program to test it: ``` "🕐")[2014 12 19 22 14 1 901 5 -28800000]5<60b675+30/24%2mdC*++ ``` [Answer] # JavaScript – ~~137~~ ~~117~~ ~~107~~ ~~102~~ 95 bytes This is going to get easily beaten, but I'll just try my best here. **EDIT 1**: Now prints in UTC like the Python answer to save 20 bytes. **EDIT 2:** Changed `new Date().getTime()` to `Date.now()` to save 10 bytes. **EDIT 3:** Changed `Math.round(x)` to `~~(x+.5)` to save 5 bytes. **EDIT 4:** Removed unnecessary `(` and `&1023)` left from some old development version where I did a more universal UTF-16 encoding to save 7 bytes. ``` d=~~(Date.now()/18e5+.5)%24;d+=d<2?24:0;alert(String.fromCharCode(55357,56655+(d%2?23+d:d)/2)); ``` JavaScript *does* allow for emojis, but in UTF-16 which encodes them as two characters. Luckily, we can simply define them as two characters; the first character is also constant (`0xD83D`), while the other changes. **Alternative, prints in local time, ~~137~~ ~~132~~ 125:** ``` a=new Date();d=~~(a.getHours()%12*2+a.getMinutes()/30+.5);d+=d<2?24:0;alert(String.fromCharCode(55357,56655+(d%2?23+d:d)/2)); ``` [Answer] # CJam, 50 bytes ``` "🕐":i~et3=C%60*et4=+30d/mo2m24+24%_2%24*+2/+]:c ``` The algorithm is simple, round the time to nearest 30 minutes, count how many 30 minutes have passed since 12 AM/PM, if the number is odd, then add 24 to it, floor divide by 2 and increment the initial unicode by that many code points to get the right clock face. Also, make sure that you start with 1 AM/PM instead of 12 so take an offset there. For testing purposes, use the following code: ``` 3:H;45:M;"🕐":i~HC%60*M+30d/mo2m48+48%_2%24*+2/+]:c ``` Where the `3:H;` part is the current hour and the `45:M;` part is the current minute of the hour. Simply replace `3` and `45` with the desired value. [Try it online here](http://cjam.aditsu.net/) *Not all unicode characters might print correctly on the online version depending upon your browser and OS and installed fonts. But for me, all print fine on Firefox with Windows 7.* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ža60*žb+45-30÷24%2‰`12*+Žü¤·+ç ``` Port of [*@jimmy23013*'s CJam answer](https://codegolf.stackexchange.com/a/42528/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##yy9OTMpM/X90X9LRfYlKzqVFRal5JQolmbmpVgqH91sd3q@kw6UUlFpcmlNipQABSvZA5YlmBlpATdomprrGBoe3G5moGj1q2JBgaKSlfXTv4T2Hlhzarn14@X/7/wA) or [verify some manual test times](https://tio.run/##LcwxCsJAEIXhqywBG7PC7r7dGKscJARUsLCyEIR0Vh4gZxBsxSaNNgm2HiIXWcm8bf5hYOY7nXf74yFe2ipT061TWdXGwvxePqxgxt75hZuuz611y/z7Gd/Dfejz8RF1rGurTaNrJ4XUS4O0kK6lpXQjtYaD32khYjUogiRogiiogizogjCSjESD9jzUvPtSQBvk2oem@QM). **Explanation:** Uses the following formula to calculate the clock codepoint based on the given \$h\$ours and \$m\$inutes: $$d(h,m) = \left\lfloor\frac{60h+m-45}{30}\right\rfloor\bmod{24} \\ C(h,m) = \left\lfloor\frac{d(h,m)}{2}\right\rfloor+12(d(h,m)\bmod{2})+128336$$ ``` ža # Push the current hours 60* # Multiply them by 60 žb+ # Add the current minutes 45- # Subtract 45 30÷ # Integer-divided by 30 24% # Modulo 24 2‰ # Divmod by 2: [n//2,n%2] ` # Pop and push n//2 and n%2 separated to the stack 12* # Multiply n%2 by 12 + # Add it to the n//2 Žü¤ # Push compressed integer 64168 · # Double it to 128336 + # Add it as well ç # Convert it to a character with this codepoint # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Žü¤` is `64168` (compressed `128336` directly is 1 byte longer: `•1ùθ•`). [Answer] # [C (gcc)](https://gcc.gnu.org/) with `-m32`, ~~104~~ ~~100~~ 98 bytes * -6 thanks to ceilingcat ``` *t;f(i){char a[]="🕐";time(&i);i=1[t=gmtime(&i)]/15;a[3]=144+(t[2]+11+i/4)%12+(i-1U<2)*12;puts(a);} ``` [Try it online!](https://tio.run/##TY1LCsIwGIT3niIEKkkf1KR1FeMtXIUuQjT1B1NLG92U3sGNa6/oCYxtQXA1fDPDjMlqY0KIvbAE6GDOukNaVRK/X88HFh7ciayBCpBMeVm7n1HlbCu0KirJyjIhXvEqYSyBvKQR4wmBjB12nMaMi/bme6KpGAM0HjkNDblf4UjRsEJotiCd7lczyGV@Q8UE/28zt93UtQRHPZJ7hFOke7Pkni65JZOM4WPsRdd9yFzBvw "C (gcc) – Try It Online") Ungolfed: ``` *t; // broken-down time structure ([1]=minutes, [2]=hours) f(i){ // time char a[]="🕐"; // base emoji in modifiable UTF-8 string time(&i); // get time and convert into structure i=1[t=gmtime(&i)]/15; // get granular 15-minute chunks a[3]= 144+ // base 4th byte of emoji (t[2]+11+i/4)%12+ // convert [0..23] to [1..24]-1 for hour, adding [0:45..1:00) (i-1U<2)*12; // add [0:15..0.45) as half-hour puts(a); } ``` [Answer] # [Go](https://go.dev), 265 bytes, function ``` import."time" func f()rune{N,H:=Now(),Hour/2 e,l:=N.Truncate(H),N.Round(H) if e.Sub(N).Abs()<l.Sub(N).Abs(){N=e}else{N=l} return []rune("🕛🕧🕐🕜🕑🕝🕒🕞🕓🕟🕔🕠🕕🕡🕖🕢🕗🕣🕘🕤🕙🕥🕚🕦")[N.Hour()%12*2+N.Minute()/30]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VdBNToQwGAbguLSnICSaVrGjuDFGFu7Y2Bh1N5kFg4UQoUygjQvCHfwb_0YdHB09g0fRU3gEX8SNiydf-7Vp872TWZw3H6MgPAliaWVBokiSjfJCW3aUaXtudLS29bWw2DW5rZNM2iQyKrQiygqjZCUcf9sT-Slljp-boucS6aTo8CMch4GW1GeO4Ae5UcdYkiSyJD80QyoY3x2WlO2k_7aV8GQt0xIve2lNCqlNoaz-oP2M2t_T8QTe4Qwe4Bwe4QKe4BKmcAUNjOEZrmEGN_ACt_AKdzCHe3izWV_wdg7KljbcFXdV8L1EGUzBepvrg7pL5HP5N4I2L8qsiiArvl8kStNSo8QU4TBG_m43TVd_AA) Gets the current time, rounds up and down to the nearest half hour, finds the closer one, and returns the emoji that represents it. # [Go](https://go.dev), 285 bytes, full program ``` package main import."time" func main(){N,H:=Now(),Hour/2 e,l:=N.Truncate(H),N.Round(H) if e.Sub(N).Abs()<l.Sub(N).Abs(){N=e}else{N=l} print(string([]rune("🕛🕧🕐🕜🕑🕝🕒🕞🕓🕟🕔🕠🕕🕡🕖🕢🕗🕣🕘🕤🕙🕥🕚🕦")[N.Hour()%12*2+N.Minute()/30]))} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VdA7TsNAEAZg0foOSJElpB0wGzANQqSgc8MWQBelcJK1tcLetexdUUS-A6_wSiAmJHAnTsER-HkVFJ92djQaaf7JPDVNs3Q22dx9X1kt4sFpnMpWHivtqbwwpeW-Vbn0vcTpwXef0UgE0V5HmDNGQWRc2Q49GWTo8JMSU7GVLKJA8CPj9BClp5KW5MeuzwTxg37FaD_79x2JjqxlVkkUWe0VpdKWVRZPyro97JTM_5iNJ_AG5zCFC3iES3iCK5jBNTQwhme4gTncwgvcwQLuYQkP8OpTV_CvaxitbYfr4Ybgh0o73ELtna0eUf2T0m9Yf6F9Ag) [Answer] # [Julia](https://julialang.org), 81 bytes ``` using Dates n=now() M=minute(n) print('🕏'+mod1(hour(n)+(M>44),12)+12(14<M<45)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lVC9TsMwEN79FCcvuVNMVYdEQlHLxNAlA2o3xBC1LjFKzsixxWMwMTHQpU_ExFvwCJgUBCs33qfv9-V4H3vbHg7HGPZnF-_XcbR8B1dtMKPgJbtHJNEsB8sxGGQSD95ywOzj9fkpywe309i56BOSY3NZlqR0QbkuUJeLZlFWRN_CbxOxZ5SAm87ANnpvOECwg4HOeAN2BKlOzrO980MbcLJXcrWqm6ZeryUpkCRJiIQDg2XYJPoMcV4X55QpuJkrXamyuiUB6Xq3bXv4G__r--8Kv6wpf0qZlAzvTtV-tvsE) Julia is generally picky with types, but some common arithmetic statements involving `Char`, `Int`, and `Bool` are permitted. The `Int` values of the clock emojis are the range `128336:128359`. The emojis are encoded in ascending order, with all the twelve that are on the hour coming before the twelve half-past emojis. In this algorithm, [the preceding character `'🕏'`](https://en.wikipedia.org/wiki/Bowl_of_Hygieia) is incremented by the 12-hour number (plus 1 if it's more than 44 minutes past the hour), and another 12 is added if the minute hand needs to be adjusted. -17 bytes (!!) thanks to MarcMush: just use `Dates.minute` instead of parsing the time string [Answer] ## Pascal, 134 characters This `program` requires a processor supporting the time-related features defined by ISO standard 10206 “Extended Pascal”. Furthermore the *implementation-defined* set of `char` values must include said Unicode characters. ``` program t(output);var t:timeStamp;begin getTimeStamp(t);write(('🕛🕧🕐🕜🕑🕝🕒🕞🕓🕟🕔🕠🕕🕡🕖🕢🕗🕣🕘🕤🕙🕥🕚🕦')[t.hour mod 12*2+round(t.minute/30)+1])end. ``` Ungolfed: ``` program clock(output); var ts: timeStamp; begin getTimeStamp(ts); { This `program` presumes `ts.timeValid` is set to `true`. Otherwise `getTimeStamp` sets the clock to midnight. Insert ts.hour := 11; ts.minute := 48; here to test the functionality of this `program`. } writeLn(('🕛🕧🕐🕜🕑🕝🕒🕞🕓🕟🕔🕠🕕🕡🕖🕢🕗🕣🕘🕤🕙🕥🕚🕦') [ts.hour mod 12 * 2 + round(ts.minute / 30) + 1]); end. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 98 bytes ``` Print@FromCharacterCode[128336+Quotient[#,2]+12Mod[#,2]&[Mod[Quotient[UnixTime[]-2700,900]/2,24]]] ``` Original Code is ``` a = Mod[Quotient[UnixTime[] - 3 * 900, 900] / 2, 24]; result = FromCharacterCode[128336 + Quotient[a, 2] + Mod[a, 2] * 12]; Print[result] ``` ]
[Question] [ Code a program or function to construct an interactive canvas on the screen of at least 400 pixels x 400 pixels in size. The canvas can be any color you wish, bordered or borderless, with or without a title bar, etc., just some form of obvious canvas. The user will click on two distinct areas of the canvas and the program must output the Euclidean distance (in pixels) between those two clicks in some fashion (STDOUT, displaying an alert, etc.). The two clicks can be only left clicks, only right clicks, a left click for the first and right click for the second, two double-left-clicks, etc., any combination is acceptable. Special Note: Clicking-and-dragging (e.g., using MOUSEUP as the second point) is specifically not allowed; they must be two distinct clicks. The user must be able do this multiple times, and must get an output each time, until the program is closed/force-quit/killed/etc. You can choose the method of closure (clicking an X, ctrl-C, etc.), whatever is golfier for your code. ### Rules * Either a full program or a function are acceptable. If a function, however, you must still display the output to the user somehow (simply returning the value is not acceptable). * Output can be to the console, displayed as an alert, populated onto the canvas, etc. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # LOGO ([FMSLogo](https://sourceforge.net/projects/fmslogo)), ~~54~~ 52 bytes ``` [mouseon[setpos mousepos]"[pr distance mousepos]"[]] ``` Unfortunately, I can't find any Logo interpreter online support mouse handling like FMSLogo. This is a "explicit-slot template", which is similar to lambda in other programming languages. Click left mouse for first point and right mouse for second point (print distance). Explanation: (Logo is a turtle graphics programming language) ``` mouseon Turn on mouse handling, with the following action: [setpos mousepos] Set the turtle to `mousepos` (the position of the mouse) on left mouse down " Do nothing on left mouse up [pr distance mousepos] Print the distance from turtle position (`distance` is Logo builtin for that purpose) to `mousepos` on right mouse down " Do nothing on right mouse up [] Do nothing on mouse movement ``` The `"` is an empty word. Normally template is expected to be a list (where `[]`, an empty list, does nothing), passing a word is acceptable (it is wrapped in a list), and in this case it saves 2 bytes. Run: ``` apply [... <put the code here> ...] [] ``` The `apply` is one way to run template in Logo, the `[]` is argument list, for which the template receive none. [Answer] ## Mathematica, 94 bytes ``` e="MouseDown";m:=x=MousePosition[];1~RandomImage~400~EventHandler~{e:>m,{e,2}:>Echo@Norm[x-m]} ``` The canvas is a random grey-scale image, the first click should be a left-click and the second one a right-click. The exact behaviour is actually that right-click prints the distance to the last click (left *or* right), so if you use right-click repeatedly, you can also get consecutive distances. The results are exact, so they might contain a square root. If the resolution of your webcam is at least 400x400, you could use `CurrentImage[]` instead of `1~RandomImage~400` for your canvas, saving 3 bytes. [Answer] # Java 8, ~~469~~ ~~389~~ ~~388~~ ~~385~~ ~~380~~ ~~357~~ ~~348~~ 325 bytes ``` import java.awt.event.*;interface F{static void main(String[]a){new java.awt.Frame(){{setSize(400,400);double[]a={-1,0};addMouseListener(new MouseAdapter(){public void mouseClicked(MouseEvent e){if(a[0]<0){a[0]=e.getX();a[1]=e.getY();}else{System.out.println(Math.hypot(e.getX()-a[0],e.getY()-a[1]));a[0]=-1;}}});}}.show();}} ``` ``` import javafx.application.*;import javafx.scene.*;import javafx.scene.layout.*;import javafx.stage.*;public class E extends Application{double[]a={-1,0};public void start(Stage s)throws Exception{Pane p=new Pane();s.setScene(new Scene(p,400,400));s.show();p.setOnMouseClicked(e->{if(a[0]<0){a[0]=e.getX();a[1]=e.getY();}else {System.out.println(Math.sqrt(Math.pow(e.getX()-a[0],2)+Math.pow(e.getY()-a[1],2)));a[0]=-1;}});}public static void main(String[]a){launch(a);}} ``` ~~Would be shorter with AWT, but I've never used it.~~ [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 282 bytes ``` import java.awt.event.*;interface M{static void main(String[]a){new java.awt.Frame(){int k,x,y;{addMouseListener(new MouseAdapter(){public void mouseClicked(MouseEvent e){x=e.getX()-k*x;y=e.getY()-k*y;k^=1;if(k<1)System.out.prin‌​tln(Math.hypot(x,y))‌​;}});setSize(800,600‌​);show();}};}} ``` I cannot test this right now; if someone could tell me if there are any compiler errors that would be great. ~~AWT would probably be shorter but I need an actual IDE for that lol. I've never used AWT before but I could make it work if I had an IDE. I could use the docs but that's really hard lol~~ -10 bytes using AWT thanks to Kevin Cruijssen -44 bytes using an initializer block; developed independently of Roberto Graham though I now see that they did the same thing, I think -6 bytes combining a few declarations thanks to Kevin -11 bytes using an `interface` thanks to Kevin -35 bytes eliminating some unnecessary variables thanks to mellamokb -9 bytes removing the unnecessary import and using a qualified name thanks to mellamokb -44 bytes thanks to mellamokb and aditsu [Answer] # TI-Basic (TI-84 Plus CE), 49 bytes (45 tokens) (possibly non-competing) ``` 0→Xmin 0→Ymin 8³→Xmax Ans→Ymax While 1 Input {X,Y Input Ans-{X,Y Disp √(sum(Ans² Pause End ``` -7 bytes with suggestions from kamoroso94 The user doesn't 'click' per se, but moves around a cursor on the graph screen with the arrow keys and hits `enter` to select a point, and the smallest movement is ~1.5 for x and ~2.4 for y. Explanation: ``` 0→Xmin # 5 bytes 0→Ymin # 5 bytes 8³→Xmax # 6 bytes, Ans→Ymax # 5 bytes, Set up graph screen size (512x512) While 1 # 3 bytes, Until interrupted with `on` button Input # 2 bytes, Get user input as a point on the graph screen in X and Y {X,Y # 5 bytes, store the list {X,Y} in Ans Input # 2 bytes, Get second user input as a point on the graph screen in X and Y Ans-{X,Y # 7 bytes, store {X1-X2,Y1-Y2} in Ans Disp √(sum(Ans² # 6 bytes, Display the distance between the two points Pause # 2 bytes, Let the user see it (press `enter` to continue) End # 1 bytes, End while loop ``` [Answer] # JavaScript (ES6) + HTML, 58 bytes The webpage itself serves as the "canvas" in question; I think it's quite safe to assume the browser window will be at least 400x400 pixels. ``` E=0,onclick=e=>(E&&alert(Math.hypot(E.x-e.x,E.y-e.y)),E=e) ``` --- # JavaScript (ES6) + HTML, 51 bytes We can save 7 bytes if we ignore the `NaN` output on the first click. ([@Nate](https://codegolf.stackexchange.com/users/75750/nate)) ``` E=onclick=e=>alert(Math.hypot(E.x-e.x,E.y-e.y),E=e) ``` --- # JavaScript (ES6) + HTML + CSS, 58 + 0 + 13 = 71 bytes **Edit**: With an additional 13 bytes of CSS, we can ensure the scroll area will be sufficiently large enough to fit the 400x400 requirement. ``` E=0,onclick=e=>(E&&alert(Math.hypot(E.x-e.x,E.y-e.y)),E=e) ``` ``` *{padding:9in ``` [Answer] # [Processing](https://processing.org/)/Java, 149 bytes ``` void setup(){size(400,400);}void draw(){}int a,b;void mousePressed(){if(mouseButton==LEFT){a=mouseX;b=mouseY;}else println(dist(a,b,mouseX,mouseY));} ``` Pretty straightforward, uses 2 global variables and 3 built-in functions to do everything. * Setup: just initializes the window to 400x400 * Draw: empty, but must exist for Processing to be interactive for >1 frame * MousePressed: if left click, save the mouse coordinates into the integers a and b. If right click, measure the distance from point (a, b) to the current position, and print to the console. [Answer] # Processing.org 126 ``` float i,d,x,y;void setup(){fullScreen();}void draw(){}void mousePressed(){d=dist(x,y,x=mouseX,y=mouseY);print(i++%2<1?" ":d);} ``` [Answer] ## Python 2, 144 Prints distance between last clicks (first one prints distance from 400,400). ``` import Tkinter as t,math r=t.Tk() p=[400]*2 r.minsize(*p) def f(e):print math.hypot(p[0]-e.x,p[1]-e.y);p[:]=e.x,e.y r.bind('<1>',f) r.mainloop() ``` [Answer] # Autohotkey, 146 bytes ``` A=0 Gui,Add,Text,W400 H400 gC Border Gui,Show Return C: If A=0 MouseGetPos,A,B Else{ MouseGetPos,C,D Msgbox % Sqrt((A-C)**2+(B-D)**2) A=0 } Return ``` You'd think a language built specifically for capturing and simulating keyboard and mouse actions would be more efficient at this challenge... This creates a window with a text box 400 x 400 pixels with a border to make it obvious. Without the border, there's a space around the edge that's in the window but outside the text box and you can't tell. Adding a border was the shortest way to differentiate them. The `gC` option make it run the subroutine `C` whenever you click on the text box. The command sequence is, therefore, Left Click followed by a different Left Click. I found another solution that's 144 bytes but it allows clicks all over the screen instead of just in the "obvious canvas". It's also annoying to end because both left and right clicks are captured and it doesn't end when you close the GUI. ``` Gui,Add,Text,W400 H400 Border Gui,Show Return LButton:: MouseGetPos,A,B Return RButton:: MouseGetPos,C,D Msgbox % Sqrt((A-C)**2+(B-D)**2) Return ``` [Answer] # Python 2 ([TigerJython](http://www.jython.tobiaskohn.ch/)), ~~125~~ 123 bytes ``` from gturtle import* n=0 def c(x,y): global n if n:print distance(x,y) else:setPos(x,y) n^=1 makeTurtle(mousePressed=c) ``` TigerJython comes with a default size of (800x, 600y) sized canvas. This spawns a temporary turtle image for every 'begin' point clicked, which disappears after the next 'begin' point is selected. This behaviour is approved by the OP. [Answer] # SmileBASIC, 86 bytes ``` @L TOUCH OUT F,X,Y S=S-X T=T-Y IF!O*F*M THEN?SQR(S*S+T*T) S=X T=Y M=M!=!O*F O=F GOTO@L ``` Uses touch screen for input. [Answer] # Java 8, 228 bytes ``` interface A{static void main(String[]a){new java.awt.Frame(){{setSize(400,400);}int i,j,t;public boolean mouseDown(java.awt.Event e,int x,int y){if(t++%2==1)System.out.println(Math.hypot(x-i,y-j));i=x;j=y;return 1>0;}}.show();}} ``` Here's a Java solution that uses a deprecated AWT method `mouseDown` that you'd have to dig deep into the API to find. I only know of it because of the programming course I took as a high school sophomore, and one of the projects was to make a small paint program using that and similar methods. I never thought I'd have a good reason to use it until now. [Answer] # Tcl/Tk, 94 ~~104~~ ``` wm ge . 400x400 bind . <1> {if [info ex x] {puts [expr hypot(%x-$x,%y-$y)]} set x %x set y %y} ``` [![enter image description here](https://i.stack.imgur.com/s9mlK.png)](https://i.stack.imgur.com/s9mlK.png) ]
[Question] [ Take a flag, like this one: ``` ----------------------------- | | | | | | |=============+=============| | | | | | | ----------------------------- ``` And a number input: the "wave length" Say the wave length was 5. Then, every 5 characters along the line from the beginning, replace the next character a `-` with `\` and shift all the characters after it one row down. Repeat this until the end. You end up with: ``` -----\ | -----\ | -----\ |===== | -----\ | ====== | ----- | ==+=== | -----\ | ====== | -----\ | ====| -----\ | -----\ | ----- ``` If you end up not being able to make a full wave length along at the end, the flag is finished. Just remain flat until the end. You can assume that all the lines are of the same length and that the top and bottom lines are composed entirely of `-` (0x2D) and the rest of the characters are in `!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~`, or is a space (). (So it's ascii value is `x`, where `31 < x < 127`) The flag will be at least 3 tall and 3 wide. Wave length will be a non-negative integer (>= 0). (You can also have wave length 1 be the smallest wavelength, so the above example would have wave length 6. This is OK.) Your i/o of flag can be as arrays of lines or a string with multiple lines. The output flag may have trailing spaces, but can only have leading spaces so long as it is the same on every flag. Trailing space on an input flag may be deleted. ## Scoring This is code-golf, so the shortest solution, in bytes, wins. ## Test cases ``` --- abc --- 2 --\ abc --\ ----- | + | ----- 10 ----- | + | ----- --------------------------------------- |&&&&&& &&&&&&| |&&&&&& &&&&&&| |&&&&&& &&&&&&| |&&&&&& .\^/. &&&&&&| |&&&&&& . | | . &&&&&&| |&&&&&& |\| |/| &&&&&&| |&&&&&& .--' '--. &&&&&&| |&&&&&& \ / &&&&&&| |&&&&&& > < &&&&&&| |&&&&&& '~|/~~|~~\|~' &&&&&&| |&&&&&& | &&&&&&| |&&&&&& &&&&&&| |&&&&&& &&&&&&| --------------------------------------- 12 ------------\ |&&&&&& ------------\ |&&&&&& ------------\ |&&&&&& &&&&&&| |&&&&&& &&&&&&| |&&&&&& .\^/. &&&&&&| |&&&&&& . | | . &&&&&&| |&&&&&& . |\| |/| &&&&&&| |&&&&&& --' '-- &&&&&&| |&&&&&& \ /. &&&&&&| |&&&&&& > < &&&&&&| |&&&&&& '~|/~~|~~\|~' &&&&&&| |&&&&&& | &&&&&&| |&&&&&& &&&&&&| ------------\ &&&&&&| ------------\ &&&&&&| ------------\ ----------------------- |-._`-._ :| |: _.-'_.-| | `-._`:| |:`_.-' | |-------`-' '-'-------| |------_.-. .-._------| | _.-'_.:| |:._`-._ | |-'_.-' :| |: `-._`-| ----------------------- 4 ----\ |-._`----\ | `-._ :----\ |-----._`:| |: ----\ |-------`-| |:`_.-'_--- | _.--_.-' '-'_.-' .-| |-'_.-'_.:. .-.----- | ----\-' :| |:._------| ----\| |: _`-._--| ----\ `-._ | ----\`-| --- --------------- --------------- --------------- --------------- --------------- 5 -----\ -----------\ --------------- --------------- -----\--------- -----\--- --- ------------------------------------------- |* * * * * |##########################| | * * * * *| | |* * * * * |##########################| | * * * * *| | |* * * * * |##########################| | * * * * *| | |* * * * * |##########################| |--------------- | |#########################################| | | |#########################################| | | |#########################################| ------------------------------------------- 0 \ |\ |*\ | \ |** \ | *\ |** \ | ** \ |** *\ |- ** \ |#- ** \ | #-** *\ |# #- ** \ | # #- ** \ \# # #-** *\ \# # #- ** \ \# # #- **|\ \# # #-** |#\ \# # #- **| #\ \# # #- |# #\ \# # #-**| # #\ \# # #- |# # #\ \# # #-| # # #\ \# # #-# # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # #\ \# # # # # # | \# # # # # #| \# # # # # | \# # # # #| \# # # # | \# # # #| \# # # | \# # #| \# # | \# #| \# | \#| \| \ ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ ~~23~~ ~~26~~ 25 bytes *-2 thanks to Adnan* *-1 thanks to Emigna* *+3 thanks to Jonathan Allan (thanks for spending the time to catch that invalidity!)* ``` øvyN>²Öi¦¨'\.ø}N²÷ú}).Bø» ``` [Try it online!](https://tio.run/nexus/05ab1e#@394R1mln92hTarxmYeWHVqhHqN3eEet36FNh7cf3lWrqed0eMeh3f//R6vr4gPqOgrqNQrIAI1HnAJbZKCNwquhjhX4fRHLZQQA "05AB1E – TIO Nexus") This is 1-indexed instead of 0, +2 bytes if that isn't okay. ``` ø # Transpose. vy } # For each column... N>²Öi¦¨'\.ø} # Replace outside dashes with slants. N²÷ # Current index / input #2. ú # Prepend that many spaces to current column. ).Bø # Join, pad, transpose back. » # Print with newlines. ``` Emigna/Adnan/Anyone - There HAS to be a better solution to replace those slants, but I'm stumped. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 35 bytes ``` j.ts.e+L*k;?qQtlb+PbjPteb*2\\bcC.zh ``` [Try it online!](http://pyth.herokuapp.com/?code=j.ts.e%2BL%2ak%3B%3FqQtlb%2BPbjPteb%2a2%5C%5CbcC.zh&input=5%0A-----------------------------%0A%7C+++++++++++++%7C+++++++++++++%7C%0A%7C+++++++++++++%7C+++++++++++++%7C%0A%7C%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%2B%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%7C%0A%7C+++++++++++++%7C+++++++++++++%7C%0A%7C+++++++++++++%7C+++++++++++++%7C%0A-----------------------------&debug=0) [Answer] # [Python 2](https://docs.python.org/2/), 129 bytes ``` lambda f,n,j=''.join:map(j,zip(*[i/n*' '+'-\\'[i%n>n-2]+j(s[1:-1])+'-\\'[i%n>n-2]+len(f[0])/n*' 'for i,s in enumerate(zip(*f))])) ``` [Try it online!](https://tio.run/nexus/python2#3VTRaoMwFH3PV1wsW5I2iev2MJDZHzEO7KYSsamoexkXf72LtoyuoHUPG2OHkIfck5Pc5HDyUB/KZLd9TSATVhQhparYGxvskooV4t1UbBkZ3y4p0BWVWtPI3NiNlffxqmBNtA7kOuaXlTK1LIvuYn7cmO1rMKIBYyG1b7u0TtqUDdIZ5zHnh6xM8gZCiDzPI3IeCN4OgDEcy/jzPKWffXWVpwDdjKCu8FAPPB@neEpKeipTKdW4nj5rwJ86d/NJe5q6H@3Q7zrsOo0dvfp@@Bv/MdMvzlqCnPxFku0LuViTs323BDgbuBiF6wG@kHG0GcD/rXvxiJO6i7no7zsXf0P3Gz5ztowJ6aOzT0cBZR@ffWgOYSkgehTwIMClb0Cgqo1tgWp7TG@WDyyXzrFqqtK0zNPW407Ehe0H "Python 2 – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` s”\⁹¦€Fð€0,1¦Zsð⁶ẋ;Ѐµ@"J;/z⁶ ``` Input and output flags are lists of lines. Wave length is 1-indexed. Always produces one line of spaces. (all of the above is explicitly allowed in the posted question) **[Try it online!](https://tio.run/nexus/jelly#@1/8qGFuzKPGnYeWPWpa43Z4A5A00DE8tCyqGMhu3PZwV7f14QlAwUNbHZS8rPWrgGL/H@7ecnh55P//usQBrho1MFDABSDSNbRXpxcTp69HUJ2eQg2QrFHQI6CuJgasTr8Gnzo9XV11qLS6rq4ebvNikDygj89eO7gyG3zuU6@r0a@rq6mri6mpUycYfjX0iA8i08t/Q2MA)** (footer to make IO look pretty - takes and receives flags as multiline text) ### How? A pretty similar method to carusocomputing's [05ab1e answer](https://codegolf.stackexchange.com/a/120113/53748), which I have not managed to golf down more. ``` s”\⁹¦€Fð€0,1¦Zsð⁶ẋ;Ѐµ@"J;/z⁶ - Main link: list of lists f, number p ¦ - apply to indexes (of f) 0,1 - ... 0 paired with 1 (i.e. last & first -> bottom & top) ð€ - the previous chain with p as right argument for €ach: s - split into chunks of length p ¦€ - apply to indexes for €ach ⁹ - ... link's right argument, p ”\ - the character '\' (a replacement - if the index is out of bounds this has no effect - although this might change in the future.) Z - transpose the edited flag s - split into chunks of length p J - range of length = [1,2,...,nChunks] ð µ@" - zip with reversed arguments (call those i): ⁶ - literal space ẋ - repeated i times ;Ѐ - concatenate mapped across the chunks ;/ - undo the split (reduce with concatenation) z⁶ - transpose with a filler of space characters ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 31 bytes ``` x"X@q1GQ&\Z"@b1G=?'\'5L(]h]Xhc! ``` [Try it online!](https://tio.run/nexus/matl#@1@hFOFQaOgeqBYTpeSQZOhua68eo27qoxGbERuRkaz4/7@hEVe0ui5xQN1avUYNDBRwAYh0Db1U6sXE6esRoVJPoQZI1ijoEVRZEwNWqV@DX6UeMDTUoSrUgeGnh8/UGCTP6OO33w6u0Aa/S9XV62r06@pq6upiaupgTsEbpjX0iydi01MsAA "MATL – TIO Nexus") Or verify all test cases: [1](https://tio.run/nexus/matl#@1@hFOFQaOgeqBYTpeSQZOhua68eo27qoxGbERuRkaz4/78pV7S6Lj6gbq1eo4AM0HjEyNsiA20UXg0VzMfv/lgA), [2](https://tio.run/nexus/matl#@1@hFOFQaOgeqBYTpeSQZOhua68eo27qoxGbERuRkaz4/78RV7S6rq6uurV6YlIykASxYwE), [3](https://tio.run/nexus/matl#@1@hFOFQaOgeqBYTpeSQZOhua68eo27qoxGbERuRkaz4/7@hAVe0ui4IqFur1yhoK9QAaQg/FgA), [4](https://tio.run/nexus/matl#@1@hFOFQaOgeqBYTpeSQZOhua68eo27qoxGbERuRkaz4/7@hEVe0ui5xQN1avUYNDBRwAYh0Db1U6sXE6esRoVJPoQZI1ijoEVRZEwNWqV@DX6UeMDTUoSrUgeGnh8/UGCTP6OO33w6u0Aa/S9XV62r06@pq6upiaupgTsEbpjX0iydi01MsAA), [5](https://tio.run/nexus/matl#@1@hFOFQaOgeqBYTpeSQZOhua68eo27qoxGbERuRkaz4/78JV7S6Lnagbq1eo6sXnwDEClY1CjVWCvF6uurqQKIGJKWgoACSSgBLJYClgEJgKagBCSAhdXUgCRVAkgSq11MA4ngkGQWYBWAjoTZDTQTbC7IB4hKI1WBtuFwfCwA), [6](https://tio.run/nexus/matl#@1@hFOFQaOgeqBYTpeSQZOhua68eo27qoxGbERuRkaz4/78pV7S6LipQt6aSSCwA), [7](https://tio.run/nexus/matl#@1@hFOFQaOgeqBYTpeSQZOhua68eo27qoxGbERuRkaz4/78BV7S6LvFA3Vq9RktBAQnVKOMENSDVCijKaxRwgpqRYzZaoBIwW5lYAHE3sWBwmU1KGowFAA). [Answer] ## JavaScript (ES6), 175 bytes ``` f=(s,l,p=++l,t=s.replace(/^-*|-*$/g,s=>s.replace(/-/g,(c,i)=>++i%l?c:`\\`)))=>t.search` `<p?t:(f(s,l,p+l,t)+` `+` `.repeat(p)).replace(eval(`/(^|(.*)\\n)(.{${p}})/g`),` $3$2`) ; test=(s,l)=>document.write(`<pre>${s} ${l}${f(s,l)}</pre>`); test(`--- abc ---`,2); test(`----- | + | -----`,10); test(`--------------------------------------- |&&&&&& &&&&&&| |&&&&&& &&&&&&| |&&&&&& &&&&&&| |&&&&&& .\\^/. &&&&&&| |&&&&&& . | | . &&&&&&| |&&&&&& |\\| |/| &&&&&&| |&&&&&& .--' '--. &&&&&&| |&&&&&& \\ / &&&&&&| |&&&&&& > < &&&&&&| |&&&&&& '~|/~~|~~\\|~' &&&&&&| |&&&&&& | &&&&&&| |&&&&&& &&&&&&| |&&&&&& &&&&&&| ---------------------------------------`,12); test(`----------------------- |-._\`-._ :| |: _.-'_.-| | \`-._\`:| |:\`_.-' | |-------\`-' '-'-------| |------_.-. .-._------| | _.-'_.:| |:._\`-._ | |-'_.-' :| |: \`-._\`-| -----------------------`,4); test(`--------------- --------------- --------------- --------------- ---------------`,5); test(`------------------------------------------- |* * * * * |##########################| | * * * * *| | |* * * * * |##########################| | * * * * *| | |* * * * * |##########################| | * * * * *| | |* * * * * |##########################| |--------------- | |#########################################| | | |#########################################| | | |#########################################| -------------------------------------------`,0); ``` I/O is as a newline-delimited string. Output includes a leading newline; this can be removed at a cost of 3 bytes. I tried computing the output string directly but that took me... 176 bytes: ``` f= (a,l,h=a.length)=>[...Array(h+(a[0].length-1)/++l|0)].map((_,i)=>a[0].replace(/./g,(k,j)=>((k=i-(j/l|0))&&h+~k)|-~j%l?(a[k]||'')[j]||' ':'\\')) ; test=(s,l)=>document.write(`<pre>${s} ${l} ${f(s.split` `,l).join` `}</pre>`); test(`--- abc ---`,2); test(`----- | + | -----`,10); test(`--------------------------------------- |&&&&&& &&&&&&| |&&&&&& &&&&&&| |&&&&&& &&&&&&| |&&&&&& .\\^/. &&&&&&| |&&&&&& . | | . &&&&&&| |&&&&&& |\\| |/| &&&&&&| |&&&&&& .--' '--. &&&&&&| |&&&&&& \\ / &&&&&&| |&&&&&& > < &&&&&&| |&&&&&& '~|/~~|~~\\|~' &&&&&&| |&&&&&& | &&&&&&| |&&&&&& &&&&&&| |&&&&&& &&&&&&| ---------------------------------------`,12); test(`----------------------- |-._\`-._ :| |: _.-'_.-| | \`-._\`:| |:\`_.-' | |-------\`-' '-'-------| |------_.-. .-._------| | _.-'_.:| |:._\`-._ | |-'_.-' :| |: \`-._\`-| -----------------------`,4); test(`--------------- --------------- --------------- --------------- ---------------`,5); test(`------------------------------------------- |* * * * * |##########################| | * * * * *| | |* * * * * |##########################| | * * * * *| | |* * * * * |##########################| | * * * * *| | |* * * * * |##########################| |--------------- | |#########################################| | | |#########################################| | | |#########################################| -------------------------------------------`,0); ``` I/O is as a string array. [Answer] # PHP, ~~168 164 187 172 167 153 150 152~~ 149 bytes ``` for($r=count($f=file(a));$y<$r+$e/$n=$argn;$y+=print" ")for($x=0;$x+1<$e=strlen($f[0])-1;)echo("\\".$f[$z=$y-($x/$n|0)][$x++]." ")[$z%($r-1)||$x%$n]; ``` takes flag from static file `a` and wave length (minimum 1) from STDIN. Run as pipe with `php -nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/c8b959d44edb1e02b0cc4b04b084b4bf07dd051f). **breakdown** ``` for($r=count($f=file(a)); # import file, count lines $y<$r+$e/$n=$argn; # loop $y through lines $y+=print"\n") # 2. print newline for($x=0;$x+1<$e=strlen($f[0])-1;) # 1. loop $x through columns echo("\\".$f[ # 3. create string=backslash+character+space $z=$y-($x/$n|0) # 1. line no. = $y - wave offset ][$x++]." " # 2. pick character from line ) [ $z%($r-1) # if not first or last line ||$x%$n # or not last position of wave ] # then index 1 (character or space), else "\\" ; ``` ]
[Question] [ ## Background An \$n\$-bit [Gray code](https://en.wikipedia.org/wiki/Gray_code) is an ordering of \$2^n\$ binary sequences so that adjacent sequences always differ by exactly one bit. A **[Beckett-Gray code](https://en.wikipedia.org/wiki/Gray_code#Beckett%E2%80%93Gray_code)** is a special kind of Gray code. In addition to being a Gray code, it has the following characteristics: * It is cyclic: the last bit pattern has one bit difference with the first pattern. (*Your input is guaranteed to be cyclic*) * The first pattern is all zeros. (*Your input is guaranteed to start with 0*) * Whenever a bit turns from 1 to 0, that bit is the one which has been 1 for the longest time (consecutively). (*You need to verify this*) It is known that a Beckett-Gray code exists for \$n=2, 5, 6, 7, 8\$, but does not exist for \$n=3\$ and \$4\$. It is not known if any such code exists for \$n \ge 9\$, and no constructive methods to build such a code are known. One example for \$n=5\$ is as follows (copied from [this paper](https://www.sciencedirect.com/science/article/pii/S1571065307001709?via%3Dihub), 1-0 transition marked): ``` 00000, 00001, 00011, 00010, 00110, 00111, 00101, 01101, ^ ^ 01001, 01000, 01010, 01011, 11011, 10011, 10111, 10101, ^ ^ ^ ^ 10100, 00100, 01100, 11100, 11000, 11010, 10010, 10110, ^ ^ ^ ^ 11110, 01110, 01111, 11111, 11101, 11001, 10001, 10000 ^ ^ ^ ^ ^ ``` ## Task Given a cyclic Gray code starting with an all-zero pattern, determine if it is a Beckett-Gray code. You may take input as a sequence of boolean arrays (possibly transposed), a sequence of strings, or a sequence of equivalent integers. Also, you may optionally take the value of \$n\$ as the second input. For output, you can choose to 1. output truthy/falsy using your language's convention (swapping is allowed), or 2. use two distinct values to represent true (affirmative) or false (negative) respectively. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins. ## Test cases Each test case is separated with an empty line. ### Truthy (Beckett) ``` 0, 1 00, 01, 11, 10 00, 10, 11, 01 00000, 00001, 00011, 00010, 00110, 00111, 00101, 01101, 01001, 01000, 01010, 01011, 11011, 10011, 10111, 10101, 10100, 00100, 01100, 11100, 11000, 11010, 10010, 10110, 11110, 01110, 01111, 11111, 11101, 11001, 10001, 10000 00000, 01000, 01001, 00001, 00011, 01011, 01010, 11010, 11000, 10000, 10001, 11001, 11101, 01101, 01111, 01110, 00110, 00010, 10010, 10110, 10100, 10101, 00101, 00111, 10111, 10011, 11011, 11111, 11110, 11100, 01100, 00100 ``` ### Falsy (Not Beckett) ``` 000, 001, 011, 010, 110, 111, 101, 100 0000, 1000, 1100, 1110, 1111, 1101, 0101, 0001, 1001, 1011, 1010, 0010, 0011, 0111, 0110, 0100 00000, 00001, 00011, 00010, 00110, 00111, 00101, 00100, 01100, 01101, 01111, 01110, 01010, 01011, 01001, 01000, 11000, 11001, 11011, 11010, 11110, 11111, 11101, 11100, 10100, 10101, 10111, 10110, 10010, 10011, 10001, 10000 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` Λ≡½hÖ▼Ẋz- ``` [Try it online!](https://tio.run/##Zc@7DYNAEATQhrA0Uw@6HIkQOXEHdgEkRLSBIIHcPZhGFiHdrXdAm7xg9tc8u9bsO@zvcV2ard/7@Td9Xg8zq2tUuVLlppvikuHFdJdeinEx3BSfGYohphhihBsQbkCeGQ0xsyGmm@HfuxkyDLsYdv1/USOlAw "Husk – Try It Online") (Version with formatting header to allow pasting testcases: [Try it online!](https://tio.run/##PY8xCgIxEEX7nCJso0KEvGvsFUSwkgWxUUSw004PsI2VR7AVbdbeO5iLRDJ/1xR54c/8mZ9mt13ldDpuFnU1m1f1KKzH/@eyu0/2@XNN51v3at5tap/fx@UwzTnHcoIvNwZ6mMgAE4k9YnClVGpIRC3IQBxgokZTFjkMHomoBRmQHQ1Do7FFDlvrUQgUCQVEcVF49JWC@AM "Husk – Try It Online")) ### Explanation If we compute differences from each binary sequence to the next with an element-by-element subtraction, we will get a series of results each containing a single -1/+1 on the flipped bit and a 0 on all other bits. In order for this Gray code to be Beckett, the subsequence of -1 lists must be identical to the subsequence of +1 lists (except for the sign). [As noted by Unrelated String](https://codegolf.stackexchange.com/a/220488/62393) we don't need to check the last element against the first, since it will always consist of a single 1 turning into a 0. ``` Λ≡½hÖ▼Ẋz- Input: list of binary sequences Ẋ For each pair of adjacent sequences: z- subtract the first from the second element by element Ö▼ Sort by the minimum (in place): all the -1 sequences move to the beginning h Discard the last (would match the final sequence turning into the first) ½ Group the sequences into two lists of equal length (the first will contain the -1s, the second the +1s) Λ Check that the two elements ≡ Have the same distribution of zeros/nonzeros ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 35 bytes ``` {(∊⍸¨↓b)≡(∨/b←2>⌿⍵)/¯1↓⊣/⍒⍤1⊥⍨¨,⍀⍵} ``` -27 from Bubbler, -13 for pointing out the input is a Gray code, -3 for removing an excess variable, and another -11 for just being an all round golfing god. ``` {(∊⍸¨↓b)≡(∨/b←2>⌿⍵)/¯1↓⊣/⍒⍤1⊥⍨¨,⍀⍵} ⊥⍨¨,⍀⍵ ⍝ cumulative sums (time a 1 has been there) ¯1↓⊣/⍋⍤1 ⍝ index of maxima (without last element) (∨⌿b←2>/⍵)/ ⍝ filter where 1s change to 0s (∊⍸¨↓b)≡ ⍝ does that equal the locations of 1s? ``` [Try it online!](https://tio.run/##bVHNSsQwEL7vU@RWF1ya2briyYsgenX3BborVaGgWD0sIghCcYtZ/MEHEBV6EPai4E3Io8yL1LSdpElrAslkvm8mX76EZ/HgcB7Gp0eDWRwmycmsKK7W8C5D8SNzTJ@nfVy8qkTuTzF9GG7j/S@K774vV6BQzN58FE8o3gGzDxS5zNdR3CjGdREpPoolZrcoPlF8yVWA6SMuX8YHO2qd7O2PC29yfnlxPPd6EYoFsCFTPMYZ9CK2YU7lBJq8hQBhVY3qMWJBDaqbZc48bg0oB21gjg0EJnQS3I2quMN32oEDOy3batTLS8WjrmagRe9lJ6DFxA6sbzIwANdyaxZwq5pinSe2Hep3uE2UZm83jJPy19gWCzrSG3lUzatnwqb6uRYXGoe0pySK0jViOUANqef/1lmNrQDMU5uUY5M2ozHF0IxAqwBsy2xrSaPlrHHP@wM "APL (Dyalog Classic) – Try It Online") [Answer] # [J](http://jsoftware.com/), 32 25 bytes ``` [:-:/[:(|/.~/:~"1)2-/\,&0 ``` [Try it online!](https://tio.run/##pVLBSsQwEL3nK4YezBbadGaPkQVB2JMn8baKiOyyiCC49SBIf70m85K03fVmIbxmyEzee3lvY@XsgTaeLDXE5MNqHd3e323HnW99t/Orn84NnR8qqddt99hc8Vibfn/qN452nvavx4@bQ/yrXMXX7nlNK0u2iSPqMGugJxPPkH34/OqP3845a7SfLDckjc2bsGMJlbh4URZGmcvpwJQNxy9UwycKkkCLkkGLokckggkb7NAuaBBtlwScQBLEvgiYiT4FycAJlCwniCSMCLhMoBdlgGilJFwg9NV/aC2ck@S5cilQmJjMiwvMbpOZK5kXWJri36UeSj5IMrWAwKO5f9nUInlyLPkHN4PWlJLty/sJIcnvj0PaoOp0rI5RDnpZkzNVzIJYaMWdIABSsAn6ImlOjw1VYAVNcAR0YbyS/U8KMYQnG87dP8vkIq9mShrPHeYskC@zpfctX21K9uJ9c/jnKRx/AQ "J – Try It Online") Based on [Leo's excellent idea](https://codegolf.stackexchange.com/a/220491/15469) * `2-/\,&0` Adjacent elementwise row deltas, with an extra row of zeros appended first. * `(|/.~/:~"1)` Group by sorted rows and take absolute value. This puts all rows with a single 1 into one bucket, and all rows with a single -1 into another. * `[:-:/` Are those buckets equal? [Answer] # [Python 2](https://docs.python.org/2/), 62 bytes Output is via exit code: `0` if it is a Beckett-Gray Codex and `1` otherwise. ``` a=p,=[1] for x in input():0<p-x!=a.pop(0)<_;a+=[x-p]*(x>p);p=x ``` [Try it online!](https://tio.run/##dZDLboMwEEX3@YrpCmidCju88qC7bvsDKKpQ5ChIKVguVcnX07k2JOkiUkQ8r3vPjLn0p65V4@@pOWuSmwX19sJf0oM@UBAEY10aUVZyvzh2lgZqWv6Znz6MNvHOLIensn41nQnjaPe5rV/Kalia/XM4vJloa8phJIgsWO6gTU8f9Zd@t7azsDC2aXuKuXj@1reEHKtYEBu6P0ErQcoHygX/K4IyQbmglDMcrwUV/EKdGxQXJKcUOhFzPuEUTyluU/xWPC7xhjjGUGexFdoxCmHIZN62cB7eHBawgga0ZOZ7MYNZAEELmpljnZ0AAqDUsQPPYebeFxzgA2fyaNvkyoO2GRuWqWtf3/G54dwNP9abhO6Y5zP6o7prpZ4SG4PyeqXitpM79rQrtpqu9wc "Python 2 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 55 bytes ``` a=>a.every(n=>(n-=a[++i]|0)>0?m<(m=a[-n]):a[n]=i,i=m=0) ``` [Try it online!](https://tio.run/##nVPBboMwDL3nK7g1qC21d9wWdtph39AiNWK0YyoBQVRp0v6dETsJtL2tUvUSx47fezHf@qqHsq87uzXtZzWe1KhVrrPqWvU/0qhcmq3S@/W6Ln4hzeGteZXNFNiaIn3We1OoelOrRkE62mqwpR6qIVHJUcAmQSFgAsBp6f7AewTeA50DpUw/JEAPFMQAFERKQQdi2vCOy5ELkMrRA3hAD67OAd/JdQQYADwQQ/DgSAhE5jIDNQrAEokSQgSY9UWeXuZSLUaI3UXgAhEWHXDhRODCzET07FFD4rWjNzICsi9Lz4KRUebskveMHCR9tKY4iaBqyqZWdCf7wDpYBl/Hd3M/doCpOz7g344Jc0Omy2KZCXv6nzkiMwTMou69vJuqm4kT86zA0i8ImuBxOqjf7RvMs3nzWmF85zk6ZravG5lmQ3eprVwdzMGs0qzRnbSJyhM7LW35JXd7wGK9O/NR6Y463Q/Vh7Gy3CRPaZq@iPidZqe2f9dTWYi4/LI1Q3upskt7lqd44grHPw "JavaScript (Node.js) – Try It Online") Input an array of equivalent integers, output true / false. ``` a=>a.every(n=> ( n-=a[++i]|0 // compare current one with next one // if current one is the last one, we compare with 0 )>0? // > 0 means some digit changed 1->0 m<(m=a[-n]) // We use a[-n] to remember when 0->1 happened // We use m to remember where the related 0->1 // happened for last 1->0 change // If we find out related 1->0 changing earlier // than m, it is not Beckett // and we return false // Remember the where the related 0->1 mutation for current // 1->0 happened by assigning m // < 0 means some digit changed 0->1 a[n]=i // Remember where 0->1 mutation happened for digit -n // This is always truthy too ,i=m=0) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` _ƝµṂƇNṖ⁼ṬƇ ``` [Try it online!](https://tio.run/##tZQ9bsMwDIUv5OG9i3QvjKBTlyIX6JgsvkG23iBrBwOdWsD3cC6i/FgUSYlOshQChA@SbD3ykfp4324/U3qbvn6/53E/DS/zeDjtfubxOA3pbzjtj68p9T02Xc/NZerRXRkdryt5htlhnplP5Z1l3NaWwcJ0LGdYMQvLt3SMilGYjrNuw3BMx3AMowFGQ47YMRxLVuCYhWnibZnmDM1dNHdpLJ4ROMCGedcZNtxGZiNGw61SrjpJcxdXKuJxRmHcsFVTc@x8XCmtG7XzcCwaigOyKiclo3KT/E0UiRrroWZVc6oqVJuqV980exqnRq@5UvWaJ3VE49QK@sc@x0p2n6mauP/X3gsGHFUBgr691591JSJ8X3wlRtXt36ymz88 "Jelly – Try It Online") Semi-translation of [Leo's excellent Husk answer](https://codegolf.stackexchange.com/a/220491/85334). ``` _Ɲ Take the vectorized differences between adjacent elements. (The deltas builtin, I, vectorizes itself instead.) ṂƇ Filter by minimum, keeping elements containing -1. N Negate. Ṗ Remove the last element. ⁼ Is this list equal to µ the differences ṬƇ filtered to only elements containing 1? ``` `Ṭ` was originally `Ṁ` (maximum), but this produced a false negative on the first test case, as the largest element of `[-1]` is -1 rather than 0. `Ṭ` produces an array with ones at the provided indices and zeros elsewhere, but ignores non-positive indices, producing an empty array (which is falsy) if there are no positive indices. # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 13 bytes ``` ṛa+ɗ\>TẇM{ʋƝP ``` [Try it online!](https://tio.run/##tZQ9bgIxEIUPlC3eu0BuECkFDVooUtBEXCCio6HgABQoN@ACSRspErkFXMThx@OZsWchTWTJ@mR712/mzfh1Np@/pXT42L487DeTx9Hhc/W0@Fl/vz@nr9VxuRun1PeYdj2np6lHd2Z0PK/kGWaHeWY@lXeu47J2HSxMx3KGFbOwfEvHqBiF6TjrNgzHdAzHMBpgNOSIHcOxZAWOWZgm3pZpztDcRXOXxuIZgQNsmDedYcNtZDZiNNwq5aCTNHdxoCLuZxTGDVs1NcfOx5XSulE7D8eioTggq3JSMio3yd9EkaixHmpWNaeqQrWpevVNs6dxavSaK1WveVJHNE6toH/scwxk9y9VE/f/0HvBgKMqQNC3t/qzrkSE74uvxKi6/ZvV9Pkv "Jelly – Try It Online") *-2 removing `ṙ1` because the all-zeros pattern can essentially be ignored--if you flip the last bit off, you already know it's the one that's been on the longest* Takes input as an array of Boolean arrays, and outputs 0 or 1. ``` ɗ\ Cumulatively reduce the input by: ṛ right argument a vectorizing-logical-AND + the vectorized sum of the arguments. ṛa+ɗ\ This turns each 1 into how "long" it's been a 1, consecutively. ʋƝ For each pair of adjacent elements from that result: T are the indices at which > the right is less than the left ẇ a sublist of M{ the maximal indices of the left? P Take the product of the results. ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~138~~ \$\cdots\$ ~~102~~ 95 bytes Saved 13 bytes thanks to [rak1507](https://codegolf.stackexchange.com/users/95516/rak1507)!!! Saved 7 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!! ``` def f(b): r,*u=1, for x,y in zip(b,b[1:]): if x<y:u+=x^y, else:r&=u.pop(0)==x^y return r ``` [Try it online!](https://tio.run/##zVXBTsMwDL33K6wdaAsB2YCENBF@ZIxDRyomoKvaVNqY9u2j6ewktMCBE61UvdaO8/xsN/XOvmyqm@Px2ZRQZkU@T6BR550mlUC5aWCrdrCu4GNdZ4UqFjRfOhdYl7C93827C7192vWuYN5aM2/OdHdVb@oMc@0MfSxju6aC5mhNa1vQkPW@ixnOFMxotlSnt@EVafh4emJvg39xCT3CQA/pX9FDFrC/iAF5wCYKgE3EzuQBBsAVkeXEAckD9IA8QA9kL4nDgAJAD1hY9IBEauEcAxKTAGkblN0jgKHDQkoB0A@qUQRGLD1vjMCIAU2VFdGJJvX4OX@RzyuLEZioP6lQLNZX9X09ThUKGvE39mEJOCpH4F15z1hfUUPEkC2Fg7ATZSV9oS/5SMpCUBIWASUDqeK0xn@bg0m3/la/yWRMpyfucRzXBkc9/l1HR@XH8YSF8o@7JwzoaA7yxGxrs7Lm2f2GScmN7s6T1YtZvZrG2dLH7vrudpUqGBDdpHnizgKrjJwFw@9cgUQczgSAQi/Wlc3Mm3k3lVXXuVvFb26lXQ5urXYnzQDrxi0o031xgMsH2LcH2DOThdG6XR7S/PgJ "Python 3 – Try It Online") Inputs a Gray-cyclic code starting with \$0\$ as list of integers and returns `1` is it's a Beckett-Gray code or `0` otherwise. [Answer] # [JavaScript (V8)](https://v8.dev/), 106 bytes ``` a=>!a.some((c,i)=>c.map((x,j)=>n+=x<(y=(a[i+1]||a[0])[j])?!!o.push(j):x>y?1<<o.shift()-j:0,n=0)&&n-1,o=[]) ``` [Try it online!](https://tio.run/##nVNNb@MgEL3zK8ilAcVxZm6rbkhv@wv25loq8sYbW61tBVolUv97FmbwR9rbWrKfBxjmvcfQ2g/rqnMz@O3Hj1ttbtYcVjZ3/dtRqSprtDlU@ZsdlLpkbQi6jbns1dUoWzQbLD8/bQGlLtpSP61WfT68u5Nq9ePlcH3C/b7P3ampvdLb9hGyzoB@eOi2mPWmKPWt6jvnZWXd0UkjX8RuJ3@f3/3pKiCTKAQEAAy/8QWOETgGmgdaEh4kwAQ0iCPQINISjCBCwBGnIycgpWMCSIAJYl4E3pPzCHAESEAMIUEkIRCZywxUaASWSJQQJoBZ38QzyVyqxQmm6mLkAhMsKuDCiZELMxOTZ981yKQdk5ETIPuy9Gw0cpI5u5Q8IwdFPO9f9tVdRTpGZkJqaBtKo5q0ORvCglgP78tFuDBbwRoiMUiHyMy5MvNm1UyJzf2fhiJXBMzqvpr6pb3uWk/MTQNL42DUBN/bhOrdH8bcpHfHNvbx3FAvuRteG6/Wz91zt9Z0rb00B@nDr69OalcAlpvdX56q4lSR53lVUvwnxuFjjFzjWmv9U9T9WSq@xv4YPn3N11nL4dx0XtUqDoeVt38 "JavaScript (V8) – Try It Online") Accepts input as a 2-dimensional array of booleans. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` ¹≔⁰ζFI⮌A«¿›ζιF¬⁼⁻ζι⊟υ⎚≔⁺⟦⁻ιζ⟧υυ≔ιζ ``` [Try it online!](https://tio.run/##Tc5Na8MwDAbgc/srTE4KuCCddxpljB5Wwq4hB1PczWCSzh89dOy3e04iOzUYnlhS9F6@lbtMyqbUOTMGoPZl/@q9@RoBpXjkr@vkBByVD/Cp79p5DafxFgO0@Yjf/c5cBbw7rYJ28JDC5Ndl5DwFePuJynr4MGP0a1GKbrpBXIaPVisHecVOW68Fr@1s7u3XETNHGKSI7XxzI/eYNdpfSn3f4HwaKRYQgyq4RBu4RNxMFbgBGVSxlKgCK6gCK8qu8h8GbcCKdQVhBUclKpmfQaVUgCVY2f4EbIYhHe72Hw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as strings and outputs a Charcoal boolean, i.e. `-` for a Beckett-Gray code, nothing if not. Explanation: ``` ¹ ``` Start by assuming that the input is a Beckett-Gray code. ``` ≔⁰ζ ``` Initialise the previous value to 0. ``` FI⮌A« ``` Convert the input to decimal (leading zeros aren't allowed as numeric input, but the cast operator is fine with them) and loop through it in reverse order. (I hope this works, as it saves a byte over skipping the leading string of all zeros.) ``` ¿›ζι ``` If the previous value is greater than this value, ... ``` F¬⁼⁻ζι⊟υ⎚ ``` ... then if the oldest saved value is not the same as a difference then clear the canvas, as this is not a Beckett-Gray code. ``` ≔⁺⟦⁻ιζ⟧υυ ``` Otherwise prepend the difference to the queue. ``` ≔ιζ ``` Save the current value. [Answer] # [C (gcc)](https://gcc.gnu.org/), 95 bytes ``` t;r;b;e;f(a,n)int*a;{int l[n];for(b=e=r=1;--n;)t=*a^a[1],r&=*a++<*a?l[e++]=t,1:l[b++]==t;r=r;}; ``` [Try it online!](https://tio.run/##fVTbjpswEH3nK0ZIqbg4argn66X7UPUrErYixNmipuwKkBo14tebztiGsE61iGTsOTNnjsdoquVLVV2vPW/5ngt@dErWuHXTeyW/oIHTtin48bV19rnI2zzgy2XD3T73yudyGxSs/YRL33/0yqfTVvh@kfcseDht97TMkTZv@cCvby2SOcQLJQMibly4WIAPkgMhUEMOK47mERoOvl@7EqdHph8de9EtDjarn2wG9oNts3JbFy63Bsv6VdaN41qKkth60fXfV9sCSS8rBsHA30PBDWIQMQjNgHAKCGXAHUNkMjBIGWQMEvTgfsNgjSvCMSBEIEBXSJG0R3@MLswKMSzEdYjpAa2pIKURjmQRhVMqERNNakqJJylrWVcJorJUnniJP0hVPvEQH4kkfqqTSv1jdRJHIhN5HpIspWdKC2kjzaQ9NqUkH3TlLjid6ya68cgkLZEUm9k5JGEmCe@oso/qavLZecdrUZcku5@oE1K36IRT19e3fsjL032ijpi34UktnZKivkCmPzdtQ20jbWNtE21TbTPzfI0i7eo/4vXoKG73s956es9gjgcGHhh4aOChgUcGHhl4bOCxgScGnhh4auCpgWcGnrmzpojzm6h6cVBtCeS1T@9KvTq8@lG2Hv6L6qdoVby9O38Ld@fNV/wlNE1m@8jWebfJ1BzEWU8nuXwcdY4qbkonjxxhFD0OuukbKZFKfScSL/gchkajeOP/gzuE1ZR@7xfon3piJo7z82K7hhOZoHHvIwdYfoHFARbdrsH@dGzqX5fnotAZgzVc/1bHU/nSXZe//wE "C (gcc) – Try It Online") Port of my [Python answer](https://codegolf.stackexchange.com/a/220487/9481). Inputs an array of integers and its length (since length of arrays passed into functions as pointers are undefined in C) and returns `1` is it's a Beckett-Gray code or `0` otherwise. [Answer] # [R](https://www.r-project.org/), ~~73~~ 64 bytes ``` function(m,d=diff(rbind(m,0)),`-`=rowSums)any(d[-d>0,]+d[-d<0,]) ``` [Try it online!](https://tio.run/##1ZNBT4NAEIXv8yuQExtpM@/uevQPeFSTYhciB2gDVOuvRwQ6zNJqTDkZsslHNjuz773Zqs1smx3KbZPvyqiInXV5lkXVa1667peNiTerja12H4@HojZJ@Rm5p5W75/jl9hvuOjBtYZN6XSRNlR@jKk3celu/R2/2IQ7qdG/DIIyDJj02NuTnEqExdJNFhSH68znigLsFQr@Yri6CfqEvdm2R4RPCSFA07MIjjDScgCL2iEeCol65ECuCIlbE0o2lWy9dESsajGFFGAmiY06QXUhlSOXTTTUNyS1zHTPCD0lgRr7SST3PyFeAi4lBKuNC2r@5yeL/NAs@nSd7PgFz/3WyrOjUbYHrNE3n6CWpjjRN3cJsyZ9HUURa6/ROJGvS06beAs1eIrGXmszPv791@wU "R – Try It Online") Based on the idea in [Leo's Husk answer](https://codegolf.stackexchange.com/a/220491/78274). Takes input as a matrix `m` of 1s and 0s with each pattern corresponding to a row. Outputs a swapped T/F value (in the footer, the results are swapped back). ]