text
stringlengths
180
608k
[Question] [ Given `a, b, c` the length of the three sides of a triangle, say if the triangle is **right-angled** (i.e. has one angle equal to 90 degrees) or not. ## Input Three **positive** integer values **in any order** ## Output Either a specific true output (`true`, `1`, `yes`, ...) or a specific false output (`false`, `0`, `no`, ...) ## Example ``` 5, 3, 4 --> yes 3, 5, 4 --> yes 12, 37, 35 --> yes 21, 38, 50 --> no 210, 308, 250 --> no ``` ## Rules * The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). * In your submission, please state the true and the false values. * No need to handle **negative** values or **invalid edge** triple * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * If possible, please include a link to an online testing environment so other people can try out your code! * [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] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ²µSHe ``` [Try it online!](https://tio.run/##y0rNyan8///QpkNbgz1S////b6xjomMKAA "Jelly – Try It Online") Technical note: Bytes are counted in Jelly codepage. Explanation: ``` ²µSHe Main link. ² Square each number. µ With the new list, S calculate its sum, H and halve it. e Check if the result exists in the new list (squared input) ``` The problem is equivalent to being given three numbers `a, b, c`, and asking if there is a permutation such that `a² + b² = c²`. This is equivalent to whether `(a² + b² + c²) ÷ 2` is one of `a², b² or c²`, so the program just checks that. [Answer] # [Python 2](https://docs.python.org/2/), 37 bytes ``` a,b,c=sorted(input()) 1/(a*a+b*b-c*c) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P1EnSSfZtji/qCQ1RSMzr6C0RENTk8tQXyNRK1E7SStJN1krWfP//2hDIx0FY3MgNo0FAA "Python 2 – Try It Online") -2 thanks to [FlipTack](https://codegolf.stackexchange.com/users/60919/fliptack). -1 thanks to [Craig Gidney](https://codegolf.stackexchange.com/users/74349/craig-gidney). Outputs via exit code (`0` = false, `1` = true). [Answer] # Java 8, 44 bytes ``` (a,b,c)->(a*=a)+(b*=b)==(c*=c)|a+c==b|b+c==a ``` **Explanation:** [Try it here.](https://tio.run/##hc5BasMwEAXQfU7xl5KjmDitaSGoN2g2WZYuRhO1KHUkEyuB0vjs7rjOthg0DGIen3@kK61S6@Px8DVwQ12HVwrxZwGEmP35g9hjN34Bl1LjKYKVnEBmFHDTYr0V08vI6zLlwNghwmJQZJxhvXpRVFjSS@UK67S1igvL@kZLttbd3Lho2E4J7cU1knAPuqZwwElqqX0@h/j59g7SU6f9d5f9qUyXXLZyyk1UsWRVGzwYPOq/Vv8qIfW8qjYS9iRTz8BNJehZMmfdWuBaZHWn/aIffgE) ``` (a,b,c)-> // Method with three integer parameters and boolean return-type (a*=a)+(b*=b)==(c*=c) // Return if `a*a + b*b == c*c` |a+c==b // or `a*a + c*c == b*b` |b+c==a // or `b*b + c*c == a*a` // End of method (implicit / single-line return-statement) ``` [Answer] # [Python 3](https://docs.python.org/3/), 37 bytes ``` lambda*l:sum(x*x/2for x in l)**.5in l ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSvHqrg0V6NCq0LfKC2/SKFCITNPIUdTS0vPFMT4X1CUmVeikaZhqqNgrKNgoqnJBRMBck1RRQyNgIrMgdgUSdDIEChgAVSLImYAFDQAihoChf8DAA "Python 3 – Try It Online") Might run into float precision issues with large inputs. [Answer] # JavaScript (ES6), ~~43~~ ~~41~~ 40 bytes *Saved 1 byte and fixed a bug thanks to @Neil* Takes input as an array of 3 integers. Returns `true` for right-angled and `false` otherwise. ``` a=>a.some(n=>Math.hypot(...a,...a)==n*2) ``` ``` let f = a=>a.some(n=>Math.hypot(...a,...a)==n*2) console.log(f([5, 3, 4 ])) // --> yes console.log(f([3, 5, 4 ])) // --> yes console.log(f([12, 37, 35 ])) // --> yes console.log(f([21, 38, 5 ])) // --> no console.log(f([210, 308, 15])) // --> no ``` --- # Original version, 44 bytes Takes input as 3 integers. Returns `1` for right-angled and `0` otherwise. ``` (a,b,c)=>(a*=a)+(b*=b)==(c*=c)|a+c==b|b+c==a ``` ### Test cases ``` let f = (a,b,c)=>(a*=a)+(b*=b)==(c*=c)|a+c==b|b+c==a console.log(f(5, 3, 4 )) // --> yes console.log(f(3, 5, 4 )) // --> yes console.log(f(12, 37, 35 )) // --> yes console.log(f(21, 38, 5 )) // --> no console.log(f(210, 308, 15)) // --> no ``` [Answer] # [Triangular](https://github.com/aaronryank/triangular), 57 bytes I haven't seen any in this language yet and it seemed appropriate to try and do one. It took a bit ... as I had to get my head around it first and I believe this could be golfed some more. ``` ,$\:$:*/%*$"`=P:pp.0"*>/>-`:S!>/U+<U"g+..>p`S:U/U"p`!g<>/ ``` [Try it online!](https://tio.run/##KynKTMxLL81JLPr/X0clxkrFSktfVUtFKcE2wKqgQM9ASctO3043wSpY0U4/VNsmVCldW0/PriAh2CpUP1SpIEEx3cZO//9/EwVTBWMA "Triangular – Try It Online") This expands to the following triangle. ``` , $ \ : $ : * / % * $ " ` = P : p p . 0 " * > / > - ` : S ! > / U + < U " g + . . > p ` S : U / U " p ` ! g < > / ``` The path is quite convoluted, but I'll try and explain what I have done. I will skip the directional pointers. Most of the code is stack manipulation. * `$:*` Square the first input. * `$:*` Square the second input. * `S":Ug!` Test if the second value is greater than the first. + ***true*** `p"` Swap with the first. + ***false*** `p` Do Nothing. * `$:*` Square the third input. * `P":USg!` Test if the third value is greater than the greatest of the previous. + ***true*** `p+U-` sum the current stack and take away stored third value + ***false*** `p"U+-` sum the least and stored third and subtract from greatest * `0=%` test equality to zero and output result. [Answer] # Haskell (33 32 31 bytes) ``` (\x->(sum x)/2`elem`x).map(^2) ``` Original version: ``` (\x->2*maximum x==sum x).map(^2) ``` Anonymous function. Takes a list in the form [a,b,c]. Outputs True or False. First version checked if the sum of the squares was twice the square of the maximum. Second, slightly better version checks if half the sum of squares is an element in the list of squares. Edit: Accidentally counted a newline, thanks H.PWiz [Answer] # [Perl 6](http://perl6.org/), 24 bytes ``` {(*²+*²==*²)(|.sort)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkPr0CZtILa1BRKaGjV6xflFJZq1/60VihMrFZRU4q0UqtMUVOJrlRTS8osUbEwVjBVM7HQUbIwVTCEMQyMFY3MFY1MQ28hQwdhCAco0UDA2sFAwNLWz/g8A "Perl 6 – Try It Online") `*²+*²==*²` is an anonymous function that returns true if the sum of the squares of its first two arguments is equal to the square of its third argument. We pass the sorted input list to this function, flattening it into the argument list with `|`. [Answer] # [R](https://www.r-project.org/), 31 ~~26~~ ~~30~~ bytes ``` cat(sum(a<-scan()^2)/max(a)==2) ``` I don't like this one as much, but it is shorter. Sums the squares and divides by the largest square. Truthy if 2. ***Previous Version (modified with cat and with @Guiseppe's tip)*** ``` cat(!sort(scan())^2%*%c(1,1,-1)) ``` Do a sum of the sorted input with the last item negated and return the `!` not. [Try it online!](https://tio.run/##K/r/v7g0VyPRRrc4OTFPQzPOSFM/N7FCI1HT1tbov6mCsYLJfwA "R – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 68 bytes ``` ({({({})({}[()])}{}<>)<>})<>({<(({}){}<>[({})])>(){[()](<{}>)}{}<>}) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6MaBGs1gThaQzNWs7a61sZO08auFog1qm00QHIgoWgQI1bTTkOzGqROw6a61g6iuFbz/38jQwUjSwUjAwA "Brain-Flak – Try It Online") Uses the observation in user202729's answer. ``` { } for each input number {({})({}[()])}{} compute the square ( <>)<> push onto second stack ( ) push sum of squares onto first stack <> move to second stack { } for each square (({}){}<>[({})]) compute 2 * this square - sum of squares < >(){[()](<{}>)}{}<> evaluate loop iteration as 1 iff equal ( ) push 1 if any squares matched, 0 otherwise ``` [Answer] # [Python 2](https://docs.python.org/2/), 43 bytes ``` lambda a,b,c:(a*a+b*b+c*c)/2in(a*a,b*b,c*c) ``` [Try it online!](https://tio.run/##VcqxDkAwFIXh3VN0pG5CS0Mk3sRyWxESSsTi6esYBMMZ/i9nO49x9ToMbRdmXmzPgsmSa2KWnFppUyddkunJ30AAuiFs@@QPMcSGREGiTKIHUOYHSuNSYeY1rdA1nl/KYTlQQcMF "Python 2 – Try It Online") # [Python 2](https://docs.python.org/2/), ~~79~~ ~~70~~ ~~68~~ 62 bytes ``` lambda*l:any(A*A+B*B==C*C for A,B,C in zip(l,l[1:]+l,l[2:]+l)) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSvHKjGvUsNRy1HbScvJ1tZZy1khLb9IwVHHScdZITNPoSqzQCNHJyfa0CpWG0QbgWhNzf8FRZl5JQppGqY6CsY6CiaaXDABIM8URcDQCKjEHIhNEWJGhkC@BVAlspABUMwAKGgIFP0PAA "Python 2 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 49 bytes ``` n(a,b,c){return(a*=a)+(b*=b)-(c*=c)&a+c-b&b+c-a;} ``` [Try it online!](https://tio.run/##fYzBCsIwDIbvfYoycTRbJ@u0KMz5JF7adGpBq8zuNPbsNXh2BhL4830JVlfEtPIB76Pr@fEdnX9ubieWgjDSSoRp6OM4UCo6A6WwRWehElh0CLkpsbK5pWnaOfkQ@cP4IIBNjFO9BlpdRLZ255DJILTkW8l3AO1PTEz/waqh8z21XjIaRfRAX5aFmoyaFPV12Jw@ "C (gcc) – Try It Online") Improves on [Kevin Cruijssens](https://codegolf.stackexchange.com/a/146064) technique Returns 0 for a valid triangle, and a non-zero value otherwise [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` SU&0)s= ``` [Try it online!](https://tio.run/##y00syfn/PzhUzUCz2Pb//2hDIx0FY3MgNo0FAA "MATL – Try It Online") ### Explanation Consider input `[12, 37, 35]`. ``` S % Implicit input. Sort % [12, 35, 37] U % Square each entry % [144, 1225, 1369] &0) % Push last entry and remaining entries % STACK: 1369, [144, 1225] s % Sum of array % STACK: 1369, 1369 = % Isequal? Implicit display % STACK: 1 ``` [Answer] # C, ~~68~~ 54 bytes Using [user202729's solution](https://codegolf.stackexchange.com/a/146061/61405). ``` f(a,b,c){return!((a*=a)+(b*=b)-(c*=c)&&a-b+c&&a-b-c);} ``` *Thanks to @Christoph for golfing 14 bytes!* [Try it online!](https://tio.run/##fY7BCoMwDIbvPkUmTBJtwerKBuKb7NJmc3iwjOJO4rN3mdfNhYRAvo@fsH4wpzSgU14xLfE@v2I4ILqyd1ShL3tPGrnsmYrCaV/xtjRTt6YxzDC5MSBlSwZSzyinAfPj7RpyBQMaBZ8m6n5zq6BVcNrlAu0/bhoJOMtY2HUa@aC9SNC3IRw2oxalFsds0pre) # C, 85 bytes ``` #define C(a,b,c)if(a*a+b*b==c*c)return 1; f(a,b,c){C(a,b,c)C(b,c,a)C(c,a,b)return 0;} ``` [Try it online!](https://tio.run/##fcxNCoMwEIbhvacYLIUknYKxlRbEldfoJommZGEoYlfi2dMPqav@BDKBvA/jjnfnUtp1vQ@xp1YYtuxk8MIoc7DKNo1TTo799Bwj6TrzbzFvtBWYbPBist1oUS8pxIkGE6KQ2ZwRzmPElxf5vrvFnMmLiunEdJay/t4Rq39dl1hwwa3opyk1@hWLPgU6raIAKWD0ipb0Ag) [Answer] # [Julia 0.6](http://julialang.org/), 16 bytes ``` !x=x⋅x∈2x.*x ``` [Try it online!](https://tio.run/##yyrNyUw0@/9fscK24lF3a8Wjjg6jCj2tiv9p@UUKFQqZeQoa0aY6CsY6CiaxOgrRQNoUyjQ0AgqbA7EpiGdkCGRZAGUhHAMgzwDINTSN1eTidCgoyswrSdNQUtU1NClW0LVTUC2OyVPSUajQUVCs0ORKzUv5DwA "Julia 0.6 – Try It Online") ### How it works Let **x = [a, b, c]**. `x⋅x` is the dot product of **x** and itself, so it yields **a² + b² + c²**. `2x.*x` is the element-wise product of **2x** and **x**, so it yields **[2a², 2b², 2c²]**. Finally, `∈` tests if the integer **a² + b² + c²** belongs to the vector **[2a², 2b², 2c²]**, which is true iff **a² + b² + c² = 2a²** or **a² + b² + c² = 2b²** or **a² + b² + c² = 2c²**, which itself is true iff **b² + c² = a²** or **a² + c² = b²** or **a² + b² = c²**. [Answer] # J, 10 bytes *-6 bytes thanks to FrownyFrog* ``` =`+/@\:~*: ``` ## original answer ``` (+/@}:={:)@/:~*: ``` `/:` sort the squares `*:`, then check if the sum of the first two `+/@}:` equals the last `{:` [Try it online!](https://tio.run/##y/qfVqxga6VgoADE/zW09R1qrWyrrTQd9K3qtKz@a3Ip6Smop9laqSvoKNRaKaQVc3GlJmfkK6QpGCuYKJgqgICfk55CZWoxQsIUKIVFwtBIwdhcwdgUQ8LIUMHYAmwYSCIvHyFuoGBsYKFgaAqX@Q8A "J – Try It Online") [Answer] # [Triangularity](https://github.com/Mr-Xcoder/Triangularity), ~~49~~ 31 bytes ``` ...)... ..IEO.. .M)2s^. }Re+=.. ``` [Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/X09PTxOIufT0PF39QbSvplFxnB5XbVCqtq2e3v//0YZGOgrG5kBsGgsA "Triangularity – Try It Online") ### Explanation Every Triangularity program must have a triangular padding (excuse the pun). That is, the **i**th line counting from the bottom of the program must be padded with **i - 1** dots (`.`) on each side. In order to keep the dot-triangles symmetrical and aesthetically pleasant, each line must consist of **2L - 1** characters, where **L** is the number of lines in the program. Removing the characters that make up for the necessary padding, here is how the code works: ``` )IEOM)2s^}Re+= Full program. Input: STDIN, Output: STDOUT, either 1 or 0. ) Pushes a zero onto the stack. IE Evaluates the input at that index. O Sorts the ToS (Top of the Stack). M)2s^} Runs the block )2s^ on a separate stack, thus squaring each. R Reverse. e Dump the contents separately onto the stack. + Add the top two items. = Check if their sum is equal to the other entry on the stack (c^2). ``` Checking if a triangle is right-angled in Triangularity... [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` m²ø½*Ux² ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bbL4vSpVeLI&input=WzEyLDM3LDM1XQ) # [Japt](https://github.com/ETHproductions/japt) [`-x¡`](https://codegolf.meta.stackexchange.com/a/14339/), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ˲ѶUx² ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXih&code=y7LRtlV4sg&input=WzEyLDM3LDM1XQ) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 39 bytes ``` $a,$b,$c=$args|sort;$a*$a+$b*$b-eq$c*$c ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyVRRyVJRyXZViWxKL24pji/qMRaJVFLJVFbJUlLJUk3tVAlWUsl@f///0aG/40t/psCAA "PowerShell – Try It Online") Sorts the input, stores that into `$a,$b,$c` variables. Then uses Pythagorean theorem to check whether `a*a + b*b = c*c`. Output is either Boolean `True` or `False`. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 6 bytes ``` s¦ΣḥuĖ ``` [Try it online!](https://tio.run/##ASEA3v9nYWlh//9zwqbOo@G4pXXElv9l4oaR/1sxMiAzNyAzNV0 "Gaia – Try It Online") * `s¦` - **s**quare each. * `Σ` - sum. * `ḥ` - **ḥ**alve. * `u` - sq**u**are root. * `Ė` - contains? Check if the square root is in the input. [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 10 bytes ``` §²2^r]‘\+e ``` ## Explained ``` §²2^r]‘\+e § # Sort the input list ²2^r # Square each element in the list. ] # Duplicate it on the reg stack. ‘ # Pop the top (largest) element off it \+ # Swap it, sum the rest of the list. e # Are they equal? ``` [Try it online!](https://tio.run/##Kyooyk/P0zX6r2FopGBsrmBsqvn/0PJDm4ziimIfNcyI0U79/x8A "RProgN 2 – Try It Online") [Answer] # [Racket](https://racket-lang.org/), ~~64~~ 60 bytes ``` (λ(a b c)(=(+(* a a)(* b b)(* c c))(*(expt(max a b c)2)2))) ``` [Try it online!](https://tio.run/##bYw7DsIwEET7nGIkmlloiDsKDrM2GxQRLGQZkbtxh1zJbEgbTfE0mk/R9LDaDpPmO8rfdLzZMGbD8M5oXL5URCThlSceoVBxRMQVyQMnbX5VPnXG1g0ukSYdP2WsNmVwfQtnhAtCL3tBj@Cj9gM "Racket – Try It Online") ### How it works Tests if `a^2 + b^2 + c^2` is equal to twice the largest of `a^2`, `b^2`, and `c^2`. Returns `#t` for right triangles and `#f` for all other inputs. --- * *-4 bytes thanks to @xnor's suggestion to use `expt`.* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` n{R`+Q ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/rzooQTvw//9oQx0gjAUA "05AB1E – Try It Online") [Answer] # Ruby, 31 bytes ``` ->a{a,b,c=*a.sort;a*a+b*b==c*c} ``` Takes input as a list of 3 integers. Uses some ideas from other solutions. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 68 bytes ``` a->{java.util.Arrays.sort(a);return a[0]*a[0]+a[1]*a[1]==a[2]*a[2];} ``` [Try it online!](https://tio.run/##lY7BasMwDIbveQodnS01cbqyQUihD7Beegw5qKk7nLlysJ2OEvLsmVK2eyuQEJK@X3@HV1y5XlN3@p5biyHAJxoaDUXtz9hq2I9H56xGglbwtG4A03IKEaNpYQ8EFcy42o4dK8khGit33uMtyOB8FHzrdRw8AdZ587KUV6zV0qmmqrAulrZoymkuk344Whb90746c4ILmxGH6A193T@PCXAcbiHqi3RDlD2voiVBshWkf@BucVxn8JbBZkrT8mFgw8zjgCoyWL9zPvGkUHz/8ZSvQuXM5Aypf2pKpvkX "Java (OpenJDK 8) – Try It Online") [Answer] # TI-Basic, ~~13~~ ~~11~~ 10 bytes ``` max(Ans=R►Pr(min(Ans),median(Ans ``` Now works for inputs in any order and is shorter as well. Another -1 thanks to @MishaLavrov [Answer] # CJam, 9 ``` q~$W%~mh= ``` [Try it online](http://cjam.aditsu.net/#code=q%7E%24W%25%7Emh%3D&input=%5B3%205%204%5D) **Explanation:** ``` q~ read and evaluate the input (given as an array) $W% sort and reverse the array ~ dump the array on the stack mh get the hypotenuse of a right triangle with the given 2 short sides = compare with the longer side ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~29~~ 24 bytes ``` f(v)=v~==2*vecmax(v)^2 ``` [Try it online!](https://tio.run/##K0gsytRNL/j/P02jTNO2TKusztbWSKssNTk3sQIoEmf0v6AoM69EI00j2ljHRMc0VlOTCy5iqgMUwxAxBor8BwA "Pari/GP – Try It Online") Saved five bytes by an obvious change from `norml2(v)` to `v*v~`. Inspired by other answers. Here `v` must be a row vector ~~or a column vector~~ with three coordinates. Example of use: `f([3,4,5])` Of course, you get rational side lengths for free, for example `f([29/6, 10/3, 7/2])`. If I do not count the `f(v)=` part, that is 19 bytes. The first part can also be written `v->` (total 22 bytes). **Explanation:** If the three coordinates of `v` are `x`, `y` and `z`, then the product of `v` and its transpose `v~` gives a scalar `x^2+y^2+^z^2`, and we need to check if that is equal to twice the square of the maximum of the coordinates `x`, `y`, `z`. **Extra:** The same `f` tests for a [Pythagorean quadruple](https://en.wikipedia.org/wiki/Pythagorean_quadruple) if your input vector has four coordinates, and so on. [Answer] # [Ohm v2](https://github.com/MiningPotatoes/Ohm), ~~8~~ 6 bytes ``` ²DS)Σε ``` [Try it online!](https://tio.run/##y8/INfr//9Aml2DNc4vPbf3/P9rQSEfB2ByITWMB "Ohm v2 – Try It Online") [Answer] # Common Lisp, 64 bytes ``` (apply(lambda(x y z)(=(+(* x x)(* y y))(* z z)))(sort(read)#'<)) ``` [Try it online!](https://tio.run/##Fck7DoAgEEXRrUxi4Rst1U4XM34KEtQJUDBsHrE6N7mHd1ErNLgnVYiqN3i591OQyagwNowYKFPmhpHxb2mnRXxDQrjk5K5fmStXLDTTxB8) As usual in Common Lisp, true is `T` and false is `NIL`. ]
[Question] [ Inspired by [this SO question](https://stackoverflow.com/q/34041614) As input you will be given a non-empty list of integers, where the first value is guaranteed to be non-zero. To construct the output, walk from the start of the list, outputting each non-zero value along the way. When you encounter a zero, instead repeat the value you most recently added to the output. You may write a program or function, and have input/output take any convenient format which does not encode extra information, as long as is still an ordered sequence of integers. If outputting from a program, you may print a trailing newline. Except for this trailing newline, your output should be an acceptable input for your submission. The shortest code in bytes wins. ## Test Cases ``` [1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9] -> [1, 1, 2, 2, 7, 7, 7, 7, 5, 5, 5, 5, 9] [1, 0, 0, 0, 0, 0] -> [1, 1, 1, 1, 1, 1] [-1, 0, 5, 0, 0, -7] -> [-1, -1, 5, 5, 5, -7] [23, 0, 0, -42, 0, 0, 0] -> [23, 23, 23, -42, -42, -42, -42] [1, 2, 3, 4] -> [1, 2, 3, 4] [-1234] -> [-1234] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` o@\ ``` [Try it online!](http://jelly.tryitonline.net/#code=b0Bc&input=&args=WzIzLCAwLCAwLCAtNDIsIDAsIDAsIDBd) ### How it works ``` o Take the logical OR of its arguments. @ Reverse the argument order of the link to the left. \ Do a cumulative reduce, using the link to the left. ``` [Answer] # Pyth, 6 bytes ``` mJ|dJQ ``` [Demonstration](https://pyth.herokuapp.com/?code=mJ%7CdJQ&input=%5B1%2C+0%2C+2%2C+0%2C+7%2C+7%2C+7%2C+0%2C+5%2C+0%2C+0%2C+0%2C+9%5D&debug=0) `m ... Q` means this maps a function over the input. The function being mapped is `J|dJ`. That means `J = d or J` in Python, since `J` is implicity assigned to the following value on first use. Unlike Python, assignment expressions return the value assigned in Pyth, so the map returns each successive value of `J`, as desired. [Answer] ## Ruby, 25 bytes ``` ->a{a.map{|x|x==0?a:a=x}} ``` This is actually really evil. Specifically, the snippet `x==0 ? a : (a=x)`. If I had used any other variable name for `a` (the previous nonzero value)—let's say `y`—I would have to declare it outside the `map` (because `y=x` would only have a scope of inside that single `map` iteration). That would use four chars more (`y=0;`). But if I use the variable name `a`... yep, you guessed it. I'm actually reassigning to *the argument that we got as input* (the original array). `map` doesn't care because it only cares about the *original* value of the thing its being called on, so this actually works. [Answer] ## Haskell, 21 bytes ``` a%0=a a%b=b scanl1(%) ``` The (anonymous) function we make is in the last line. The first two lines define a helper function. ``` scanl1(%) [1,0,2,0,7,7,7,0,5,0,0,0,9] [1,1,2,2,7,7,7,7,5,5,5,5,9] ``` The binary function `%` outputs the second argument, unless it's `0`, in which case it outputs the first argument instead. `scanl1` iterates this function over the input list, outputting the result at each step. [Answer] ## J, 8 bytes ``` {:@-.&0\ ``` This is a unary function, invoked as follows. ``` f =: {:@-.&0\ f 2 0 0 4 0 _1 0 2 2 2 4 4 _1 _1 ``` ## Explanation ``` {:@-.&0\ \ Map over non-empty prefixes: -. remove all occurrences &0 of the number 0 and {:@ take the last element. ``` [Answer] # Sed, 8 ``` /^0$/g h ``` * `/^0$/` matches a zero on a line - if so `g` copies the hold space to the pattern space * `h` copies the pattern space to the hold space Integers are newline separated. e.g: ``` $ printf -- "-1\n0\n5\n0\n0\n7\n" | sed -f zerocover.sed -1 -1 5 5 5 7 $ ``` [Answer] # Javascript ES6, 19 bytes ``` s=>s.map(i=>p=i||p) ``` Straightforward solution, loop through input, assign `p` to current element `i` or to `p` if `i` is `0` and output it. Example run (assigning anonymous function to `f`): ``` >> f([1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9]) << Array [1, 1, 2, 2, 7, 7, 7, 7, 5, 5, 5, 5, 9] ``` [Answer] ## Dyalog APL, ~~12~~ ~~10~~ 9 bytes ``` (⊃0~⍨,⍨)\ ``` Inspired by @Zgarb's J answer. ``` (⊃0~⍨,⍨)\ Monadic function: \ Cumulative reduce by (⊃0~⍨,⍨) the dyadic function: ,⍨ Arguments concatenated in reverse order 0~⍨ With zeroes removed ⊃ Take the first element ``` Try it [here](http://tryapl.org/?a=%28%7B%u2283%u233D%u2375%7E0%7D%A8%2C%5C%29%20%AF1%200%205%200%200%20%AF7&run). [Answer] ## [Retina](https://github.com/mbuettner/retina), 15 bytes ``` +`(\S+) 0 $1 $1 ``` [Try it online.](http://retina.tryitonline.net/#code=K2AoXFMrKSAwCiQxICQx&input=MSAwIDIgMCA3IDcgNyAwIDUgMCAwIDAgOSAxIDAgMCAwIDAgMCAtMSAwIDUgMCAwIC03IDIzIDAgMCAtNDIgMCAwIDAgMSAyIDMgNCAtMTIzNA) Repeatedly replaces a number followed by a zero with twice that number until the string stops changing. [Answer] ## Java, 78 ``` int[]f(int[]a){for(int i=-1,b=i;++i<a.length;a[i]=b=a[i]==0?b:a[i]);return a;} ``` Here we just keep track of the last non-zero and shove it in where appropriate. Seems like the obvious way to do it. [Answer] ## Python 2, 29 bytes ``` while 1:x=input()or x;print x ``` Takes input as numbers given one per line, and outputs in the same format. Terminates with error after finishing. Using the short-circuiting nature of `or`, the variable `x` is updated to the input, unless that input is 0 (which is Falsey), in which case it remains its current value. Then, `x` is printed. Note that since the first list value is nonzero, `x` is not evaluated in the right hand side before it is assigned. [Answer] ## Pyth, 8 bytes ``` t.u|YNQ0 ``` Uses `.u` (cumulative reduce) by `|` (Python's `or`), with base case 0. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 54 bytes ``` [X,0|T]+[X,X|Y]:-[X|T]+[X|Y]. [X|T]+[X|Y]:-T+Y. []+[]. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/PzpCx6AmJFYbSEfURMZa6UZHQLhAjh4XEsdKN0Q7EigC5MbqAfUZ6hgAoREQGwKhrlmsdoQeAA "Prolog (SWI) – Try It Online") ## Explanation I'm really happy with this answer. First we say that the empty list is the solution of the empty list: ``` []+[]. ``` Then we say that `[X,X|Y]` is the solution of `[X,0|T]`, if by removing the second entry of each of the remaining solutions. ``` [X,0|T]+[X,X|Y]:-[X|T]+[X|Y]. ``` Lastly we say that any thing left over is valid if they start with the same value and the rest of the the two lists match each other. If that explanation isn't working for you here is the code translated into Haskell: ``` g(a:0:x)=a:g(a:x) g(a:x)=a:g x g x=x ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P10j0crAqkLTNtEKxKzQ5IJQIL5CBRcQ21b8z03MzLMtKMrMK1FJjzbUMdIxAEPj2P8A "Haskell – Try It Online") [Answer] # Mathematica 38 bytes Pattern matching repeatedly replaces `...a,0,...` with `...a,a...` ``` #//.{b___,a_/;a!=0,0,e___}:>{b,a,a,e}& ``` [Answer] # Matlab, 41 ~~46~~ bytes This is inspired in my [original answer](https://stackoverflow.com/a/34043697/2586922), with the following differences: 1. Use logical indexing instead of `nonzeros`. 2. Double logical negation instead of comparing with `0`. 3. The transpose can be removed, as the output format is flexible 4. Removing an intermediate variable. Thanks to [Tom Carpenter](https://codegolf.stackexchange.com/questions/65770/cover-up-zeroes-in-a-list/65797#comment159390_65797) for item 4, and for his suggestion to use a program instead of a function; together these allowed a reduction of 5 bytes. ``` x=input('');u=x(~~x);disp(u(cumsum(~~x))) ``` Example: ``` >> x=input('');u=x(~~x);disp(u(cumsum(~~x))) [4 0 3 2 0 5 6 0] 4 4 3 2 2 5 6 6 ``` [Answer] # [Gol><>](https://github.com/Sp3000/Golfish/wiki), 8 bytes ``` IE;:Z~:N ``` Input and output are newline separated numbers. Explanation: ``` I push next integer to stack E; halt if EOF :Z~ remove top stack element if 0 :N print top stack element while also keeping it on the stack wrap around code implicitly ``` [Try it online here.](https://golfish.herokuapp.com/#) [Answer] # Japt, ~~8~~ 7 bytes ``` N£U=XªU ``` Pretty simple. Takes input separated by commas. [Try it online!](http://ethproductions.github.io/japt?v=master&code=TqNVPViqVQ==&input=MSwwLDIsMCw3LDcsNywwLDUsMCwwLDAsOQ==) ### Ungolfed and explanation ``` N£ U=Xª U NmXYZ{U=X||U // Implicit: N = input, U = first item NmXYZ{ // Map each item X to: U=Z||U // Set U to (X || U) and return. // If X is non-zero, this sets U to X. // Otherwise, this leaves U as the last non-zero we've encountered. // Implicit: output last expression ``` **4-byte** version: ``` Nå!ª ``` Explanation: ``` Nå!ª Nå!|| NåXY{Y||X} // Implicit: N = input, U = first item NåXY{ // Cumulatively reduce N; take each item Y and prev value X, Y||X} // and return Y if it is non-zero; return X otherwise. // Implicit: output last expression ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=TuUhqg==&input=MSwwLDIsMCw3LDcsNywwLDUsMCwwLDAsOQ==) [Answer] # GolfScript, 10 bytes ``` ~{1$or}*]` ``` This program takes input from stdin, in the form of a GolfScript array literal (e.g. `[1 0 2 0]`), and writes its output to stdout in the same format (e.g. `[1 1 2 2]`). [Try it online.](http://golfscript.apphb.com/?c=IyBDYW5uZWQgaW5wdXQ6CjsiWzEgMiAwIDMgMCAwIDQgNSAtMSAtMiAwIC0xMjM0IDBdIgoKIyBQcm9ncmFtOgp%2BezEkb3J9Kl1g) A function (taking and returning a GolfScript array) would be three bytes longer, due to the need to wrap it in a block and assign it to a symbol: ``` {[{1$or}*]}:f ``` Of course, if only the function *body* (i.e. `[{1$or}*]`) is counted, then I can actually save one byte compared to the stand-alone program. [Answer] ## [Minkolang 0.14](https://github.com/elendiastarman/Minkolang), ~~12~~ 10 bytes ``` $I?.nd?xdN ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=%24I%3F%2End%3FxdN&input=-1%2C%200%2C%205%2C%200%2C%200%2C%20-7) Input can be given as in the question, but **without brackets**. ### Explanation ``` $I Push the length of the input on the stack. ?. If this is 0, stop. Otherwise, continue. nd Take number from input and duplicate it. ?x If this number is 0, dump the top of stack. dN Duplicate the top of stack and output as number ``` Minkolang is toroidal, so this loops around to the beginning and keeps going until it hits the `.` and stops. [Answer] # 𝔼𝕊𝕄𝕚𝕟, 7 chars / 12 bytes ``` ïⓜa=$⋎a ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=%5B1%2C%200%2C%202%2C%200%2C%207%2C%207%2C%207%2C%200%2C%205%2C%200%2C%200%2C%200%2C%209%5D&code=%C3%AF%E2%93%9Ca%3D%24%E2%8B%8Ea)` ## Explanation ``` // implicit: ï = input array ïⓜ // map over input a= // set a to: $ // (if element is truthy (not 0)) element itself ⋎a // else whatever a was set to before // implicit output ``` [Answer] # [O](https://github.com/phase/o), 31 bytes ``` [[I',T%T/]{n#}d]{n.{:V}{;V}?}d] ``` This takes an input separated by `,` and outputs the same list in `[]`. ``` 7,0,3,0,0,2,-50,0,0 => [7,7,3,3,3,2,-50,-50,-50] ``` Explanation: ``` [ ] Put result into array [I',T%T/]{n#}d] Format input into array of numbers {n.{:V}{;V}?}d Fill in zeros (see below for how this works) ``` # 17 bytes ``` I~]{n.{:V}{;V}?}d ``` Takes input as a list of numbers separated by spaces using postfix notation and can only handle single digit hexadecimal numbers. Negatives are postfixed with `_`. ``` 5 4 0 0 1 0 0 => 5 4 4 4 1 1 1 A 3 0 0 1 B 0 => 10 3 3 3 1 11 11 67* 0 0 78* 0 => 42 42 42 56 56 67*_ 4 3_ 0 0 => -42 4 -3 -3 -3 ``` Explanation: ``` I~] Puts input into integer array { }d For each number in the input n.{;V}{:V}? If the number is 0, push V If not, set V to the number ``` [Answer] ## R, 36 bytes ``` function(x)x[cummax(seq(a=x)*(!!x))] ``` Let's see how this works using `x=` ``` c(1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9) ``` as an example. Here, `!!x` will be the logical (True/False) vector: ``` c(T, F, T, F, T, T, T, F, T, F, F, F, T) ``` Also, `seq(a=x)` gives a vector of indices as long as `x`: ``` c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13) ``` We multiply both, giving: ``` c(1, 0, 3, 0, 5, 6, 7, 0, 9, 0, 0, 0, 13) ``` We take the cumulative maximum: ``` c(1, 1, 3, 3, 5, 6, 7, 7, 9, 9, 9, 9, 13) ``` Finally, we use that last vector as the indices to extract from `x`: ``` c(1, 1, 2, 2, 7, 7, 7, 7, 5, 5, 5, 5, 9) ``` [Answer] # R, ~~39~~ ~~37~~ 33 bytes ``` function(x)zoo::na.locf(x*(x|NA)) ``` This is an unnamed function that accepts a vector and returns a vector. It requires the `zoo` package to be installed. Note that it doesn't require `zoo` to be attached to the namespace since we're referencing it directly. The name for this operation in the world of statistics is LOCF imputation, where LOCF stands for Last Observation Carried Forward. To accomplish this in R, we can use `na.locf` from the `zoo` package, which replaces `NA` values with the last known non-`NA` value. We just have to replace the zeros in the input with `NA`s first. To do that, we use `x|NA`, which will be `TRUE` when `x != 0` and `NA` otherwise. If we multiply this by `x`, the `TRUE` elements are replaced by the corresponding elements of `x` and the `NA`s stay `NA`, thereby replacing all zeros. This is then passed to `zoo::na.locf` which gives us exactly what we want. Saved 4 bytes thanks to flodel! [Answer] # Rust, 100 bytes ``` fn f(i:&[i64])->Vec<i64>{let(mut o,mut l)=(i.to_vec(),0); for x in&mut o{if *x==0{*x=l}else{l=*x}};o} ``` Stumbled across this challenge, thought I'd try it in my favorite language. Tried using `[T]::windows_mut()` at first, before finding out that [it doesn't exist](https://github.com/rust-lang/rust/issues/23783). And it might've actually been longer than this. Anyway, it turns out that golfed Rust is very ugly and very not-competitive (especially with all those goshdarned esoterics!)1 The newline isn't included in the bytecount; it's only there so you don't have to scroll sideways. It doesn't change the meaning of the code. Ungolfed: ``` fn cover_zeroes(input: &[i64]) -> Vec<i64> { let mut output = input.to_vec(); let mut last_nonzero = 0; for item in &mut output { if *item == 0 { *item = last_nonzero; } else { last_nonzero = *item; } } output } ``` [1] At least it's not as bad as Java. [Answer] # [Husk](https://github.com/barbuz/Husk), 2 bytes ``` G| ``` [Try it online!](https://tio.run/##yygtzv5/aFtueW5w6qOmxv/uNf///4@ONtQx0DECYnMwNNAxBWIQtIzVActBIZCnawiX1jUH8o2MIWwTI7gSQ6BRxjomYMVGxiaxsQA "Husk – Try It Online") scan from left with or. [Answer] # [Milky Way 1.2.1](https://github.com/zachgates7/Milky-Way), 33 bytes ``` :y;=<:&{~<?{0b_^;:3≤_;}1-}^<Ω! ``` This assumes that the list of integers is solely on the stack. --- ### Explanation ``` : : : : # duplicate the TOS y # push the length of the TOS ; ; ; # swap the TOS and STOS = # dump a list to the stack < < < < # rotate the stack leftward &{~ } # while loop ?{ _ _ } # if-else statements 0 3 1 # push an integer b # == on the TOS and STOS ^ ^ # pop the TOS without output ≤ # rotate the top N stack elements leftward - # subtract the TOS from the STOS Ω # push a list made of the top N stack elements ! # output the TOS ``` [Answer] # Julia, 33 bytes ``` g(x,a=0)=[(i!=0&&(a=i);a)for i=x] ``` This is a function `g` that accepts an array and returns an array. We start a temporary variable `a` at 0. For each element `i` of the input, if `i` isn't 0 then we assign `a` to `i`. If `i` is 0, `a` doesn't change at that iteration. We use `a` as the value in that position in the output array. [Answer] ## [Perl 6](http://perl6.org), 21 bytes ``` *.map: {$_=($^a||$_)} ``` usage: ``` # store the Whatever lambda as a subroutine # just so that we don't have to repeat it my &code = *.map: {$_=($^a||$_)} say code [1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9]; # (1 1 2 2 7 7 7 7 5 5 5 5 9) say [-1, 0, 5, 0, 0, -7].&code; # (-1 -1 5 5 5 -7) say ([1, 0, 0, 0, 0, 0],[-1, 0, 5, 0, 0, -7]).map: &code; # ((1 1 1 1 1 1) (-1 -1 5 5 5 -7)) ``` [Answer] # CJam, 11 bytes ``` q~{1$e|}*]p ``` [Try it online.](http://cjam.aditsu.net/#code=q~%7B1%24e%7C%7D*%5Dp&input=%5B23%200%200%20-42%200%200%200%5D) ### How it works ``` q~ Read and evaluate all input. { }* Fold; for each element but the first: 1$e| Copy the previous element and take their logical OR. ]p Wrap all results in an array and print it. ``` [Answer] ## Powershell, 32 bytes ``` param($x)$x|%{($t=($_,$t)[!$_])} ``` `$x|%{...}` does the script block for each element in `$x`. `($_,$t)` is an array of current element and `$t`, and `[!$_]` means that we use `!$_` to index into the array. The index will be `0` (false) for non-zero elements and `1` (true) when current element is zero, so `$t` will be either current element or `$t`. The parentheses surround the assignment expression so its value is emitted. Without parantheses it would be just a "quiet" assignment to `$t`. ]
[Question] [ ## The challenge: Write a very short program that, when compiled, creates the most amount of compiler warnings and errors. It can be written in any programming language. ## Scoring: The score is determined by this equation: `errors_and_warnings_length/code_length`. Highest score wins. ## Example: The C# program `class` is 5 chars long and generates 3 warnings, which is a score of (1/5)\*3 = 0.6. ## EDIT: Because of some confusion, programs have to be at least 1 char long. Otherwise it would get a score of infinity. [Answer] ## GCC, score 2200 / 36 ≈ 4.5 × 1058 ``` #include __FILE__ #include __FILE__ ``` I have not actually finished compiling this code, but based on testing and simple mathematics, it should produce a total of 2200 `#include nested too deeply` errors. Of course, the program is trivially extensible. Adding a third line brings the score up to **3200 / 54 ≈ 4.9 × 1093**. Four lines give **4200 / 72 ≈ 3.6 × 10118**, and so on. [Answer] ## C, 0 characters - Score=(1/0)\*1=Infinity generates 1 error: ``` /usr/lib/gcc/i686-pc-linux-gnu/4.7.0/../../../crt1.o: In function `_start': (.text+0x18): undefined reference to `main' collect2: error: ld returned 1 exit status ``` Note: <http://ideone.com/xdoJyA> [Answer] ## GCC, score 5586.6 (and more if needed) 179 chars, 1000003 warnings/errors (using `-Wall`) ``` #define E a,a,a,a,a,a,a,a,a,a #define D E,E,E,E,E,E,E,E,E,E #define C D,D,D,D,D,D,D,D,D,D #define B C,C,C,C,C,C,C,C,C,C #define A B,B,B,B,B,B,B,B,B,B _(){A,A,A,A,A,A,A,A,A,A} ``` This can be extended arbitrarily, of course. For example, using 10 `#define`s instead of 5 and a length of 20 "calls" instead of 10 would lead to a score of about (20\*\*10)/(179\*4) = 14301675977.65 (and would take quite some time to run ;) [Answer] ## GCC twice, 86 22 chars, 1898 errors+warnings on my system. I'm sure this approach can be much improved, by choosing longer files with shorter names. ``` #include</usr/bin/gcc> ``` [Answer] ## HQ9++, 1 (limit of (n+29)/n) The following emits the warning `Warning: this is not a quine` for each Q in the code. ``` QQQQQ...Q Warning: this is not a quine ``` Small is good, right? Hmm... [Answer] ## C, .727 11 chars, 5 errors, 3 warnings, (1/11)\*8 = .727273 ``` m(;){@,x}2 ``` ```` cc -g -Wall er.c -o er er.c:1: error: expected declaration specifiers or '...' before ';' token er.c:1: warning: return type defaults to 'int' er.c: In function 'm': er.c:1: error: stray '@' in program er.c:1: error: expected expression before ',' token er.c:1: error: 'x' undeclared (first use in this function) er.c:1: error: (Each undeclared identifier is reported only once er.c:1: error: for each function it appears in.) er.c:1: warning: left-hand operand of comma expression has no effect er.c:1: warning: control reaches end of non-void function er.c: At top level: er.c:1: error: expected identifier or '(' before numeric constant ```` [Answer] ## NASM, score 63/40 \* 2^32 ≈ 2.905 \* 10^19 ``` %rep 1<<32 %rep 1<<32 ! %endrep %endrep ``` Will output `c.asm:3: error: label or instruction expected at start of line` 2^64 times. Again this is easily extensible to much bigger outputs. [Answer] **C++98 (211 bytes)** g++-5 (Ubuntu 5.2.1-23ubuntu1~12.04) 5.2.1 0151031 I wanted to see how well I could do in C++ without using the preprocessor at all. This program produces 2,139,390,572 bytes of output, most of which is a single error message. ``` template<int i,class S,class T>struct R{typedef R<i,typename R<i-1,S,S>::D,typename R<i-1,S,S>::D>D;};template<class S,class T>struct R<0,S,T>{typedef S D;};void f(){R<27,float,R<24,int*const*,int>::D>::D&E=4;} me@Basement:~/src/junk$ ls -l a.C -rw-rw-r-- 1 me me 211 Apr 27 21:44 a.C me@Basement:~/src/junk$ g++-5 a.C -fmax-errors=1 2>a.C.errors.txt me@Basement:~/src/junk$ ls -l a.C.errors.txt -rw-rw-r-- 1 me me 2139390572 Apr 27 22:01 a.C.errors.txt ``` Ungolfed: ``` template <int i, class S, class T> struct R { typedef R<i, typename R<i-1,S,S>::D, typename R<i-1,S,S>::D> D; }; template <class S, class T> struct R<0, S, T> { typedef S D; }; void f() { R<27, float, R<24, int*const*, int>::D>::D &E = 4; } ``` This program works by defining a recursive struct template R which holds a typedef D containing two copies of R. This results in an type name which grows exponentially, which is printed out in full in the error message. Unfortunately, g++ seems to choke while attempting to print an error message longer than (1<<31) bytes. 2,139,390,572 bytes was the closest I could get to the limit without going over. I'm curious if anyone can adjust the recursion limits and parameter types `27, float, 24, int*const*` to get closer to the limit (or find a compiler which can print an even longer error message). Excerpts from the error message: ``` a.C: In function ‘void f()’: a.C:1:208: error: invalid initialization of non-const reference of type ‘R<27, float, R<24, R<23, R<22, R<21, R<20, R<19, R<18, R<17, R<16, R<15, R<14, R<13, R<12, R<11, R<10, R<9, R<8, R<7, R<6, R<5, R<4, R<3, R<2, R<1, int* const*, int* const*>, R<1, int* const*, int* const*> >, R<2, R<1, int* const*, int* const*>, R<1, int* const*, int* const*> > >, R<3, R<2, R<1, int* const*, int* const*>, R<1, int* const*, int* const*> >, R<2, R<1, int* const*, int* const*>, R<1, int* const*, int* const*> > > >, R<4, R<3, R<2, R<1, int* const*, int* const*>, R<1, ... int* const*, int* const*> > > > > > > > > > > > > > > > > > > > > > > > >::D& {aka R<27, R<26, R<25, R<24, R<23, R<22, R<21, R<20, R<19, R<18, R<17, R<16, R<15, R<14, R<13, R<12, R<11, R<10, R<9, R<8, R<7, R<6, R<5, R<4, R<3, R<2, R<1, float, float>, R<1, float, float> >, R<2, R<1, float, float>, R<1, float, float> > >, R<3, R<2, R<1, float, float>, R<1, float, float> >, R<2, R<1, float, float>, R<1, float, float> > > >, R<4, ... , R<1, float, float>, R<1, float, float> > >, R<3, R<2, R<1, float, float>, R<1, float, float> >, R<2, R<1, float, float>, R<1, float, float> > > > > > > > > > > > > > > > > > > > > > > > > > >&}’ from an rvalue of type ‘int’ template<int i,class S,class T>struct R{typedef R<i,typename R<i-1,S,S>::D,typename R<i-1,S,S>::D>D;};template<class S,class T>struct R<0,S,T>{typedef S D;};void f(){R<27,float,R<24,int*const*,int>::D>::D&E=4;} ^ compilation terminated due to -fmax-errors=1. ``` 2,139,390,572 bytes / 211 bytes = 10,139,291.8 [Answer] ## Rust, 206 chars, 220+2 errors, score 5090, tunable. ``` macro_rules! e { ($e:expr, $($es:expr),+) => { compile_error!(stringify!($e, $($es),+)); e! { $(a + $es),+ } e! { $(b + $es),+ } }; } e! {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} ``` And you can actually see it finish compilation, in about 3 minutes for me: ``` error: could not compile `a` due to 1048578 previous errors ``` Like the C `#include __FILE__` example above, it is tunable, but * if you want to go beyond 2256, you need to set `#![recursion_limit = "9999999"]` * rustc will OOM long before you can reach that * longer expressions mean slower execution, so the more errors you want, the slower they will be printed What I actually wanted to do is implement the Péter's variant of the Ackermann function. But I don't quite grok macros well enough to do that with the unary encoding. Anyone help? [Answer] # SmileBASIC, 1/1 = 1 ``` A ``` Generates the error `Syntax Error in 0:1` ]
[Question] [ Your task, if you wish to accept it, is to write a program that outputs a positive integer (higher than 0). If the source code is duplicated the output must remain the same. The tricky part is that if the source code is typed three times **(triplicated?)** the output will be multiplied by 3. # Rules * You must build a **full program**. That is, your output has to be printed to STDOUT. * The initial source must be at least 1 byte long. * Both the integers must be in base 10 (outputting them in any other base or with scientific notation is forbidden). * Your program must *not* take input (or have an unused, empty input). * Outputting the integers with trailing / leading spaces is allowed. * Leading Zeroes are allowed only if the numbers of digits is consistent eg: 001 - 001 - 003 or 004 - 004 - 012 * You may not assume a newline between copies of your source. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest (original) code *in each language* wins! * **[Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)** apply. ### Example Let's say your source code is `Abc` and its corresponding output is `4`. If I write `AbcAbc` instead and run it, the output must still be `4`. However if I write `AbcAbcAbc` and run it, the output must be `12`. --- ~~Shamelessly stolen~~ Derived from Mr. Xcoder's [challenge](https://codegolf.stackexchange.com/questions/132558/i-double-the-source-you-double-the-output) [Answer] ## [Wumpus](https://github.com/m-ender/wumpus), 6 bytes ``` {~) @O ``` [Try it online!](https://tio.run/##Ky/NLSgt/v@/uk6Ty8H//38A "Wumpus – Try It Online") [Try it doubled!](https://tio.run/##Ky/NLSgt/v@/uk6Ty8EfQv7/DwA "Wumpus – Try It Online") [Try it tripled!](https://tio.run/##Ky/NLSgt/v@/uk6Ty8Efmfz/HwA "Wumpus – Try It Online") Prints `1` and `3`. ### Explanation I found a ton of 6-byte solutions by brute force search, but none for 5 bytes. That doesn't necessarily mean there aren't any at 5 bytes but they'd probably use weird characters or something. I ended up picking this solution because it doesn't print any leading zeros (most of them do) and it has some interesting control flow. Let's start with the single program: [![enter image description here](https://i.stack.imgur.com/da5X5.png)](https://i.stack.imgur.com/da5X5.png) So the executed code is: ``` {~)O@ { Turn the IP left by 60°. ~ Swap two implicit zeros on the stack, does nothing. ) Increment the top zero to 1. O Print it. @ Terminate the program. ``` Easy enough. Now the doubled program. Since the first line gets appended onto the second line, the grid extends to width 5 (and height 3) which changes the control flow significantly: [![enter image description here](https://i.stack.imgur.com/2lXt0.png)](https://i.stack.imgur.com/2lXt0.png) The IP goes around that loop exactly once, so the executed code is: ``` {~){~)){~O@ {~) As before, we end up with a 1 on top of the stack. { Turn left by 60° again. ~ Swap the 1 with the 0 underneath. )) Increment the zero to 2. { Turn left by 60° again. ~ Swap the 2 with the 1 underneath. O Print the 1. @ Terminate the program. ``` Finally, the tripled program is quite similar to the doubled one, but we get a couple more important commands onto that third line: [![enter image description here](https://i.stack.imgur.com/aMq4d.png)](https://i.stack.imgur.com/aMq4d.png) So the executed code is: ``` {~){~)){~~)O@ {~){~)){~ As before. We end up with a 1 on top of the stack and a 2 underneath. ~ Swap the 1 with the 2 underneath. ) Increment the 2 to a 3. O Print the 3. @ Terminate the program. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` KΣK+1 ``` [Try it online!](https://tio.run/##yygtzv7/3/vcYm9tw///AQ "Husk – Try It Online") [Repeated twice!](https://tio.run/##yygtzv7/3/vcYm9tQwj5/z8A) [Repeated thrice!](https://tio.run/##yygtzv7/3/vcYm9tQ2Ty/38A) ## Explanation It's quite difficult to construct a repeatable program in Husk. Because the type system forbids a function that can be applied to itself, I have to somehow allow the first part to evaluate to a function, and the remainder to evaluate to a value, and the types of existing built-ins are designed to prevent this kind of ambiguity. The tokens of the program are * `K`, which constructs a constant function. `K a b` is equivalent to `a`. * `Σ`, which takes an integer **n** and returns the **n**th triangular number. * `+`, which adds two numbers. * `1`, which is the literal 1. The original program is interpreted like this: ``` K Σ (K+) 1 == Σ 1 == 1 ``` The `(K+)` is a nonsensical function that gets eaten by the first `K`. The twice repeated program is interpreted like this: ``` K Σ (K+1KΣK+) 1 == Σ 1 == 1 ``` The function in parentheses is again eaten by the first `K`. The thrice repeated program is interpreted like this: ``` K (Σ (K (+1) (KΣK+) 1)) (KΣK+1) == Σ (K (+1) (KΣK+) 1) == Σ ((+1) 1) == Σ (+1 1) == Σ 2 == 3 ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 5 bytes ``` )<@OP ``` Try it online: [once](https://tio.run/##Sy5Nyqz4/1/TxsE/4P9/AA "Cubix – Try It Online"), [twice](https://tio.run/##Sy5Nyqz4/1/TxsE/AEz8/w8A "Cubix – Try It Online"), [thrice](https://tio.run/##Sy5Nyqz4/1/TxsE/AEH8/w8A "Cubix – Try It Online"). --- ## Explanation Cubix is a stack-based language whose instructions are wrapped around the outside of a cube. Important to note is that the stack is initially filled with infinite zeroes, which allows us to "pull values out of thin air" with operators rather than pushing them explicitly. I must admit that this was found by a brute-forcer; I never would have found it on my own. In fact, @MartinEnder was the one who asked me to try brute-forcing, as he had been looking for this solution without luck. This is the only solution the brute-forcer found, and I do believe it is the one and only shortest solution in Cubix. ### Single program [Watch it run!](http://ethproductions.github.io/cubix/?code=KTxAT1A=&input=&speed=2) The original program fits on a unit cube. Here's the unfolded net: ``` ) < @ O P . ``` The IP (instruction pointer) starts on the leftmost face (the `<`) headed east. The `<` immediately points it west, and it wraps around to the `P`. `P` is exponentiation, and since there's nothing on the stack, the interpreter pulls out two **0**s and calculates **00**, which is **1** according to JavaScript. `O` then prints this value, and `@` ends the program. ### Double program [Watch it run!](http://ethproductions.github.io/cubix/?code=KTxAT1ApPEBPUA==&input=&speed=2) ``` )<@OP)<@OP ``` The 10-byte program is too long to fit onto a unit cube, and so it is expanded to a size-2 cube: ``` ) < @ O P ) < @ O P . . . . . . . . . . . . . . ``` As before, the IP starts out at the top-left of the left-most face. This time, the very first instruction is `P`, which pushes a **1** as before. Next is `)`, which increments the top item, turning it into a **2**. Then `<` turns the IP around, and it hits the `)` again, transforming the **2** into a **3**. Here's where it gets interesting. `P` raises the second-from-top item to the power of the first item, which gives **03 = 0**. Then the IP wraps around to the rightmost face and passes through two no-ops `.` before hitting another `P`. Here we see another quirk of Cubix: binary operators (such as `P`) don't remove their operands from the stack. So since the stack is now `[3, 0]`, we calculate **30 = 1**, which `O` outputs, and `@` terminates the program. ### Triple program [Watch it run!](http://ethproductions.github.io/cubix/?code=KTxAT1ApPEBPUCk8QE9Q&input=&speed=2) ``` )<@OP)<@OP)<@OP ``` As with the double program, the triple can fit on a size-2 cube: ``` ) < @ O P ) < @ O P ) < @ O P . . . . . . . . . ``` This program starts out in the same way as the previous: `P` pushes **1**, `)` increments, `<` points the IP west, `)` increments again, and `P` now pushes **0**. The IP is then wrapped around to the `<` on the rightmost face, which does nothing since the IP is already pointed west. Here is the one difference from the double program: the `)` increments the **0** on top of the stack to a **1**. When `P` performs its magic again, this time it calculates **31 = 3**. `O` outputs and `@` terminates, and we prove conclusively that the third time is indeed the charm. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 5 bytes ``` »‘µ*Ḃ ``` [Try it online!](https://tio.run/##y0rNyan8///Q7kcNMw5t1Xq4o@n/fwA "Jelly – Try It Online") [Try it doubled!](https://tio.run/##y0rNyan8///Q7kcNMw5t1Xq4owmJ@f8/AA "Jelly – Try It Online") [Try it tripled!](https://tio.run/##y0rNyan8///Q7kcNMw5t1Xq4owk78/9/AA "Jelly – Try It Online") ### How it works ``` »‘µ*Ḃ Main link. No arguments. Implicit argument: x = 0 ‘ Increment; yield x + 1 = 1. » Take the maximum of x and 1. Yields 1. µ Begin a new, monadic chain. Argument: y = 1 Ḃ Bit; yield 1 if y is odd, 0 if it is even. Yields 1. * Power; yield y**1 = 1. ``` ``` »‘µ*Ḃ»‘µ*Ḃ Main link. »‘µ*Ḃ As before. ‘ Increment; yield y + 1 = 2. » Take the maximum of 1 and 2. Yields 2. µ Begin a new, monadic chain. Argument: z = 2 Ḃ Bit; yield 1 if z is odd, 0 if it is even. Yields 0. * Power; yield z**0 = 1. ``` ``` »‘µ*Ḃ»‘µ*Ḃ»‘µ*Ḃ Main link. »‘µ*Ḃ»‘µ*Ḃ As before. ‘ Increment; yield z + 1 = 3. » Take the maximum of 1 and 3. Yields 3. µ Begin a new, monadic chain. Argument: w = 3 Ḃ Bit; yield 1 if w is odd, 0 if it is even. Yields 1. * Power; yield w**1 = 3. ``` [Answer] # [Haskell](https://www.haskell.org/), 24 bytes ``` main=print.div 3$4 -1-- ``` Prints `1`: [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0QvJbNMwVjFhEtB11BX9/9/AA "Haskell – Try It Online") ``` main=print.div 3$4 -1--main=print.div 3$4 -1-- ``` Also prints `1`: [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0QvJbNMwVjFhEtB11BXF5f4//8A "Haskell – Try It Online") ``` main=print.div 3$4 -1--main=print.div 3$4 -1--main=print.div 3$4 -1-- ``` Prints `3`: [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0QvJbNMwVjFhEtB11BXl1Tx//8B "Haskell – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 10 bytes ``` <>([]{}()) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/38ZOIzq2ulZDU/P/fwA "Brain-Flak – Try It Online") [Try it doubled!](https://tio.run/##SypKzMzTTctJzP7/38ZOIzq2ulZDUxPB@v8fAA "Brain-Flak – Try It Online") [Try it tripled!](https://tio.run/##SypKzMzTTctJzP7/38ZOIzq2ulZDUxMb6/9/AA "Brain-Flak – Try It Online") Explanation: ``` #Toggle stacks <> #Push ( #Stack-height (initially 0) + [] #The TOS (initially 0) + {} #1 () ) ``` When we run this once, it will put `(0 + 0 + 1) == 1` onto the alternate stack. Ran a second time, it puts the same onto the main stack. Run a *third* time however, it evaluates to `(1 + 1 + 1) == 3`, and pushes that to the alternate stack and implicitly prints. [Answer] ## SQL, ~~25~~ ~~24~~ 23 bytes (**-1 Byte** *Removed a mistyped character that was always commented out and doing nothing*) (**-1 Byte** *Changed `SELECT` to `PRINT` as recommended by Razvan Socol*) ``` PRINT 2/* *2+1--*/-1 -- ``` **How it works:** In SQL, you can comment out the comment tags, like so: ``` /* 'Comment'--*/ ``` vs ``` --/* 'Not Comment'--*/ ``` *Code on 1 line with comments excluded:* First iteration: `SELECT 2-1` Output: `1` Second iteration: `SELECT 2-1*2+1` Output: `1` Third iteration: `SELECT 2-1*2+1*2+1` Output: `3` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~7~~ ~~5~~ 4 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ē»«I ``` [Try it here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTEzJUJCJUFCSQ__,v=0.12) [Try it doubled!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTEzJUJCJUFCSSV1MDExMyVCQiVBQkk_,v=0.12) [Try it tripled!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTEzJUJCJUFCSSV1MDExMyVCQiVBQkkldTAxMTMlQkIlQUJJ,v=0.12) Explanation: ``` ē»«I ē push counter, then increment it. First time running this will push 0, then 1, then 2. TOS on each: 0 1 2 » floor divide by 2 0 0 1 « multiply by 2 0 0 2 I and increment 1 1 3 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes ``` .gDÈ+ ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fL93lcIf2//8A "05AB1E – Try It Online") or [Try it doubled!](https://tio.run/##MzBNTDJM/f9fL93lcIc2hPz/HwA) or [Try it tripled!](https://tio.run/##MzBNTDJM/f9fL93lcIc2Mvn/PwA) **Explanation** ``` .g # push length of stack D # duplicate È # check if even + # add ``` **Single: `0 + (0 % 2 == 0) -> 1` Double: `1 + (1 % 2 == 0) -> 1` Triple: `2 + (2 % 2 == 0) -> 3`** [Answer] # [Lost](https://github.com/Wheatwizard/Lost), 38 bytes ``` \\<<<<</<<<<> 2>((1+@>?!^%^ .........v ``` [Try it online!](https://tio.run/##y8kvLvn/PybGBgT0QYQdl5GdhoahtoOdvWKcahyXHgyU/f//XzcQAA "Lost – Try It Online") ``` \\<<<<</<<<<> 2>((1+@>?!^%^ .........v\\<<<<</<<<<> 2>((1+@>?!^%^ .........v ``` [Try it online!](https://tio.run/##y8kvLvn/PybGBgT0QYQdl5GdhoahtoOdvWKcahyXHgyUEafq////uoEA "Lost – Try It Online") ``` \\<<<<</<<<<> 2>((1+@>?!^%^ .........v\\<<<<</<<<<> 2>((1+@>?!^%^ .........v\\<<<<</<<<<> 2>((1+@>?!^%^ .........v ``` [Try it online!](https://tio.run/##y8kvLvn/PybGBgT0QYQdl5GdhoahtoOdvWKcahyXHgyUUVPV////dQMB "Lost – Try It Online") ## Explanation Lost is a very interesting language for this challenge. The usual Lost technique is to build a "trap". A trap is a section of the program designed to catch all the ips in one place so that their stacks can be cleared and they can be controlled to go in a specific direction. This makes writing programs in Lost a lot more manageable. However since the program is duplicated we need to avoid trap duplication as well. This requires us to design a new trap that works properly but when duplicated only one of the traps works. My basic idea here is the following ``` v<<<<> >%?!^^ ``` While the stack is non-empty the `?` will remove a item and cause it to jump back to the begining if that item is non-zero. The key here is that when this stacks the `^^`s line up ``` v<<<<> >%?!^^v<<<<> >%?!^^v<<<<> >%?!^^v<<<<> >%?!^^v<<<<> >%?!^^ ``` Meaning that no matter how you enter you will always exit in the same place. From here we can attempt to implement the same idea from [my Klein answer](https://codegolf.stackexchange.com/a/158056/56656). ``` \\<<<<<v<<<<> 2>((1+@>?!^%^ ``` The backbone of our program is the left had side which pushes a number of `2`s. Each time we add a copy of the program another `2` gets added to the backbone of the program meaning an additional 2 is pushed to the stack. Once it goes off the bottom it bounces through `\\>` and executes the code ``` ((1+@ ``` This removes the first 2 stack items, adds one to the whatever is left, and exits. Once our backbone has 3 2s we will add 1 and get 3, if we have any less than 3 items we will just discard the entire stack and return 1. Now the only problem left is that the `!` in our program can cause an infinite loop. If the ip starts on `!` going upwards it will jump and land right back where it was. This means we have to add another line underneath to prevent the loop. ``` \\<<<<</<<<<> 2>((1+@>?!^%^ .........^ ``` This has the slight problem of putting some slashes in between our `^`s in the trap. However, rather miraculously, everything works out. Our ips bounce around properly so that it doesn't make a difference. [Answer] # [><>](https://esolangs.org/wiki/Fish), 9 bytes ``` \5 n; \\1 ``` [Try it online!](https://tio.run/##S8sszvj/P8ZUIc@aKybG8P9/AA "><> – Try It Online") [Try it doubled!](https://tio.run/##S8sszvj/P8ZUIc@aKybGEM74/x8A "><> – Try It Online") [Try it tripled!](https://tio.run/##S8sszvj/P8ZUIc@aKybGEJPx/z8A "><> – Try It Online") I found this sort of by luck, using the philosophy that "if you make the fish's path convoluted enough, eventually something will work". The original and doubled versions print a 5, and the tripled version prints 1 then 5 to make 15 = 3×5. Here are the multiplied versions, for your perusal: ``` \5 n; \\1\5 n; \\1 ``` ``` \5 n; \\1\5 n; \\1\5 n; \\1 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~46 45~~ 39 bytes Inspired by [Halvard's answer](https://codegolf.stackexchange.com/a/140886/59487). I'm glad that my challenge inspired a new one, which I find even more interesting. Saved 6 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). ``` print open(__file__,"a").tell()/79*3|1# ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EIb8gNU8jPj4tMyc1Pl5HKVFJU68kNSdHQ1Pf3FLLuMZQ@f9/AA "Python 2 – Try it online!") [Try it doubled!](https://tio.run/##K6gsycjPM/r/v6AoM69EIb8gNU8jPj4tMyc1Pl5HKVFJU68kNSdHQ1Pf3FLLuMZQmUhl//8DAA "Python 2 – Try It Online") [Try it tripled!](https://tio.run/##K6gsycjPM/r/v6AoM69EIb8gNU8jPj4tMyc1Pl5HKVFJU68kNSdHQ1Pf3FLLuMZQmbrK/v8HAA "Python 2 – Try It Online") ## How it works (outdated) ``` k=open(__file__,"a").tell() # Read the source code in "append" mode and get its length. # Assign it to a variable k. ;print k>>(k==90)# # Print k, with the bits shifted to the right by 1 if k # is equal to 90, or without being shifted at all overwise. # By shifting the bits of a number to the right by 1 (>>1), # we basically halve it. ``` When it is doubled, the length becomes **90**, but the new code is ignored thanks to the `#`, so `k==90` evaluates to `True`. Booleans are subclasses of integers in Python, so `k>>True` is equivalent to `k>>1`, which is essentially **k / 2 = 45**. When it is tripled, the new code is again ignored, hence the new length is **135**, which doesn't get shifted because `k==90` evaluates to `False`, so `k>>(k==90) ⟶ k>>(135==90) ⟶ k>>False ⟶ k>>0 ⟶ k`, and **k** is printed as-is. --- # [Python 2](https://docs.python.org/2/), 36 bytes This was a suggestion by Aidan F. Pierce at 38 bytes, and I golfed it by 2 bytes. I’m not posting this as my main solution because I didn’t come up with it by myself. ``` 0and"" True+=1 print True>3and 3or 1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/3yAxL0VJiSukqDRV29aQq6AoM69EAcSzMwbKKBjnFykY/v8PAA "Python 2 – Try It Online") [Try it doubled!](https://tio.run/##K6gsycjPM/r/3yAxL0VJiSukqDRV29aQq6AoM69EAcSzMwbKKBjnFykYEqPm/38A "Python 2 – Try It Online") [Try it tripled!](https://tio.run/##K6gsycjPM/r/3yAxL0VJiSukqDRV29aQq6AoM69EAcSzMwbKKBjnFykYUkvN//8A "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~37~~ ~~31~~ 28 bytes Thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) for golfing off the final 3 bytes. ``` length(readLines())%/%2*2+1 ``` (with a trailing newline). [Try it once!](https://tio.run/##K/r/Pyc1L70kQ6MoNTHFJzMvtVhDU1NVX9VIy0jbkOv/fwA "R – Try It Online") [Try it twice!](https://tio.run/##K/r/Pyc1L70kQ6MoNTHFJzMvtVhDU1NVX9VIy0jbkAuf3P//AA "R – Try It Online") [Try it thrice!](https://tio.run/##K/r/Pyc1L70kQ6MoNTHFJzMvtVhDU1NVX9VIy0jbkItcuf//AQ "R – Try It Online") This uses the `readLines()` trick from [Giuseppe's answer to the 8-ball challenge](https://codegolf.stackexchange.com/questions/157546/create-a-magic-8-ball/157613#157613), where `stdin` redirects to the source file. This code basically just counts up how many lines exist below the first line and outputs `1` if there are 1 or 3 lines (i.e. code is single or doubled), or `3` if there are 5 lines (i.e. code is tripled). [Answer] ## [C (gcc)](https://gcc.gnu.org/), 107 bytes My first submission in C (gcc). Way too long ... ``` i; #ifdef c #define c #ifdef b i=2; #else #define b #endif #else #define c main(){putchar(i+49);} #endif c ``` TIO links: [single](https://tio.run/##S9ZNT07@/z/Tmks5My0lNU0hmUsZSGXmpYJYEKEkrkxbI6CC1JziVLhsEpCfl5KZhiacrJCbmJmnoVldUFqSnJFYpJGpbWKpaV0LUw20CwA "C (gcc) – Try It Online"), [double](https://tio.run/##S9ZNT07@/z/Tmks5My0lNU0hmUsZSGXmpYJYEKEkrkxbI6CC1JziVLhsEpCfl5KZhiacrJCbmJmnoVldUFqSnJFYpJGpbWKpaV0LU53MRT@r/v8HAA "C (gcc) – Try It Online"), [triple](https://tio.run/##S9ZNT07@/z/Tmks5My0lNU0hmUsZSGXmpYJYEKEkrkxbI6CC1JziVLhsEpCfl5KZhiacrJCbmJmnoVldUFqSnJFYpJGpbWKpaV0LU53MNSyt@v8fAA "C (gcc) – Try It Online"). [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 bytes ``` |dhH^ ``` [Run and debug online!](https://staxlang.xyz/#c=%7CdhH%5E&a=1) · [Doubled](https://staxlang.xyz/#c=%7CdhH%5E%7CdhH%5E&a=1) · [Tripled](https://staxlang.xyz/#c=%7CdhH%5E%7CdhH%5E%7CdhH%5E&a=1) ## Explanation ``` |dhH^ |d Push Current stack depth `d`, originally 0 Doubled -> 1, Tripled -> 2 hH^ Map d to 2*(floor(d/2))+1 Implicit print ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~95~~ ~~91~~ 85 bytes ``` #ifndef a #define a-1 main(){puts(3 #include __FILE__ ?"1":"3");} #define a #endif a ``` [Try it online!](https://tio.run/##S9ZNT07@/185My0vJTVNIZFLGUhl5qUqJOoacuUmZuZpaFYXlJYUaxhzKWfmJeeUpqQqxMe7efq4xsdz2SsZKlkpGStpWtci9HEpp@alZKZxJXL9/w8A "C (gcc) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~8~~ ~~6~~ 5 bytes *-1 byte thanks to @ETHproductions* ``` °U-v ``` ## Explanation: ``` °U-v U # variable U=0 # U=0 °U # ++U # U=1 - # minus: v # 1 if U is divisible by 2 # else # 0 # U=1 ``` [This evaluates to `1-0 = 1`](https://tio.run/##y0osKPn//9CGUN0yrv//AQ) [Doubled evaluates to `2-1 = 1`](https://tio.run/##y0osKPn//9CGUN0yLgj5/z8A) [Tripled evaluates to `3-0 = 3`](https://tio.run/##y0osKPn//9CGUN0yLmTy/38A) [Answer] # Pure Bash (no `wc` or other external utils), 27 ``` trap echo\ $[a++&2|1] EXIT ``` * [Try it once.](https://tio.run/##S0oszvj/v6QosUAhNTkjP0ZBJTpRW1vNqMYwVsE1wjOE6/9/AA) * [Try it twice.](https://tio.run/##S0oszvj/v6QosUAhNTkjP0ZBJTpRW1vNqMYwVsE1wjOEC4/U//8A) * [Try it thrice.](https://tio.run/##S0oszvj/v6QosUAhNTkjP0ZBJTpRW1vNqMYwVsE1wjOEizyp//8B) [Answer] # [Perl 5](https://www.perl.org/), ~~18~~ ~~15~~ ~~13~~ ~~12~~ 11 bytes -3 bytes thanks to [nwellnhof](https://codegolf.stackexchange.com/users/9296/nwellnhof) ``` say 1| +.7# ``` Once [Try it online!](https://tio.run/##K0gtyjH9/784sVLBsIZLW89c@f//f/kFJZn5ecX/dX1N9QwN9AwA "Perl 5 – Try It Online") Twice [Try it online!](https://tio.run/##K0gtyjH9/784sVLBsIZLW89cGYn5//@//IKSzPy84v@6vqZ6hgZ6BgA "Perl 5 – Try It Online") Thrice [Try it online!](https://tio.run/##K0gtyjH9/784sVLBsIZLW89cGTvz//9/@QUlmfl5xf91fU31DA30DAA "Perl 5 – Try It Online") [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~10 9~~ 8 bytes ``` 562gn| ``` [Try it online!](https://tio.run/##S8sszvj/39TMKD2vhpHr/38A "><> – Try It Online") [Try it doubled!](https://tio.run/##S8sszvj/39TMKD2vhpELRv//DwA) [Try it tripled!](https://tio.run/##S8sszvj/39TMKD2vhpELnf7/HwA) ~~I'm sure there's an 8 byte solution somewhere out there.~~ The unprintable at the end has ASCII value 1, and is only fetched by the `g`et command on the third iteration. For the first two it prints `05`, and then prints `15`. [Answer] # [Labyrinth](https://github.com/m-ender/labyrinth), ~~12~~ ~~11~~ 9 bytes ``` :#%!@ 7 ``` [TIO (1x)](https://tio.run/##y0lMqizKzCvJ@P/fQFlV0YFLwZzr/38A), [TIO (2x)](https://tio.run/##y0lMqizKzCvJ@P/fQFlV0YFLwZwLzvj/HwA), [TIO (3x)](https://tio.run/##y0lMqizKzCvJ@P/fQFlV0YFLwZwLk/H/PwA) [Answer] # JavaScript, ~~81 77 74~~ 70 bytes Saved 4 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) ``` var t,i=(i||[3,1,1]),a=i.pop() clearTimeout(t) t=setTimeout(alert,9,a) ``` Pretty lame JS solution. Consumes the values from the `[3,1,1]` array from the right (`pop()`). Registers a timeout to display the current value in the future. If a timeout was already registered, cancel it. Relies on the dirty nature of `var`, which hoists variable declarations. ## Two times: ``` var t,i=(i||[3,1,1]),a=i.pop() clearTimeout(t) t=setTimeout(alert,9,a) var t,i=(i||[3,1,1]),a=i.pop() clearTimeout(t) t=setTimeout(alert,9,a) ``` ## Three times: ``` var t,i=(i||[3,1,1]),a=i.pop() clearTimeout(t) t=setTimeout(alert,9,a) var t,i=(i||[3,1,1]),a=i.pop() clearTimeout(t) t=setTimeout(alert,9,a) var t,i=(i||[3,1,1]),a=i.pop() clearTimeout(t) t=setTimeout(alert,9,a) ``` [Answer] # [Lost](https://github.com/Wheatwizard/Lost), 27 bytes ``` \\<<<<//<<<> 2>((1+@>((%^ v ``` [Try it online!](https://tio.run/##y8kvLvn/PybGBgj09YGEHZeRnYaGobYDkFSN4yr7//@/biAA "Lost – Try It Online") [Try it doubled!](https://tio.run/##y8kvLvn/PybGBgj09YGEHZeRnYaGobYDkFSN4yrDI/X//3/dQAA) [Try it tripled!](https://tio.run/##y8kvLvn/PybGBgj09YGEHZeRnYaGobYDkFSN4yojT@r///@6gQA) This is mostly an improvement of [Post Left Garf Hunter's answer](https://codegolf.stackexchange.com/a/158144/76162) that removes all the pesky no-ops from that last line, To do this, we have to remove the `!`, otherwise the program always gets stuck in a loop. So we change the clearing section from `>?!^%^` to `>))%^`' since there can only be a max of two elements on the stack anyway. Unfortunately, this means that the path from the extra copies to the original is broken, so we place an extra `/` in the first line to compensate. This forces the pointer to go through the clearing section for all copies of the program until it reaches the first one, where the `^` instead redirects it to the `>` instead. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~53~~ 52 bytes Note the space after `#endif`. ``` n;main(){putchar(n+49);} #if __LINE__>7 n=2; #endif ``` [Try it online!](https://tio.run/##S9ZNT07@/z/POjcxM09Ds7qgtCQ5I7FII0/bxFLTupZLOTNNIT7ex9PPNT7ezpwrz9bImks5NS8FKPz/PwA "C (gcc) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` ⎚≔⁺ι¹ιI⁻ι⁼ι² ``` [Try it online!](https://tio.run/##HYoxDoAgDAC/wlgSGHR1MsSdxBdUYpSkwdiC36/ojXeXTuR0IakG2pHBTmYWyUeBSE0gOzNYZ3LXkXOpEFAqrG2rjKl@ebkb0j@OtjOpqn/Ue6EX "Charcoal – Try It Online") Link is to verbose code. [Try it doubled!](https://tio.run/##S85ILErOT8z5/985JzWxSEPTWsGxuDgzPU8jIKe0WCNTR8FQU0chEygcUJSZV6LhnFhcohFcmlRSlJhcApJ2LSxNzAErNNIEAmsFKpnz//9/3bL/urrFOQA) [Try it tripled!](https://tio.run/##S85ILErOT8z5/985JzWxSEPTWsGxuDgzPU8jIKe0WCNTR8FQU0chEygcUJSZV6LhnFhcohFcmlRSlJhcApJ2LSxNzAErNNIEAmuFQWbO////dcv@6@oW5wAA) ### Explanation ``` ⎚ Clear ≔⁺ι¹ι Assign plus(i, 1) to i I Cast (and implicitly print) ⁻ ⁼ι² Subtract equals(i, 2) from ι i ``` [Answer] # JavaScript, ~~43~~ 40 Bytes ``` var t=t?--t:~!setTimeout`t=alert(1|~t)`; ``` 2x: ``` var t=t?--t:~!setTimeout`t=alert(1|~t)`;var t=t?--t:~!setTimeout`t=alert(1|~t)`; ``` 3x: ``` var t=t?--t:~!setTimeout`t=alert(1|~t)`;var t=t?--t:~!setTimeout`t=alert(1|~t)`;var t=t?--t:~!setTimeout`t=alert(1|~t)`; ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~54~~ ~~48~~ ~~45~~ 44 bytes ``` if(99-gt(gc $PSCOMMANDPATH|wc -c)){1;exit}3# ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/PzNNw9JSN71EIz1ZQSUg2Nnf19fRzyXAMcSjpjxZQTdZU7Pa0Dq1IrOk1lj5/38A "PowerShell – Try It Online") [Try it doubled!](https://tio.run/##K8gvTy0qzkjNyfn/PzNNw9JSN71EIz1ZQSUg2Nnf19fRzyXAMcSjpjxZQTdZU7Pa0Dq1IrOk1liZFLX//wMA "PowerShell – Try It Online") [Try it tripled!](https://tio.run/##K8gvTy0qzkjNyfn/PzNNw9JSN71EIz1ZQSUg2Nnf19fRzyXAMcSjpjxZQTdZU7Pa0Dq1IrOk1liZVmr//wcA "PowerShell – Try It Online") Gets its own invocation path with `$PSCOMMANDPATH` and performs a `g`et-`c`ontent on the file. `If` the character count of that file is less than `99` (checked via `wc -c` from coreutils), then we output `1` and `exit` (i.e., stop execution). That accounts for the original code and the doubled code. Otherwise we output `3` and exit. The actual code that's in the doubled or tripled sections is meaningless, since either we'll `exit` before we get to it, or it's behind a comment `#`. *Saved 6 bytes thanks to Mr. Xcoder* *Saved ~~3~~ 4 bytes thanks to Pavel* [Answer] ## C# (178 Bytes) ``` Console.WriteLine(1+2*4%int.Parse(System.Configuration.ConfigurationManager.AppSettings["z"]=(int.Parse(System.Configuration.ConfigurationManager.AppSettings["z"]??"0"))+1+"")); ``` crazy C# solution, but I am happy it's possible in one line in C# at all. :) For me the hardest part was having valid C# that would either intialize or increment the same variable, so I ended up abusing the ConfigurationManager because I needed a global static NameValueCollection and ConfigurationManager was the only one I could think of that I could update in memory. EnvironmentVariables was another option I Iooked at but it doesn't have an indexer so I am not sure how to do that in one line that can be copy pasted to produce the required output as per the spec. [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 35 bytes ``` ^w3'\ f 1 /1@ / '54\w /yyy ``` [Try it online!](https://tio.run/##KyrNy0z@/z@u3Fg9hksBCNLApCGXvqEDlz6XgrqpSUw5l35lZeX//wA "Runic Enchantments – Try It Online") Working on this one allowed me to find an error in my parser dealing with the new delay modifier characters, although the final result ends up not being affected by it, as I ended up not needing them. Functions due to the fact that the final line does not have a trailing newline (or for that matter, trailing spaces), allowing the duplicate IPs to spawn in a different place. The top-left one ends up making a large loop around the grid while the second IP performs a Reflection operation to replace the `\` on the 6th line with a . This IP then will loop forever and do nothing. The third IP also makes this same replacement at the same time, but because it's situated on the *13th* line, its copy of that reflector sends it upwards and it executes the `1f'3w` sequence present in the upper right corner, which replaces the `1` with a `3` on the 14th line, just before the original IP executes it, causing the tripled program to output `3` instead of `1` (values could also be `2` and `6`, `3` and `9`, `4` and `12`, or `5` and `15` due to the availability of `a-f` numerical constants; `1` and `3` were chosen arbitrarily). It is then left in an endless loop performing more reflection commands that do nothing. [Try it in triplicate!](https://tio.run/##KyrNy0z@/z@u3Fg9hksBCNLApCGXvqEDlz6XgrqpSUw5l35lZSV1lPz/DwA "Runic Enchantments – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~31~~ 25 bytes ``` p [*DATA][3]?3:1 __END__ ``` [Try it online!](https://tio.run/##KypNqvz/v0AhWsvFMcQxNto41t7YypArPt7VzyU@nuv/fwA "Ruby – Try It Online") [Try it online!Try it online!](https://tio.run/##KypNqvz/v0AhWsvFMcQxNto41t7YypArPt7VzyU@ngunxP//AA "Ruby – Try It Online") [Try it online!Try it online!Try it online!](https://tio.run/##KypNqvz/v0AhWsvFMcQxNto41t7YypArPt7VzyU@not0if//AQ "Ruby – Try It Online") ### Explanation: `__END__` is not part of the code and everything that follows it is returned by the iterator `DATA` as lines of text, simply count those lines and check if there are enough of them to switch from 1 to 3. ]
[Question] [ I noticed that there's no such question, so here it is: Do you have general tips for golfing in x86/x64 machine code? If the tip only applies to a certain environment or calling convention, please specify that in your answer. > > Please only one tip per answer (see [here](https://codegolf.meta.stackexchange.com/a/9296/48198)). > > > [Answer] # Choose your calling convention to put args where you want them. **The language of your answer is asm (actually machine code), so treat it as part of a program written in asm, not C-compiled-for-x86.** Your function doesn't have to be easily callable from C with any standard calling convention. That's a nice bonus if it doesn't cost you any extra bytes, though. In a pure asm program, it's normal for some helper functions to use a calling convention that's convenient for them and for their caller. Such functions document their calling convention (inputs/outputs/clobbers) with comments. In real life, even asm programs do (I think) tend to use consistent calling conventions for most functions (especially across different source files), but any given important function could do something special. In code-golf, you're optimizing the crap out of one single function, so obviously it's important/special. --- **To test your function from a C program, you can write a wrapper** that puts args in the right places, saves/restores any extra registers you clobber, and puts the return value into `e/rax` if it wasn't there already. --- ### The limits of what's reasonable: anything that doesn't impose an unreasonable burden on the caller: * `esp`/`rsp` must be call-preserved1; other integer regs are fair game for being call-clobbered. (`rbp` and `rbx` are usually call-preserved in normal conventions, but you *could* clobber both.) * Any arg in any register (except `rsp`) is reasonable, but asking the caller to copy the same arg to multiple registers is not. * Requiring `DF` (string direction flag for `lods`/`stos`/etc.) to be clear (upward) on call/ret is normal. Letting it be undefined on call/ret would be ok. Requiring it to be cleared or set on entry but then leaving it modified when you return would be weird. * Returning FP values in x87 `st0` is reasonable, but returning in `st3` with garbage in other x87 registers isn't. The caller would have to clean up the x87 stack. Even returning in `st0` with non-empty higher stack registers would also be questionable (unless you're returning multiple values). * Your function will be called with `call`, so `[rsp]` is your return address. You *can* avoid `call`/`ret` on x86 using a link register like `lea rbx, [ret_addr]`/`jmp function` and return with `jmp rbx`, but that's not "reasonable". That's not as efficient as `call`/`ret`, so it's not something you'd plausibly find in real code. * Clobbering unlimited memory above `rsp` is not reasonable, but clobbering your function args on the stack is allowed in normal calling conventions. x64 Windows requires 32 bytes of shadow space above the return address, while x86-64 System V gives you a 128 byte red-zone below `rsp`, so either of those are reasonable. (Or even a much larger red-zone, especially in a stand-alone program rather than function.) Note 1: or have some well-defined sensible rule for how RSP is modified: e.g. callee-pops stack args like with `ret 8`. (Although stack args and a larger `ret imm16` encoding are usually not what you want for code-golf). Or even returning an array by value on the stack is an unconventional but usable calling-convention. e.g. pop the return address into a register, then push in a loop, then `jmp reg` to return. Probably only justifiable with a size in a register, else the caller would have to save the original RSP somewhere. RBP or some other reg would have to be call-preserved so a caller could use it as a frame pointer to easily clean up the result. Also probably not smaller than using `stos` to write an output pointer passed in RDI. Borderline cases: write a function that produces a sequence in an array, given the first 2 elements *as function args*. [I chose](https://codegolf.stackexchange.com/questions/101145/stewies-sequence/102741#102741) to have the caller store the start of the sequence into the array and just pass a pointer to the array. This is definitely bending the question's requirements. I considered taking the args packed into `xmm0` for `movlps [rdi], xmm0`, which would also be a weird calling convention and ever harder to justify / more of a stretch. --- ### Return a boolean in FLAGS (condition codes) OS X system calls do this (`CF=0` means no error): [Is it considered bad practice to use the flags register as a boolean return value?](https://stackoverflow.com/questions/48381234/is-it-considered-bad-practice-to-use-the-flags-register-as-a-boolean-return-valu). Any condition that can be checked with one `jcc` is perfectly reasonable, especially if you can pick one that has any semantic relevance to the problem. (e.g. a compare function might set flags so `jne` will be taken if they weren't equal). --- ### Require narrow args (like a `char`) to be sign or zero extended to 32 or 64 bits. This is not unreasonable; using `movzx` or `movsx` [to avoid partial-register slowdowns](https://stackoverflow.com/questions/41573502/why-doesnt-gcc-use-partial-registers) is normal in modern x86 asm. In fact clang/LLVM already makes code that depends on an undocumented extension to the x86-64 System V calling convention: [args narrower than 32 bits are sign or zero extended to 32 bits by the caller](https://stackoverflow.com/questions/36706721/is-a-sign-or-zero-extension-required-when-adding-a-32bit-offset-to-a-pointer-for/36760539#36760539). You can document/describe extension to 64 bits by writing `uint64_t` or `int64_t` in your prototype if you want, e.g. so you can use a `loop` instruction, which uses the whole 64 bits of `rcx` unless you use an address-size prefix to override the size down to 32 bit `ecx` (yes really, address-size not operand-size). Note that `long` is only a 32-bit type in the Windows 64-bit ABI, and [the Linux x32 ABI](https://en.wikipedia.org/wiki/X32_ABI); `uint64_t` is unambiguous and shorter to type than `unsigned long long`. --- ### Existing calling conventions: * Windows 32-bit `__fastcall`, [already suggested by another answer](https://codegolf.stackexchange.com/questions/132981/tips-for-golfing-in-x86-x64-machine-code/133048#133048): integer args in `ecx` and `edx`. * **x86-64 System V**: passes lots of args in registers, and has lots of call-clobbered registers you can use without REX prefixes. More importantly, it was [actually chosen](https://stackoverflow.com/questions/63891991/whats-the-best-way-to-remember-the-x86-64-system-v-arg-register-order) to allow compilers to inline (or implement in libc) `memcpy` or `memset` as `rep movsb` easily: the first 6 integer/pointer args are passed in `rdi`, `rsi`, `rdx`, `rcx`, `r8`, and `r9`. If your function uses `lodsd`/`stosd` inside a loop that runs `rcx` times (with the `loop` instruction), you can say "callable from C as `int foo(int *rdi, const int *rsi, int dummy, uint64_t len)` with the x86-64 System V calling convention". [example: chromakey](https://codegolf.stackexchange.com/questions/132719/the-chroma-key-to-success/132757#132757). * 32-bit GCC `regparm`: **Integer args in `eax`**, `ecx`, and `edx`, return in EAX (or EDX:EAX). Having the first arg in the same register as the return value allows some optimizations, [like this case with an example caller and a prototype with a function attribute](https://codegolf.stackexchange.com/questions/160100/the-repetitive-byte-counter/160236#160236). And of course AL/EAX is special for some instructions. * The Linux x32 ABI uses 32-bit pointers in long mode, so you can save a REX prefix when modifying a pointer ([example use-case](https://codegolf.stackexchange.com/questions/101145/stewies-sequence/102741#102741)). You can still use 64-bit address-size, unless you have a 32-bit negative integer zero-extended in a register (so it would be a large unsigned value if you did `[rdi + rdx]`, going outside the low 32 bits of address space.). Note that `push rsp`/`pop rax` is 2 bytes, and equivalent to `mov rax, rsp`, so you can still *copy* full 64-bit registers in 2 bytes. [Answer] ## `mov`-immediate is expensive for constants This might be obvious, but I'll still put it here. In general it pays off to think about the bit-level representation of a number when you need to initialize a value. ### Initializing `eax` with `0`: ``` b8 00 00 00 00 mov $0x0,%eax ``` should be shortened ([for performance as well as code-size](https://stackoverflow.com/questions/33666617/what-is-the-best-way-to-set-a-register-to-zero-in-x86-assembly-xor-mov-or-and/33668295#33668295)) to ``` 31 c0 xor %eax,%eax ``` ### Initializing `eax` with `-1`: ``` b8 ff ff ff ff mov $-1,%eax ``` can be shortened to ``` 31 c0 xor %eax,%eax 48 dec %eax ``` or ``` 83 c8 ff or $-1,%eax ``` --- Or more generally, **any 8-bit sign-extended value can be created in 3 bytes with `push -12` (2 bytes) / `pop %eax` (1 byte).** This even works for 64-bit registers with no extra REX prefix; `push`/`pop` default operand-size = 64. ``` 6a f3 pushq $0xfffffffffffffff3 5d pop %rbp ``` Or given a known constant in a register, you can create another nearby constant using `lea 123(%eax), %ecx` (3 bytes). This is handy if you need a zeroed register *and* a constant; xor-zero (2 bytes) + `lea-disp8` (3 bytes). ``` 31 c0 xor %eax,%eax 8d 48 0c lea 0xc(%eax),%ecx ``` See also [Set all bits in CPU register to 1 efficiently](https://stackoverflow.com/questions/45105164/set-all-bits-in-cpu-register-to-1-efficiently) [Answer] In a lot of cases, accumulator-based instructions (i.e. those that take `(R|E)AX` as the destination operand) are 1 byte shorter than general-case instructions; see [this question](https://stackoverflow.com/questions/38019386/what-is-the-significance-of-operations-on-the-register-eax-having-their-own-opco) on StackOverflow. [Answer] **Use special-case short-form encodings for AL/AX/EAX, and other short forms and single-byte instructions** Examples assume 32 / 64-bit mode, where the default operand size is 32 bits. An operand-size prefix changes the instruction to AX instead of EAX (or the reverse in 16-bit mode). * **`inc/dec` a register** (other than 8-bit): `inc eax` / `dec ebp`. (Not x86-64: the `0x4x` opcode bytes were repurposed as REX prefixes, so `inc r/m32` is the only encoding.) 8-bit `inc bl` is 2 bytes, using the [`inc r/m8` opcode + ModR/M operand encoding](http://felixcloutier.com/x86/INC.html). So **use `inc ebx` to increment `bl`, if it's safe.** (e.g. if you don't need the ZF result in cases where the upper bytes might be non-zero). * `scasd`: `e/rdi+=4`, requires that the register points to readable memory. Sometimes useful even if you don't care about the FLAGS result (like `cmp eax,[rdi]` / `rdi+=4`). And **in 64-bit mode, `scasb` can work as a 1-byte `inc rdi`**, if lodsb or stosb aren't useful. * **[`xchg eax, r32`](http://felixcloutier.com/x86/XCHG.html)**: this is where 0x90 NOP came from: `xchg eax,eax`. Example: re-arrange 3 registers with two `xchg` instructions in a `cdq` / `idiv` loop [for GCD in 8 bytes](https://codegolf.stackexchange.com/questions/77270/greatest-common-divisor/77364#77364) where most of the instructions are single-byte, including an abuse of `inc ecx`/`loop` instead of `test ecx,ecx`/`jnz` * [`cdq`](http://felixcloutier.com/x86/CWD:CDQ:CQO.html): sign-extend EAX into EDX:EAX, i.e. copying the high bit of EAX to all bits of EDX. To create a zero with known non-negative, or to get a 0/-1 to add/sub or mask with. [x86 history lesson: `cltq` vs. `movslq`](https://stackoverflow.com/questions/37743476/assembly-cltq-and-movslq-difference/37746322#37746322), and also AT&T vs. Intel mnemonics for this and the related `cdqe`. * [lodsb/d](http://felixcloutier.com/x86/LODS:LODSB:LODSW:LODSD:LODSQ.html): like `mov eax, [rsi]` / `rsi += 4` without clobbering flags. (Assuming DF is clear, which standard calling conventions require on function entry.) Also stosb/d, sometimes scas, and more rarely movs / cmps. * [`push`](http://felixcloutier.com/x86/PUSH.html)/[`pop reg`](http://felixcloutier.com/x86/POP.html). e.g. in 64-bit mode, `push rsp` / `pop rdi` is 2 bytes, but `mov rdi, rsp` needs a REX prefix and is 3 bytes. [`xlatb`](http://felixcloutier.com/x86/XLAT:XLATB.html) exists, but is rarely useful. A large lookup table is something to avoid. I've also never found a use for AAA / DAA or other packed-BCD or 2-ASCII-digit instructions, except for a [hacky use of DAS as part of converting a 4-bit integer to an ASCII hex digit](https://codegolf.stackexchange.com/questions/193793/little-endian-number-to-string-conversion/193842#193842), thanks to Peter Ferrie. 1-byte `lahf` / `sahf` are rarely useful. You *could* `lahf` / `and ah, 1` as an alternative to `setc ah`, but it's typically not useful. And for CF specifically, there's `sbb eax,eax` to get a 0/-1, or even **un-documented but universally supported 1-byte `salc` (set AL from Carry)** which effectively does `sbb al,al` without affecting flags. (Removed in x86-64). I used SALC in [User Appreciation Challenge #1: Dennis ♦](https://codegolf.stackexchange.com/questions/123194/user-appreciation-challenge-1-dennis/123458#123458). 1-byte `cmc` / `clc` / `stc` (flip ("complement"), clear, or set CF) are rarely useful, although I did find [**a use for `cmc`** in extended-precision addition](https://codegolf.stackexchange.com/questions/133618/extreme-fibonacci/135618#135618) with base 10^9 chunks. To unconditionally set/clear CF, usually arrange for that to happen as part of another instruction, e.g. `xor eax,eax` clears CF as well as EAX. There are no equivalent instructions for other condition flags, just DF (string direction) and IF (interrupts). The carry flag is special for a lot of instructions; shifts set it, `adc al, 0` can add it to AL in 2 byte, and I mentioned earlier the undocumented SALC. **`std` / `cld` rarely seem worth it**. Especially in 32-bit code, it's better to just use `dec` on a pointer and a `mov` or memory source operand to an ALU instruction instead of setting DF so `lodsb` / `stosb` go downward instead of up. Usually if you need downward at all, you still have another pointer going up, so you'd need more than one `std` and `cld` in the whole function to use `lods` / `stos` for both. Instead, just use the string instructions for the upward direction. (The standard calling conventions guarantee DF=0 on function entry, so you can assume that for free without using `cld`.) --- ### 8086 history: why these encodings exist In original 8086, AX was very special: instructions like `lodsb` / `stosb`, `cbw`, `mul` / `div` and others use it implicitly. That's still the case of course; current x86 hasn't dropped any of 8086's opcodes (at least not any of the officially documented ones, [except](https://stackoverflow.com/questions/32868293/x86-32-bit-opcodes-that-differ-in-x86-x64-or-entirely-removed) in [64-bit mode](https://stackoverflow.com/questions/44089163/is-x86-32-bit-assembly-code-valid-x86-64-bit-assembly-code)). But later CPUs added new instructions that gave better / more efficient ways to do things without copying or swapping them to AX first. (Or to EAX in 32-bit mode.) e.g. 8086 lacked later additions like `movsx` / `movzx` to load or move + sign-extend, or 2 and 3-operand [`imul cx, bx, 1234`](http://felixcloutier.com/x86/IMUL.html) that don't produce a high-half result and don't have any implicit operands. Also, **8086's main bottleneck was instruction-fetch, so optimizing for code-size was important for performance back then**. 8086'[s ISA designer (Stephen Morse)](https://retrocomputing.stackexchange.com/questions/5121/why-are-first-four-x86-gprs-named-in-such-unintuitive-order#comment11346_5128) spent a lot of opcode coding space on special cases for AX / AL, [including special (E)AX/AL-destination opcodes for all the basic immediate-src ALU- instructions](https://stackoverflow.com/questions/38019386/what-is-the-significance-of-operations-on-the-register-eax-having-their-own-opco), just opcode + immediate with no ModR/M byte. 2-byte `add/sub/and/or/xor/cmp/test/... AL,imm8` or `AX,imm16` or (in 32-bit mode) `EAX,imm32`. But there's no special case for `EAX,imm8`, so the regular ModR/M encoding of `add eax,4` is shorter. The assumption is that if you're going to work on some data, you'll want it in AX / AL, so swapping a register with AX was something you might want to do, maybe even more often than *copying* a register to AX with `mov`. Everything about 8086 instruction encoding supports this paradigm, from instructions like `lodsb/w` to all the special-case encodings for immediates with EAX to its implicit use even for multiply/divide. --- [Answer] ### Create 3 zeroes with `mul` (then `inc`/`dec` to get +1 / -1 as well as zero) You can zero eax and edx by multiplying by zero in a third register. ``` xor ebx, ebx ; 2B ebx = 0 mul ebx ; 2B eax=edx = 0 inc ebx ; 1B ebx=1 ``` will result in EAX, EDX, and EBX all being zero in just four bytes. You can zero EAX and EDX in three bytes: ``` xor eax, eax cdq ``` But from that starting point you can't get a 3rd zeroed register in one more byte, or a +1 or -1 register in another 2 bytes. Instead, use the mul technique. Example use-case: [concatenating the Fibonacci numbers in binary](https://codegolf.stackexchange.com/questions/160857/binary-fibonacci/160894#160894). Note that after a `LOOP` loop finishes, ECX will be zero and can be used to zero EDX and EAX; you don't always have to create the first zero with `xor`. [Answer] # Subtract -128 instead of add 128 ``` 0100 81C38000 ADD BX,0080 0104 83EB80 SUB BX,-80 ``` Samely, add -128 instead of subtract 128 [Answer] # Skipping instructions Skipping instructions are opcode fragments that combine with one or more subsequent opcodes. The subsequent opcodes can be used with a different entrypoint than the prepended skipping instruction. Using a skipping instruction instead of an unconditional short jump can save code space, be faster, and set up incidental state such as `NC` (No Carry). My examples are all for 16-bit Real/Virtual 86 Mode, but a lot of these techniques can be used similarly in 16-bit Protected Mode, or 32- or 64-bit modes. Quoting [from my ACEGALS guide](https://pushbx.org/ecm/doc/acegals.htm#skipping): > > ## 11: Skipping instructions > > > The constants \_\_TEST\_IMM8, \_\_TEST\_IMM16, and \_\_TEST\_OFS16\_IMM8 are defined to the respective byte strings for these instructions. They can be used to skip subsequent instructions that fit into the following 1, 2, or 3 bytes. However, note that they modify the flags register, including always setting NC. The 16-bit offset plus 16-bit immediate test instruction is not included for these purposes because it might access a word at offset 0FFFFh in a segment. Also, the \_\_TEST\_OFS16\_IMM8 as provided should only be used in 86M, to avoid accessing data beyond a segment limit. After the db instruction using one of these constants, a parenthetical remark should list which instructions are skipped. > > > The 86 Mode defines [in lmacros1.mac 323cc150061e (2021-08-29 21:45:54 +0200)](https://hg.pushbx.org/ecm/lmacros/file/323cc150061e/lmacros1.mac#l246): ``` %define __TEST_IMM8 0A8h ; changes flags, NC %define __TEST_IMM16 0A9h ; changes flags, NC ; Longer NOPs require two bytes, like a short jump does. ; However they execute faster than unconditional jumps. ; This one reads random data in the stack segment. ; (Search for better ones.) %define __TEST_OFS16_IMM8 0F6h,86h ; changes flags, NC ``` The `0F6h,86h` opcode in 16-bit modes is a `test byte [bp + disp16], imm8` instruction. I believe I am not using this one anywhere actually. (A stack memory access might actually be slower than an unconditional short jump, in fact.) `0A8h` is the opcode for `test al, imm8` in any mode. The `0A9h` opcode changes to an instruction of the form `test eax, imm32` in 32- and 64-bit modes. Two use cases [in ldosboot boot32.asm 07f4ba0ef8cd (2021-09-10 22:45:32 +0200)](https://hg.pushbx.org/ecm/ldosboot/file/07f4ba0ef8cd/boot32.asm): First, chain two different entrypoints for a common function which both need to initialise a byte-sized register. The `mov al, X` instructions take 2 bytes each, so `__TEST_IMM16` can be used to skip one such instruction. (This pattern can be repeated if there are more than two entrypoints.) ``` error_fsiboot: mov al,'I' db __TEST_IMM16 ; (skip mov) read_sector.err: mov al, 'R' ; Disk 'R'ead error error: ``` Second, a certain entrypoint that needs two bytes worth of additional teardown but can otherwise be shared with the fallthrough case of a later code part. ``` mov bx, [VAR(para_per_sector)] sub word [VAR(paras_left)], bx jbe @F ; read enough --> loop @BB pop bx pop cx call clust_next jnc next_load_cluster inc ax inc ax test al, 8 ; set in 0FFF_FFF8h--0FFF_FFFFh, ; clear in 0, 1, and 0FFF_FFF7h jz fsiboot_error_badchain db __TEST_IMM16 @@: pop bx pop cx call check_enough jmp near word [VAR(fsiboot_table.success)] ``` Here's a use case [in inicomp lz4.asm 4d568330924c (2021-09-03 16:59:42 +0200)](https://hg.pushbx.org/ecm/inicomp/file/4d568330924c/lz4.asm#l491) where we depend on the `test al, X` instruction clearing the Carry Flag: ``` .success: db __TEST_IMM8 ; (NC) .error: stc retn ``` Finally, here's a very similar use of a skipping instruction in [DOSLFN Version 0.41c (11/2012)](http://adoxa.altervista.org/doslfn/). Instead of `test ax, imm16` they're using `mov cx, imm16` which has no effect on the status flags but clobbers the `cx` register instead. (Opcode `0B9h` is `mov ecx, imm32` in non-16-bit modes, and writes to the full `ecx` or `rcx` register.) ``` ;THROW-Geschichten... [english: THROW stories...] SetErr18: mov al,18 db 0B9h ;mov cx,nnnn SetErr5: mov al,5 db 0B9h ;mov cx,nnnn SetErr3: mov al,3 db 0B9h ;mov cx,nnnn SetErr2: mov al,2 SetError: ``` [Answer] # CPU registers and flags are in known startup states For a full/standalone program, we can assume that the CPU is in a known and documented default state based on platform and OS. For example: DOS <http://www.fysnet.net/yourhelp.htm> Linux x86 ELF <http://asm.sourceforge.net/articles/startup.html> - in `_start` in a static executable, most registers are zero other than the stack pointer, to avoid leaking info into a fresh process. `pop` will load `argc` which is a small non-negative integer, `1` if run normally from a shell with no args. Same applies for x86-64 processes on Linux. [Answer] # `mov` small immediates into lower registers when applicable If you already know the upper bits of a register are 0, you can use a shorter instruction to move an immediate into the lower registers. ``` b8 0a 00 00 00 mov $0xa,%eax ``` versus ``` b0 0a mov $0xa,%al ``` # Use `push`/`pop` for imm8 to zero upper bits Credit to Peter Cordes. `xor`/`mov` is 4 bytes, but `push`/`pop` is only 3! ``` 6a 0a push $0xa 58 pop %eax ``` [Answer] # Use do-while loops instead of while loops This is not x86 specific but is a widely applicable beginner assembly tip. If you know a while loop will run at least once, rewriting the loop as a do-while loop, with loop condition checking at the end, often saves a 2 byte jump instruction. In a special case you might even be able to use [`loop`](https://codegolf.stackexchange.com/a/133095/17360). [Answer] # The [FLAGS](https://en.wikipedia.org/wiki/FLAGS_register) are set after many instructions After many arithmetic instructions, the Carry Flag (unsigned) and Overflow Flag (signed) are set automatically ([more info](https://stackoverflow.com/questions/791991/about-assembly-cfcarry-and-ofoverflow-flag)). The Sign Flag and Zero Flag are set after many arithmetic and logical operations. This can be used for conditional branching. Example: ``` d1 f8 sar %eax ``` ZF is set by this instruction, so we can use it for condtional branching. [Answer] # `lea` for math This is probably one of the first things one learns about x86, but I leave it here as a reminder. `lea` can be used to do multiplication by 2, 3, 4, 5, 8, or 9, and adding an offset. For example, to calculate `ebx = 9*eax + 3` in one instruction (in 32-bit mode): ``` 8d 5c c0 03 lea 0x3(%eax,%eax,8),%ebx ``` Here it is without an offset: ``` 8d 1c c0 lea (%eax,%eax,8),%ebx ``` Wow! Of course, `lea` can be used to also do math like `ebx = edx + 8*eax + 3` for calculating array indexing. [Answer] # Use `fastcall` conventions x86 platform has [many calling conventions](https://en.wikipedia.org/wiki/X86_calling_conventions). You should use those that pass parameters in registers. On x86\_64, the first few parameters are passed in registers anyway, so no problem there. On 32-bit platforms, the default calling convention (`cdecl`) passes parameters in stack, which is no good for golfing - accessing parameters on stack requires long instructions. When using `fastcall` on 32-bit platforms, 2 first parameters are usually passed in `ecx` and `edx`. If your function has 3 parameters, you might consider implementing it on a 64-bit platform. C function prototypes for `fastcall` convention (taken from [this example answer](https://codegolf.stackexchange.com/a/119057/25315)): ``` extern int __fastcall SwapParity(int value); // MSVC extern int __attribute__((fastcall)) SwapParity(int value); // GNU ``` --- Note: you can also use other calling conventions, including custom ones. I never use custom calling conventions; for any ideas related to these, see [here](https://codegolf.stackexchange.com/a/165020/25315). [Answer] # Combinations with CDQ for certain piecewise-linear functions `CDQ` sign-extends EAX into EDX, making EDX 0 if EAX is nonnegative and -1 (all 1s) if EAX is negative. This can be combined with several other instructions to apply certain piecewise-linear functions to a value in EAX in 3 bytes: `CDQ` + `AND` → \$ \min(x, 0) \$ (in either EAX or EDX). (I have used this [here](https://codegolf.stackexchange.com/a/241451/104752).) `CDQ` + `OR` → \$ \max(x, -1) \$. `CDQ` + `XOR` → \$ \max(x, -x-1) \$. `CDQ` + `MUL EDX` → \$ \max(-x, 0) \$ in EAX and \$ \left\{ \begin{array}{ll} 0 & : x \ge 0 \\ x - 1 & : x < 0 \end{array} \right.\$ in EDX. [Answer] The loop and string instructions are smaller than alternative instruction sequences. Most useful is `loop <label>` which is smaller than the two instruction sequence `dec ECX` and `jnz <label>`, and `lodsb` is smaller than `mov al,[esi]` and `inc si`. [Answer] # Entry point doesn't necessarily have to be first byte of submission I came across [this answer](https://codegolf.stackexchange.com/questions/118444/stay-away-from-zero/151115#151115), and didn't understand it at first until I realized that the intention is: ``` ; ---- example calling code starts here ------------- MOV ECX, 1 CALL entry RET ; ---- code golf answer code starts here (5 bytes) -- 41 INC ECX entry: E3 FD JECXZ SHORT $-1 91 XCHG EAX,ECX C3 RETN ; ---- code golf answer code ends here ------------- ``` Does not seem to conflict with any of the conditions of "[Choose your calling convention](https://codegolf.stackexchange.com/questions/132981/tips-for-golfing-in-x86-x64-machine-code/132983#132983)" and is otherwise valid assembly language. [Answer] # Use a good assembler There are dozens of x86 assemblers out there, and they are **not** created equal. Not only can a bad assembler be painful to use, but **they might not always output the most optimal code.** Most x86 instructions have multiple valid encodings, some shorter than others. For example, I saw one user with a 16-bit assembler that emitted different code depending on the order of `xchg`'s operands. It is a commutative operation, it shouldn't make a difference. ``` 87 D8 xchg ax, bx 93 xchg bx, ax ``` Life is too short for bad assemblers, and it should **not** be the thing getting in the way of golfing. The three assemblers I would suggest are: * [nasm](http://www.nasm.us/) is the first one I would recommend to everyone (and I wish I had learned it first). + It fully supports 16-bit, 32-bit, *and* 64-bit code + It can easily assemble all sorts of object formats, as well as raw binaries/`.com` files (a multi-step ritual with GAS). + **It is officially supported on DOS** as well as all modern OSes. + While it doesn't support C macros, it has a god-tier preprocessor that is much better than C. + The way it handles local labels is really nice. + Good error messages, mostly fairly beginner-friendly pointing you in the direction of why an instruction isn't allowed or what it doesn't like about a source line. * [GAS](https://sourceware.org/binutils/docs/as/index.html) ([GCC](https://gcc.gnu.org)'s assembler) is another fairly good assembler. + It is the assembler used by GCC and Clang. You might recognize it if you use Godbolt or `gcc -S`. + It supports AT&T syntax which some might prefer + With `.intel_syntax noprefix`, you can switch to Intel syntax + While its built-in preprocessor is pretty limited, it can be easily combined with a C preprocessor. + For x87, beware of [the AT&T syntax design bug](https://sourceware.org/binutils/docs/as/i386_002dBugs.html) that interchanges `fsubr` with `fsub` in some cases, same for `fdiv[r]`. Older GAS versions applied the same swap in Intel-syntax mode, and so did older binutils `objdump -d` versions. (This is AT&T's fault, not GNU's, and current GAS versions do as well as possible, but is an inherent downside in using AT&T syntax for x87.) + Error messages are less helpful than NASM about why an instruction is invalid + Ambiguous instructions other than `mov` default to dword operand-size instead of being an error in AT&T syntax, such as `add $123, (%rdi)` assembling as `addl`. Clang, and GAS in Intel syntax mode, error on this. * [Clang](https://clang.llvm.org) is, in most cases, completely exchangeable for GAS. + It has much more helpful error messages and doesn't silently treat x86\_64 registers as symbols in 32-bit mode. + While AT&T syntax is fully supported, Intel syntax currently has a few bugs. - It is the **only** reason I am recommending GAS over Clang. 😔 - It still works as a solid linter. + It also supports C macros. I haven't used enough of the other assemblers to give a good opinion, as I am more than satisfied with those three. [FASM](https://flatassembler.net/) is also well-regarded, using very nearly the same syntax as NASM, and is supported on <https://TIO.run/> ; It's able to make 32-bit executables on TIO, unlike with other assemblers, using the directive `format ELF executable 3` to emit a 32-bit ELF executable, not a `.o` object file that would need linking. [EuroAssembler](https://euroassembler.eu/eadoc/) is also open-source; its maintainer is [active on Stack Overflow](https://stackoverflow.com/users/2581418/vitsoft) in the [assembly] and [x86] tags. [Answer] To add or subtract 1, use the one byte `inc` or `dec` instructions which are smaller than the multibyte add and sub instructions. [Answer] # Try `XLAT` for byte memory access [`XLAT`](https://www.felixcloutier.com/x86/xlat:xlatb) is a **one byte** instruction that is equivalent to `AL = [BX+AL]`. Yes, that's right, it lets you use `AL` as an index register for memory access. [Answer] # Take advantage of the x86\_64 code model Linux's default code model will put all of your code and globals in the low 31 bits of memory, so 32-bit pointer arithmetic here is perfectly safe. The stack, libraries, and any dynamically allocated pointers are not, though. [Try it online!](https://tio.run/##tZHbigIxDIbv@xRB8EotnvDCZ9g3WEUytc4WMm1Jqoy@/DieZkZQ2IW1l8n3fyUJitgio@MoN6aqdE4hIyjQeaWdT5Y2cvQJS/Ahst25Ul16SwX3F/fyA4xlUyCLwFs3hG92EQagvyLXop0kXjdQEQ7AUkM12RQNEsENfrZJ18ZhiwnXf/vvd@qPiTORf/DGEJ82zTapTri9iUYx7gS9/niyICpXvte2xJrkggd926N6LLSTpuBzmE1fZO6JN3zL1fOq69Qd6mQ5wFxV1Rk "Assembly (gcc, x64, Linux) – Try It Online") Make sure to still use the entire 64 bits in memory operands (**including lea**), because using `[eax]` requires a `67` prefix byte. [Answer] # Use interrupts and syscalls wisely In general, unlike the C calling conventions, most syscalls and interrupts will preserve your registers and flags unless noted otherwise, except for a return value usually in AL/EAX/RAX depending on the OS. (e.g. the x86-64 `syscall` instruction itself [destroys RCX and R11](https://stackoverflow.com/questions/47983371/why-do-x86-64-linux-system-calls-modify-rcx-and-what-does-the-value-mean)) #### Linux specific: * If exiting with a crash is okay, `int3`, `int1`, or `into` can usually do the job in one byte. Don't try this on DOS though, it will lock up. + Note that the error messages like `Segmentation fault (core dumped)` or `Trace/breakpoint trap` are actually printed by your *shell*, not the program/kernel. Don't believe me? Try running `set +m` before your program or redirecting stderr to a file. * You can use `int 0x80` in 64-bit mode. [It will use the 32-bit ABI though](https://stackoverflow.com/questions/46087730/what-happens-if-you-use-the-32-bit-int-0x80-linux-abi-in-64-bit-code) (eax, ebx, ecx, edx), so make sure all pointers are in the low 32 bits. On the small code model, this true for all code stored in your binary. Keep this in mind for [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'"). + Additionally, `sysenter` and `call dword gs:0x10` can also do syscalls in 32-bit mode, although the calling convention is quite....weird for the former. #### DOS/BIOS specific: * Use `int 29h` instead of `int 21h:02h` for printing single bytes to the screen. `int 29h` doesn't need `ah` to be set and *very* conveniently uses `al` instead of `dl`. It writes directly to the screen, so you can't just redirect to a file, though. * DOS also has `strlen` and `strcmp` interrupts (see [this helpful page for this and other undocumented goodies](http://www.fysnet.net/undoc.htm)) * Unless you modified `cs`, **don't** use `int 20h` or `int 21h:4Ch` for exiting, just `ret` from your `.com` file. Alternatively, if you happen to have `0x0000` on the top of your stack, you can also `ret` to that. * In the rare case that you need to call helper functions more than 4 times, consider registering them to the `int1`, `int3`, or `into` interrupts. Make sure to use `iret` instead of `ret`, though. ``` ; AH: 0x25 (set interrupt) ; AL: 0x03 (INT3) ; Use 0x2504 for INTO, or 0x2501 for INT1 mov ax, 0x2503 ; DX: address to function (make sure to use IRET instead of RET) mov dx, my_interrupt_func int 0x21 ; Now instead of this 3 byte opcode... call my_func ; ...just do this 1 byte opcode. int3 ; or int1, into ``` * [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") tip: Your interrupt vector table is a table of far pointers at `0000:0000` (so for example, `int 21h` is at `0000h:0084h`). [Answer] # Use conditional moves [`CMOVcc`](http://www.felixcloutier.com/x86/CMOVcc.html) and sets [`SETcc`](https://c9x.me/x86/html/file_module_x86_id_288.html) This is more a reminder to myself, but conditional set instructions exist and conditional move instructions exist on processors P6 (Pentium Pro) or newer. There are many instructions that are based on one or more of the flags set in EFLAGS. [Answer] # Use whatever calling conventions are convenient System V x86 uses the stack and System V x86-64 uses `rdi`, `rsi`, `rdx`, `rcx`, etc. for input parameters, and `rax` as the return value, but it is perfectly reasonable to use your own calling convention. [\_\_fastcall](https://msdn.microsoft.com/en-us/library/6xa169sk.aspx) uses `ecx` and `edx` as input parameters, and [other compilers/OSes use their own conventions](https://en.wikipedia.org/wiki/X86_calling_conventions#List_of_x86_calling_conventions). Use the stack and whatever registers as input/output when convenient. Example: [The repetitive byte counter](https://codegolf.stackexchange.com/a/160236/17360), using a clever calling convention for a 1 byte solution. Meta: [Writing input to registers](https://codegolf.meta.stackexchange.com/a/8508/17360), [Writing output to registers](https://codegolf.meta.stackexchange.com/a/8509/17360) Other resources: [Agner Fog's notes on calling conventions](http://agner.org/optimize/calling_conventions.pdf) [Answer] # Save on `jmp` bytes by arranging into if/then rather than if/then/else This is certainly very basic, just thought I would post this as something to think about when golfing. As an example, consider the following straightforward code to decode a hexadecimal digit character: ``` cmp $'A', %al jae .Lletter sub $'0', %al jmp .Lprocess .Lletter: sub $('A'-10), %al .Lprocess: movzbl %al, %eax ... ``` This can be shortened by two bytes by letting a "then" case fall into an "else" case: ``` cmp $'A', %al jb .digit sub $('A'-'0'-10), %eax .digit: sub $'0', %eax movzbl %al, %eax ... ``` [Answer] # (way too many) ways of zeroing a register I remember being taught these by a certain person (I "invented" some of these myself); I don't remember who did I get them from, anyways these are the most interesting; possible use cases include restricted source code challenges or other bizzare stuff. `=>` Zero mov: ``` mov reg, 0 ; mov eax, 0: B800000000 ``` `=>` `push`+`pop`: ``` push [something equal to zero] pop reg ; push 0 / pop eax: 6A0058 ; note: if you have a register equal to zero, it will be ; shorter but also equal to a mov. ``` `=>` `sub` from itself: ``` sub reg, reg ; sub eax, eax: 29C0 ``` `=>` `mul` by zero: ``` imul reg, 0 ; imul eax, 0: 6BC000 ``` `=>` `and` by zero: ``` and reg, 0 ; and eax, 0: 83E000 ``` `=>` `xor` by itself: ``` xor reg, reg ; xor eax, eax: 31C0 ; possibly the best way to zero an arbitrary register, ; I remembered this opcode (among other). ``` `=>` `or` and `inc` / `not`: ``` or reg, -1 inc reg ; or not reg ; or eax, -1 / inc eax: 83C8FF40 ``` `=>` reset `ECX`: ``` loop $ ; loop $: E2FE ``` `=>` flush `EDX`: ``` shr eax, 1 cdq ; D1E899 ``` `=>` zero `AL` (`AH = AL, AL = 0`) ``` aam 1 ; D401 ``` `=>` reset `AH`: ``` aad 0 ; D500 ``` `=>` Read 0 from the port ``` mov dx, 81h in al, dx ; 66BA8100EC ``` `=>` Reset `AL` ``` stc setnc al ; F90F93C0 ``` `=>` Use the zero descriptor from `gdt`: ``` sgdt [esp-6] mov reg, [esp-4] mov reg, [reg] ; with eax: 0F014424FA8B4424FC8B00 ``` `=>` Read zero from the `fs` segment (PE `exe` only) ``` mov reg, fs:[10h] ; with eax: 64A110000000 ``` `=>` The brainfuck way ``` inc reg jnz $-1 ; with eax: 4075FD ``` `=>` Utilize the coprocessor ``` fldz fistp dword ptr [esp-4] mov eax, [esp-4] ; D9EEDB5C24FC8B4424FC ``` Another possible options: * Read zero using the builtin random number generator. * calculate sine from `pi * n` (use `fmul`). There are way cooler and potentially useful ways to execute this operation; although I didn't come up with them, therefore I'm not posting. [Answer] # Use multiplication for hashing [IMUL](https://c9x.me/x86/html/file_module_x86_id_138.html), multiplication by an immediate signed number, is a powerful instruction which can be used for hashing. The regular multiplication instruction hard-codes one of the input operands and the output operand to be in `eax` (or `ax` or `al`). This is inconvenient; it requires instructions for setup and sometimes also to save and restore `eax` and `edx`. But if one of the operands is a constant, the instruction becomes much more versatile: * No need to load the constant into a register * The other operand can be in any register, not only `eax` * The result can be in any register, not necessarily overwriting the input! * The result is 32-bit, not a pair of registers * If the constant is between -128 and 127, it can be encoded by only one byte I used this many times (I hope I can be excused for these shameless plugs: [1](https://codegolf.stackexchange.com/a/193500/25315) [2](https://codegolf.stackexchange.com/a/205522/25315) [3](https://codegolf.stackexchange.com/a/187720/25315) ...) [Answer] "Free bypass": If you already have an instruction with an immediate on a register that you only care about the low part of, making the immediate longer than necessary could allow you to insert into its high part other instructions that can be jumped to (but don't execute when coming from before). This works because of little-endianness. [Example](https://codegolf.stackexchange.com/a/244118/104752); [another example](https://codegolf.stackexchange.com/a/245361/104752). [Answer] **To copy a 64-bit register, use `push rcx` ; `pop rdx`** instead of a 3-byte `mov`. The default operand-size of push/pop is 64-bit without needing a REX prefix. ``` 51 push rcx 5a pop rdx vs. 48 89 ca mov rdx,rcx ``` (An operand-size prefix can override the push/pop size to 16-bit, but [32-bit push/pop operand-size is not encodeable in 64-bit mode](https://stackoverflow.com/questions/45127993/how-many-bytes-does-the-push-instruction-push-onto-the-stack-when-i-dont-specif) even with REX.W=0.) If either or both registers are `r8`..`r15`, use `mov` because push and/or pop will need a REX prefix. Worst case this actually loses if both need REX prefixes. Obviously you should usually avoid r8..r15 anyway in code golf. --- You can keep your source more readable while developing with this **NASM macro**. Just remember that it steps on the 8 bytes below RSP. (In the red-zone in x86-64 System V). But under normal conditions it's a drop-in replacement for 64-bit `mov r64,r64` or `mov r64, -128..127` ``` ; mov %1, %2 ; use this macro to copy 64-bit registers in 2 bytes (no REX prefix) %macro MOVE 2 push %2 pop %1 %endmacro ``` Examples: ``` MOVE rax, rsi ; 2 bytes (push + pop) MOVE rbp, rdx ; 2 bytes (push + pop) mov ecx, edi ; 2 bytes. 32-bit operand size doesn't need REX prefixes MOVE r8, r10 ; 4 bytes, don't use mov r8, r10 ; 3 bytes, REX prefix has W=1 and the bits for reg and r/m being high xchg eax, edi ; 1 byte (special xchg-with-accumulator opcodes) xchg rax, rdi ; 2 bytes (REX.W + that) xchg ecx, edx ; 2 bytes (normal xchg + modrm) xchg rcx, rdx ; 3 bytes (normal REX + xchg + modrm) ``` The `xchg` part of the example is because sometimes you need to get a value into EAX or RAX and don't care about preserving the old copy. push/pop doesn't help you actually exchange, though. [Answer] # Try `AAM` or `AAD` for byte division operations If you are working with only 8 bit values, using the [`AAM`](https://www.felixcloutier.com/x86/aam) instruction can sometimes save several bytes over [`DIV reg8`](https://www.felixcloutier.com/x86/div) since it will take an `imm8` and returns remainder and quotient in opposite `AH/AL` registers as `DIV`. ``` D4 0A AAM ; AH = AL / 10, AL = AL % 10 ``` It can also accept any byte value as the divisor as well by altering the second byte. ``` D4 XX AAM XX ; AH = AL / XX, AL = AL % XX ``` And `AAD` is the inverse of this, which is two operations in one. ``` D5 XX AAD XX ; AL = AH * XX + AL ``` [Answer] # Avoid registers which need prefixes Quite a simple tip I haven't seen mentioned before. **Avoid `r8-r15` (as well as `dil`, `sil`, `bpl`, and `spl`) on x86\_64 like the plague.** Even just thinking about these registers requires an extra REX prefix. The only exception is if you are using them exclusively for 64-bit arithmetic (which also needs REX prefixes). Even still, you are usually better off using a low register since some operations can be done using the implicit zero extension. Note that this tip also applies to ARM Thumb-2. Additionally, be careful when using 16-bit registers in 32/64-bit mode (as well as 32-bit registers in 16-bit mode, but this is rare), as these need a prefix byte as well. However, unlike the extra x86\_64 registers, 16-bit instructions can be useful: Many instructions which would otherwise need a full 32-bit immediate argument will only use a 16-bit argument. So, if you were to bitwise and `eax` by `0xfffff00f`, `and ax, 0xf00f` would be smaller. ]
[Question] [ # Do While False At work today one of my colleagues was describing the use-case for do while(false). The person he was talking to thought that this was silly and that simple if statements would be much better. We then proceeded to waste half of our day discussing the best manner to write something equivalent to: ``` do { //some code that should always execute... if ( condition ) { //do some stuff break; } //some code that should execute if condition is not true if ( condition2 ) { //do some more stuff break; } //further code that should not execute if condition or condition2 are true } while(false); ``` This is an idiom which is found in c quite often. Your program should produce the same output as the below pseudo-code depending on the conditions. ``` do { result += "A"; if ( C1) { result += "B"; break; } result += "C" if ( C2 ) { result += "D"; break; } result += "E"; } while(false); print(result); ``` Therefore the input could be: ``` 1. C1 = true, C2 = true 2. C1 = true, C2 = false 3. C1 = false, C2 = true 4. C1 = false, C2 = false ``` and the output should be: ``` 1. "AB" 2. "AB" 3. "ACD" 4. "ACE" ``` This is code-golf so answers will be judged on bytes. Standard loopholes are banned. Yes this is a simple one, but hopefully we will see some creative answers, I'm hoping the simplicity will encourage people to use languages they are less confident with. [Answer] # Python 3, 31 Saved 1 byte thanks to xnor. Only one byte away from ES6. :/ Stupid Python and its long anonymous function syntax. Hooray for one liners! ``` lambda x,y:x*"AB"or"AC"+"ED"[y] ``` Test cases: ``` assert f(1, 1) == "AB" assert f(1, 0) == "AB" assert f(0, 1) == "ACD" assert f(0, 0) == "ACE" ``` [Answer] # JavaScript ES6, ~~30~~ ~~26~~ 25 bytes A simple anonymous function taking two inputs. Assign to a variable to call. **Update**: Let's jump on the index bandwagon. It saves 4 bytes. *I have secured my lead over Python*. Saved a byte by currying the function; call like `(...)(a)(b)`. Thanks Patrick Roberts! ``` a=>b=>a?"AB":"AC"+"ED"[b] ``` Old, original version, 30 bytes (included to not melt into the python answer `(;`): ``` (a,b)=>"A"+(a?"B":b?"CD":"CE") ``` [Answer] # C preprocessor macro, 34 * 1 byte saved thanks to @TobySpeight ``` #define f(a,b)a?"AB":b?"ACD":"ACE" ``` [Try it online](https://tio.run/##ZY9NbsMgEIX3PsWIqJJJaIqzjJNU/ckpUi/IGBKkFleAu2jksztj2XUdhQXwzXvMPPDxhNi2s1Ib6zSYVIkjV8/s5ZWtj3S8vbM17XvWzqzDz7rUsAmxtNXyvEsgsS7Cl7IO0u6m/AkF4Fl5mM8JfjhcEqDViTYnfwch@hrjoPQaZvmUVj01EHWIqIIOhwK244tLJiBrxITkP8kbTXZa3@xvvKk8paV2MgcLGwj2V1cmHUdxeLqrHWTByb1Y8DHEt6eoJmUP4cMxAVOzLZZIoW4LK86HXw05vI61d5Qiador). [Answer] ## Haskell, 28 bytes ``` x#y|x="AB"|y="ACD"|1<2="ACE" ``` Usage example: `False # True` -> `"ACD"`. Using the input values directly as guards. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 15 ~~17~~ bytes ``` ?'AB'}'AC'69i-h ``` Inputs are `0` or `1` on separate lines. Alternatively, `0` can be replaced by `F` (MATL's `false`) and `1` by `T` (MATL's `true`). [**Try it online!**](http://matl.tryitonline.net/#code=PydBQid9J0FDJzY5aS1o&input=MAowCg) ``` ? % if C1 (implicit input) 'AB' % push 'AB' } % else 'AC' % push 'AC' 69 % push 69 ('E') i- % subtract input. If 1 gives 'D', if 0 leaves 'E' h % concatenate horizontally % end if (implicit) ``` [Answer] ## Brainfuck, 65 bytes This assumes that C1 and C2 are input as raw 0 or 1 bytes. e.g. ``` echo -en '\x00\x01' | bf foo.bf ``` Golfed: ``` ++++++++[>++++++++<-]>+.+>+>,[<-<.>>-]<[<+.+>>,[<-<.>>-]<[<+.>-]] ``` Ungolfed: ``` Tape _0 ++++++++[>++++++++<-]>+.+ print A 0 _B >+>, read C1 0 B 1 _0 or 0 B 1 _1 [<-<.>>-]< print B 0 B _0 0 or 0 B _1 0 [<+.+>> print C 0 D 1 _0 , read C2 0 D 1 _0 or 0 D 1 _1 [<-<.>>-]< print D 0 D _0 0 or 0 D _1 0 [<+.>-] print E 0 D _0 or 0 E _0 ] ``` I believe it worth noting that this solution *is* in fact based on breaking out of while loops. [Answer] # GNU Sed, 21 ``` /^1/cAB /1$/cACD cACE ``` [Ideone](https://ideone.com/2GUPrv). [Answer] # [NTFJ](https://github.com/ConorOBrien-Foxx/NTFJ/), 110 bytes ``` ##~~~~~#@|########@|~#~~~~~#@*(~#~~~~#~@*########@^)~#~~~~##@*##~~~~~#@|########@|(~#~~~#~~@*):~||(~#~~~#~#@*) ``` More readable: ``` ##~~~~~#@|########@|~#~~~~~#@*(~#~~~~#~@*########@^)~#~~~~##@*##~~~~~#@|########@|(~#~~~#~~@* ):~||(~#~~~#~#@*) ``` That was certainly entertaining. [Try it out here](http://conorobrien-foxx.github.io/NTFJ/), using two characters (`0` or `1`) as input. Using ETHProduction's method for converting to 0, 1 (characters) to bits, this becomes simpler. ``` ##~~~~~#@|########@| ``` This is the said method. Pushing 193 (`##~~~~~#@`), NANDing it (`|`) with the top input value (in this case, the first char code, a 48 or 49). This yields 254 for 1 and 255 for 0. NANDing it with 255 (`########@`) yields a 0 or 1 bit according to the input. ``` ~#~~~~~#@* ``` This prints an `A`, since all input begins with `A`. `*` pops the `A` when printing, so the stack is unchanged from its previous state. ``` (~#~~~~#~@*########@^) ``` Case 1: the first bit is `1`, and `(` activates the code inside. `~#~~~~#~@*` prints `B`, and `########@^` pushes 255 and jumps to that position in the code. This being the end of the program, it terminates. Case 2: the first bit is `0`. `(` skips to `)` and the code continues. ``` ~#~~~~##@* ``` This prints a `C`, because that's the next character. ``` ##~~~~~#@|########@| ``` This converts our second input to a bit. ``` (~#~~~#~~@*) ``` If our second bit is a 1, we proceed to print an `E`. ``` :~|| ``` This is the NAND representation of the Boolean negation of our bit: `A NAND (0 NAND A) = NOT A`. ``` (~#~~~#~#@*) ``` This now activates if the bit was a `0`, and prints `E`. [Answer] # Pyth, 16 bytes ``` +\A?Q\B+\C?E\D\E ``` [Test suite](https://pyth.herokuapp.com/?code=%2B%5CA%3FQ%5CB%2B%5CC%3FE%5CD%5CE&test_suite=1&test_suite_input=1%0A1%0A1%0A0%0A0%0A1%0A0%0A0&debug=0&input_size=2) Ternaries! Explanation: ``` +\A Start with an A ?Q\B If the first variable is true, add a B and break. +\C Otherwise, add a C and ?E\D If the second variable is true, add a D and break. \E Otherwise, add a E and finish. ``` Input on two consecutive lines. [Answer] # CJam, 15 ~~16~~ ~~17~~ bytes ``` 'Ali'B'C'Eli-+? ``` [**Try it online!**](http://cjam.tryitonline.net/#code=J0FsaSdCJ0MnRWxpLSs_&input=MAox) *One byte off thanks to @randomra, and one byte off thanks to @Dennis* Explanation: ``` 'A e# push "A" li e# read first input as an integer 'B e# push "B" 'C e# push "C" 'E e# push "E" li- e# leave "E" or change to "D" according to second input + e# concatenate "C" with "E" or "D" ? e# select "B" or "C..." according to first input ``` --- Old version (16 bytes): ``` 'Ali'B{'C'Eli-}? ``` Explanation: ``` 'A e# push character "A" ? e# if-then-else li e# read first input as an integer. Condition for if 'B e# push character "B" if first input is true { } e# execute this if first input is false 'C e# push character "C" 'E e# push character "E" li e# read second input as an integer - e# subtract: transform "E" to "D" if second input is true e# implicitly display stack contents ``` [Answer] ## Pyth, 13 chars, 19 bytes ``` .HC@"૎્««"iQ2 ``` Takes input in form [a,b] Explanation ``` - autoassign Q = eval(input()) iQ2 - from_base(Q, 2) - convert to an int @"૎્««" - "૎્««"[^] C - ord(^) .H - hex(^) ``` [Try it here](http://pyth.herokuapp.com/?code=.HC%40%22%E0%AB%8E%E0%AB%8D%C2%AB%C2%AB%22iQ2&input=%5B0%2C1%5D&debug=0) [Or use a test suite](http://pyth.herokuapp.com/?code=.HC%40%22%E0%AB%8E%E0%AB%8D%C2%AB%C2%AB%22iQ2&input=%5B0%2C1%5D&test_suite=1&test_suite_input=%5B0%2C0%5D%0A%5B0%2C1%5D%0A%5B1%2C0%5D%0A%5B1%2C1%5D&debug=0) [Answer] # C, 76 bytes I renamed `c1` to `c`, `c2` to `C` and `result` to `r`. C programmers go to extremes to avoid `goto`. If you ever have a problum with absurd syntax in C, it is most likely to be because you did not use `goto`. ``` char r[4]="A";if(c){r[1]=66;goto e;}r[1]=67;if(C){r[2]=68;goto e;}r[2]=69;e: ``` ### Ungolfed ``` char r[4] = "A"; if(c1){ r[1] = 'B'; goto end; } r[1] = 'C'; if(c2){ r[2] = 'D'; goto end; } r[2] = 'E'; end: ``` [Answer] ## C, 41 bytes I'm not sure if the question requires a program, a function or a code snippet. Here's a function: ``` f(a,b){a=a?16961:4473665|b<<16;puts(&a);} ``` It gets the input in two parameters, which must be 0 or 1 (well, `b` must), and prints to stdout. Sets `a` to one of `0x4241`, `0x454341` or `0x444341`. When printed as a string, on a little-endian ASCII system, gives the required output. [Answer] # [R](https://www.r-project.org/), ~~41~~ ~~39~~ 37 bytes ``` pryr::f(c("ACD","ACE","AB")[1+a+a^b]) ``` [Try it online!](https://tio.run/##K/qfZvu/oKiyyMoqTSNZQ8nR2UVJB0i6gkgnJc1oQ@1E7cS4pFjN/2kaIUGhrjoKIFKTC8Zzc/QJBnPBDIQslAuR/g8A "R – Try It Online") In R, `TRUE` and `FALSE` are coerced to `1` and `0` respectively when you attempt to use them as numbers. We can convert these numbers to indices `1`, `2`, and `3` through the formula `1+a+a^b`. ``` a | b | 1+a+a^b TRUE | TRUE | 1+1+1^1 = 3 TRUE | FALSE| 1+1+1^0 = 3 FALSE| TRUE | 1+0+0^1 = 1 FALSE| FALSE| 1+0+0^0 = 2 ``` These values are then used to index the list `ACD`, `ACE`, `AB` to yield the correct output. Saved two bytes thanks to JayCe. If instead you prefer a version with an `if` statement, there's the following for 41 bytes: ``` pryr::f(`if`(a,"AB",`if`(b,"ACD","ACE"))) ``` [Try it online!](https://tio.run/##K/qfZvu/oKiyyMoqTSMhMy1BI1FHydFJSQfMTgKynV2UQKSrkqam5v80jZCgUFcdBRCpyQXjuTn6BIO5YAZCFsqFSP8HAA "R – Try It Online") [Answer] # Mathematica, ~~35~~ 30 bytes ``` If[#,"AB",If[#2,"ACD","ACE"]]& ``` Very simple. Anonymous function. [Answer] ## Retina, 22 bytes ``` 1.+ AB .+1 ACD .+0 ACE ``` [Try it Online](http://retina.tryitonline.net/#code=MS4rCkFCCi4rMQpBQ0QKLiswCkFDRQ&input=MSAxCjEgMAowIDEKMCAw) [Answer] # JavaScript, 38 bytes Use no-delimiter `0` or `1` instead of `false`/`true` ``` _=>"ACE ACD AB AB".split` `[+('0b'+_)] ``` [Answer] ## [**Caché ObjectScript**](http://docs.intersystems.com/cache20152/csp/docbook/DocBook.UI.Page.cls?KEY=GCOS), 27 bytes ``` "A"_$s(x:"B",y:"CD",1:"CE") ``` [Answer] # [ArnoldC](http://mapmeld.github.io/ArnoldC/), 423 bytes ``` IT'S SHOWTIME HEY CHRISTMAS TREE a YOU SET US UP 0 HEY CHRISTMAS TREE b YOU SET US UP 0 BECAUSE I'M GOING TO SAY PLEASE a BECAUSE I'M GOING TO SAY PLEASE b TALK TO THE HAND "ABD" BULLSHIT TALK TO THE HAND "ABE" YOU HAVE NO RESPECT FOR LOGIC BULLSHIT BECAUSE I'M GOING TO SAY PLEASE b TALK TO THE HAND "ACD" BULLSHIT TALK TO THE HAND "ACE" YOU HAVE NO RESPECT FOR LOGIC YOU HAVE NO RESPECT FOR LOGIC YOU HAVE BEEN TERMINATED ``` Since ArnoldC doesn't seem to have formal input, just change the first 2 `YOU SET US UP` values to either 0 or 1 instead. # Explanation This is just a whole bunch of conditional statements which account for all the possible outputs. Why, you may ask? Well, ArnoldC doesn't really have string comprehension. It can't even concatenate strings! As a result, we have to resort to the more... inefficient... method. [Answer] # Java, 28 bytes Same boilerplate as a lot of the answers. type is `BiFunction<Boolean,Boolean, String>`. ``` (c,d)->c?"AB":d?"ACD":"ACE" ``` [Answer] # Pyth, 21 bytes ``` @c"ACE ACD AB AB"diz2 ``` [Try it here!](http://pyth.herokuapp.com/?code=%40c%22ACE+ACD+AB+AB%22diz2&input=00&test_suite=1&test_suite_input=11%0A10%0A01%0A00&debug=0) Input is taken as 0 or 1 instead of true/false while C1 comes first. ## Explanation Just using the fact that there are only 4 possible results. Works by interpreting the input as binary, converting it to base 10 and using this to choose the right result from the lookup string. ``` @c"ACE ACD AB AB"diz2 # z= input iz2 # Convert binary input to base 10 c"ACE ACD AB AB"d # Split string at spaces @ # Get the element at the index ``` [Answer] # [Y](https://github.com/ConorOBrien-Foxx/Y/), 20 bytes In the event that the first input is one, only one input is taken. I assume that this behaviour is allowed. [Try it here!](http://conorobrien-foxx.github.io/Y/) ``` 'B'AjhMr$'C'E@j-#rCp ``` Ungolfed: ``` 'B'A jh M r$ 'C 'E@ j - # r C p ``` Explained: ``` 'B'A ``` This pushes the characters `B` then `A` to the stack. ``` jh M ``` This takes one input, increments it, pops it and moves over that number of sections. Case 1: `j1 = 0`. This is the more interesting one. `r$` reverses the stack and pops a value, `'C'E` pushes characters `C` and `E`. `@` converts `E` to its numeric counterpart, subtracts the second input from it, and reconverts it to a character. `r` un-reverses the stack. Then, the program sees the C-link and moves to the next link `p`, and prints the stack. Case 2: the program moves to the last link `p`, which merely prints the entire stack. [Answer] ## PowerShell, 40 bytes ``` param($x,$y)(("ACE","ACD")[$y],"AB")[$x] ``` Nested arrays indexed by input. In PowerShell, `$true` / `1` and `$false` / `0` are practically equivalent (thanks to very loose typecasting), so that indexes nicely into a two-element array. This is really as close to a ternary as PowerShell gets, and I've used it plenty of times in golfing. ### Examples ``` PS C:\Tools\Scripts\golfing> .\do-while-false.ps1 1 1 AB PS C:\Tools\Scripts\golfing> .\do-while-false.ps1 1 0 AB PS C:\Tools\Scripts\golfing> .\do-while-false.ps1 0 1 ACD PS C:\Tools\Scripts\golfing> .\do-while-false.ps1 0 0 ACE ``` [Answer] # K, 37 bytes ``` {?"ABCDE"@0,x,(1*x),(2*~x),(~x)*3+~y} ``` [Answer] # [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), 26 bytes Expects inputs as 1s or 0s through STDIN with a newline separating. ``` W([1m;]'DCA'W(Zr1+rZ 'BA'Z ``` ~~I actually discovered a serious problem with if statements during this challenge. D: This is posted with the broken version, but it works just fine. (I'll update this after I fix the problem)~~ Please note that I have updated Vitsy with a fix of if/ifnot. This change does not grant me any advantage, only clarification. Explanation: ``` W([1m;]'DCA'W(Zr1+rZ W Get one line from STDIN (evaluate it, if possible) ([1m;] If not zero, go to the first index of lines of code (next line) and then end execution. 'DCA' Push character literals "ACD" to the stack. W Get another (the second) line from STDIN. ( If not zero, do the next instruction. Z Output all of the stack. r1+r Reverse the stack, add one (will error out on input 0, 1), reverse. Z Output everything in the stack. 'BA'Z 'BA' Push character literals "AB" to the stack. Z Output everything in the stack. ``` [Try it Online!](http://vitsy.tryitonline.net/#code=VyhbMW07XSdEQ0EnVyhacjErcloKJ0JBJ1o&input=MAow) [Answer] # Jelly, 14 bytes ``` Ḥoị“ACD“AB“ACE ``` This expects the Booleans (**1** or **0**) as separate command-line arguments. [Try it online!](http://jelly.tryitonline.net/#code=4bikb-G7i-KAnEFDROKAnEFC4oCcQUNF&input=&args=MQ+MQ) ### How it works ``` Ḥoị“ACD“AB“ACE Main link. Left input: C1. Right input: C2. Ḥ Double C1. Yields 2 or 0. o Logical OR with C2. 2o1 and 2o0 yield 2. 0o1 and 0o0 yield 1 and 0, resp. “ACD“AB“ACE Yield ['ACD', 'AB', 'ACE']. ị Retrieve the string at the corresponding index. ``` [Answer] # [beeswax](http://esolangs.org/wiki/Beeswax), 26 bytes Interpreting `0` as false, `1` as true. ``` E`< D`d"`C`~< _T~T~`A`"b`B ``` Output: ``` julia> beeswax("codegolfdowhile.bswx",0,0.0,Int(20000)) i1 i1 AB Program finished! julia> beeswax("codegolfdowhile.bswx",0,0.0,Int(20000)) i1 i0 AB Program finished! julia> beeswax("codegolfdowhile.bswx",0,0.0,Int(20000)) i0 i1 ACD Program finished! julia> beeswax("codegolfdowhile.bswx",0,0.0,Int(20000)) i0 i0 ACE Program finished! ``` Clone my beeswax interpreter from [my Github repository](https://github.com/m-lohmann/BeeswaxEsolang.jl). [Answer] # C, ~~47~~ 45 bytes Since there are only 3 different outcomes, we can pick one of three strings like this: ``` char*f(c,d){return"AB\0 ACE\0ACD"+(!c<<d+2);} ``` Thanks to [Herman L](/users/70894) for 2 bytes ## Demo ``` #include<stdio.h> int main() { printf("%s\n%s\n%s\n%s\n", f(1,1), f(1,0), f(0,1), f(0,0)); } ``` [Answer] ## Perl, 23 bytes ``` say<>>0?AB:<>>0?ACD:ACE ``` Requires the `-E`|`-M5.010` flag and takes input as 1 and 0: ``` $ perl -E'say<>>0?AB:<>>0?ACD:ACE' <<< $'0\n0' ACE $ perl -E'say<>>0?AB:<>>0?ACD:ACE' <<< $'0\n1' ACD $ perl -E'say<>>0?AB:<>>0?ACD:ACE' <<< $'1\n0' AB ``` Alternative solution that requires `-p` and is 22 + 1 = 23 bytes: ``` $_=/^1/?AB:/1/?ACD:ACE ``` ``` perl -pe'$_=/^1/?AB:/1/?ACD:ACE' <<< '0 1' ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ 20 bytes Code: ``` Ii"AB"?q}"AC"?69I-ç? ``` [Try it online!](http://05ab1e.tryitonline.net/#code=SWkiQUIiP3F9IkFDIj82OUktw6c_&input=MQow) ]
[Question] [ Anyone remember [Boaty](https://en.wikipedia.org/wiki/Boaty_McBoatface)? You could totally make any old word, right? * Write a function to turn a string into Somethingy McSomethingface. * It should accept one string as input. Ignore the case of the input. * If the word ends in 'y', your function should not add an additional 'y' to the first instance, but should remove it in the second instance. * If the word ends in 'ey', it should not have an additional 'y' added in the first instance, but should remove both in the second instance. * The output should only have upper case letters in the first character, the 'M' of 'Mc' and the first character after 'Mc'. * it only needs to work with strings of 3 or more characters. Examples: ``` boat => Boaty McBoatface Face => Facey McFaceface DOG => Dogy McDogface Family => Family McFamilface Lady => Lady McLadface Donkey => Donkey McDonkface Player => Playery McPlayerface yyy => Yyy McYyface DJ Grand Master Flash => Dj grand master flashy McDj grand master flashface ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 27 ~~28~~ ~~30~~ bytes ``` Vu~Ùóe¿y$ Hóy$ ÁyJaMc<Esc>Aface ``` [Try it online!](https://tio.run/##K/v/P6y07vDMw5tTD@2vVOHyOLwZSB5urPRK9E2WdkxLTE79/z8tNTI5NRIA "V – Try It Online") `<Esc>` represents `0x1b` * Golfed two bytes after learning that we did not need to support inputs with less than 3 characters. * 1 byte saved thanks to @DJMcMayhem by working on the second line before the first one, thus removing the `G` The input is in the buffer. The program begins by converting everything to lowercase `V` selects the line and `u` lowercases it `~` toggles the case of the first character (converting it to uppercase) and `Ù` duplicates this line above, leaving the cursor at the bottom line `ó` and replaces `e¿y$`, compressed form of `e\?y$` (optional `e` and a `y` at the end of the line), with nothing (happens on the second line) `H` goes to the first line `ó` replaces `y$` (`y` at the end of the line) with nothing on the first line `Á` appends a `y` to the end of the first line `J` and joins the last line with the first with a space in the middle, and the cursor is moved to this space `a` appends `Mc` (`<Esc>` returns to normal mode) `A` finally, appends `face` at the end of the line [Answer] # Python, 144 bytes ``` def f(s): s=s[0].upper()+s[1:].lower() y=lambda s:s[:-1]if s[-1]=='y'else s t=y(s) u=s[:-2]if s[-2:]=='ey'else y(s) return t+'y Mc%sface'%u ``` [Try it online here](https://tio.run/##TY7LCsIwEEX3@YrZSFp8oF0Gsiu6UfyA0EVsJ1isScmkSL6@Nlofs5l7Lodh@hiuzhbj2KABk1EuGJAkta02Q9@jz/IlqZ2oNp17JGIQZafvl0YDCVJivataA6SmLSWPHDtCIAZBxukYg0EmqZilQiQLZ@1teAyDtxCWPMKpXpDRNfLFwJhxHgJSqPXkthYUg2n4xenAV@@8T@6cy/PhV9/bLn7oqJtvLp294ZfgL74mYSVeTe9bGzKTfT7I83F8Ag) [Answer] # Excel, ~~204~~ ~~144~~ ~~137~~ 165 bytes ``` =SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(REPT(REPLACE(LOWER(A1),1,1,UPPER(LEFT(A1)))&"~",2),"~","y Mc",1),"yy ","y "),"ey~","~"),"y~","~"),"~","face") ``` From the inside outwards: ``` REPLACE(LOWER(A1),1,1,UPPER(LEFT(A1))) Replaces PROPER to handle space-delimited cases REPT(%&"~",2) Duplicate. Donkey~Donkey~ SUBSTITUTE(%,"~","y Mc",1) Replace first ~. Donkeyy McDonkey~ SUBSTITUTE(%,"yy ","y ") Handle words ending in 'y'. Donkey McDonkey~ SUBSTITUTE(%,"ey~","~") Handle words ending in 'ey' Donkey McDonk~ SUBSTITUTE(%,"y~","~") Handle words ending in 'y' Donkey McDonk~ SUBSTITUTE(%,"~","face") Adding face. Donkey McDonkface ``` --- Old answer, creating all bits separately, and then concatenating (176 bytes). Does not handle space-delimited cases correctly. ``` =PROPER(A1)&IF(LOWER(RIGHT(A1,1))="y",,"y")&" Mc"&IF(LOWER(RIGHT(A1,2))="ey",LEFT(PROPER(A1),LEN(A1)-2),IF(LOWER(RIGHT(A1,1))="y",LEFT(PROPER(A1),LEN(A1)-1),PROPER(A1)))&"face" ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~42~~ ~~37~~ 35 bytes ``` {S/y$//~"y Mc{S/e?y$//}face"}o&tclc ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Oli/UkVfv06pUsE3GchJtQdxa9MSk1OVavPVSpJzkv9bcxUnViqkaajEayqk5Rcp2CTlJ5YouAGVKLj4uwMZuZk5lQo@iSmVCi75edmplQoBOYmVqUV2/wE "Perl 6 – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~122~~ ~~108~~ ~~139~~ ~~175~~ ~~180~~ ~~179~~ 154 bytes Thanks a lot, lee! ``` s=>((s.EndsWith("y")?s:s+"y")+" Mc"+(s+"$").Replace("ey$","")+"face").Replace(s,s.ToUpper()[0]+s.Substring(1).ToLower()).Replace("y$","").Replace("$",""); ``` [Try it online!](https://tio.run/##TVDRagIxEHy@@4ol@JDj7NG@arUPtQpFqdQWEfEhxqihZ3Jkc8oh9@3XjVewITCzO7AzjMQHaZ1qStTmAIsKvTr14yi8uCi3uZYgc4EIc2cPTpziaxz97dELT3C2egczoQ1P4ojU6CwcaFOUHgZg1GW9gSvbWuFZl42FVASjj8ltOOm8IjIVuwAja35UIPNcVMoRqarb/h0mTphgQukcjCnPkUEdYtIfl0Y@o3eUvwstDmFF3g0Ohpxj9mZ2uNT@yFnFkhfsYRpIymAmWcpp6rAk@1RFTuE4U1WHPIO@D2HvCnYx@7LfRaEcT9aPmxSzRbltDflTQtrUXoL279jfrfuinfsNUPA99S7kEXgoDKmytrUkaKHH6NUatLnKlk57NdWGMkAKrAeMYMUxSUIFdRwD1HHd/AI "C# (.NET Core) – Try It Online") # C# (.NET Core, with LINQ), 152 bytes ``` s=>((s.Last()=='y'?s:s+"y")+" Mc"+(s+"$").Replace("ey$","")+"face").Replace(s,s.ToUpper()[0]+s.Substring(1).ToLower()).Replace("y$","").Replace("$",""); ``` [Try it online!](https://tio.run/##TVHfa8IwEH5u/oojCCbUle1VV/cwURiVyX4wRHyINWpZTbpcqxTxb@8uVtAQ@O7uI3dfvkvxIbVONxVmZgufNZZ6P2D3WZRk5m/AAn9YUa3yLIU0V4gwc3br1J6dWHCtY6lKgoPN1jBVmRGSBcQGB@UgM0VVQgxGHxdLOPGVVSXv8bFKNcHofXJJ9lleU5CotYeRNb/aB7Nc1dpRUNeX@htMnDJ@CEl0MCY9Ow5nL5PuuDLpM5aOPtGDFocwp9kNxkMhMEromZBx3K27L9jHkNdchhymKQ8FZR0uow9d5CRNcF13aKLnN17qjcEeRl/2uyi0E3LxuAwx@qxW7TjxJIlL7NFzd82uvW6FNh80QLI3tAiV7kB4u5AMaz2TnvMuBq/WoM119OOyUtNaSAOEwPvACeYCpfQGnBkDOLNz8w8 "C# (.NET Core) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~61~~ 49 bytes ``` ->s{s.capitalize=~/(e)?y$|$/;"#$`#$1y Mc#$`face"} ``` [Try it online!](https://tio.run/##DcxBCsIwEEDRqwxJBF3Y4lpSN0U3igcQwTQmGFptMVNkTOLVY3bvb/577ihbmdeND77SanKoBvc18lcvzWpHIop6y7i4cbEhOOkiq7RhKS8@oRsVwr4ktOdDwdMNBEd1J2jHV28oVUbpB4SIEaYZPTAeMIFsgAd7wWsqmz8 "Ruby – Try It Online") Saved 12 sweet bytes thanks to @MartinEnder: * a slimmer regular expression, which made use of * some of [Ruby's special global variables](http://ruby-doc.org/core-2.5.0/Regexp.html#class-Regexp-label-Special+global+variables) which I tend to forget, and * bracketless string interpolation (see e.g. <https://codegolf.stackexchange.com/a/52357/11071>), which I never knew existed. [Answer] # [Stax](https://github.com/tomtheisen/stax), 26 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ëO╛εh╕⌠î&!}∞┌C^U╟«äδ◙Bg⌠└¿ ``` [Run and debug it](https://staxlang.xyz/#p=894fbeee68b8f48c26217decda435e55c7ae84eb0a4267f4c0a8&i=boat%0AFace%0ADOG%0AFamily%0ALady%0ADonkey%0A+ey%0Ayyy&a=1&m=2) ``` ^ convert input to upper case "FACE" B~ chop first character and push it back to input 70 "ACE" v+ lowercase and concatenate "Face" c'yb copy, push "y", then copy both "Face" "Face" "y" "Face" "y" :] string ends with? "Face" "Face" "y" 0 T trim this many character "Face" "Face" "y" + concatenate "Face" "Facey" p output with no newline "Face" "e?y$"z push some strings "Face" "e?y$" "" " Mc`Rface execute string template; `R means regex replace " Mc Faceface" result is printed because string is unterminated ``` [Run this one](https://staxlang.xyz/#c=%5E+++++++++%09convert+input+to+upper+case++++++++++++++++++++%09%22FACE%22%0AB%7E++++++++%09chop+first+character+and+push+it+back+to+input+%0970+%22ACE%22%0Av%2B++++++++%09lowercase+and+concatenate++++++++++++++++++++++%09%22Face%22%0Ac%27yb++++++%09copy,+push+%22y%22,+then+copy+both+++++++++++++++++%09%22Face%22+%22Face%22+%22y%22+%22Face%22+%22y%22%0A%3A]++++++++%09string+ends+with%3F++++++++++++++++++++++++++++++%09%22Face%22+%22Face%22+%22y%22+0%0AT+++++++++%09trim+this+many+character+++++++++++++++++++++++%09%22Face%22+%22Face%22+%22y%22%0A%2B+++++++++%09concatenate++++++++++++++++++++++++++++++++++++%09%22Face%22+%22Facey%22%0Ap+++++++++%09output+with+no+newline+++++++++++++++++++++++++%09%22Face%22%0A%22e%3Fy%24%22z+++%09push+some+strings++++++++++++++++++++++++++++++%09%22Face%22+%22e%3Fy%24%22+%22%22%0A%22+Mc%60Rface&i=boat%0AFace%0ADOG%0AFamily%0ALady%0ADonkey%0A+ey%0Ayyy&a=1&m=2) [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 38 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` lW y≠F u⁽³:F y*+pF‽j:lW e=⌡j}"‰θ`√►׀‘p ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=bFclMjB5JXUyMjYwRiUwQXUldTIwN0QlQjMlM0FGJTIweSorcEYldTIwM0RqJTNBbFclMjBlJTNEJXUyMzIxaiU3RCUyMiV1MjAzMCV1MDNCOCU2MCV1MjIxQSV1MjVCQSV1MDVDMCV1MjAxOHA_,inputs=Ym9hdA__,v=0.12) [Answer] # [Python 3](https://docs.python.org/3/), 80 bytes Long time avid reader, my first submission at last ! ``` lambda y:re.sub("([\w ]+?)((e)?y)?$",r"\1\3y Mc\1face",y.capitalize()) import re ``` [Try it online](https://tio.run/##JYvBCsIwEETP@hVLEZpgEcSboL2Igih6FeNh26Y0mCZlE5H152urp3nDm@k4Nt6t@nqjeottUSHwmvQivAqRiLt6w2OeSyG0zFnmsySjRC3ViuFcqmWNpU4yXpTYmYjWfLSQcmrazlME0n3tCQIYB2nhMaYZpPvhMebucvjX1tjbSCes@Ce8e@ofXS2yppGY/@oIB0JXwRlD1AR7i6FJ19NJR8ZFEYaJipvtMK1FkLL/Ag "Python 3 – Try It Online") [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), 29 bytes ``` .+ $T 0`(e)?y$|$ $1y Mc$`face ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8F9Pm0slhMsgQSNV075SpUaFS8WwUsE3WSUhLTE59f//pPzEEi43IJPLxd8dyMjNzKnk8klMqeRyyc/LTq3kCshJrEwtAgA "Retina – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~88~~ 92 bytes ``` lambda s:(s+'y'*-~-(s[-1]in'yY')).title()+' Mc'+re.sub('e?y$','',s.title())+'face' import re ``` [Try it online!](https://tio.run/##NYq7DoIwFIZneYozmJxWLomOJuhidNE4E2Ao0MZGaElbhy6@ei0ap//yfbN3D612QZRNGNnUDQzsntgUPW7yd05snW9bqdBXSGnhpBs5oSnCrcfU8MK@OoL86NeYIWb2L0RDsJ5jIqdZGweGB6ENWJAKauw0c5gBnhcl5ul@@c1JjtXSrmzwX6DVk3ts98lqNlI5sPFsXHmIUBBLwwc "Python 2 – Try It Online") [Answer] # Java 8, ~~121~~ ~~112~~ ~~107~~ 106 bytes ``` s->(s=(char)(s.charAt(0)&95)+s.toLowerCase().substring(1)).split("y$")[0]+"y Mc"+s.split("e?y$")[0]+"face" ``` -1 byte thanks to *@OliverGrégoire*. **Explanation:** [Try it online.](https://tio.run/##jU9NSwMxEL33VwxBJKE01IMHKVXEope2Cp6k9DCbTWvabLLsZCtB9rev2bp6kxUSkpl58z4OeMLJIT@2yiIRrNC4zxGAcUFXO1Qa1l0J8Boq4/ageP8hMUv9Jt10KGAwCtbgYA4tTW45zbl6x0pwkt17H/hUXN5cizHJ4Jf@Q1cPSJoLSXVGZ0Z@JVJVWhM4ixdMbKbbMYuwUizt9H199zvpvLF29q1f1plN@r2Nkzc5FClI73WzRdGHiBR0IX0dZJkmwTrupOIs8xiYOCf6G/TYKQ6BFs9P/yAqjI2DsCXmw6CFd0c9DHuxGHU1CItvP1TNqGm/AA) ``` s-> // Method with String as both parameter and return-type (s= // Replace and return the input with: (char)(s.charAt(0)&95) // The first character of the input as Uppercase +s.toLowerCase().substring(1)) // + the rest as lowercase .split("y$")[0] // Remove single trailing "y" (if present) +"y Mc" // Appended with "y Mc" +s.split("e?y$")[0] // Appended with the modified input, with "y" or "ey" removed +"face" // Appended with "face" ``` [Answer] # JavaScript, ~~103~~ ~~96~~ 94 bytes Pretty naïve first pass at this. ``` s=>(g=r=>s[0].toUpperCase()+s.slice(1).toLowerCase().split(r)[0])(/y$/)+`y Mc${g(/e?y$/)}face` ``` [Try it online](https://tio.run/##NYtBDoIwFESv4oJFG7DoAaoLiW4wrlwhya@lkGLpbyjRNMazVzBxNTPvZXrxFF6O2k1ri42KLY@e70jHR77z1aZmE16dU@NBeEVo6pk3WiqypbMo8fUXzDujJzLS@UJJHpKcphBWZ5m8O5Kr/QI@rZAKokTr0ShmsCMV3FFMkMFxURkUl9NvDNqEuZSiWaJA@1ABajYIR1rKetQWbhZo/AI) [Answer] # vim, 35 34 bytes ``` Vu~Yp:s/ey$ :%s/y$ kgJiy Mc<ESC>Aface<ESC> ``` `<ESC>` is `0x1b` ### Ungolfed ``` Vu~ # Caseify McCaseface Yp # dup line :s/ey$ :%s/y$ # Get the suffixes right kgJiy Mc<ESC>Aface<ESC> # Join lines and add the extra chars ``` [Try it online!](https://tio.run/##K/v/P6y0rrKywKpYP7VShctKtVgfSGWne2VWKvgmSzumJSanSv//n5SfWAIA "V – Try It Online") Saved 1 byte thanks to DJMcMayhem [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~47~~ 39 bytes *Saved 6 bytes with @OlegV.Volkov's suggestions, 1 with @mwellnhof's, and 1 on my own* ``` $_=lc^$";$_=s/y?$/y Mc/r.s/e?y$//r.face ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3jYnOU5FyRrIKNavtFfRr1TwTdYv0ivWT7WvVNEHstISk1P//3dL9M3MSY38l19QkpmfV/xftwAA "Perl 5 – Try It Online") [Answer] # C++ 14 (g++), ~~181~~ ~~171~~ ~~148~~ ~~147~~ 134 bytes ``` [](auto s){s[0]&=95;int i=1,b;for(;s[i];)s[i++]|=32;b=s[--i]-'y';return s+(b?"y":"")+" Mc"+(b?s:s.substr(0,s[i-1]-'e'?i:i-1))+"face";} ``` Note that clang will not compile this. Credit goes to [Kevin Cruijssen](https://codegolf.stackexchange.com/a/160529/79343) and [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%C3%A9goire) for the `&95` trick. Thanks to [Chris](https://codegolf.stackexchange.com/users/58834/chris) for golfing 11 bytes. Try it online [here](https://tio.run/##dY9Ra4MwFIWf568IGayKdbQbe5ip68tooax0705KjGkXprEk8UG6/naXxDIGS16813P8zrmS0yk5EjLgTrWgARkY8iK0LzI6y3xW3GXPT4hxBVg2n5bo0IoQyZwVKNLPOC6@s8cHVGYyTxJWJJN@ggRVneBAxmG5hD1MIYxiCLYEGkGm8l52pVQinE11QjLXEJ0sWarXSH94wIRCdBlQENwyTuquomDBWg1Q3LwEDWY8jMA5uJGqSlMtM34EZYuVvh2aCdHVI22nwGIBmtDIkVnhB/@1r@hK9xl0ZXv/oUb2oa@7tSH1cIBa9Vc2rO7HUrM5a43hC3jDlcXNdMBG9t7c8i9q4XFzXW4NX8B7jXsqTMC4OQJGwxfQ97ZeDweqVe/lm/1aYF7tt1gqKvarGstP@yMbYA0wGsAarv9yBfxpuww/). Ungolfed version: ``` [] (auto s) { // lambda taking an std::string as argument and returning an std::string s[0] &= 95; // convert the first character to upper case int i = 1, // for iterating over the string b; // we'll need this later for(; s[i] ;) // iterate over the rest of the string s[i++] |= 32; // converting it to lower case // i is now s.length() b = s[--i] - 'y'; // whether the last character is not a 'y' // i is now s.length()-1 return s + (b ? "y" : "") // append 'y' if not already present + " Mc" + (b ? s : s.substr(0, s[i-1] - 'e' ? i : i-1)) // remove one, two, or zero chars from the end depending on b and whether the second to last character is 'e' + "face"; } ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~38~~ ~~36~~ 32 bytes -5 byte thanks to @Cows quack ``` Vu~hy$ó[^y]$/&y A Mc<esc>póe¿y$ Aface ``` `<esc>` is a literal escape character and `[^` is encoded as `\x84` [Try it online!](https://tio.run/##K/v/P6y0LqNS5fDm6LjKWBV9tUouRwXfZJvU4mS7gsObUw/tr1ThckxLTE79/x9EVv7XLQMA "V – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 30 bytes ``` ™D'y©Ü®«s¤®Qi¨¤'eQi¨]’McÿŠÑ’ðý ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcsiF/XKQysPzzm07tDq4kNLDq0LzDy04tAS9VQQHfuoYaZv8uH9RxccnghkHt5weO///y75edmplQA "05AB1E – Try It Online") or as a [Test suite](https://tio.run/##MzBNTDJM/V9TVvn/UcsiF/XKQysPzzm07tDq4kNLDq0LzDy04tAS9VQQXVv7qGGmb/Lh/UcXHJ4IZB7ecHjv/0qlw/sVdO0UDu9X0vmflJ9YwuWWmJzK5eLvDmTkZuZUcvkkplRyueTnZadWcgXkJFamFgEA) [Answer] # [Python 3](https://docs.python.org/3/), ~~117~~ 114 bytes *-3 bytes thanks to Dead Possum* ``` def f(s):s=s.title();return s+'y'*(s[-1]!='y')+' Mc'+([s,s[:-1],0,s[:-2]][(s[-1]=='y')+((s[-2:]=='ey')*2)])+'face' ``` [Try it online!](https://tio.run/##PYzBDoIwEETvfMV6agtoFG81vRG9aPyApjEIbWzEQtj1wNdjgcS9zLzd2elHenXhOE2NdeA4CokKd@SptVycBkvfIQBmbGQpR709mI2KXmQMbjXLuMYctYzrfL@Ywhi95tSa4zMVckYbOS2Eic@uqi2byCI96gotKNDs2VXEcmDn@Ra1vF9W/Ph2nN21ahYtu/COXSZx3QAefIB/kUwgTj/4QNxxL8T0Aw "Python 3 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 87 bytes * thanks to @Shaggy for 5 reducing 5 bytes ``` s=>(g=r=>Buffer(s.replace(r,"")).map((x,i)=>i?x|32:x&~32))(/y$/)+`y Mc${g(/e?y$/)}face` ``` [Try it online!](https://tio.run/##dY7NasMwEITvfQohQpFoakNyK8iBEBIoDe01t6i25DqRLSO5xaI/r@5q5TiHYJ92dvebYU78i9vUFHXzWOlMdJJ1liUkZ4Yl608phSE2MqJWPBXEzDGmNCp5TUg7LyhLilX7s1w8tfd/ywWlJHazmD4cHdqns@@cxGIFh1/pzccu1ZXVSkRK50QS/K55gyliDOG1l@CBCSymdzfwNlwDDBJgmOPw5nV3YTc6B9SPqdiyUO4aDEtI9mLc8MKzAQfpYT8mWujqLNy1CCyhSnUe598Ud8Jc@H4BQ6/GLc4N@QcH7MFNVHlGO8OrDO25bYRBW8Xtx9DshPLwK/ufhF9oOvbo87t/ "JavaScript (Node.js) – Try It Online") [Answer] # [K4](http://kx.com/download/), ~~74~~ ~~69~~ 68 bytes **Solution:** ``` {$[r;x;x,"y"]," Mc",_[r:0&1-2/:"ye"=2#|x;x:@[_x;0;.q.upper]],"face"} ``` **Examples:** ``` q)k)f:{$[r;x;x,"y"]," Mc",_[r:0&1-2/:"ye"=2#|x;x:@[_x;0;.q.upper]],"face"} q)f each ("boat";"Face";"DOG";"Family";"Lady";"Donkey";"Player") "Boaty McBoatface" "Facey McFaceface" "Dogy McDogface" "Family McFamilface" "Lady McLadface" "Donkey McDonkface" "Playery McPlayerface" ``` **Explanation:** Figure out if the last characters are equal to `"ey"`, convert result to base-2 so we can ignore words that end `"e?"`. Index into a list of numbers of characters to trim. Managed to shave 5 bytes off my code to determine whether the last two chars at `"ey"` but struggling to better it... ``` {$[r;x;x,"y"]," Mc",_[r:0&1-2/:"ye"=2#|x;x:@[_x;0;.q.upper]],"face"} / the solution { } / lambda function ,"face" / join with "face" _[ ; ] / cut function @[_x; ; ] / apply (@) to lowercased input 0 / at index 0 .q.upper / uppercase function x: / save back into x |x / reverse x 2# / take first two chars of x "ye"= / equal to "ye"? 2/: / convert to base 2 1- / subtract from 1 0& / and with 0 (take min) r: / save as r ," Mc", / join with " Mc" $[r;x;x,"y"] / join with x (add "y" if required) ``` **Bonus:** **67 byte** port in [K (oK)](https://github.com/JohnEarnest/ok): ``` {$[r;x;x,"y"]," Mc",((r:0&1-2/"ye"=2#|x)_x:@[_x;0;`c$-32+]),"face"} ``` [Try it online!](https://tio.run/##y9bNz/7/v1olusi6wrpCR6lSKVZHScE3WUlHQ6PIykDNUNdIX6kyVcnWSLmmQjO@wsohOr7C2sA6IVlF19hIO1ZTRyktMTlVqVbJJT8vO7VS6f9/AA "K (oK) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 69 bytes ``` ->s{"#{(s.capitalize!||s)[-1]==?y?s:s+?y} Mc#{s.gsub /e?y$/,""}face"} ``` Explanation: ``` ->s{ } # lambda "#{ } Mc#{ }face" # string interpolation (s.capitalize!||s) # returns string capitalized or nil, in that case just use the original string [-1]==?y # if the last character == character literal for y ?s:s+?y # then s, else s + "y" s.gsub /e?y$/,"" # global substitute # remove "ey" from end ``` [Try it online!](https://tio.run/##KypNqvyfpmCrEPNf1664Wkm5WqNYLzmxILMkMSezKlWxpqZYM1rXMNbW1r7SvtiqWNu@slbBN1m5ulgvvbg0SUE/1b5SRV9HSak2LTE5Van2f0FpSbFCWnR6aklx7H@X/Lzs1EoA "Ruby – Try It Online") [Answer] # [Jstx](https://github.com/Quantum64/Jstx), 27 [bytes](https://quantum64.github.io/Jstx/codepage) ``` h</►yT↓►y/◙♂ Mc♀/◄eyg►yg/íå ``` Explanation ``` # Command line args are automatically loaded onto the stack h # Title case the top of the stack < # Duplicate the top value on the stack twice / # Print the top value on the stack ►y # Load 'y' onto the stack T # Returns true if the 2nd element on the stack ends with the top ↓ # Execute block if the top of the stack is false ►y # Load 'y' onto the stack / # Print the top value on the stack ◙ # End the conditional block ♂ Mc♀ # Load ' Mc' onto the stack / # Print the top value on the stack ◄ey # Load 'ey' onto the stack g # Delete the top of the stack from the end of the 2nd element on the stack if it exists ►y # Load 'y' onto the stack g # Delete the top of the stack from the end of the 2nd element on the stack if it exists / # Print the top of the stack íå # Load 'face' onto the stack # Print with newline is implied as the program exits ``` [Try it online!](https://quantum64.github.io/Jstx/JstxGWT-1.0.1/JstxGWT.html?code=aDwv4pa6eVTihpPilrp5L%24KXmeKZgiBNY%24KZgC_il4RleWfilrp5Zy_DrcOl&args=Ym9hdA%3D%3D) [Answer] # [Red](http://www.red-lang.org), 143 142 bytes ``` func[s][s: lowercase s s/1: uppercase s/1 w: copy s if"y"<> last s[append w"y"]rejoin[w" Mc"parse s[collect keep to[opt["y"|"ey"]end]]"face"]] ``` [Try it online!](https://tio.run/##VYuxDsIgFEX3fsXL@4Gma2OcjC4ajSthQHgkVQQCNITEf0c6qHU859wbSNUrKWC802PVs5UschZHMC5TkCISRIj9MMLs/Uf0Q5dHkM6XFieNBTdbMCImiEy0mVWQm@SB7m6yLCOcJHoRli@TzhiSCR5EHpJjzifWxi@k9mhXzlELSch59WGyCTTgzYmE3Rf3S//h7nz4i8/JlJU4CrVG5eyD1uJiRKGA9Q0 "Red – Try It Online") Ungolfed: ``` f: func[s][ s: lowercase s ; make the entire string lowercase s/1: uppercase s/1 ; raise only its first symbol to uppercase w: copy s ; save a copy of it to w if "y" <> last s[append w "y"] ; append 'y' to w if it doesn't have one at its end rejoin[w ; assemble the result by joining: " Mc" ; keep the string until "y", "ey" or its end parse s[collect keep to [opt ["y" | "ey"] end]] "face" ] ] ``` [Answer] # PHP: 132 ``` <?php function f($s){$s=ucfirst(strtolower($s));return $s.(substr($s,-1)=='y'?'':'y').' Mc'.preg_replace('/(ey|y)$/','',$s).'face';} ``` ## Explanation: ``` <?php function f($s) { // Take the string, make it all lowercase, then make the first character uppercase $s = ucfirst(strtolower($s)); // Return the string, followed by a 'y' if not already at the end, then ' Mc' // and the string again (this time, removing 'y' or 'ey' at the end), then // finally tacking on 'face'. return $s . (substr($s, -1) == 'y' ? '' : 'y') . ' Mc' . preg_replace('/(ey|y)$/', '', $s) . 'face'; } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~77~~ ~~75~~ ~~74~~ 73 bytes ``` 2ḶNṫ@€⁼"“y“ey”S ØA;"ØaF ¢y⁸µ¢Uyµ1¦ Çṫ0n”yẋ@”y;@Ç;“ Mc” ⁸JU>ÑTị3Ŀ;@Ç;“face ``` [Try it online!](https://tio.run/##y0rNyan8/9/o4Y5tfg93rnZ41LTmUeMepUcNcyqBOBVIzA3mOjzD0Vrp8IxEN65DiyofNe44tPXQotDKQ1sNDy3jOtwO1GaQB1RX@XBXtwOItnY43G4N1K3gmwzkcgE1eIXaHZ4Y8nB3t/GR/TDZtMTk1P///6s75SeWqAMA "Jelly – Try It Online") Any golfing suggestions are welcome (and wanted)! [Answer] # Pyth, ~~36~~ 34 bytes ``` ++Jrz4*\yqJK:J"e?y$"k+" Mc"+K"face ``` [Try it online!](http://pyth.herokuapp.com/?code=%2B%2BJrz3%2a%5CyqJK%3AJ%22%28e%29%3Fy%24%22k%2B%22+Mc%22%2BK%22face&input=donkey&test_suite=1&test_suite_input=boat%0AFace%0ADOG%0AFamily%0ALady%0ADonkey%0APlayer%0Ayyy%0ADJ+Grand+Master+Flash&debug=0) Explanation: ``` ++Jrz4*\yqJK:J"(e)?y$"k+" Mc"+K"face Jrz4 Set J to the titlecase of z (input) K:J"e?y$"k Set K to (replace all matches of the regex e?y$ in J with k (empty string)) qJ Compare if equal to J *\y Multiply by "y" (if True, aka if no matches, this gives "y", else it gives "") + Concatenate (with J) +K"face Concatenate K with "face" +" Mc" Concatenate " Mc" with that + Concatenate ``` [Answer] # [Elixir](https://elixir-lang.org/), ~~112~~ ~~110~~ ~~107~~ 106 bytes *now as short as java* ``` fn x->x=String.capitalize x;"#{x<>if x=~~r/y$/,do: "",else: "y"} Mc#{String.replace x,~r/e?y$/,""}face"end ``` [Try it online!](https://tio.run/##LY89D4IwEIZ3fsXlcICEj10RF6Ix0TA4GocCV9NYW1IYiop/HSlxet5cnsvdS1JYYSauDSjIYrhipVmPESBnNTkW5cFhz55CDi6dWLOw0OpBA96g0V4wcQU2zu320huh7knNWtEzKV4EdoP@22a54GC3369Jh1UaNXoNiBHJjuYw4Ajn2n//lw21cr4ONppt2jkfcVweItVMYRKo0PvkcCwTobqW6j6QrCK5hnnuDNfhBw "Elixir – Try It Online") Explanation: ``` x=String.capitalize x ``` Gets `x` with the first character in uppercase and all others lowercase. ``` #{ code } ``` Evaluate the code and insert it into the string. ``` #{x<>if x=~ ~r/y$/, do: "", else: "y"} ``` Concatenates **x** with `y` if it does not end with `y` (ie it does not match the regex `y$`). ``` #{String.replace x, ~r/e?y$/, "")} ``` Removes trailing `ey` and trailing `y`. [Answer] # [PHP](https://php.net/), 45 ~~46~~ bytes ``` <?=($s=ucfirst(fgets(STDIN)))."y Mc{$s}face"; ``` [Try it online!](https://tio.run/##K8go@P/fxt5WQ6XYtjQ5LbOouEQjLT21pFgjOMTF009TU1NPqVLBN7lapbg2LTE5Vcne7v//5MSS/yn56QA "PHP – Try It Online") [Answer] ## Pyth, ~~60~~ 59 bytesSBCS ``` K"ey"Jrz4Iq>2JK=<2J=kK.?=k\yIqeJk=<1J))%." s÷ WZÞàQ"[JkJ ``` [Test suite](https://pyth.herokuapp.com/?code=K%22ey%22Jrz4Iq%3E2JK%3D%3C2J%3DkK.%3F%3Dk%5CyIqeJk%3D%3C1J%29%29%25.%22+s%C2%9C%C2%82%C2%8C%C3%B7%09WZ%C3%9E%C3%A0Q%22%5BJkJ&test_suite=1&test_suite_input=boat%0AFace%0ADOG%0AFamily%0ALady%0ADonkey%0APlayer%0Ayyy%0ADJ+Grand+Master+Flash&debug=0) They don't display here, but three bytes, `\x9c`, `\x82`, and `\x8c` are in the packed string between `s` and `÷`. Rest assured, the link includes them. Python 3 translation: ``` K="ey" J=input().capitalize() if J[-2:]==K: J=J[:-2] k=K else: k="y" if J[-1]==k: J=J[:-1] print("{}{} Mc{}face".format(J,k,J)) ``` ]
[Question] [ # Task Given a String as input, your task is to output `42` **only** if the input String happens to be *exactly* the following : ``` abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz ``` It may output any other value, produce an error or not output at all, if the input does not equal the aforementioned String. --- ## Winning Criterion This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] ## Golfscript, 20 ``` 26,{.97+\{.}*}%=42`* ``` with new line, 21 chars (by Nabb) ``` 26,{).[96+]*}%n+=42`* ``` Actually Nabb beat mine, here is original solution for with new line, 22 chars ``` 26,{.97+\{.}*}%n+=42`* ``` This is simply generating source string and just comparing it against string from stdin. [Answer] ## Ruby 1.9, ~~46 42~~ 39 characters ``` p (?a..?z).map{|a|a*$.+=1}*""==gets&&42 ``` Assumes the input isn't terminated with a newline. [Answer] ## C program - 78 89 **Edit:** Do not print 42 when there are extra characters. Assumes input does not have a trailing newline. ``` main(i,j){for(i=1;i<27;i++)for(j=i;j--;getchar()==96+i?0:exit(1));puts("42"+!!gets(&i));} ``` If the prefix does not match, the program exits. If the prefix matches but there is 1-3 or so extra characters, prints 2. Otherwise, produces undefined behavior. This can be made one character shorter by changing `exit(1)` to `fork()`. Oh, and on an unrelated note, remember to save any open documents in case, for [whatever reason](http://en.wikipedia.org/wiki/Fork_bomb), your system happens to lock up. [Answer] ## PHP (60) Assuming the input is provided in the commandline: ``` for(;$i<702;)$s.=chr(96.5+sqrt($i+=2));echo$s!=$argv[1]?:42; ``` **Explanation**: you can view the string as a triangle structure. ``` j i val 0 0 a 1 1-2 bb 2 3-5 ccc 3 6-9 dddd 4 10-14 eeeee 5 15-20 ffffff ... ``` Line `j` starts at index `i = j*(j+1)/2` (that's the triangular number formula). Solving the quadratic equation results in index `i` being on line `j = int((sqrt(8*i+1)-1)/2)` and therefore containing character `97 + int((sqrt(8*i+1)-1)/2)`. The `0-350` index range allows us to simplify that to `96.5 + sqrt(2*(i+1))`, but that no longer holds true for larger values. **Edit**: Switched to commandline input as suggested in the comments. **Edit**: Uses conditional operator to save a character [Answer] ## Perl, 35 ~~43~~ ``` map$s.=$_ x++$a,a..z;say 42if<>~~$s ``` Needs Perl 5.10 or later (run with `-E`), no newline in input. I liked my side-effects regex better, but the shorter code has spoken. Here it is as a souvenir. Also intended for Perl 5.10 or later, but only for the advanced/experimental regex features, so only a `p` command-line option is needed. ``` $a=a;$_=/^(??{$b++;$a++."{$b}"}){26}$/&&42 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` AƶJQi42 ``` [Try it online!](https://tio.run/##dcHXFUAwAADAlfAYwK8/IyQRRO9tMCNYKzqpd4YDoIkpdbfV84ltUQogRAgFB3wKL9EtfpBX8kl/GSNnFZySVwlqUSNpZZ1CrzIojWqTxqyzaO0 "05AB1E – Try It Online") ### Explanation ``` A push lowercase alphabet ƶ lift every letter, push it and multiply it by its index J join the list Qi does it equal the input? 42 push 42 and output implicitly ``` Just going through some challenges to learn 05AB1E (and golfing in general). This challenge was marked as active yesterday and I found a short solution, so why not share? :) [Answer] ## Haskell program - 71 67 64 57 Assumes no trailing newline, and does not output one either. ``` f x|x==[c|c<-['a'..'z'],_<-['a'..c]]="42" main=interact f ``` Usage: ``` $ echo -n 'abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz' | { ./42; echo; } 42 $ echo -n 'something else' | { ./42; echo; } 42: 42.hs:1:0-54: Non-exhaustive patterns in function f $ ``` [Answer] ## J, 29 ``` f=:42#~((>:#a.{~97+])i.26)-:] ``` example: ``` f 'oasijfiojasef' f 23841235 f 'abbccc...' 42 ``` [Answer] # D: 94 Characters ``` void f(S)(S s){S t;foreach(i;0..26)t~=array(repeat(cast(char)(i+'a'),i+1));s==t&&writeln(42);} ``` More Legibly: ``` void f(S)(S s) { S t; foreach(i; 0 .. 26) t ~= array(repeat(cast(char)(i + 'a'), i + 1)); s == t && writeln(42); } ``` [Answer] ## Delphi, 164 132 This one builds a string and just compares it against the first command-line argument. It's shorter and less tricky than my other submission : ``` var s:string;c,i:int8;begin repeat s:=s+Char(c+97);i:=i-1;c:=c+Ord(i<0);if i<0then i:=c;until c=26;Write(42*Ord(s=ParamStr(1)));end. ``` (Note, that this version assumes that the `c` and `i` variables start out initialized at 0, as is the case in my version of Delphi (2010).) Like my other submission, this one needs less characters if the string-building doesn't take place in a function, like I did before : ## Delphi, 181 ``` program a;{$APPTYPE CONSOLE}function s(c,i:byte):string;begin if(i>0)then Exit(Char(c)+s(c,i-1));if(c<122)then Exit(s(c+1,c-95));end;begin if(s(97,1)=ParamStr(1))then Write(42);end. ``` Note that the output doesn't need a newline, so WriteLn() became Write(). [Answer] ## PHP - 45 characters I'm surprise nobody posted any answer that used hashing. It's a very size effecient way of testing for exact string. ``` echo md5($argv[1],1)!='¯è a@ÛÚƒ:ïT�p'?:42; ``` The data is kind of hard to copy/paste since there is a null-byte in the middle of the code. Here's an hex-dump of the code for testing purposes. > > 65 63 68 6f 20 6d 64 35 28 24 61 72 67 76 5b 31 5d 2c 31 29 21 3d 27 af e8 a0 61 40 db da 7f 11 0f 83 3a ef 54 00 70 27 3f 3a 34 32 3b > > > [Answer] **Scala 79** ``` if((for(i <- 1 to 26;j<-1 to i)yield(96+i).toChar).mkString==args(0))print(42) ``` [Answer] # Pyth, 14 ``` *42qzsm*dhxGdG ``` Just constructs the necessary string, then compares with the input and multiplies by 42. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (2), 15 bytes, language postdates challenge ``` ⊇Ạ∧?o?ọtᵐ~⟦₁+₁₆ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/@oq/3hrgWPOpbb59s/3N1b8nDrhLpH85c9amrUBuJHTW3//yslJiUlJyenAEEqCKSBQToEZEBBJgxkwUE2AuQggVxkkIcC8lFBARooRAdFGKAYE5RgAaXYQBlWUI4dVOAAlbhAFU6g9D8KAA "Brachylog – TIO Nexus") And now for an answer which works on a completely different principle to most seen here. This is a function submission (the question doesn't specify what sort of submission is desired, but functions are permitted by default). ## Explanation This answer works by defining a sort of string: those which a) contain all lowercase letters of the alphabet, b) are in sorted order, and c) for which taking the number of occurrences of each character in the string produces a sequence of consecutive integers starting from 1. (It should be clear that there are many such strings, but the one we want to special-case is the shortest.) Then if the string fulfils those criteria, we add 16 to the number of distinct characters in the string; this will produce 42 if the string is the one the question asks us to special-case, and at least 43 in all other cases. (If the string fails any of the criteria to belong to the category, the function will end in failure, which is kind-of like throwing an exception.) Here's how to interpret the source code: ``` ⊇Ạ∧?o?ọtᵐ~⟦₁+₁₆ ⊇Ạ {the input} contains all lowercase letters ∧ and ?o? the input sorts to itself {and; implied when two conditions overlap} ?ọ the {character, number of occurrences} pairs for the input tᵐ when the second element of each is taken ~ create an output that could have been produced by ⟦₁ outputting the list of integers from 1 to some input inclusive; +₁₆ add 16 to that input {and output it} ``` [Answer] # R, ~~60~~ 58 ~~``` if(readline()==paste0(rep(letters,1:26),collapse=""))cat(42) ```~~ ``` if(scan(,"")==paste(rep(letters,1:26),collapse=""))cat(42) ``` Thanks for the suggestion by @giusppe [Answer] ## Python (84) Assumes a trailing newline at the end of the input. ``` import sys if''.join(c*chr(c+96)for c in range(27))+'\n'==sys.stdin.read():print 42 ``` [Answer] ## Python - 62 chars ``` print("".join(x*chr(x+96) for x in range(27))==raw_input())*42 ``` [Answer] ## Perl, 49 46 characters to be used in a program, not on the command line `$..=chr($*+96)x$* for 1..26;$.eq(pop)&&print '42'` ``` join('',map$_ x++$x,'a'..'z')eq pop&&print'42' ``` Regards rbo Edit: Idea ripped from Ventero [Answer] **PHP 92 88 87 chars** ``` function _($a){for($i=97;$i<123;$i++)for($j=$i-96;$j;$j--)$b.=chr($i);echo($b==$a)*42;} ``` **EDIT** Replaced `$j<0` with `$j` and `return $b==$a?42:0;` with `echo $b==$a?42:0;` Replaced `echo $b==$a?42:0;` with `echo($b==$a)*42;` [Answer] **ECLiPSe Prolog - 173** ``` c(_,[],_):-!. c(A,M,N):-length(L,N),checklist('='(A),L),append(F,L,M),P is N-1,B is A-1,c(B,F,P). ?- read_string(end_of_file,351,S),string_list(S,L),c(122,L,26),writeln(42). ``` [Answer] ## JavaScript (91 93 94 98 102 116) Usage: `a('string')`, returns `42` if valid according to spec, or `0`. ``` function a(z){for(i=r='';i++<26;)for(j=i;j--;)r+=String.fromCharCode(i+96);return(z==r)*42} ``` <http://jsfiddle.net/g25M3/6/> **Edit**: Removed `var` and eliminated two spaces in `for (`. **Edit 2**: Changed `j>0` to `j`, and 1. `return (z==r)?42:0;` to 2. `return z==r?42:0` **Edit 3**: Initialize `i` with `i=''`, change 1. `(z==r)?42:0` to 2. `(z==r)*42` **Edit 4**: Change 1. `for(;i<27;i++)` to 2. `while(i++<26)` **Edit 5**: Change 1. `i=r='';while(i++<26)` to 2. `for(i=r='';i++<26;)` and 3. `for(j=i;j;j--)` to 4. `for(j=i;j--;)` [Answer] ## JavaScript 1.8, 99 chars ``` function c(x)(x.replace(/([a-z])\1*/g,function(m)!(a-m.length)*m.charCodeAt(0)-96-a++,a=1)==0)*a+15 ``` I dare you to make sense of it :) [Answer] # PHP - 59 Assumes at least 1 input is provided over cli ``` echo md5($argv[1])!='afe8a06140dbda7f110f833aef540070'?:42; ``` It more or less works, except that md5 is can technically have duplications with the hashing algo. [Answer] ## PowerShell v2+, 47 bytes ``` 42*(-join(1..26|%{,[char]($_+96)*$_})-ceq$args) ``` Constructs a range `1..26`, feeds that through a loop with `|%{...}`. Each iteration we use the [comma operator](https://technet.microsoft.com/en-us/library/hh847732.aspx) to construct an array literal of the current `[char]` multiplied by the current loop number. We then `-join` that all together to construct the string `abbcccdddd...` and then use a case-sensitive `-ceq` comparison against our input `$args`, which will result in either `$TRUE` or `$FALSE`. In PowerShell, Boolean values can be implicitly cast as `1` or `0`, respectively, which is what happens here with the `42*`. Will print out `42` iff the input is `abbccc...zzzzzzzzzzzzzzzzzzzzzzzzzz` and will output `0` otherwise. [Answer] ### K, 26 Bytes ``` {(::;42)x~,/(1+!26)#'.Q.a} {(::;42)x~,/(1+!26)#'.Q.a}"hello" {(::;42)x~,/(1+!26)#'.Q.a}"abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz" 42 ``` Thanks [Answer] # VBA 91 There weren't any VBA answers but this works: ``` Function f(t) For i = 1 To 26 o = o & String(i, Chr(i + 96)) Next f = -42 * (t = o) End Function ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~18~~ 17 bytes ``` 42/⍨⍞≡819⌶⎕A/⍨⍳26 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdMa@4PLXov4mR/qPeFY/6pj7qXGhhaPmoZxuQ7QgW691sZAZSyeWZV1Ba8qhtQvWjruZHPXtBitsmqINFrdQf9W6t/a8ABhAjIcrVPVJzcvLVubDIuBelppZk5qUXY5NVwOIIAA "APL (Dyalog Unicode) – Try It Online") Four obvious bytes can be saved if we are allowed to use uppercase. `42` 42 `/⍨` if (lit. replicated by) `⍞` character input `≡` is identical to `819⌶` the lowercased `⎕A` **A**lphabet `/⍨` replicated by `⍳` one through `26` 26 [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` AƶJQ42* ``` [Try it online!](https://tio.run/##dcHHFUAwAADQfZzwGMDVzQhJRO@dwYxgreik/q/bABqYEGdbXc8yNUIAhAgh/4BPwSW8RY/4lXzSX0bJaQWjZFWcmtcIWlEn0csMUqPcpDCrLEo7 "05AB1E – Try It Online") --- Wellp, 05AB1E keeps evolving. [Answer] # **Clojure** - 61 chars ``` (fn[a](if(=(mapcat #(repeat%(char(+% 96)))(range 1 27))a)42)) ``` Exploits the following facts: * Clojure can interpret any string automatically as a sequence of chars * I can use the range of numbers from 1 to 26 to both create the characters and repeat them the correct number or times to generate the "correct" input [Answer] ## Javascript 144 Probably can be significantly improved, recursion has always been a head far for me. **Compressed** ``` function r(a,b,d,c){c++;if(b<d)a+=r(a,b+1,d,c);for(i=0;i<c;i++)a=String.fromCharCode(b)+a;return a}function q(a){if(q==r(a,97,122,0))return 42}; ``` **Less Compressed** ``` function r(s, c, x, w){ w++; if(c < x) s += r(s, c + 1, x, w); for(i = 0; i < w; i++) s = String.fromCharCode(c) + s; return s; } function q(z){ if(q==r(z,97, 122, 0)) return 42; } alert(q("rgrg")); ``` ]
[Question] [ This [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") challenge is based off of the game show, [Weakest Link](https://en.wikipedia.org/wiki/Weakest_Link). For those unfamiliar with the show, **the crux of this challenge deals with who you vote off**: * If the other players are smarter than you, then you have less of a chance of getting the pot. * If the other players are dumber than you, then you have less of a pot to get. At the start of each round, the *Pot* starts out with $0. A group of 9 players is formed, and each player is given a unique *Smartness* from 1 to 9. At the start of each turn, `Pot += Smartness` for each player still in the round. Then, players vote on the player they wish to remove. The player with the most votes is removed. In case of a tie, the smarter player is kept. When there are only 2 players are left in the round, they face off in a battle of wits. The chance of the player winning is `Smartness/(Smartness+OpponentSmartness)`. The winning player then receives the entire pot. The player who has received the most money at the end of the game wins. # Input / Output Each turn, you will receive the current list of opponents. You will have access to your smartness and **all players' entire voting history** for the round via functions in the Player class. As output, you must return a single integer, representing the player you wish to vote for (representing their smartness). Voting for yourself *is* allowed (but not recommended). Rounds of 9 will repeat until all players have played at least ~~1000~~10000 rounds, and all players have played in the same number of rounds. You can find the controller here: <https://github.com/nathanmerrill/WeakestLink> To create a player, you need to extend the Player class, and add your player to the PlayerFactory class. Your class must follow the following rules: 1. Communication or interference with any other player (include your other players of the same type) is strictly prohibited. 2. Reflection and static variables (except for constants) are not allowed. 3. If you want to use randomness, I have provided a `getRandom()` function in the Player class. Use it, so simulations can be deterministic. I have provided many functions in the Player class for easy access to data. You can find them online [on Github](https://github.com/nathanmerrill/WeakestLink/blob/master/src/WeakestLink/Players/Player.java). Your player will be instantiated each new round. "Dumb/suicidal" players are allowed (but not players with the same strategy). # Scores ``` 377195 WeakestLink.Players.PrudentSniper 362413 WeakestLink.Players.Sniper 353082 WeakestLink.Players.VengefulSniper 347574 WeakestLink.Players.AntiExtremist 298006 WeakestLink.Players.BobPlayer 273867 WeakestLink.Players.MedianPlayer 247881 WeakestLink.Players.TheCult 240425 WeakestLink.Players.Leech 235480 WeakestLink.Players.SniperAide 223128 WeakestLink.Players.Guard 220760 WeakestLink.Players.Anarchist 216839 WeakestLink.Players.RevengePlayer 215099 WeakestLink.Players.IndependentVoter 213883 WeakestLink.Players.SniperKiller 210653 WeakestLink.Players.MaxPlayer 210262 WeakestLink.Players.Bandwagon 209956 WeakestLink.Players.MeanPlayer 208799 WeakestLink.Players.Coward 207686 WeakestLink.Players.Spy 204335 WeakestLink.Players.Hero 203957 WeakestLink.Players.MiddleMan 198535 WeakestLink.Players.MinPlayer 197589 WeakestLink.Players.FixatedPlayer 197478 WeakestLink.Players.HighOrLowNotSelf 181484 WeakestLink.Players.RandomPlayer 165160 WeakestLink.Players.BridgeBurner ``` [Answer] ## Sniper The general idea is to keep around one of the *stupid players* (i.e. ones we are more likely to beat in the face-off) to snipe for the points. After that we try to remove the other low-value players to raise the pot. But when we get to the intelligent players we opt to remove for the most dangerous ones in case our *stupid player* gets removed. That way if we don't have someone to snipe we should get someone we at least stand a chance against. Also, since we always vote with either a min or max player, I expect we are fairly effective in getting our way. ``` package WeakestLink.Players; import java.util.Collections; import java.util.Iterator; import java.util.Set; public class Sniper extends Player { @Override public int vote(Set<Integer> currentOpponents) { int smrt = getSmartness(); //count number of players smarter/stupider than me Iterator<Integer> opps = currentOpponents.iterator(); int cnt_smrt=0, cnt_stpd=0, opp_smrt, min_stpd=10, max_smrt=0; while(opps.hasNext()){ opp_smrt = opps.next().intValue(); if(opp_smrt > smrt){ cnt_smrt++; if(opp_smrt > max_smrt) max_smrt = opp_smrt; } else if(opp_smrt < smrt){ cnt_stpd++; if(opp_smrt < min_stpd) min_stpd = opp_smrt; } } //remove low-value, then dangerous players if(cnt_stpd>1) return min_stpd; else return max_smrt; } } ``` [Answer] # PrudentSniper [Sniper](https://codegolf.stackexchange.com/a/65427/6828), but with two special-case behaviors. One is that if there are three bots left, and PrudentSniper is the smartest, it will vote for the middle bot instead of the least smart. This allows it to win a few more showdowns. The other behavior is that if the smartest bot is gunning for it (voted for it or the analogous bot last time) and the least smart isn't, it will vote for the smartest in self defense. ``` package WeakestLink.Players; import WeakestLink.Game.Vote; import java.util.Collections; import java.util.Iterator; import java.util.Set; public class PrudentSniper extends Player { @Override public int vote(Set<Integer> currentOpponents) { int smrt = getSmartness(); //count number of players smarter/stupider than me, find max/min Iterator<Integer> opps = currentOpponents.iterator(); int cnt_smrt=0, cnt_stpd=0, opp_smrt, min_stpd=10, max_smrt=0; while(opps.hasNext()){ opp_smrt = opps.next().intValue(); if(opp_smrt > max_smrt) max_smrt = opp_smrt; if(opp_smrt < min_stpd) min_stpd = opp_smrt; if(opp_smrt > smrt){ cnt_smrt++; } else if(opp_smrt < smrt){ cnt_stpd++; } } //identify enemies Iterator<Vote> votes = getRecentVotes().iterator(); boolean[] voted_for_me = new boolean[9]; while(votes.hasNext()) { Vote opp_vote = votes.next(); voted_for_me[opp_vote.getVoter()] = (opp_vote.getVoted() == getSmartness() || (opp_vote.getVoted() < getSmartness() && cnt_stpd < 1) || (opp_vote.getVoted() > getSmartness() && cnt_smrt < 1)); } if (currentOpponents.size() < 3 || cnt_stpd < 2 || (voted_for_me[max_smrt] && !voted_for_me[min_stpd] && cnt_smrt > 0) ) return max_smrt; else return min_stpd; } } ``` [Answer] ## TheCult The cult players have a mildly esoteric voting scheme by which they attempt to identify each other and vote as a group, using only the voting record. Since each member of the cult knows how to vote, anyone who votes differently is revealed as a non-member and eventually targeted for elimination. **The voting scheme at a glance:** * on the first turn vote for weakest contestant, working in concert with min & sniper helps the cult gain power * on subsequent turns vote off known non-members until only the cult remains (we vote off the lowest-value non-member to rack up points as long as we think we are in control). * when only members remain, vote off low-value members for points (indeed sacrificing yourself for the good of the cult). **The Code:** ``` package WeakestLink.Players; import WeakestLink.Game.Vote; import java.util.Iterator; import java.util.Set; public class TheCult extends Player { private int cult_vote; private boolean[] isMember = null; @Override public int vote(Set<Integer> currentOpponents) { //on first turn, vote the code if(isMember == null){ isMember = new boolean[10]; for(int i=10; --i!=0;) isMember[i]=true; //runs 9-1 return cult_vote = 1; } //on all other turn, assess who is not voting with the cult Vote opp_vote; int cult_cnt=0; Iterator<Vote> votes = getRecentVotes().iterator(); while(votes.hasNext()){ opp_vote = votes.next(); if(opp_vote.getVoted() != cult_vote) isMember[opp_vote.getVoter()] = false; else cult_cnt++; } //find weakest and stongest non-members, and weakest members Iterator<Integer> opps = currentOpponents.iterator(); int opp_smrt, min_mem=10, min_non=10, max_non=0; while(opps.hasNext()){ opp_smrt = opps.next().intValue(); if(isMember[opp_smrt]){ if(opp_smrt < min_mem) min_mem = opp_smrt; }else{ if(opp_smrt < min_non) min_non = opp_smrt; if(opp_smrt > max_non) max_non = opp_smrt; } } if(cult_cnt>2 && min_non!=10) cult_vote = min_non; else if(max_non!=0) cult_vote = max_non; else cult_vote = min_mem; return cult_vote; } } ``` **Final Thoughts:** The cult now switch's to voting for the most dangerous players when there are only two or fewer cult-members remaining for the face-off. I tested it several times with `cult_cnt>1` and `cult_cnt>2` conditions and the later wins more often. Still, this is a precaution and the cult really isn't designed to work as lone player, so as the number of new players increase the cult should still lose eventually. [Answer] # BridgeBurner Not somewhere where I can test this right now, and this came out feeling like really ugly/dumb code, but it *should* work. This bot just wants to be hated. It votes for whoever has voted against it the *least*. In the event of a tie, it picks whoever has gone the longest without voting for it. In the event of another tie, it picks the smartest of those (presumably because they will make the worst enemy). It will not vote for itself, because no one will really hate it when it's not around. ``` package WeakestLink.Players; import WeakestLink.Game.Vote; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class BridgeBurner extends Player{ @Override public int vote(Set<Integer> currentOpponents) { List<Integer> votes_against = Stream.generate(() -> 0).limit(9).collect(Collectors.toList()); List<Integer> last_voted_against = Stream.generate(() -> 0).limit(9).collect(Collectors.toList()); Iterator<Vote> votes_against_me = getVotesForSelf().iterator(); for (int c = 0; c < 9; c++){ if (!currentOpponents.contains(c)){ votes_against.set(c,-1); last_voted_against.set(c,-1); } } while(votes_against_me.hasNext()){ Vote vote = votes_against_me.next(); int voter = vote.getVoter(); int round = vote.getRound(); if (currentOpponents.contains(voter)){ votes_against.set(voter, votes_against.get(voter)+1); last_voted_against.set(voter, Math.max(round, last_voted_against.get(voter))); } else { votes_against.set(voter, -1); last_voted_against.set(voter, -1); } } int min_tally = Collections.max(votes_against); for (int c = 0; c < 9; c++){ int current_tally = votes_against.get(c); if (current_tally != -1 && current_tally < min_tally){ min_tally = current_tally; } } if (Collections.frequency(votes_against, min_tally) == 1){ return votes_against.indexOf(min_tally); } else { List<Integer> temp_last_against = new ArrayList<>(); for (int c = 0; c < 9; c++){ if (votes_against.get(c) == min_tally){ temp_last_against.add(last_voted_against.get(c)); } } return last_voted_against.lastIndexOf(Collections.min(temp_last_against)); } } } ``` [Answer] # Bandwagon Follows the crowd in voting, unless he's the one being targeted. ``` package WeakestLink.Players; import WeakestLink.Game.Vote; import java.util.Map; import java.util.Set; /** * Votes for the currently most voted bot in the game. Or the lowest one. */ public class Bandwagon extends Player { @Override public int vote(Set<Integer> currentOpponents) { int self = getSmartness(), vote = -1; java.util.Map<Integer, Integer> votes = new java.util.TreeMap<>(); getVotingHistory().stream().map((Vote v)-> v.getVoted()).filter((Integer i)-> !i.equals(self)).forEach((Integer tgt)-> { if(!votes.containsKey(tgt)) { votes.put(tgt, 1); } else { votes.put(tgt, votes.get(tgt) + 1); } }); do { if(votes.entrySet().isEmpty()) { vote = currentOpponents.stream().filter((Integer i)-> !i.equals(self)).sorted().findFirst().get(); } else { if(votes.containsKey(vote)) { votes.remove(vote); vote = -1; } for(Map.Entry<Integer, Integer> vv: votes.entrySet()) { Integer key = vv.getKey(); Integer value = vv.getValue(); if((vote == -1) || (value > votes.get(vote))) { vote = key; } } } } while(!currentOpponents.contains(vote)); return vote; } } ``` I'm guessing this one will just make snipers stronger by following them, but also avoids being targeted by the cult and sniper-aides in a slightly effective manner. It may as well be a meatshield for sniper killers or aid them if there's more of them. (Need to test with the latest updates). Using java 8 features because the game needs that to run anyway. [Answer] # RevengePlayer This bot will vote for whoever voted for him the most times, tiebreaker being the smartest player. The theory is that a player that voted for you in the past will likely vote for you again. ``` package WeakestLink.Players; import java.util.Collections; import java.util.Set; import java.util.Iterator; import WeakestLink.Game.Vote; public class RevengePlayer extends Player{ @Override public int vote(Set<Integer> opponents) { int[] A; A = new int[10]; for(int i = 1;i < 10;i++) A[i] = opponents.contains(i)? i+1 : 0; Set<Vote> H = getVotingHistory(); Iterator<Vote> I = H.iterator(); while(I.hasNext()){ Vote v = I.next(); if(v.getVoted() == getSmartness()) A[v.getVoter()] += A[v.getVoter()] != 0?10:0; } int maxI = 0; for(int i = 1;i < 10;i++) if(A[i] > A[maxI]) maxI = i; return maxI; } } ``` [Answer] # MeanPlayer Vote neither the stupidest nor the smartest players, and he's carrying a gun (sneaked it past security) ``` public class MeanPlayer extends Player{ @Override public int vote(Set<Integer> currentOpponents) { int mid = currentOpponents.size() / 2; Object[] sortedOpponents = currentOpponents.toArray(); Arrays.sort(sortedOpponents); return (int) sortedOpponents[mid]; } } ``` [Answer] # AntiExtremist This extreme socialist believes that all people should be of equal smartness. He tries to kill those who are much smarter or dumber than he is. He considers both but he favors dumb in general. He favors dumb people in the beginning and smart in the end, but it's weighted based on how extreme those people are. ``` package WeakestLink.Players; import java.util.Arrays; import java.util.Set; public class AntiExtremist extends Player { Object[] currentPlayers; @Override public int vote(Set<Integer> currentOpponents) { currentPlayers = (Object[]) currentOpponents.toArray(); Arrays.sort(currentPlayers); int smartness = getSmartness(); int turns = getTurnNumber(); //// Lets get an idea of who's smart and who's dumb //// int smarter = 0, dumber = 0; int max_smart = 0, min_smart = 10; currentOpponents.toArray(); for (int i = 0; i < currentPlayers.length; i++) { int osmart = (int)currentPlayers[i]; if (osmart == smartness) continue; if (osmart > smartness) { smarter++; if (osmart > max_smart) max_smart = osmart; } else if (osmart < smartness) { dumber++; if (osmart < min_smart) min_smart = osmart; } } // int total = smarter+dumber; double smarter_ratio = smarter > 0 ? (max_smart-smartness)/4.5 : 0; double dumber_ratio = dumber > 0 ? (smartness-min_smart)/3.0 : 0;//Favor dumber smarter_ratio*=.25+(turns/9.0*.75); dumber_ratio*=1-(turns/8.0*.75); return smarter_ratio > dumber_ratio ? max_smart : min_smart; } } ``` **NOTE:** According to Linus this will vote the same as sniper the vast majority of the time (525602:1228). [Answer] # MedianPlayer This player attempt to be the meanest (well, medianness) one left. It votes to eliminate the smartest and dumbest opponents (with a slight bias towards voting off the smartest), depending on if there are more or less smarter/dumber than themself. ``` package WeakestLink.Players; import java.util.Collections; import java.util.Iterator; import java.util.Set; public class MedianPlayer extends Player { @Override public int vote(Set<Integer> currentOpponents) { int smrt = getSmartness(); //count number of players smarter/stupider than me Iterator<Integer> opps = currentOpponents.iterator(); int cnt_smrt=0, cnt_stpd=0, min_stpd=10, max_smrt=0; while(opps.hasNext()){ int opp_smrt = opps.next().intValue(); if(opp_smrt > smrt){ cnt_smrt++; if(opp_smrt > max_smrt) max_smrt = opp_smrt; } else if(opp_smrt < smrt){ cnt_stpd++; if(opp_smrt < min_stpd) min_stpd = opp_smrt; } } // the middle must hold if(cnt_stpd>cnt_smrt) return min_stpd; else return max_smrt; } } ``` framework blatantly stolen from @Linus above. [Answer] # Coward ``` package WeakestLink.Players; import WeakestLink.Game.Vote; import java.util.Collections; import java.util.Iterator; import java.util.Set; public class Coward extends Player { @Override public int vote(Set<Integer> currentOpponents) { boolean[] currentOpponent = new boolean[10]; Iterator<Integer> opps = currentOpponents.iterator(); while(opps.hasNext()){ currentOpponent[opps.next().intValue()] = true; } int[] voteCounts = new int[9]; for(int i=0; i<9; i++) { voteCounts[i] = 0; } Iterator<Vote> votes = getRecentVotes().iterator(); while(votes.hasNext()){ Vote opp_vote = votes.next(); if(currentOpponent[opp_vote.getVoter()]) voteCounts[opp_vote.getVoted()] += 1; else voteCounts[opp_vote.getVoter()] += 100; } int previous_weakest = -1; int max_votes_gotten = 0; for(int i=0;i<9;i++){ if (voteCounts[i] > max_votes_gotten) { max_votes_gotten = voteCounts[i]; previous_weakest = i; } } int min_closeness = 10; int to_vote = -1; int opp; int closeness; opps = currentOpponents.iterator(); while(opps.hasNext()){ opp = opps.next(); closeness = Math.abs(opp - previous_weakest); if(closeness <= min_closeness) { to_vote = opp; min_closeness = closeness; } } return to_vote; } } ``` Just doesn't want to get voted off, so votes for the opponent most similar to the player that got voted off last round in order to maximize the chance of being on the winning team. Doesn't do particularly well right now, but might as well throw it in the mix. [Answer] # Hero Votes off those who pick on the weak ... or annoy him. ``` package WeakestLink.Players; import WeakestLink.Game.Game; import WeakestLink.Game.Vote; import java.util.*; /** * Created by thenumberone on 12/2/15. * @author thenumberone */ public class Hero extends Player{ @Override public int vote(Set<Integer> currentOpponents) { int me = getSmartness(); Set<Vote> history = getVotingHistory(); history.removeIf(vote -> !currentOpponents.contains(vote.getVoter()) || vote.getVoter() == me); int[] evilnessLevel = new int[Game.NUMBER_PLAYERS_PER_ROUND]; for (Vote vote : history){ evilnessLevel[vote.getVoter()] += vote.getVoted() == me ? 1_000_000 : Game.NUMBER_PLAYERS_PER_ROUND - vote.getVoted(); } int mostEvilOpponent = -1; for (int opponent : currentOpponents){ if (mostEvilOpponent == -1 || evilnessLevel[opponent] > evilnessLevel[mostEvilOpponent]){ mostEvilOpponent = opponent; } } return mostEvilOpponent; } } ``` [Answer] ## Bob Bob is just the average guy that thinks he is smarter then he really is. Cannot win the *sniper* family but get top 5 in my simulations most of the time. ``` package WeakestLink.Players; import java.util.Collections; import java.util.Set; import WeakestLink.Game.Vote; public class BobPlayer extends Player { @Override public int vote(Set<Integer> currentOpponents) { int smartness; // Bob sometimes thinks he is smarter than he really is if (getRandom().nextInt(10) == 0) { smartness = 10; } else { smartness = getSmartness(); } // If there is still some competition if (currentOpponents.size() > 3) { // And Bob is the dumbest if (smartness < Collections.min(currentOpponents)) { // Go for the smartest one return Collections.max(currentOpponents); // But if he is the smartest } else if (smartness > Collections.max(currentOpponents)) { // Go for the weak link return Collections.min(currentOpponents); } else { // Else revenge! for (Vote v : getRecentVotes()) { if (v.getVoted() == smartness && currentOpponents.contains(v.getVoter())) { return v.getVoter(); } } } return Collections.min(currentOpponents); } else { //If there are few opponents just revenge! for (Vote v : getRecentVotes()) { if (v.getVoted() == smartness && currentOpponents.contains(v.getVoter())) { return v.getVoter(); } } return Collections.max(currentOpponents); } } } ``` [Answer] # FixatedPlayer Picks a random target, then votes for them until they're gone. Won't vote for himself though. ``` package WeakestLink.Players; import WeakestLink.Game.Vote; import java.util.*; public class FixatedPlayer extends Player{ @Override public int vote(Set<Integer> currentOpponents) { int self = getSmartness(); Vote previous_vote = getLastVote(); if (previous_vote == null || !currentOpponents.contains(previous_vote.getVoted())){ return (int) currentOpponents.toArray()[getRandom().nextInt(currentOpponents.size())]; } else { return previous_vote.getVoted(); } } } ``` [Answer] # Spy Spy is reserved. He doesn't like to gun for the smartest people. Likewise, he doesn't like picking on ~~quartata~~ defenseless idiots. So, he likes to eliminate those closest to him in smartness. ``` package WeakestLink.Players; import java.util.Iterator; import java.util.Set; public class Spy extends Player{ @Override public int vote(Set<Integer> currentOpponents) { int selfIntel = getSmartness(); int closestIntel = 100; // default // get closest player Iterator<Integer> enemies = currentOpponents.iterator(); while(enemies.hasNext()){ int enemyIntel = enemies.next().intValue(); if(Math.abs(enemyIntel - selfIntel) < closestIntel) closestIntel = enemyIntel; } return closestIntel; } } ``` You've just been backstabbed, *mes amis*. He doesn't care if he wins. He just like the sound of the knife in your back as he votes you off successfully. [![You've just been backstabbed.](https://i.stack.imgur.com/RRBpO.jpg)](https://i.stack.imgur.com/RRBpO.jpg) [Answer] # Statistics This is not an entry to the contest. This is merely a way to get useful statistics of a game. These statistics print off the percentage likelihood that a particular player will be voted off in a round. To do this add the following lines to `Round.java` so that the top of the file looks like this: ``` package WeakestLink.Game; import WeakestLink.Players.Player; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Round { private static int[][] statistics = new int[Game.NUMBER_PLAYERS_PER_ROUND - 2][Game.NUMBER_PLAYERS_PER_ROUND + 1]; private static int[] counts = new int[Game.NUMBER_PLAYERS_PER_ROUND - 2]; static { Runtime.getRuntime().addShutdownHook(new Thread(() -> { for (int i = 0; i < Game.NUMBER_PLAYERS_PER_ROUND - 2; i++){ System.out.println(); System.out.println("For " + (i+1) + "th round:"); for (int j = 1; j <= Game.NUMBER_PLAYERS_PER_ROUND; j++){ System.out.println(String.format("%f%% voted for %d", 100.0*statistics[i][j]/counts[i], j)); } } })); } ... ``` Then modify the vote method to look like this: ``` private Vote vote(Player player){ player.setVotingHistory(new HashSet<>(votes)); player.setTurnNumber(currentTurn); player.setPot(pot); Set<Integer> players = currentPlayers.stream() .filter(p -> p != player) .map(playerToSmartness::get) .collect(Collectors.toSet()); int vote = player.vote(players); if (!currentPlayers.contains(smartnessToPlayer.get(vote))){ throw new RuntimeException(player.getClass().getSimpleName()+" voted off non-existent player"); } Vote v = new Vote(playerToSmartness.get(player), vote, currentTurn); counts[v.getRound()]++; statistics[v.getRound()][v.getVoted()]++; return v; } ``` Example Output: ``` For 1th round: 55.554756% voted for 1 4.279166% voted for 2 1.355189% voted for 3 1.778786% voted for 4 3.592771% voted for 5 3.952368% voted for 6 1.779186% voted for 7 6.427149% voted for 8 21.280630% voted for 9 For 2th round: 2.889877% voted for 1 34.080927% voted for 2 6.826895% voted for 3 4.990010% voted for 4 5.914753% voted for 5 4.985510% voted for 6 3.302524% voted for 7 11.304360% voted for 8 25.705144% voted for 9 For 3th round: 2.152783% voted for 1 13.005153% voted for 2 21.399772% voted for 3 7.122286% voted for 4 6.122008% voted for 5 6.761774% voted for 6 11.687049% voted for 7 19.607500% voted for 8 12.141674% voted for 9 For 4th round: 2.122183% voted for 1 10.105719% voted for 2 11.917105% voted for 3 17.547460% voted for 4 8.626131% voted for 5 12.079103% voted for 6 18.819449% voted for 7 11.065111% voted for 8 7.717738% voted for 9 For 5th round: 1.689826% voted for 1 7.364821% voted for 2 9.681763% voted for 3 11.704946% voted for 4 20.336237% voted for 5 20.691914% voted for 6 13.062855% voted for 7 9.332565% voted for 8 6.135071% voted for 9 For 6th round: 1.456188% voted for 1 6.726546% voted for 2 10.154619% voted for 3 16.355569% voted for 4 22.985816% voted for 5 17.777558% voted for 6 11.580207% voted for 7 7.757938% voted for 8 5.205558% voted for 9 For 7th round: 1.037992% voted for 1 6.514748% voted for 2 15.437876% voted for 3 22.151823% voted for 4 17.015864% voted for 5 14.029088% voted for 6 11.907505% voted for 7 7.957136% voted for 8 3.947968% voted for 9 ``` [Answer] # MaxPlayer A know-it-all. Prefers to remove anybody with high-intelligence (who can therefore challenge his unmatched intellect) ``` public class MaxPlayer extends Player{ @Override public int vote(Set<Integer> currentOpponents) { return Collections.max(currentOpponents); } } ``` [Answer] # Guard Votes off those that pick on the strong ... or those that annoy him. ``` package WeakestLink.Players; import WeakestLink.Game.Game; import WeakestLink.Game.Vote; import java.util.Set; /** * Created by thenumberone on 12/2/15. * @author thenumberone */ public class Guard extends Player{ @Override public int vote(Set<Integer> currentOpponents) { int me = getSmartness(); Set<Vote> history = getVotingHistory(); history.removeIf(vote -> !currentOpponents.contains(vote.getVoter()) || vote.getVoter() == me); int[] evilnessLevel = new int[Game.NUMBER_PLAYERS_PER_ROUND]; for (Vote vote : history){ evilnessLevel[vote.getVoter()] += vote.getVoted() == me ? 1_000_000 : vote.getVoted(); } int mostEvilOpponent = -1; for (int opponent : currentOpponents){ if (mostEvilOpponent == -1 || evilnessLevel[opponent] > evilnessLevel[mostEvilOpponent]){ mostEvilOpponent = opponent; } } return mostEvilOpponent; } } ``` [Answer] # Leech Relies on other bots to vote the smartest and dumbest guys off.. sort of. He is satisfied with turning up somewhere in the middle and eventually splitting the pot with the winner (since he is actually a really decent ~~guy~~ bot). ``` package WeakestLink.Players; import java.util.ArrayList; import java.util.Collections; import java.util.Set; public class Leech extends Player { /** * Copyrighted (not really, use this however you want friends) by Sweerpotato :~)! */ @Override public int vote(Set<Integer> currentOpponents) { int mySmartness = getSmartness(); ArrayList<Integer> opponentSmartness = new ArrayList<Integer>(); opponentSmartness.addAll(currentOpponents); opponentSmartness.add(mySmartness); Collections.sort(opponentSmartness); if(mySmartness > 4 && mySmartness > Collections.min(opponentSmartness)) { //There's somebody dumber than me, vote that dude off return opponentSmartness.get(opponentSmartness.indexOf(mySmartness) - 1); } else { //Vote off the smartest guy, so we have a better chance to win if(mySmartness == Collections.max(opponentSmartness)) { //Apparently, we're the smartest guy return opponentSmartness.get(opponentSmartness.indexOf(mySmartness) - 1); } else { return Collections.max(opponentSmartness); } } } } ``` [Answer] # SniperKiller [Another](https://codegolf.stackexchange.com/a/65479/31203) answer shamelessly stolen from [Linus's code](https://codegolf.stackexchange.com/a/65595/31203). This one in will kill all snipers, not protect them. If it knows that no snipers are left it will act like a sniper itself. ``` package WeakestLink.Players; import WeakestLink.Game.Vote; import java.util.Collections; import java.util.Iterator; import java.util.Set; public class SniperKiller extends Player { boolean[] sniperish; int[] sniperwouldvote; @Override public int vote(Set<Integer> currentOpponents) { int smrt = getSmartness(); currentOpponents.add(smrt); if(sniperish==null){ sniperish = new boolean[10]; sniperwouldvote = new int[10]; for(int i=10;--i!=0;){ sniperish[i] = true; sniperwouldvote[i] = 1; } sniperish[smrt]=false; //knows we are not the sniper return 1; } //figure out who isn't a sniper Vote opp_vote; int opp_smrt; Iterator<Vote> votes = getRecentVotes().iterator(); while(votes.hasNext()){ opp_vote = votes.next(); opp_smrt = opp_vote.getVoter(); if(opp_vote.getVoted() != sniperwouldvote[opp_smrt]) sniperish[opp_smrt] = false; } //figure out how snipers would vote this round Iterator<Integer> opps = currentOpponents.iterator(); int cnt_opp=0, min_opp=10, max_opp=0; int[] snpr_votes = new int[10]; while(opps.hasNext()){ opp_smrt = opps.next().intValue(); if(smrt == opp_smrt) continue; sniperwouldvote[opp_smrt] = hypothetically(opp_smrt, currentOpponents); cnt_opp++; if(sniperish[opp_smrt]){ snpr_votes[sniperwouldvote[opp_smrt]]++; } if(opp_smrt<min_opp) min_opp=opp_smrt; if(opp_smrt>max_opp) max_opp=opp_smrt; } for(int i = 1;i<10;i++){//hit the weakest sniper. if(sniperish[i] && currentOpponents.contains(i)) return i; } return hypothetically(smrt, currentOpponents); } private int hypothetically(int smrt, Set<Integer> currentOpponents) { Iterator<Integer> opps = currentOpponents.iterator(); int cnt_smrt=0, cnt_stpd=0, opp_smrt, min_stpd=10, max_smrt=0; while(opps.hasNext()){ opp_smrt = opps.next().intValue(); if(opp_smrt > smrt){ cnt_smrt++; if(opp_smrt > max_smrt) max_smrt = opp_smrt; } else if(opp_smrt < smrt){ cnt_stpd++; if(opp_smrt < min_stpd) min_stpd = opp_smrt; } } if(cnt_stpd>1) return min_stpd; return max_smrt; } } ``` [Answer] # RandomPlayer ``` public class RandomPlayer extends Player{ @Override public int vote(Set<Integer> currentOpponents) { return (int) currentOpponents.toArray()[getRandom().nextInt(currentOpponents.size())]; } } ``` [Answer] # MinPlayer An Elitist. Prefers to remove anybody with low intelligence. ``` public class MinPlayer extends Player { @Override public int vote(Set<Integer> currentOpponents) { return Collections.min(currentOpponents); } } ``` [Answer] ## HighOrLowNotSelf Removes randomly lowest or highest intelligence player (but not self). ``` public class HighOrLowNotSelf extends Player{ @Override public int vote(Set<Integer> ops) { int b=Math.round(Math.random()*1); int p; if(b==1) p=Collections.max(ops) else p=Collections.min(ops); if(p==getSmartness()) { return vote(ops); } return p; } } ``` [Answer] # VengefulSniper This started as something I *thought* was original called `StupidBuffering` (a name I hated to give up), then ended up being just a PrudentSniper who didn't care if he was being targeted. This also seemed to be the only reason he couldn't beat PrudentSniper, so I tweaked things around a bit to make that his focus. Now, this is basically a sniper, but if the smartest or dumbest bot targets him, he will target whichever one got the most votes last round. If they both got the same number of votes and both targeted him, he goes back to normal sniper-y behavior. In my tests, this actual beats PrudentSniper on occasion. ``` package WeakestLink.Players; import java.util.*; import WeakestLink.Game.Vote; public class VengefulSniper extends Player{ @Override public int vote(Set<Integer> currentOpponents) { int me = getSmartness(); int smartOpp = Collections.max(currentOpponents); int dumbOpp = Collections.min(currentOpponents); int votesAgainstSmart=0, votesAgainstDumb=0; Boolean targetedBySmart = false, targetedByDumb = false; Set<Vote> votesForMe = getRecentVotes(); Iterator<Vote> votes = votesForMe.iterator(); while(votes.hasNext()){ Vote vote = votes.next(); int voter = vote.getVoter(); int voted = vote.getVoted(); if(voted == me){ if(voter == smartOpp){ targetedBySmart = true; } if(voter == dumbOpp){ targetedByDumb = true; } } else if (voted == smartOpp){ votesAgainstSmart++; } else if (voted == dumbOpp){ votesAgainstDumb++; } } // If being targeted by smartest or dumbest, take them out // Try to go with the rest of the crowd if they both targeted me if(targetedBySmart ^ targetedByDumb){ return targetedBySmart ? smartOpp : dumbOpp; } else if (targetedBySmart && targetedByDumb){ if (votesAgainstSmart > votesAgainstDumb){ return smartOpp; } else if (votesAgainstDumb > votesAgainstSmart){ return dumbOpp; } } Iterator<Integer> opps = currentOpponents.iterator(); int cnt_stpd=0; while(opps.hasNext()){ int opp_smrt = opps.next().intValue(); if(opp_smrt < me){ cnt_stpd++; } } if (cnt_stpd < 2 || (currentOpponents.size() < 4)){ //buffer is small, protect myself return smartOpp; } else { return dumbOpp; } } } ``` [Answer] # MiddleMan The MiddleMan trys his best to maximize profits while keeping a wary eye that he's not cut from the game. He keeps around lesser contestants to improve his chance of making it to the next round (and to leave an easy finish). He will vote off someone smarter than him only if there are more smarter contestants than there are lesser contestants. Whichever of the two groups, he always votes for the lowest of the group to keep the pot climbing. ``` package WeakestLink.Players; import java.util.Collections; import java.util.Iterator; import java.util.Set; public class MiddleMan extends Player { @Override public int vote(Set<Integer> currentOpponents) { int smrt = getSmartness(); //count number of players smarter/stupider than me Iterator<Integer> opps = currentOpponents.iterator(); int cnt_smrt=0, cnt_stpd=0, opp_smrt, min_stpd=9, min_smrt=9; while(opps.hasNext()){ opp_smrt = opps.next().intValue(); if(opp_smrt > smrt){ cnt_smrt++; if(opp_smrt < min_smrt) min_smrt = opp_smrt; } else if(opp_smrt < smrt){ cnt_stpd++; if(opp_smrt < min_stpd) min_stpd = opp_smrt; } } //Keep myself in the middle of the pack, favoring the point earners if(cnt_stpd>cnt_smrt) return min_stpd; else return min_smrt; } } ``` P.S. hope it compiles, I'm not a Java guy. Had this scheme in mind before reading the other entries. Then I was surprised how close (but critically different) [Sniper](https://codegolf.stackexchange.com/a/65427/47078) was so I went ahead and used that as a jumping off point since I don't know Java syntax. Thanks @Linus [Answer] # ApproximatePosition This bot is trying to shooting approximately around the missing smartness values, assuming that the group will continue with the same pattern, meaning it will target the same type of target. It always vote for the smartest of two player when there's a choice. Long time I didn't use Java, and currently at work so... Can't test it, hope it's not too buggy, be gentle please :). By the way, it uses awt.Point only because I'm too lazy to implement a tuple n\_n. ``` package WeakestLink.Players; import WeakestLink.Game.Vote; import java.util.*; import java.awt.Point; public class ApproximatePosition extends Player { @Override public int vote(Set<Integer> currentOpponent) { List<Integer> present = new ArrayList<>(currentOpponent); List<Integer> emptyPosition = new ArrayList<Integer>(); Collections.sort(present); //If it is the first round, vote for the smartest buddy if(present.size()==8) return present.get(present.size()-1); int lastCheck=present.get(0); if(lastCheck>0) for(int i=0;i<lastCheck;i++) if(i!=getSmartness()&&!emptyPosition.contains(i)) emptyPosition.add(i); for(int i=1;i<present.size();i++) { if(present.get(i)-lastCheck>1) for (int j=lastCheck+1;j<present.get(i);j++) if(j!=getSmartness()&&!emptyPosition.contains(j)) emptyPosition.add(j); lastCheck=present.get(i); } //untill there's at least 3 excluded members, we continue with this behaviour if(emptyPosition.size()<=2) { if(emptyPosition.isEmpty()) return present.get(present.size()-1); return decide(emptyPosition.get(0),present.get(present.size()-1),present.get(0),present); } Point maxRangeOfBlank=new Point(present.get(present.size()-1),present.get(present.size()-1)); for (int i=0;i<emptyPosition.size()-1;i++) if(emptyPosition.get(i+1)-emptyPosition.get(i)==1) { int size=0; while(i+size+1<emptyPosition.size() && emptyPosition.get(i+size+1)-emptyPosition.get(i+size)==1) size++; if(size>=sizeOfRange(maxRangeOfBlank)) maxRangeOfBlank=new Point(emptyPosition.get(i),emptyPosition.get(size)); i+=size; } return decide(maxRangeOfBlank,present.get(present.size()-1),present.get(0),present); } private int decide(int blankSeat, int smartest,int dumbest,List<Integer> present) { return decide(new Point(blankSeat,blankSeat),smartest,dumbest,present); } private int decide(Point rangeBlankSeat, int smartest,int dumbest,List<Integer> present) { int target= smartest; if (rangeBlankSeat.getY()==smartest||((int)rangeBlankSeat.getY()+1)==getSmartness()){ if ((rangeBlankSeat.getX()==dumbest||(int)rangeBlankSeat.getX()-1==getSmartness())){ target= smartest; //should not happen } else { target= (int) rangeBlankSeat.getX()-1; //Vote for dumber than the missing } } else { target= (int) rangeBlankSeat.getY() +1; //Vote for smarter than the missing, default comportment } if(present.contains(target)) return target; return smartest; } //Return the number of consecutive values between X and Y (included) private int sizeOfRange(Point range) { return (int)(range.getY()-range.getX())+1; } } ``` [Answer] ## SniperAide Before the addition of [PrudentSniper](https://codegolf.stackexchange.com/questions/65420/you-are-the-weakest-link-goodbye#65587) I wrote a bot to help [Sniper](https://codegolf.stackexchange.com/questions/65420/you-are-the-weakest-link-goodbye#65427) beat [AntiExtremist](https://codegolf.stackexchange.com/questions/65420/you-are-the-weakest-link-goodbye#65499) and other *frauds* (I use the word with love). The bot, SniperAide, looks for players who vote like snipers and votes as it thinks they would when there is a consensuses. If all players look like snipers he votes for the max, protecting lower Snipers (who would also switch to the max at this point), even if it is himself. **The Code**: ``` package WeakestLink.Players; import WeakestLink.Game.Vote; import java.util.Collections; import java.util.Iterator; import java.util.Set; public class SniperAide extends Player { boolean[] sniperish; int[] sniperwouldvote; @Override public int vote(Set<Integer> currentOpponents) { int smrt = getSmartness(); if(sniperish==null){ sniperish = new boolean[10]; sniperwouldvote = new int[10]; for(int i=10;--i!=0;){ sniperish[i] = true; sniperwouldvote[i] = 1; } sniperish[smrt]=false; //knows we are not the sniper return 1; } //figure out who might isn't a sniper Vote opp_vote; int opp_smrt; Iterator<Vote> votes = getRecentVotes().iterator(); while(votes.hasNext()){ opp_vote = votes.next(); opp_smrt = opp_vote.getVoter(); if(opp_vote.getVoted() != sniperwouldvote[opp_smrt]) sniperish[opp_smrt] = false; } //include ourself in the simulation of other snipers. currentOpponents.add(smrt); //figure out how snipers would vote this round Iterator<Integer> opps = currentOpponents.iterator(); int cnt_snpr=0, cnt_opp=0, min_opp=10, max_opp=0; int[] snpr_votes = new int[10]; while(opps.hasNext()){ opp_smrt = opps.next().intValue(); if(smrt == opp_smrt) continue; sniperwouldvote[opp_smrt] = hypothetically(opp_smrt, currentOpponents); cnt_opp++; if(sniperish[opp_smrt]){ cnt_snpr++; snpr_votes[sniperwouldvote[opp_smrt]]++; } if(opp_smrt<min_opp) min_opp=opp_smrt; if(opp_smrt>max_opp) max_opp=opp_smrt; } //figure out how to vote in sniper's intrest when not identified if(cnt_snpr == cnt_opp) return max_opp; if(cnt_snpr == 0) return hypothetically(smrt, currentOpponents); //if multiple hypothetical snipers only vote how they agree int onlyvote = -1; for(int i=10; --i!=0;){ if(onlyvote>0 && snpr_votes[i]!=0) onlyvote=-2; if(onlyvote==-1 && snpr_votes[i]!=0) onlyvote=i; } if(onlyvote>0) return onlyvote; return max_opp; } private int hypothetically(int smrt, Set<Integer> currentOpponents) { Iterator<Integer> opps = currentOpponents.iterator(); int cnt_smrt=0, cnt_stpd=0, opp_smrt, min_stpd=10, max_smrt=0; while(opps.hasNext()){ opp_smrt = opps.next().intValue(); if(opp_smrt > smrt){ cnt_smrt++; if(opp_smrt > max_smrt) max_smrt = opp_smrt; } else if(opp_smrt < smrt){ cnt_stpd++; if(opp_smrt < min_stpd) min_stpd = opp_smrt; } } if(cnt_stpd>1) return min_stpd; return max_smrt; } } ``` He currently is not much help against PrudentSniper. [Answer] # IndependentVoter This bot knows that the general population is always wrong! So it votes for whoever is getting the least votes. Code is nearly Identical to SolarAaron's "Bandwagon", but the end logic is flipped. ``` package WeakestLink.Players; import WeakestLink.Game.Vote; import java.util.Map; import java.util.Set; /** * Votes for the currently lest voted bot in the game. * Or the lowest one. */ public class IndependentVoter extends Player { @Override public int vote(Set<Integer> currentOpponents) { int self = getSmartness(), vote = -1; java.util.Map<Integer, Integer> votes = new java.util.TreeMap<>(); getVotingHistory().stream().map((Vote v)-> v.getVoted()).filter((Integer i)-> !i.equals(self)).forEach((Integer tgt)-> { if(!votes.containsKey(tgt)) { votes.put(tgt, 1); } else { votes.put(tgt, votes.get(tgt) + 1); } }); do { if(votes.entrySet().isEmpty()) { vote = currentOpponents.stream().filter((Integer i)-> !i.equals(self)).sorted().findFirst().get(); } else { if(votes.containsKey(vote)) { votes.remove(vote); vote = -1; } for(Map.Entry<Integer, Integer> vv: votes.entrySet()) { Integer key = vv.getKey(); Integer value = vv.getValue(); if((vote == -1) || (value < votes.get(vote))) { vote = key; } } } } while(!currentOpponents.contains(vote)); return vote; } } ``` [Answer] # Anarchist The anarchist doesn't like regimes. The anarchist will try to kill the current president. If the anarchist is president, he decides to abuse his power and kill useless peagents. Unless he was targeted by one of his inferiors, for they should burn instead. ``` package WeakestLink.Players; import WeakestLink.Game.Vote; import java.util.LinkedList; import java.util.Set; public class Anarchist extends Player { LinkedList<Integer> opponents; @Override public int vote(Set<Integer> currentOpponents) { opponents = new LinkedList(); opponents.addAll(currentOpponents); opponents.sort(Integer::compare); int me = getSmartness(); if (getPresident() != me) { return getPresident(); } else { // treason ? Vote voteForMe = getRecentVotes().stream().filter(v -> v.getVoted() == me).findAny().orElse(null); if (voteForMe == null) { // No treason ! Hurray. Kill the peagants. return getPeagant(); } else { // TREASON! return opponents.get(opponents.indexOf(voteForMe.getVoter())); } } } private int getPresident() { return opponents.getLast(); } private int getPeagant() { return opponents.getFirst(); } } ``` ]
[Question] [ The text of the children's book [*Polar Bear, Polar Bear, What Do You Hear?*](http://www.eric-carle.com/ECbooks.html#anchor009) has a very simple pattern. You might use the text to teach introductory programming concepts. My son was quickly bored by this idea, so I decided to play some golf with it instead. ## The Challenge In your programming language of choice, write the smallest program possible which will print the following text. Output should match exactly, including case, spacing, and punctuation. ``` Polar Bear, Polar Bear, what do you hear? I hear a lion roaring in my ear. Lion, Lion, what do you hear? I hear a hippopotamus snorting in my ear. Hippopotamus, Hippopotamus, what do you hear? I hear a flamingo fluting in my ear. Flamingo, Flamingo, what do you hear? I hear a zebra braying in my ear. Zebra, Zebra, what do you hear? I hear a boa constrictor hissing in my ear. Boa Constrictor, Boa Constrictor, what do you hear? I hear an elephant trumpeting in my ear. Elephant, Elephant, what do you hear? I hear a leopard snarling in my ear. Leopard, Leopard, what do you hear? I hear a peacock yelping in my ear. Peacock, Peacock, what do you hear? I hear a walrus bellowing in my ear. Walrus, Walrus, what do you hear? I hear a zookeeper whistling in my ear. Zookeeper, Zookeeper, what do you hear? I hear children... ...growling like a polar bear, roaring like a lion, snorting like a hippopotamus, fluting like a flamingo, braying like a zebra, hissing like a boa constrictor, trumpeting like an elephant, snarling like a leopard, yelping like a peacock, bellowing like a walrus... that's what I hear. ``` [Answer] ## 05AB1E, ~~349~~ ~~331~~ ~~330~~ ~~322~~ ~~314~~ 311 bytes ``` •4i;kV_†©:š×Îj€Yå—‚‘%˜ESδþ¤çÑ9¶‹{Å€7¾à{Ì®qA•35B0¡…ing«lV•7ü[¿‘¢wÀ¶à-‚¤î„jHâ™ÐJ'µ‡ÀÂý6›ü‚š¸€%NtÅýµL›fU¥ì€€uîT¡›Ÿ{!œ>'Ì&ý§¨Ü?é>•36B1ð:0¡™D©„, «D‚ø“€À€·€î—«?“¶«¸â€˜€JU¦“„¾“‚˜lv„I “—«0€†€¯¶å.“«0¡`yð«Y¦õ‚˜Nè«sr„ aN5Qi'n«}ð«N9›ijrj¨ðs«…...«}srJˆ}X¯‚ø€Jvy,¶?}…...DU?Y¨vN__i',¶}yð“€è€…“N6Qi'n«}ð®NèJl?}X,“€Š's€À I—«.“? ``` [Try it online](http://05ab1e.tryitonline.net/#code=4oCiNGk7a1Zf4oCgwqk6xaHDl8OOauKCrFnDpeKAlOKAmuKAmCXLnEVTw47CtMO-wqTDp8OROcK24oC5e8OF4oKsN8K-w6B7w4zCrnFB4oCiMzVCMMKh4oCmaW5nwqtsVuKAojfDvFvCv-KAmMKid8OAwrbDoC3igJrCpMOu4oCeakjDouKEosOQSifCteKAocOAw4LDvTbigLrDvOKAmsWhwrjigqwlTnTDhcO9wrVM4oC6ZlXCpcOs4oKs4oKsdcOuVMKh4oC6xbh7IcWTPifDjCbDvcKnwqjDnD_DqT7igKIzNkIxw7A6MMKh4oSiRMKp4oCeLCDCq0TigJrDuOKAnOKCrMOA4oKswrfigqzDruKAlMKrP-KAnMK2wqvCuMOi4oKsy5zigqxKVcKm4oCc4oCewr7igJzigJrLnGx24oCeSSDigJzigJTCqzDigqzigKDigqzCr8K2w6Uu4oCcwqswwqFgecOwwqtZwqbDteKAmsucTsOowqtzcuKAniBhTjVRaSduwqt9w7DCq0454oC6aWpyasKow7BzwqvigKYuLi7Cq31zckrLhn1Ywq_igJrDuOKCrEp2eSzCtj994oCmLi4uRFU_WcKodk5fX2knLMK2fXnDsOKAnOKCrMOo4oKs4oCm4oCcTjZRaSduwqt9w7DCrk7DqEpsP31YLOKAnOKCrMWgJ3PigqzDgCBJ4oCUwqsu4oCcPw&input=) **Explanation** `•4i;kV_†©:š×Îj€Yå—‚‘%˜ESδþ¤çÑ9¶‹{Å€7¾à{Ì®qA•` Packed string containing the sounds `GROWL0ROAR0SNORT0FLUT0BRAY0HISS0TRUMPET0SNARL0YELP0BELLOW0WHISTL` `35B0¡…ing«lV` Unpack, split on 0, add "ing" to each word, convert to lower and store in variable Y `•7ü[¿‘¢wÀ¶à-‚¤î„jHâ™ÐJ'µ‡ÀÂý6›ü‚š¸€%NtÅýµL›fU¥ì€€uîT¡›Ÿ{!œ>'Ì&ý§¨Ü?é>•` Packed string containing the animals `POLAR1BEAR0LION0HIPPOPOTAMUS0FLAMINGO0ZEBRA0BOA1CONSTRICTOR0ELEPHANT0LEOPARD0PEACOCK0WALRUS0ZOOKEEPER` `36B1ð:0¡™` Unpack, replace 1 with space, split on 0 and convert to title case `D©„, «D‚ø` Duplicate, save to register for later use, add ", " to one copy, duplicate that and zip. `“€À€·€î—«?“¶«¸` Dictionary words "what do you hear?", followed by a new line, added to a new list `‘€JU` Cartesian product of list of "Animal, Animal, " and "what do you hear?\n", flattened and joined and stores it in variable X. Pruduces list of strings of the form "Animal, Animal, what do you hear?n". `¦“„¾“‚˜l` Take the remaining list of animals from before, remove the zookeeper and add children, convert to lower case. `v` For each animal: ``` „I “—«0€†€¯¶å.“«0¡` ``` Push "I hear0 in my ear.", split on 0 and push as separate strings. `yð«Y¦õ‚˜Nè«` Push "animal sound" with children having no sound `sr„ a` Push "a" in correct place `N5Qi'n«}` If the animal is "Elephant" add "n" `ð«` Add space. `N9›ijrj¨ðs«…...«}` If animal is children, remove space and add "..." `srJˆ}` Join the sentence "I hear a(n) animal sound in my ear." (as well as the children one), store in global array and end loop `X¯‚ø€J` Retrieve the first lines, zip and join producing the first part of the rhyme "Animal, Animal, what do you hear?\nI hear a(n) animal sound in my ear." `vy,¶?}` Print followed by new line. `…...DU?` Print "..." and store a copy in variable X. `Y¨v` For each sound except "whistling": N\_\_i',¶} For each line except the first one, start it with ",\n" (making the comma go on previous line) `yð“€è€…“` Push sound, space and "like a" `N6Qi'n«}` If Elephant add "n". `ð®NèJl?}X,` Retrieve the animal saved in register, join everything, print and end loop followed by "...". This produces the "sound like a(n) animal," lines. `“€Š's€À I—«.“?` Print dictionary string "that's what I hear." [Answer] # PHP, ~~420~~ ~~414~~ ~~434~~ ~~414~~ 412 bytes call from CLI or prepend `<pre>` to output. ``` $v=[growl,roar,snort,flut,bray,hiss,trumpet,snarl,yelp,bellow,whistl];$a[6]=n;foreach($n=['polar bear',lion,hippopotamus,flamingo,zebra,'boa constrictor',elephant,leopard,peacock,walrus,zookeeper]as$i=>$p)echo$i?"I hear a$a[$i] $p $v[$i]ing in my ear. ":"",$q=ucwords($p),", $q, what do you hear? ",$i>9?"I hear children... ...":""&$z[]="$v[$i]ing like a$a[$i] $p";echo join(", ",$z),"... that's what I hear."; ``` * a couple of notices for undefined constants; PHP´s implicit cast to literal string kicks in again * adding the "n" for "an elephant" took 20 bytes ... hmpf. * got the 20 bytes back by reordering stuff :) **breakdown** ``` $n=['polar bear',lion,hippopotamus,flamingo,zebra,'boa constrictor',elephant,leopard,peacock,walrus,zookeeper]; $v=[growl,roar,snort,flut,bray,hiss,trumpet,snarl,yelp,bellow,whistl]; $a[6]=n; // loop through nouns with index $i foreach($n as$i=>$p) echo // print first part: // not first noun: print second line to previous step $i?"I hear a$a[$i] $p $v[$i]ing in my ear.\n\n":"", // uppercase the first letter of each word in the noun, print $q=ucwords($p), // print uppercase noun again and the rest of the line ", $q, what do you hear?\n", // for last noun print bridge, else print nothing $i>9?"I hear children...\n\n...":"" // ... AND add line to second part &$z[]="$v[$i]ing like a$a[$i] $p" ; // print second part and final line echo join(",\n",$z),"...\nthat's what I hear."; ``` [Answer] # JavaScript, ~~545~~ ~~541~~ 497 bytes ``` a="Polar Bear|Lion|Hippopotamus|Flamingo|Zebra|Boa Constrictor|Elephant|Leopard|Peacock|Walrus|Zookeeper".split`|`;s=btoa`º0:èj¼ìíÍùn·6ëk,áË3¶»¦¥ës²v«<ÛzYhÃ<!Ëe`.split`z`;a.map((m,n)=>{console.log(m+", "+m+", what do you hear?\n "+((n>9)?"I hear children...\n":"I hear a"+(n==5?"n ":" ")+a[n+1].toLowerCase()+" "+s[n+1]+"ing in my ear.\n"))});p="...";a.map((m,n)=>{if(n>9)return;p+=s[n]+"ing like a"+(n==6?"n ":" ")+m.toLowerCase()+(n>8?"...\nthat's what I hear.":",\n")});console.log(p) ``` Quite a fun challenge! Thanks Downgoat for saving me ~~27~~ a ton of bytes using `atob`, and Titus for 4 bytes! Ungolfed: ``` a="Polar Bear|Lion|Hippopotamus|Flamingo|Zebra|Boa Constrictor|Elephant|Leopard|Peacock|Walrus|Zookeeper".split`|`; s=btoa`º0:èj¼ìíÍùn·6ëk,áË3¶»¦¥ës²v«<ÛzYhÃ<!Ëe`.split`z`; a.map((m,n)=>{ console.log(m+", "+m+", what do you hear?\n "+((n==10)?"I hear children...\n":"I hear a" + (n==5?"n ":" ") + a[n+1].toLowerCase() + " " + s[n+1] + "ing in my ear.\n")) }); p="...";a.map((m,n)=>{ if(n==10) return; p+=s[n] + "ing like a" + (n==6?"n ":" ") + m.toLowerCase() + (n==9?"...\nthat's what I hear.":",\n") }); console.log(p); ``` [Answer] # [///](https://esolangs.org/wiki////), ~~523~~ 512 bytes ``` /_/\/\///:/ar_!/, what do you he:? I he: _$/!a_#/ing in my e:. _%/ing like a_&/, _*/, _0/Pol: Be:_1/ion_2/ippopotamus_3/lamingo_4/ebra_5/oa _S/onstrictor_6/lephant_7/eopard_8/eacock_9/alrus_Q/ookeeper_R/trumpet/0&0$ l1 ro:#L1&L1$ h2 snort#H2&H2$ f3 flut#F3&F3$ z4 bray#Z4&Z4$ b5cS hiss#B5CS&B5CS$n e6 R#E6&E6$ l7 snarl#L7&L7$ p8 yelp#P8&P8$ w9 bellow#W9&W9$ zQ whistl#ZQ&ZQ!children... ...growl% pol: be:*ro:% l1*snort% h2*flut% f3*bray% z4*hiss% b5cS*R%n e6*snarl% l7*yelp% p8*bellow% w9... that's what I he:. ``` [Try it online!](//slashes.tryitonline.net/#code=L18vXC9cLy8vOi9hcl8hLywgd2hhdCBkbyB5b3UgaGU6PwpJIGhlOiBfJC8hYV8jL2luZyBpbiBteSBlOi4KCl8lL2luZyBsaWtlIGFfJi8sIF8qLywKXzAvUG9sOiBCZTpfMS9pb25fMi9pcHBvcG90YW11c18zL2xhbWluZ29fNC9lYnJhXzUvb2EgX1Mvb25zdHJpY3Rvcl82L2xlcGhhbnRfNy9lb3BhcmRfOC9lYWNvY2tfOS9hbHJ1c19RL29va2VlcGVyX1IvdHJ1bXBldC8wJjAkIGwxIHJvOiNMMSZMMSQgaDIgc25vcnQjSDImSDIkIGYzIGZsdXQjRjMmRjMkIHo0IGJyYXkjWjQmWjQkIGI1Y1MgaGlzcyNCNUNTJkI1Q1MkbiBlNiBSI0U2JkU2JCBsNyBzbmFybCNMNyZMNyQgcDggeWVscCNQOCZQOCQgdzkgYmVsbG93I1c5Jlc5JCB6USB3aGlzdGwjWlEmWlEhY2hpbGRyZW4uLi4KCi4uLmdyb3dsJSBwb2w6IGJlOipybzolIGwxKnNub3J0JSBoMipmbHV0JSBmMypicmF5JSB6NCpoaXNzJSBiNWNTKlIlbiBlNipzbmFybCUgbDcqeWVscCUgcDgqYmVsbG93JSB3OS4uLgp0aGF0J3Mgd2hhdCBJIGhlOi4) 608 bytes less than the actual message (1120), this is less than half of it (560)! [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 387 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` ⎕UCS¯2(219⌶)¯128+⎕UCS'øZýÓÁî°üÁ~`Û¯ß(4Õ+ÖjáïvXô ¶Dhkë ©4¹³`LxÖ4¢gͼ4ªBáDÚN¼ùV ÂÅF]@¸hÆà bKÚ¸_oQãÔÝ ¸$8§ú_ÔÈxÖ ~6*ãªd ¿ð>¥ÐB8þôÍxwÄ6Å ô¡é¢wBlDµ¯ë Ãbqè+ý+ÜÈýgu!gWËØ#0="«ë"HDÝÀV·¦/ÕMÆí}h<àì7å ÝÒëëñX³ýM <dÄ<ëmµñqP]¥c¬l¾¤ìÚã/$ÝÕqÙÞîCLéMÝÏ}OÔϤr$¤è©~ì2[¢{·YWÒ俦à¶)YØ©;s÷¬¥+ó&¿ÉâgËr ,Ýî©)¥Ö­2è´ÝÅd{úK5­·Õ}ýÚ' ``` To ease reading: `⎕UCS¯2(219⌶)¯128+⎕UCS'`...`'` `⎕UCS '`...`'` convert string to Unicode code points `¯128+` subtract 128 to get -128 ≤ n ≤ 127 `¯2(219⌶)` un-zlib `⎕UCS` convert Unicode code points to string The source string is the following 365 bytes of zlib'ed Unicode code points: ``` F8 5A FD D3 C1 EE 04 B0 8C FC C1 7E 60 DB AF 91 DF 28 34 D5 2B D6 6A E1 EF 15 76 96 58 F4 09 B6 44 11 93 04 68 6B EB A0 A9 94 34 B9 10 98 0F B3 60 4C 78 0C D6 91 1C 34 A2 89 67 CD BC 34 AA 42 95 E1 44 9E DA 4E BC 0B 0F F9 87 85 56 20 83 C2 C5 46 5D 40 B8 68 C6 E0 20 92 62 13 81 89 4B DA B8 5F 9A 6F 51 E3 D4 DD 9F A0 B8 24 38 A7 FA 5F D4 C8 78 7F D6 A0 7E 36 2A E3 AA 64 20 BF F0 3E A5 D0 42 9A 95 38 FE F4 CD 8A 78 99 77 C4 17 89 11 10 36 82 C5 0D 8A 9A F4 A1 12 E9 A2 92 77 9D 42 1E 6C 44 B5 AF EB 0D 04 C3 62 71 87 9C E8 2B FD 2B DC 04 C8 FD 67 75 21 67 57 04 CB D8 23 12 30 9A 3D 22 AB EB 22 48 9E 44 DD C0 56 B7 87 85 A6 2F D5 03 4D 9D C6 ED 7D 1E 68 3C E0 EC 37 9C 94 08 86 E5 09 DD D2 EB EB F1 58 B3 FD 4D 20 04 3C 17 64 C4 3C EB 6D B5 F1 11 89 71 50 5D A5 63 AC 6C 9A BE A4 EC DA E3 2F 24 DD D5 71 D9 DE EE 04 43 4C E9 4D DD CF 7D 4F 13 D4 CF 13 A4 72 24 A4 E8 1A 9E A9 7E EC 1F 32 5B 19 10 A2 7B B7 01 59 57 D2 E4 BF A6 E0 B6 29 94 59 D8 A9 3B 73 1D 94 9B F7 AC A5 2B F3 26 BF C9 E2 67 7F CB 72 0A 2C DD EE A9 29 A5 D6 AD 92 32 E8 B4 DD C5 64 7B FA 8A 4B 35 AD B7 D5 7D 82 0F FD 1 DA ``` [Answer] # Python 3, ~~497~~ ~~484~~ 480 bytes ``` P=print N=lambda m:"an"[:("E"==m[0])+1]+" "+m.lower() h="I hear " A=[a.split("|")for a in"Polar Bear|growl:Lion|roar:Hippopotamus|snort:Flamingo|flut:Zebra|bray:Boa Constrictor|hiss:Elephant|trumpet:Leopard|snarl:Peacock|yelp:Walrus|bellow:Zookeeper|whistl".split(":")] for i in range(11): a,b=A[i] if i:P(h+N(a)+" "+b+"ing in my ear.\n") a+=", ";P(a+a+"what do you hear?") P(h+"children...\n\n..."+",\n".join([z+"ing like "+N(y)for y,z in A[:-1]])+"...\nthat's what I hear.") ``` (Credit for 13 bytes saved should go to Gábor Fekete, and an additional 4 bytes were saved by Taylor Lopez.) So you could probably guess I was going to use a language like Python as a teaching tool. This was the program before I started golfing it. ``` def startsWithVowel(name): firstLetter = name[0] return firstLetter in ["A", "E", "I", "O", "U"] def aOrAn(name): return "an" if startsWithVowel(name) else "a" animals = [ # NAME (0), SOUND (1) ("Polar Bear", "growling"), ("Lion", "roaring"), ("Hippopotamus", "snorting"), ("Flamingo", "fluting"), ("Zebra", "braying"), ("Boa Constrictor", "hissing"), ("Elephant", "trumpeting"), ("Leopard", "snarling"), ("Peacock", "yelping"), ("Walrus", "bellowing"), ("Robot Dragon", "screeching"), ("Owl", "hooting"), ("Monkey", "laughing"), ("Zookeeper", "whistling")] NAME = 0 SOUND = 1 for animalNumber in range(len(animals)): thisAnimal = animals[animalNumber] if animalNumber + 1 < len(animals): nextAnimal = animals[animalNumber + 1] else: nextAnimal = None print("{n}, {n}, what do you hear?".format(n=thisAnimal[NAME])) if nextAnimal != None: print("I hear {a} {n} {s} in my ear.".format(n=nextAnimal[NAME].lower(), s=nextAnimal[SOUND], a=aOrAn(nextAnimal[NAME]))) else: print("I hear children...") children = [] for animal in animals[:-1]: children.append("{s} like {a} {n}".format(n=animal[NAME].lower(), s=animal[SOUND], a=aOrAn(animal[NAME]))) print("...{}...".format(",\n".join(children))) print("that's what I hear.") ``` [Answer] # Pyth - 427 384 Bytes ``` =G"1, 1, what do you hear?\nI hear a 2 in my ear.\n"=Hc"growling/Polar Bear/roaring/Lion/snorting/Hippopotamus/fluting/Flamingo/braying/Zebra/hissing/Boa Constrictor/trumpeting/Elephant/snarling/Leopard/yelping/Peacock/bellowing/Walrus/whistling/Zookeeper"\/FNT ::G\1@H+yN1\2++r@H+yN3Zd@H+yN2)p+::G"I(.|\n)*"k\1@H20"I hear children...\n\n..."FN9 ::"1 like a 2,"\1@HyN\2r@H+yN1Z)p"bellowing like a walrus...\nthat's what I hear. ``` ``` J"%s, %s, what do you hear?"K"I hear a%sing in my ear.\n"=Hc"Polar Bear/roar/Lion/snort/Hippopotamus/flut/Flamingo/bray/Zebra/hiss/Boa Constrictor/trumpet/Elephant/snarl/Leopard/yelp/Peacock/bellow/Walrus/whistl/Zookeeper/growl"\/FN11 %J*2[@HyN)?qNT"I hear children...\n"%Kjd[?qN5\nkr@H+yN2Z@HhyN))p"..."FN9 +%=J"%sing like a%s"[@HtyN+?qN5\nk+dr@HyNZ)?qN8"..."\,) "that's what I hear" ``` Try it here - [permalink](http://pyth.herokuapp.com/?code=J%22%25s%2C+%25s%2C+what+do+you+hear%3F%22K%22I+hear+a%25sing+in+my+ear.%5Cn%22%3DHc%22Polar+Bear%2Froar%2FLion%2Fsnort%2FHippopotamus%2Fflut%2FFlamingo%2Fbray%2FZebra%2Fhiss%2FBoa+Constrictor%2Ftrumpet%2FElephant%2Fsnarl%2FLeopard%2Fyelp%2FPeacock%2Fbellow%2FWalrus%2Fwhistl%2FZookeeper%2Fgrowl%22%5C%2FFN11%0A%25J%2a2%5B%40HyN%29%3FqNT%22I+hear+children...%5Cn%22%25Kjd%5B%3FqN5%5Cnkr%40H%2ByN2Z%40HhyN%29%29p%22...%22FN9%0A%2B%25%3DJ%22%25sing+like+a%25s%22%5B%40HtyN%2B%3FqN5%5Cnk%2Bdr%40HyNZ%29%3FqN8%22...%22%5C%2C%29%0A%22that%27s+what+I+hear%22&debug=0) [Answer] # C#, ~~575~~ ~~525~~ ~~520~~ ~~526~~ ~~507~~ ~~504~~ ~~497~~ ~~494~~ 493 bytes ``` ()=>{var t="growl,Polar Bear,roar,Lion,snort,Hippopotamus,flut,Flamingo,bray,Zebra,hiss,Boa Constrictor,trumpet,Elephant,snarl,Leopard,yelp,Peacock,bellow,Walrus,whistl,Zookeeper".Split(',');string r="",s="",z="a ",n="an ";for(int i=0,j=0;i<21;r+=t[++i]+$", {t[i]}, what do you hear?\nI hear "+(i>19?@"children... ...":(i==11?n:z)+t[++i+1].ToLower()+$" {t[i]}ing in my ear.\n\n"))s+=j<20?t[j]+"ing like "+(j==12?n:z)+t[++j].ToLower()+(++j<20?@", ":@"... "):"that's what I hear.";return r+s;}; ``` C# lambda where the output is a `string`. ### Explanation 1. Init `t` as a string with the format `noise,animal,noise,animal,...` and split by `,`. 2. Declare `r` and `s`. `r` is the first part of the song and `s` the last part. `z` and `n` are here to handle `Elephant`. 3. Walk `t` and build `r` and `s` in the same loop. Weird ternary+interpolated stuff. 4. Return the first part of the song followed by the last part. ### Code ``` ()=>{ var t="growl,Polar Bear,roar,Lion,snort,Hippopotamus,flut,Flamingo,bray,Zebra,hiss,Boa Constrictor,trumpet,Elephant,snarl,Leopard,yelp,Peacock,bellow,Walrus,whistl,Zookeeper".Split(','); string r="",s="",z="a ",n="an "; for(int i=0,j=0;i<21;r+=t[++i]+$", {t[i]}, what do you hear?\nI hear "+(i>19?@"children... ...":(i==11?n:z)+t[++i+1].ToLower()+$" {t[i]}ing in my ear.\n\n")) s+=j<20?t[j]+"ing like "+(j==12?n:z)+t[++j].ToLower()+(++j<20?@", ":@"... "):"that's what I hear."; return r+s; }; ``` [Try it online!](https://dotnetfiddle.net/mlzBeA) [Answer] # Python 2 - 454 bytes ``` a="polar bear,lion,hippopotamus,flamingo,zebra,boa constrictor,elephant,leopard,peacock,walrus,zookeeper,whistl,bellow,yelp,snarl,trumpet,hiss,bray,flut,snort,roar,growl".split(',') e='...\n\n' r=range print'\n'.join([(a[i].title()+', ')*2+"what do you hear?\nI hear "+((i<10)*("a%s %sing in my ear.\n"%("n "[i!=5:]+a[i+1],a[~-~i]))or"children%s..."%e+",\n".join(a[~j]+"ing like a"+"n "[j!=6:]+a[j]for j in r(10))+e+"that's what I hear.")for i in r(11)]) ``` [Answer] # R 518 509 482 477 474 465 452 456 bytes [Link](http://www.r-fiddle.org/#/fiddle?id=5pqkHPyL&version=2 "Link") to R-Fiddle to try code ``` a=c("Polar Bear","Lion","Hippopotamus","Flamingo","Zebra","Boa Constrictor","Elephant","Leopard","Peacock","Walrus","Zookeeper") b=c("...growl","roar","snort","flut","bray","hiss","trumpet","snarl","yelp","bellow","whistl") d=c(rep("a ",6),"an ") f=tolower(a) cat(c(paste0(a,", ",a,", what do you hear?\nI hear ",c(paste0(d,f," ",b,"ing in my ear.")[-1],"children..."),"\n\n"),paste0(b,"ing like ",d,f,c(rep(",\n",9),"...\nthat's what I hear."))[-11])) ``` * Moved `children` out of the vector `a`, and got rid of corresponding entry in the `d` vector to save 8 bytes * More tidying up and removing of subscripts made redundant by moving `children`, saved further 27 bytes. * Globalised the `tolower` function, saved 5 bytes * Replace `writeLines` with `cat` and reformatted appropriately (added `\n` in places) saved 3 bytes * Realised that if `d` is only 7 elements not the full 11, R will just loop back to the start again. As 11 < 14 then this works for us. Saved 9 bytes. * globalised subscripts, saved 13 bytes. * `cat` function was separating with `" "`, changed back to `writeLines`. Added 4 bytes (`cat` can be fixed by adding `,sep=""` to the function) [Answer] # C#, 592 572 Bytes ``` using System;class p{static void Main(){string[] s={"","","Polar Bear","Lion","Hippopotamus","Flamingo","Zebra","Boa Contrictor","Elephant","Leopard","Peacock","Walrus","Zookeeper","growl","roar","snort","flut","bray","hiss","trumpet","snarl","yelp","bellow","whistl"};for(int i=2;i<13;i++){s[0]+=(s[i]+", "+s[i]+", what do you hear?\nI hear "+(i<12?"a"+(i==7?"n ":" ")+s[i+1].ToLower()+" "+s[i+12]+"ing in my ear.\n\n":"children...\n\n..."));if(i<12)s[1]+=s[i+11]+"ing like a"+(i==8?"n ":" ")+s[i].ToLower()+(i<11?",\n":"...\nthat's what I hear.\n");}Console.Write(s[0]+s[1]);}} ``` Had such a great time taking this challenge with my colleague! Thanks for the idea. Formatted: ``` using System; class p { static void Main() { string[] s = { "", "", "Polar Bear", "Lion", "Hippopotamus", "Flamingo", "Zebra", "Boa Contrictor", "Elephant", "Leopard", "Peacock", "Walrus", "Zookeeper", "growl", "roar", "snort", "flut", "bray", "hiss", "trumpet", "snarl", "yelp", "bellow", "whistl" }; for (int i = 2; i < 13; i++) { s[0] += (s[i] + ", " + s[i] + ", what do you hear?\nI hear " + (i < 12 ? "a" + (i == 7 ? "n " : " ") + s[i + 1].ToLower() + " " + s[i + 12] + "ing in my ear.\n\n" : "children...\n\n...")); if (i < 12) s[1] += s[i + 11] + "ing like a" + (i == 8 ? "n " : " ") + s[i].ToLower() + (i < 11 ? ",\n" : "...\nthat's what I hear.\n"); } Console.Write(s[0] + s[1]); Console.ReadKey(); } } ``` **EDIT:** Thank you for your numerous and awesome tips, they helped a lot and I'll try to get the other ones working as well. [Answer] ## Batch, ~~650~~ 647 bytes ``` @echo off set e=echo( set s=shift call:d a "polar bear" ...growl "Polar Bear" a lion roar Lion a hippopotamus snort Hippopotamus a flamingo flut Flamingo a zebra bray Zebra a "boa constrictor" hiss "Boa Constrictor" an elephant trumpet Elephant a leopard snarl Leopard a peacock yelp Peacock a walrus bellow exit/b :d call:v %* Walrus a zookeeper whistl Zookeeper %e%I hear children... %e% :l %e%%3ing like %1 %~2, %s% %s% %s% %s% if not "%5"=="" goto l %e%%3ing like a %2... %e%that's what I hear. exit/b :v %e%%~4, %~4, what do you hear? if "%5"=="" exit/b %e%I hear %5 %~6 %7ing in my ear. %e% %s% %s% %s% %s% goto v ``` Because `%*` is the nearest thing Batch has to an array. If I can use `Polar bear` and `Boa constrictor` then I can save 10%... but I'm still more than 50% of the original text... Edit: Saved 3 bytes by setting `e=echo(` with a `(` instead of a space, which allows me to use it to echo blank lines, although I then have to write out `@echo off` in full. [Answer] ## Bash + zcat, 402 bytes Just a joke: a 2 lines bash script that tails itself and pipe the second line to zcat. The second line is the gzipped text. How to prepare it: all the text in a file `a`. Then ``` echo "tail -n+2 \$0|zcat;exit" > go.sh gzip a ; cat a.gz >> go.sh chomod u+x go.sh ``` The file so created when executed returns the starting text, 402 Bytes. [Answer] # F#, ~~591~~ ~~589~~ ~~579~~ ~~576~~ ~~573~~ ~~567~~ 552 bytes This is my first try at code golfing with a language i like. I bet there are some ways this could be made shorter. Runs in FSI, so no need for .NET boilerplate. Edit: Shaved 10 bytes by removing `\r`. It still renders fine in VSCode so go figure. Cut another three bytes with function composition, and another three with a lambda, then six with a for loop instead of Seq.iter (getting rid of the lambda). Finally 15 bytes were cut by rearranging `a(s:string)` ``` let A="Polar Bear,Lion,Hippopotamus,Flamingo,Zebra,Boa Constrictor,Elephant,Leopard,Peacock,Walrus,Zookeeper".Split(',') let S="growl,roar,snort,flut,bray,hiss,trumpet,snarl,yelp,bellow,whistl".Split(',') let a(s:string)=(if s.[0]='E'then"an "else"a ")+s.ToLower() let f i=sprintf"%s, %s, what do you hear?\nI hear "A.[i]A.[i] for i in 0..9 do printfn"%s%s %sing in my ear.\n"(f i)(a A.[i+1])S.[i+1] printf"%schildren...\n\n..."(f 10) let t i=sprintf"%sing like %s"S.[i](a A.[i]) Seq.iter(t>>printfn"%s,")[0..8] printfn"%s...\nthat's what I hear."(t 9) ``` [Answer] ## Emacs Lisp, 576 (621) bytes ``` (let*((a'("polar bear""lion""hippopotamus""flamingo""zebra""boa constrictor""elephant""leopard""peacock""walrus""zookeeper"))(l(length a))(m(- l 1))(s'("growl""roar""snort""flut""bray""hiss""trumpet""snarl""yelp""bellow""whistl")))(dotimes(i l)(message"%s, what do you hear?"(let((a(capitalize(nth i a))))(concat a", "a)))(if(not(eq i m))(message "I hear a %s %sing in my ear.\n"(nth(1+ i)a)(nth(1+ i)s))(message"I hear children...\n")(dotimes(j m)(message(concat(when(eq j 0)"...")"%sing like a %s"(if(eq(1+ j)m)"..."","))(nth j s)(nth j a)))(message"That's what I hear.")))) ``` When fixing "an elephant", it takes slightly longer: ``` (let*((a'("polar bear""lion""hippopotamus""flamingo""zebra""boa constrictor""elephant""leopard""peacock""walrus""zookeeper"))(l(length a))(m(- l 1))(s'("growl""roar""snort""flut""bray""hiss""trumpet""snarl""yelp""bellow""whistl")))(dotimes(i l)(message"%s, what do you hear?"(let((a(capitalize(nth i a))))(concat a", "a)))(if(not(eq i m))(message "I hear a %s %sing in my ear.\n"(nth(1+ i)a)(nth(1+ i)s))(message"I hear children...\n")(dotimes(j m)(message(concat(when(eq j 0)"...")"%sing like a"(and(string-match-p"^[aeiou]"(nth j a))"n")" %s"(if(eq(1+ j)m)"..."","))(nth j s)(nth j a)))(message"That's what I hear.")))) ``` Ungolfed: ``` (let* ((animals '("polar bear" "lion" "hippopotamus" "flamingo" "zebra" "boa constrictor" "elephant" "leopard" "peacock" "walrus" "zookeeper")) (l (length animals)) (m(- l 1)) (sounds '("growl" "roar" "snort" "flut" "bray" "hiss" "trumpet" "snarl" "yelp" "bellow" "whistl"))) (dotimes (i l) (message "%s, what do you hear?" (let ((animal (capitalize (nth i animals)))) (concat animal ", " animal))) (if (not (eq i m)) (message "I hear a %s %sing in my ear.\n" (nth (1+ i) animals) (nth (1+ i) sounds)) (message "I hear children...\n") (dotimes (j m) (message (concat (when (eq j 0) "...") "%sing like a" (and (string-match-p"^[aeiou]" (nth j animals)) "n") " %s" (if (eq (1+ j) m) "..." ",")) (nth j sounds ) (nth j animals))) (message"That's what I hear.")))) ``` [Answer] # C, 596 bytes Call `f()` without any arguments. This is not the best golf in the world, I probably can shrink it more. ``` f(n){char*t,a[99][99]={"Polar Bear","Lion","Hippopotamus","Flamingo","Zebra","Boa Constrictor","Elephant","Leopard","Peacock","Walrus","Zookeeper","growl","roar","snort","flut","bray","hiss","trumpet","snarl","yelp","bellow","whistl"};for(n=0;n<11;){strcpy(t=a[n+30],n^6?" ":"n ");strcat(t,a[n++]);for(;*t=tolower(*t);++t);}for(n=0;printf("%s, %s, what do you hear?\n",a[n],a[n]),n<10;++n)printf("I hear a%s %sing in my ear.\n\n",a[n+31],a[12+n]);puts("I hear children...\n");for(n=11;n<21;++n)printf("%s%sing like a%s%s\n",n^11?"":"...",a[n],a[n+19],n^20?",":"...");puts("that's what I hear.");} ``` [Try it on ideone.](http://ideone.com/cyOIob) [Answer] # Python 3, ~~442~~ 441 bytes ``` h=t='' for n,s in zip('polar bear,lion,hippopotamus,flamingo,zebra,boa constrictor,elephant,leopard,peacock,walrus,zookeeper'.split(','),'...growl roar snort flut bray hiss trumpet snarl yelp bellow whistl'.split()):u='n'[:'el'in n],n,s,n.title();h+="I hear a{0} {1} {2}ing in my ear.\n\n{3}, {3} what do you hear?\n".format(*u);t+="{2}ing like a{0} {1},\n".format(*u) print((h+'I hear children...\n\n'+t)[44:-30]+"...\nthat's what I hear.") ``` # ungolfed: ``` animals = 'polar bear,lion,hippopotamus,flamingo,zebra,boa constrictor,elephant,leopard,peacock,walrus,zookeeper'.split(',') sounds = '...growl roar snort flut bray hiss trumpet snarl yelp bellow whistl'.split() h=t='' for n,s in zip(animals,sounds): u='n'[:'el'in n], n, s, n.title() h+="I hear a{0} {1} {2}ing in my ear.\n\n{3}, {3} what do you hear?\n".format(*u) t+="{2}ing like a{0} {1},\n".format(*u) print((h+'I hear children...\n\n'+t)[44:-30]+"...\nthat's what I hear.") ``` Basically, just a loop that builds up two strings representing the two parts of the story. The `'n'[:'el'in n]` handles the "an" for elephant. The `[44:-30]` chops off the leading "I hear a polar bear growling in my ear" and the trailing "whistling like a zookeeper". [Answer] ## QB64 (QuickBASIC), 581 bytes The code expands a bit when you throw it in the interpreter, but this source file is valid to load as-is. If you want to see the whole output before it scrolls past, then you'll need to add a `width 80,46` statement to the beginning. ``` READ a$,v$ FOR x=0 TO 10 ?a$+", "+a$+", what do you hear?" IF x>9THEN ?"I hear children...":?:?"..."; RESTORE FOR y=0 TO 9 READ a$,v$ ?v$+"ing like "; CALL j(a$) IF y<9THEN?", "ELSE?"...":?"that's what I hear." NEXT END ELSE READ a$,v$ ?"I hear "; CALL j(a$) ?" "+v$+"ing in my ear." ? END IF NEXT DATA"Polar Bear","growl","Lion","roar","Hippopotamus","snort","Flamingo","flut","Zebra","bray","Boa Constrictor","hiss","Elephant","trumpet","Leopard","snarl","Peacock","yelp","Walrus","bellow","Zookeper","whistl" SUB j (A$) ?"a"; IF LEFT$(A$,1)="E"THEN?"n"; ?" "+LCASE$(A$); END SUB ``` [Answer] # **LUA 535 bytes** ``` p=print a="growl.roar.snort.flut.bray.hiss.trumpet.snarl.yelp.bellow.whist"b="polar bear.lion.hippopotamus.flamingo.zebra.boa constrictor.elephant.leopard.peacock.walrus.zookeeper."z=a.gmatch(a,"%P+")x=b.gmatch(b,"%P+")w=''for j=1,11 do i=x()v=z()e=j==7 and'n 'or' 'p(j==1 and''or'I hear a'..e..i..' '..v..'ing in my ear.\n')w=w..(j>10 and''or v..'ing like a'..e..i..(j>9 and'...'or',')..'\n')y=i:gsub("^%l",a.upper):gsub("%s%l",a.upper)p(y..', '..y..' what do you hear?')end p('I hear children...\n')p('...'..w.."that's what I hear.") ``` ## **ungolfed:** ``` sound_list = "growl.roar.snort.flut.bray.hiss.trumpet.snarl.yelp.bellow.whist" animal_list = "polar bear.lion.hippopotamus.flamingo.zebra.boa constrictor.elephant.leopard.peacock.walrus.zookeeper." sound_it = string.gmatch(sound_list, "%P+") animal_it = string.gmatch(animal_list, "%P+") part_2 = '' for i = 1, 11 do animal = animal_it() sound = sound_it() aORan = i == 7 and 'n ' or ' ' print(i == 1 and '' or 'I hear a'..aORan..animal..' '..sound..'ing in my ear.\n') part_2 = part_2..(i > 10 and '' or sound..'ling like a'..aORan..animal..(i > 9 and '...' or ',')..'\n') big_animal = animal:gsub("^%l", string.upper):gsub("%s%l", string.upper) print(big_animal..', '..big_animal..' what do you hear?') end print('I hear children...\n') print('...'..part_2.."that's what I hear.") ``` [Try it online](http://goo.gl/Bcu0AZ) [Answer] # PHP, 366 bytes Lazy answer, but why write a custom decompressor when gzip is available? Hex dump of PHP code (can be saved with *xxd -r*) ``` 0000000: 3c3f 3d67 7a69 6e66 6c61 7465 2827 7d53 <?=gzinflate('}S 0000010: c16a 8430 10bd e72b e6d6 cbe0 2f14 b6b4 .j.0...+..../... 0000020: b4d0 c3de 0abd 8d6e baca c64c 1823 62bf .......n...L.#b. 0000030: be51 3354 1472 58f3 76de f864 e6bd 5cd9 .Q3T.rX.v..d..\. 0000040: 91c0 c592 20ec f1d4 5284 1bc3 cc23 b4a9 .... ...R....#.. 0000050: f26c 3ed6 1308 5cc7 1e84 493a 7f87 ce43 .l>...\...I:...C 0000060: 3f43 222a 633e 1381 b03d 0bef b75d 081c ?C"*c>...=...].. 0000070: 3852 3f0e 3078 9678 147a df75 20ec ff15 8R?.0x.x.z.u ... 0000080: 857f 1cf5 498a 1318 4f9a 6f99 4450 54d4 ....I...O.o.DPT. 0000090: fab5 b510 a4df 7c14 fa5e 1884 7c14 246a ......|..^..|.$j 00000a0: 2668 d80f 51ba 26b2 a4b9 87e1 2876 6182 &h..Q.&.....(va. 00000b0: 97ff 1e84 63a1 f001 0fd6 d9d0 928f 1065 ....c..........e 00000c0: ec83 3dcd fc9a 7904 4565 632d 0792 5bf2 ..=...y.Eec-..[. 00000d0: 84c4 9dcc dd48 0405 25a5 60a9 e1e6 01b3 .....H..%.`..... 00000e0: 75e1 2874 dd38 0405 25a1 899c a494 d4d6 u.(t.8..%....... 00000f0: 399e 8e4a 5f2b 89a0 67c9 4ee6 87b5 c10a 9..J_+..g.N..... 0000100: 4cc9 86e8 4ea6 2a8f a0b0 b4fb a6ed dc4d L...N.*........M 0000110: acaf aaf4 6e7a dc85 a755 d375 0fbb ccbf ....nz...U.u.... 0000120: dea4 3ab5 a211 2651 2adf 1e34 1a7b adb6 ..:...&Q*..4.{.. 0000130: fb8c 1bcd 6f26 35d7 6896 3c2a a121 45a3 ....o&5.h.<*.!E. 0000140: c1ca d543 eed0 683a b465 971c 34d9 6ca5 ...C..h:.e..4.l. 0000150: 3404 68d4 3b1d 29bb 65b2 17ca a847 cb2a 4.h.;.).e....G.* 0000160: 624b f169 d8d6 b66d aa32 7f27 293b bK.i...m.2.'); ``` I used a few iterations of [zopfli](https://github.com/google/zopfli) to convert the source text to 349 bytes of compressed data, avoiding the ' character which would otherwise have to be escaped with backslashes. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~308~~ ~~303~~ ~~299~~ ~~295~~ ~~288~~ ~~280~~ ~~294~~ ~~289~~ 286 bytes Contains a bunch of unprintables; follow the link below to view them. ``` `Pol BÁLiyHippopotam«yFlaÚÁoyZeßBoa CÆqÎtyE¤pÊCyLeopÂýPea¬ckyWalr«yZookeep`qy `gwÓ2ÂüÍdfl©dßdÊdtruÛFdsnÓ)lpdÞ)owdØtl`qd [¡[X',SX`, Ø º y Ê#? I Ê# `Y<A?[Y¶5?``:'aSUg°Y v SVgY `g my e.`R]¬:[`å,Á`Q='.³R²QU¯J £[Vv `g ¦ke `Y¶6?``:'aSXv]¬Ãq`, ` QR`È 's Ø I Ê#.`]¬]¬Ã·]¬ ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=YFBvbIcgQsEdTGmNeUhpcHBvcG90YW2reUZsYdrBb3laZd+fQm9hIEPGcc50jnlFpHDKQ3lMZW9wwv1QZWGsY2t5V2Fscqt5Wm9va2VlcIBgcXkKYGeed9MywvzNFmRmbKlk359kyo1kdHJ120Zkc26H0ylscGTeKW93ZNiRdGxgcWQKW6FbWCcsU1hgLCDYiSC6IHmMIMojPwpJIMojIGBZPEE/W1m2NT9ghGA6J2FTVWewWSB2IFNWZ1kgYIhnIIggbXkgZYcuYFJdrDpbYOWRLMFgUT0nLrNSslFVr0ogo1tWdiBgiGcgpmtlIGBZtjY/YIRgOidhU1h2XazDcWAsCmAgUVJgyAkncyDYiSBJIMojLmBdrF2sw7ddrA==&input=) +14 bytes 'cause I'd ballsed up the walrus' line; will need to take another pass over it next week to see if I can get any of those bytes back. [Answer] # Pyth, 342 bytes ``` L:b"a e""an e"y>sm.F" I hear a {1} {0} in my ear. {2}, {2}, what do you hear?"+dr3edJC,+R"ing"c"growl roar snort flut bray hiss trumpet snarl yelp bellow whistl"bc"polar bear lion hippopotamus flamingo zebra boa constrictor elephant leopard peacock walrus zookeeper"b42"I hear children... "jPPysm+j" like a "d", "PJc2*6\."that's what I hear. ``` Try it online [here](https://pyth.herokuapp.com/?code=L%3Ab%22a+e%22%22an+e%22y%3Esm.F%22%0AI+hear+a+%7B1%7D+%7B0%7D+in+my+ear.%0A%0A%7B2%7D%2C+%7B2%7D%2C+what+do+you+hear%3F%22%2Bdr3edJC%2C%2BR%22ing%22c%22growl%0Aroar%0Asnort%0Aflut%0Abray%0Ahiss%0Atrumpet%0Asnarl%0Ayelp%0Abellow%0Awhistl%22bc%22polar+bear%0Alion%0Ahippopotamus%0Aflamingo%0Azebra%0Aboa+constrictor%0Aelephant%0Aleopard%0Apeacock%0Awalrus%0Azookeeper%22b42%22I+hear+children...%0A%22jPPysm%2Bj%22+like+a+%22d%22%2C%0A%22PJc2%2a6%5C.%22that%27s+what+I+hear.&debug=0). Explanation to follow. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~400~~ 399 bytes ``` ((my \a=<<"Polar Bear"Lion Hippopotamus Flamingo Zebra"Boa Constrictor"Elephant Leopard Peacock Walrus Zookeeper>>)>>.&{"$_, $_, what do you hear? I hear a {a[++$!].lc} {($/=<growl roar snort flut bray hiss trumpet snarl yelp bellow whistl>)[$!]}ing in my ear. "},"...{a[^10]>>.&{$/[$++]~"ing like a",.lc}.join(", ")}... that's what I hear.")>>.trans(["a e",/a\s\s.*r/]=>["an e","children.."])>>.say ``` [Try it online!](https://tio.run/##JY9Bb8IwDIXv/AovqrayVmG77ASdxLRpkzhwmwR0kykZzUjjyAlCFer@epfCwbJk@/l9zyk2T32fpk0LG5xNp2JJBhnmClksNFl4186Ro4DN0cObwUbbPcFKbRnFnBBeyPrAugrE4tUoV6MNsFDkkHewVFhRdYBPNBzlK6KDUk5xUYyLQt6eRfKdw1CnGgPsCFo6Qh29n0cflw4IZ1xnWXJTSlN1cE6TyWy6ZzoZYIp7b4kD/JhjgEjUQq29h8DHxqkQl8gGWmUcbJUxdIo@2gdTjNfxYReTgLYQo0cnORJdLqSU0e/r8aG88CWTdZJl5Z8YTo0@KECRDyDyl7RNRT4S4y5qRiHy3/lrjCu5FEPEwGh9uhYISuQT3PiNl/c8KWdFnNlhKKpamx0rK6UoB4nHtu//AQ "Perl 6 – Try It Online") Sub-400 bytes! [Answer] # Powershell ~~921~~ ~~889~~ ~~886~~ 898 Bytes it's not perfect, but it saves 300 Bytes :) **EDIT:** Thanks Jonathan Frech, i saved 32 Bytes. And thank you Veskah for correcting the Output. ``` filter Z($1,$2){while($1){$x,$1=$1 $y,$2=$2 [tuple]::Create($x,$y)}} $0="ing" $$="hear" $1="I $$ a " $3='in my ear.' $a='Polar Bear' $b='Lion' $c='Hippopotamus' $d='Flamingo' $e='Zebra' $f='Boa Constrictor' $g='Elephant' $h='Leopard' $i='Peacock' $j='Walrus' $k='Zookeeper' $v="children" $2="roar$0" $4="snort$0" $5="flut$0" $6="bray$0" $7="hiss$0" $8="trumpet$0" $9="snarl$0" $x="yelp$0" $y="bellow$0" $^="whistl$0" $l="$1$b $2$3" $m="$1$c $4$3" $n="$1$d $5$3" $o="$1$e $6$3" $p="$1$f $7$3" $q="I $$ an $g $8$3" $r="$1$h $9$3" $s="$1$i $x$3" $t="$1$j $y$3" $u="$1$k $^$3" $z=' like a ' $w="I $$ $v..." z $a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k $l,$m,$n,$o,$p,$q,$r,$s,$t,$u,$w|%{"$($_.item1),"*2+"what do you $$?";$_.item2;""} "...growl$0$z$a," z $b,$c,$d,$e,$f $2,$4,$5,$6,$7|%{$_.item2+$z+$_.item1+","} "$8 like an $g," z $h,$i $9,$x,$y|%{$_.item2+$z+$_.item1+","} $y+$z+"Walrus..." "that's what I $$." ``` [Answer] # clojure, 526 bytes ``` (use 'clojure.string)(let[l lower-case a(partition 2(split"Polar Bear,...growl,Lion,roar,Hippopotamus,snort,Flamingo,flut,Zebra,bray,Boa Constrictor,hiss,Elephant,trumpet,Leopard,snarl,Peacock,yelp,Walrus,bellow,Zookeeper,whistl,children,x"#","))b(map(fn[[w x][y e]][(str w", "w", what do you hear? I hear a "(l y)" "e"ing in my ear. ")(str x"ing like a "(l w))])a(rest a))r replace](print(r(str(r(join""(map first b))#".*x.*""I hear children...")(join", "(butlast(map last b)))"... that's what I hear.")#"(?i)a(?= e)""an"))) ``` Here's my initial attempt. Gotta love the formatting and how unreadable it is. Hope the warnings from `use 'clojure.string` are acceptable. [Try it online.](http://ideone.com/UUrWEN) Formatted code: ``` (use 'clojure.string) (let [animal-sound (partition 2 (split "Polar Bear,...growl,Lion,roar,Hippopotamus,snort,Flamingo,flut,Zebra,bray,Boa Constrictor,hiss,Elephant,trumpet,Leopard,snarl,Peacock,yelp,Walrus,bellow,Zookeeper,whistl,children,x" #",")) sentences (map (fn [[animal-1 sound-1] [animal-2 sound-2]] [(str animal-1 ", " animal-1 ", what do you hear?\nI hear a " (lower-case animal-2) " " sound-2 "ing in my ear.\n\n") (str sound-1 "ing like a " (lower-case animal-1))]) animal-sound (rest animal-sound))] (print (replace (str (replace (join "" (map first sentences)) #".*x.*" "I hear children...") (join ",\n" (butlast (map last sentences))) "...\nthat's what I hear.") #"(?i)a(?= e)" "an"))) ``` [Answer] # Java, ~~571 555~~ 538 or 516 Bytes ``` String p(){String r="",z="...",b,x;String[]a="Polar Bear!Lion!Hippopotamus!Flamingo!Zebra!Boa Constrictor!Elephant!Leopard!Peacock!Walrus!Zookeeper!growling!roaring!snorting!fluting!braying!hissing!trumpeting!snarling!yelping!bellowing!whistling".split("!");for(int i=1;i<11;i++){b=i==6?"n ":" ";x=a[i-1];z+=a[i+10]+" like a"+b+x+(i==10?"...":"\n");r+=x+" , "+x+", what do you hear?\n I hear a"+b+a[i].toLowerCase()+" "+a[i+11]+" in my ear.\n\n";}r+=a[10]+" what do you hear?\n\tI hear children...\n"+z+"\nthat's what I hear.";return r;} ``` But only 516 bytes is required to get result in JShell ``` String r="",z="...",b,x;String[]a="Polar Bear!Lion!Hippopotamus!Flamingo!Zebra!Boa Constrictor!Elephant!Leopard!Peacock!Walrus!Zookeeper!growling!roaring!snorting!fluting!braying!hissing!trumpeting!snarling!yelping!bellowing!whistling".split("!");for(int i=1;i<11;i++){b=i==6?"n ":" ";x=a[i-1];z+=a[i+10]+" like a"+b+x+(i==10?"...":"\n");r+=x+" , "+x+", what do you hear?\n I hear a"+b+a[i].toLowerCase()+" "+a[i+11]+" in my ear.\n\n";}r+=a[10]+" what do you hear?\n\tI hear children...\n"+z+"\nthat's what I hear." ``` [Answer] ## Swift2, **519 bytes** ``` var a=["Polar Bear","Lion","Hippopotamus","Flamingo","Zebra","Boa Constrictor","Elephant","Leopard","Peacock","Warlus","Zookeeper"],b=["...growl","roar","snort","flut","bray","hiss","trumpet","snarl","yelp","bellow","whistl"].map{"\($0)ing"},c=a.enumerate().map{"\($0.0==6 ?"an":"a") \($0.1)".lowercaseString},i=0,j=0 while i<11{print("\(a[i]), \(a[i++]), what do you hear?\nI hear \(i>10 ?"children...":"\(c[i]) \(b[i]) in my ear")\n")} while j<10{print("\(b[j]) like \(c[j++])\(j>9 ?"...\nthat's what I hear.":",")")} ``` [Answer] # Haskell 537 499 497 Bytes ``` import Data.Char a&b=a++b b=putStr c=concat d=init e('E':s)="an e"&s e s="a "&map toLower s f="I hear " l=zip(lines"Polar Bear\nLion\nHippopotamus\nFlamingo\nZebra\nBoa Constrictor\nElephant\nLeopard\nPeacock\nWalrus\nZookeeper")$words"growl roar snort flut bray hiss trumpet snarl yelp bellow whistl" main=(b.drop 41.c)[f&e n&" "&v&"ing in my ear.\n\n"&n&", "&n&", what do you hear?\n"|(n,v)<-l]>>b(f&"children...\n\n..."&(d.d.c)[v&"ing like "&e n&",\n"|(n,v)<-d l]&"...\nthat's what I hear.\n") ``` Using the convention that a solution does not have be executable, only produce the output via some function, this can be shortened to 479 Bytes. The output is in `g`: ``` import Data.Char a&b=a++b c=concat d=init e('E':s)="an e"&s e s="a "&map toLower s f="I hear " l=zip(lines"Polar Bear\nLion\nHippopotamus\nFlamingo\nZebra\nBoa Constrictor\nElephant\nLeopard\nPeacock\nWalrus\nZookeeper")$words"growl roar snort flut bray hiss trumpet snarl yelp bellow whistl" g=(drop 41.c)[f&e n&" "&v&"ing in my ear.\n\n"&n&", "&n&", what do you hear?\n"|(n,v)<-l]&f&"children...\n\n..."&(d.d.c)[v&"ing like "&e n&",\n"|(n,v)<-d l]&"...\nthat's what I hear.\n" ``` [Answer] # [C (clang)](http://clang.llvm.org/), 552 bytes ``` (*P)()=printf;l(char*s){for(;*s;s++)putchar(*s>64?*s|32:*s);}char*a[]={"Zookeeper","Walrus","Peacock","Leopard","Elephant","Boa Constrictor","Zebra","Flamingo","Hippopotamus","Lion","Polar Bear"},*s[]={"whistl","bellow","yelp","snarl","trumpet","hiss","bray","flut","snort","roar","growl"};f(i){for(i=11;i--;)P("%s, %s, what do you hear?\nI hear%s ",a[i],a[i],i?i^5?" a":" an":""),i?l(a[i-1]):0,P(i?" %sing in my ear.\n\n":"children...\n\n...",s[i-1]);for(i=11;--i;)P("%sing like a%s ",s[i],i^4?"":"n"),l(a[i]),P(i-1?",\n":"...\nthat's what I hear.");} ``` [Try it online!](https://tio.run/##PVLBitswED03XyEEoZLXDk1320NMatjS0sIecivsJguzjhyLyBohyYSQ5tvTkVz24JnH6Om9N7bbqjVgD7ebKDZSyLXz2sauNqLtwRdBXjr0oi5CHe7upBtjGosifPv60BTh7/3nFXHqaybDy2594c@IR6Wc8rzkf8D4MRDYKGixPRJ6UujA7wn9MMr1YCPBRwT2HW2IXrcR081n9eaB@k8Dg7YHJPhLO4cOIwxZ8kmjTcpowLNHBZ5fyyLkCKdeh2jo8E0ZgycCZ2UctWDBp3n04@BUciZmEiOzM7XOjDHT0KfuEVKWg8eT4de6E3p6HXq9XNa6qmq5EXweSpaeUw@R7ZGdcWQ9xWm29ncG88B4CS96NxXd6NcvDWfAV1QsVS5paASdVsudXH0qN0ITYR5ocaYtG86MZBZbu03sttdm75VdLPKEGi/DdLV@D1dV@n@4pGH0UTHIOUKO8PrQcJKy5Jx9dzJ5VsuGl9kja0da6GOY9po2WXD61Df6P9gA2go5u8w@dELWs@vtHw "C (clang) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 413 bytes ``` @t=('Polar Bear',growl,Lion,roar,Hippopotamus,snort,Flamingo,flut,Zebra,bray,'Boa Constrictor',hiss,Elephant,trumpet,Leopard,snarl,Peacock,yelp,Walrus,bellow,Zookeeper,whistl);say$_=$t[$i],", $_, what do you hear? I hear ",/Zo/?"children... ":"a".n x(/C/).lc" $t[$i+=2] $t[$i+1]ing in my ear. "while!/Zo/;pop@t;pop@t;print'...';say+(shift@t)."ing like a ".lc.(@t?",":'...')while$_=shift@t;say"that's what I hear." ``` [Try it online!](https://tio.run/##NZFNawIxEIbv/oo0CLuL06wWvCjiorS0YMFbwSIS1@gGYyYkI3b/fLfZ1R7ycZh53nkSp7wZN01BszRZo5GeLZT0CZw83gysNFrwKD28a@fQIcnLNUCw6AnejLxoe0I4mivBRu29hLhqSBYo2RJtIK9LwkirdAjwapSrpCUgf704RbBS6KQ/RJz0BtZKllieoVbGwZc0PgbtlTF4gw3iWSmnPNwiiUw2DbLu72Z9@u7rLXBg/R2wWyWJHZDVeGVVlJj3PrqTccg3mM95WWlz8MoKIXp8wiUXlv2k@TLPhCk562iD2cv2cRttox3Tll1qFjGxJ6Yb9dTCpvExCvrfvbaURGrSzjVIQ6WPVFAmeAsw@qyYZDxmiLSgOQc@6YqzDhc1HvVtM6cokYS7y318wZvmFx3FrwjN8@dYDEfDPw "Perl 5 – Try It Online") ]
[Question] [ The challenge is to write an interpreter for the [untyped lambda calculus](http://en.wikipedia.org/wiki/Lambda_calculus) in as few characters as possible. We define the untyped lambda calculus as follows: # Syntax There are the following three kinds of expressions: * A lambda expression has the form `(λ x. e)` where `x` could be any legal variable name and `e` any legal expression. Here `x` is called the parameter and `e` is called the function body. For simplicity's sake we add the further restriction that there must not be a variable with the same name as `x` currently in scope. A variable starts to be in scope when its name appears between `(λ` and `.` and stops to be in scope at the corresponding `)`. * Function application has the form `(f a)` where `f` and `a` are legal expressions. Here `f` is called the function and `a` is called the argument. * A variable has the form `x` where `x` is a legal variable name. # Semantics A function is applied by replacing each occurrence of the parameter in the functions body with its argument. More formally an expression of the form `((λ x. e) a)`, where `x` is a variable name and `e` and `a` are expressions, evaluates (or reduces) to the expression `e'` where `e'` is the result of replacing each occurrence of `x` in `e` with `a`. A normal form is an expression which can not be evaluated further. # The Challenge Your mission, should you choose to accept it, is to write an interpreter which takes as its input an expression of the untyped lambda calculus containing no free variables and produces as its output the expression's normal form (or an expression alpha-congruent to it). If the expression has no normal form or it is not a valid expression, the behaviour is undefined. The solution with the smallest number of characters wins. A couple of notes: * Input may either be read from stdin or from a filename given as a command line argument (you only need to implement one or the other - not both). Output goes to stdout. * Alternatively you may define a function which takes the input as a string and returns the output as a string. * If non-ASCII characters are problematic for you, you may use the backslash (`\`) character instead of λ. * We count the number of characters, not bytes, so even if your source file is encoded as unicode λ counts as one character. * Legal variable names consist of one or more lower case letters, i.e. characters between a and z (no need to support alphanumeric names, upper case letters or non-latin letters - though doing so will not invalidate your solution, of course). * As far as this challenge is concerned, no parentheses are optional. Each lambda expression and each function application will be surrounded by exactly one pair of parentheses. No variable name will be surrounded by parentheses. * Syntactic sugar like writing `(λ x y. e)` for `(λ x. (λ y. e))` does not need to be supported. * If a recursion depth of more than 100 is required to evaluate a function, the behaviour is undefined. That should be more than low enough to be implemented without optimization in all languages and still large enough to be able to execute most expressions. * You may also assume that spacing will be as in the examples, i.e. no spaces at the beginning and end of the input or before a `λ` or `.` and exactly one space after a `.` and between a function and its argument and after a `λ`. # Sample Input and Output * Input: `((λ x. x) (λ y. (λ z. z)))` Output: `(λ y. (λ z. z))` * Input: `(λ x. ((λ y. y) x))` Output: `(λ x. x)` * Input: `((λ x. (λ y. x)) (λ a. a))` Output: `(λ y. (λ a. a))` * Input: `(((λ x. (λ y. x)) (λ a. a)) (λ b. b))` Output: `(λ a. a)` * Input: `((λ x. (λ y. y)) (λ a. a))` Output: `(λ y. y)` * Input: `(((λ x. (λ y. y)) (λ a. a)) (λ b. b))` Output: `(λ b. b)` * Input: `((λx. (x x)) (λx. (x x)))` Output: anything (This is an example of an expression that has no normal form) * Input: `(((λ x. (λ y. x)) (λ a. a)) ((λx. (x x)) (λx. (x x))))` Output: `(λ a. a)` (This is an example of an expression which does not normalize if you evaluate the arguments before the function call, and sadly an example for which my attempted solution fails) * Input: `((λ a. (λ b. (a (a (a b))))) (λ c. (λ d. (c (c d)))))` Output: ``(λ a. (λ b. (a (a (a (a (a (a (a (a b))))))))))` This computes 2^3 in Church numerals. [Answer] **Newest:** I've squeezed it down to **644 chars**, I factored parts of cEll into cOpy and Par; cached calls to cell and cdr into temporary local variables, and moved those local variables to globals in "terminal" (ie. non-recursive) functions. Also, decimal constants are shorter than character literals and this nasty business ... ``` atom(x){ return m[x]>>5==3; } ``` ... correctly identifies lowercase letters (assuming ASCII), but also accepts any of `{|}~. (This same observation about ASCII is made in this [excellent video about UTF-8](https://www.youtube.com/watch?v=MijmeoH9LT4).) Et viola:| ``` #include<stdio.h> #include<string.h> #define X m[x] #define R return char*n,*m;int u,w,d;C(x,y){w=n-m;n+=sprintf(n,y?"(%s %s)":"(%s)",&X,m+y)+1;R w;}T(x){R X>>5==3;} L(x){R X==92;}O(x,j){w=n-m;memcpy(n,&X,j);n+=j;*n++=0;R w;}E(x){X==' '?++x:0;R X==41?0:L(x)?O(x,4):P(x);}P(x){d=0,w=x;do{X==40?d++:X==41?d--:0;++x;}while(d>0);R O(w,x-w);}D(x){u=E(x+1);R u?E(x+1+strlen(m+u)):0;}V(x){int a=E(x+1),b=D(x);R T(x)|T(a)?x:L(a)?C(a,V(b)):L(E(a+1))?V(S(V(b),E(a+3),D(a))):V(C(V(a),b?V(b):0));}S(w,y,x){R T(x)?(X==m[y]?w:x):C(L(w+1)?E(x+1):S(w,y,E(x+1)),D(x)?S(w,y,D(x)):0);} Y(char*s){n+=strlen(s=strcpy(n,s))+1;printf("%s\n%s\n\n",s,m+V(s-m));n=m+1;} char*s[]={ "((\\ a. a) (b))", "((\\ x. x) (\\ y. (\\ z. z)))", "(\\ x. ((\\ y. y) x))", "(((\\ x. (\\ y. x)) (\\ a. a)) (\\ b. b))", "((\\ x. (\\ y. y)) (\\ a. a))", "(((\\ x. (\\ y. y)) (\\ a. a)) (\\ b. b))", "((\\x. (x x)) (\\x. (x x)))",0}; #include<unistd.h> main(){char**k;n=m=sbrk(4096);*n++=0;for(k=s;*k;k++)Y(*k);R 0;} ``` **Earlier:** Can I get a few votes for effort? I've been working on this day and night for a week. I dug out the original McCarthy paper and was plagued by a bug in the paper itself until I read the appendix to Paul Graham's *The Roots of Lisp*. I was so distracted that I locked myself out of my house, then completely forgot until arriving home again that night at 12:30 (a little late to be calling the building manager who lives way out in the county), and had to spend the night at my grandmother's (hacking away until my laptop battery was dry). And after all that, it's not even close to the winning entry! I'm not sure how to make this any shorter; and I've used all the dirty tricks I can think of! Maybe it can't be done in C. With some generosity in the counting (the first chunk takes a string and prints out the result), it's *778* **770** **709** **694** chars. But to make it stand-alone, it has to have that `sbrk` call. And to handle more complicated expressions, it needs the `signal` handler, too. And of course it cannot be made into a module with any code that tries to use `malloc`. So, alas, here it is: ``` #include<stdio.h> #include<string.h> #define K(j) strncpy(n,m+x,j);n+=j;goto N; #define R return #define X m[x] #define L =='\\' char*m,*n;T(x){R islower(X);}V(x){int a=E(x+1);R T(x)?x:T(a)?x:m[a]L?C(a,V(D(x))):m[E(a+1)]L?V(S(V(D(x)),E(a+3),D(a))):V(C(V(a),D(x)?V(D(x)):0));} C(x,y){char*t=n;sprintf(n,y?"(%s %s)":"(%s)",m+x,m+y);n+=strlen(n)+1;R t-m;}Y(char*s){char*t=strcpy(n,s);n+=strlen(n)+1;printf("%s=>%s\n",s,m+V(t-m));n=m+1;}S(x,y,z){R T(z)?(m[z]==m[y]?x:z):C(m[z+1]L?E(z+1):S(x,y,E(z+1)),D(z)?S(x,y,D(z)):0);}D(x){R E(x+1)?E(x+strlen(m+E(x+1))+1):0;}E(x){char*t=n,d=0;if(X==' ')++x;if(T(x)){K(1)}if(X L){K(4)}do{d=X?(X=='('?d+1:(X==')'?d-1:d)):0;*n++=m[x++];}while(d);N:*n++=0;R t-m;} char*samp[]={ "a","a","b","b", "((\\ a. a) (b))", "(b)", "((\\ x. x) (\\ y. (\\ z. z)))", "(\\ y. (\\ z. z))", "(\\ x. ((\\ y. y) x))", "(\\ x. x)", "(((\\ x. (\\ y. x)) (\\ a. a)) (\\ b. b))", "(\\ a. a)", "((\\ x. (\\ y. y)) (\\ a. a))", "(\\ y. y)", "(((\\ x. (\\ y. y)) (\\ a. a)) (\\ b. b))", "(\\ b. b)", "((\\x. (x x)) (\\x. (x x)))", "undef", NULL}; #include<unistd.h> unsigned sz; #include<signal.h> void fix(x){signal(SIGSEGV,fix);brk(m+(sz*=2));} main(){ char**t; signal(SIGSEGV,fix); m=n=sbrk(sz=10*getpagesize()); *n++=0; for(t=samp;*t;t+=2){ Y(*t); printf("s.b. => %s\n\n", t[1]); } return 0; } ``` Here's the block just before the final reductions. The tricks here are integer cursors instead of pointers (taking advantage of the 'implicit int' behavior), and the use of 'scratch memory': the `char*n` is the 'new' or 'next' pointer into the free space. But sometimes I write a string into the memory, then call strlen and increment n; effectively using memory and *then* allocating it, after the size is easier to calculate. You can see it's pretty much straight from the McCarthy paper, with the exception of `cell()` which interfaces between the functions and the string representation of data. ``` #include<stdio.h> #include<string.h> char*m,*n; //memory_base, memory_next atom(x){ // x is an atom if it is a cursor to a lowercase alpha char. return x?(islower(m[x])?m[x]:0):0; } eq(x,y){ // x and y are equal if they are both atoms, the same atom. return x&&y&&atom(x)==atom(y); } cell(x){ // return a copy of the list-string by cursor, by parsing char*t=n,d=0; if(!x||!m[x]) return 0; if(m[x]==' ') ++x; if(atom(x)){ *n++=m[x]; *n++=0; return(n-m)-2; } if(m[x]=='\\'){ // our lambda symbol memcpy(n,m+x,4); n+=4; *n++=0; return(n-m)-5; } do{ // um ... d=m[x]?(m[x]=='('?d+1:(m[x]==')'?d-1:d)):0; *n++=m[x++]; }while(d); *n++=0; return t-m; } car(x){ // return (copy of) first element return x?cell(x+1):0; } cdr(x){ // return (copy of) rest of list return car(x)?cell(x+strlen(m+car(x))+1):0; } cons(x,y){ // return new list containing first x and rest y char*t=n; return x?(sprintf(n,y?"(%s %s)":"(%s)",m+x,m+y),n+=strlen(n)+1,t-m):0; } subst(x,y,z){ // substitute x for z in y if(!x||!y||!z) return 0; return atom(z)? (eq(z,y)?x:z): cons(m[z+1]=='\\'?car(z): subst(x,y,car(z)),cdr(z)?subst(x,y,cdr(z)):0); } eval(x){ // evaluate a lambda expression int a; return atom(x)?x: atom(a=car(x))?x: m[a]=='\\'?cons(a,eval(cdr(x))): m[car(a)]=='\\'?eval(subst(eval(cdr(x)),cell(a+3),cdr(a))): eval( cons(eval(a),cdr(x)?eval(cdr(x)):0)); } try(char*s){ // handler char*t=strcpy(n,s); n+=strlen(n)+1; printf("input: %s\n", s); printf("eval => %s\n", m+eval(t-m)); n=m+1; } ``` [Answer] # Binary Lambda Calculus 186 The program shown in the hex dump below ``` 00000000 18 18 18 18 18 18 44 45 1a 10 18 18 45 7f fb cf |......DE....E...| 00000010 f0 b9 fe 00 78 7f 0b 6f cf f8 7f c0 0b 9f de 7e |....x..o.......~| 00000020 f2 cf e1 b0 bf e1 ff 0e 6f 79 ff d3 40 f3 a4 46 |[[email protected]](/cdn-cgi/l/email-protection)| 00000030 87 34 0a a8 d0 80 2b 0b ff 78 16 ff fe 16 fc 2d |.4....+..x.....-| 00000040 ff ff fc ab ff 06 55 1a 00 58 57 ef 81 15 bf bf |......U..XW.....| 00000050 0b 6f 02 fd 60 7e 16 f7 3d 11 7f 3f 00 df fb c0 |.o..`~..=..?....| 00000060 bf f9 7e f8 85 5f e0 60 df 70 b7 ff ff e5 5f f0 |..~.._.`.p...._.| 00000070 30 30 6f dd 80 5b b3 41 be 85 bf ff ca a3 42 0a |00o..[.A......B.| 00000080 c2 bc c0 37 83 00 c0 3c 2b ff 9f f5 10 22 bc 03 |...7...<+...."..| 00000090 3d f0 71 95 f6 57 d0 60 18 05 df ef c0 30 0b bf |=.q..W.`.....0..| 000000a0 7f 01 9a c1 70 2e 80 5b ff e7 c2 df fe e1 15 55 |....p..[.......U| 000000b0 75 55 41 82 0a 20 28 29 5c 61 |uUA.. ()\a| 000000ba ``` doesn't accept quite the format you propose. Rather, it expects a lambda term in binary lambda calculus (blc) format. However, it does show every single step in the normal form reduction, using minimal parentheses. Example: computing 2^3 in Church numerals Save the above hex dump with xxd -r > symbolic.Blc Grab a blc interpreter from <http://tromp.github.io/cl/uni.c> ``` cc -O2 -DM=0x100000 -m32 -std=c99 uni.c -o uni echo -n "010000011100111001110100000011100111010" > threetwo.blc cat symbolic.Blc threetwo.blc | ./uni (\a \b a (a (a b))) (\a \b a (a b)) \a (\b \c b (b c)) ((\b \c b (b c)) ((\b \c b (b c)) a)) \a \b (\c \d c (c d)) ((\c \d c (c d)) a) ((\c \d c (c d)) ((\c \d c (c d)) a) b) \a \b (\c (\d \e d (d e)) a ((\d \e d (d e)) a c)) ((\c \d c (c d)) ((\c \d c (c d)) a) b) \a \b (\c \d c (c d)) a ((\c \d c (c d)) a ((\c \d c (c d)) ((\c \d c (c d)) a) b)) \a \b (\c a (a c)) ((\c \d c (c d)) a ((\c \d c (c d)) ((\c \d c (c d)) a) b)) \a \b a (a ((\c \d c (c d)) a ((\c \d c (c d)) ((\c \d c (c d)) a) b))) \a \b a (a ((\c a (a c)) ((\c \d c (c d)) ((\c \d c (c d)) a) b))) \a \b a (a (a (a ((\c \d c (c d)) ((\c \d c (c d)) a) b)))) \a \b a (a (a (a ((\c (\d \e d (d e)) a ((\d \e d (d e)) a c)) b)))) \a \b a (a (a (a ((\c \d c (c d)) a ((\c \d c (c d)) a b))))) \a \b a (a (a (a ((\c a (a c)) ((\c \d c (c d)) a b))))) \a \b a (a (a (a (a (a ((\c \d c (c d)) a b)))))) \a \b a (a (a (a (a (a ((\c a (a c)) b)))))) \a \b a (a (a (a (a (a (a (a b))))))) ``` Since the hexdump is rather unreadable, here is a "disassembled" version ``` @10\\@10\\@10\\@10\\@10\\@10\@\@\@\@@\@1010\@\\\@10\\@10\@\@@@1111111111101 1110@11111110\@@110@11111110\\\\@1110\@1111110\@@101101111110@111111110\@111 111110\\\\@@110@111111011110@11111011110@@10@1111110\@10110\@@111111110\@111 111110\@110@101111011110@1111111111010@1010\\@1110@11010@\@\@1010\@110@1010\ \@@@@@\@1010\@\\\\@@@10\@@111111111011110\\@@101111111111111110\@@101111110\ @@10111111111111111111111110@@@@1111111110\\110@@@@\@1010\\\\@@10\@@@1111101 11110\\@\@@@10111111101111110\@@1011011110\\@@11111010110\\@111110\@@1011110 1110@111010\10\1011111110@111110\\\@101111111111011110\\@@11111111110@@11111 0111110\10\@@@@11111110\\@10\\1101111101110\@@1011111111111111111111110@@@@1 11111110\\@10\\@10\\11011111101110110\\\@@101110110@1010\\11011111010\@@1011 111111111111110@@@@\@1010\@\\@@@10\@@@1110@10\\\@1011110\\110\\\@10\\\@1110\ @@@11111111110@1111111101010\10\\@\@@@1110\\\@10@1110111110\\1110\110@@@1111 0110@@@1111010\\110\\\@10\\\@@1101111111101111110\\\@10\\\@@1101111110111111 10\\\110@1010110\\101110\\@@11010\\\@@1011111111111110@11110\@@1011111111111 101110\@\@@@@@@@@11010101010101010\\110\\10\\1010\10\\\1010\\1010@@@110\110\ @ ``` replacing 00 (lambda) with \ and 01 (application) with @ Now it's almost as readable as brainfuck:-) Also see <http://www.ioccc.org/2012/tromp/hint.html> [Answer] ## Haskell, ~~342~~ ~~323~~ ~~317~~ 305 characters As of this writing, this is the only solution that evaluates ((λ f. (λ x. (f x))) (λ y. (λ x. y))) to the correct result (λ x. (λ z. x)) rather than (λ x. (λ x. x)). Correct implementation of the lambda calculus requires [capture-avoiding substitution](https://en.wikipedia.org/wiki/Lambda_calculus#Capture-avoiding_substitutions), even under this problem’s simplifying guarantee that no variable shadows another variable in its scope. (My program happens to work even without this guarantee.) ``` data T=T{a::T->T,(%)::ShowS} i d=T(i. \x v->'(':d v++' ':x%v++")")d l f=f`T`\v->"(λ "++v++". "++f(i(\_->v))%('x':v)++")" (?)=q.lex q[(v,s)]k|v/="("=k(maybe T{}id.lookup v)s|'λ':u<-s,[(w,_:t)]<-lex u=t? \b->k(\e->l$b.(:e).(,)w).tail|0<1=s? \f->(?(.tail).k. \x z->f z`a`x z) main=interact(? \f->(f[]%"x"++)) ``` Notes: * This runs in GHC 7.0, as required because this challenge was set in January 2011. It would be [13 characters shorter](https://github.com/andersk/tiny-lambda/blob/master/TinyLambda-minimized.hs) if I were allowed to assume GHC 7.10. [Ungolfed version](https://github.com/andersk/tiny-lambda/blob/master/TinyLambda.hs) with documentation. [Answer] ### Ruby 254 characters ``` f=->u,r{r.chars.take_while{|c|u+=c==?(?1:c==?)?-1:0;u>0}*''} l=->x{x=~/^(\(*)\(\\ (\w+)\. (.*)/&&(b,v,r=$1,$2,$3;e=f[1,r];(e==s=l[e])?b==''?x:(s=f[2,r];(x==y=b.chop+e.gsub(v,s[2+e.size..-1])+r[1+s.size..-1])?x:l[y]):(b+'(\\ '+v+'. '+s+r[e.size..-1]))||x} ``` It can be used like ``` puts l["((\\ x. (\\ y. x)) (\\ a. a))"] # <= (\ y. (\ a. a)) ``` The solution is not yet fully golfed but already almost unreadable. [Answer] Edit: check my answer below for 250 under pure JavaScript. **~~2852~~ 243 characters using LiveScript (No Regex! Not fully golfed - could be improved)** ``` L=(.0==\\) A=->it.forEach?&&it.0!=\\ V=(.toFixed?) S=(a,b,t=-1,l=0)->|L a=>[\\,S(a.1,b,t,l+1)];|A a=>(map (->S(a[it],b,t,l)),[0 1]);|a==l+-1=>S(b,0,l+-1,0)||a|l-1<a=>a+t;|_=>a R=(a)->|L a=>[\\,R a.1]|(A a)&&(L a.0)=>R(S(R(a.0),R(a.1)).1)|_=>a ``` Test: ``` a = [\\,[\\,[1 [1 0]]]] b = [\\,[\\,[1 [1 [1 0]]]]] console.log R [a, b] # outputs ["\\",["\\",[1,[1,[1,[1,[1,[1,[1,[1,[1,0]]]]]]]]]]] ``` Which is `3^2=9`, as stated on OP. If anyone is curious, here is an extended version with some comments: ``` # Just type checking λ = 100 isλ = (.0==λ) isA = -> it.forEach? && it.0!=λ isV = (.toFixed?) # Performs substitutions in trees # a: trees to perform substitution in # b: substitute bound variables by this, if != void # f: add this value to all unbound variables # l: internal (depth) S = (a,b,t=-1,l=0) -> switch | isλ a => [λ, (S a.1, b, t, l+1)] | isA a => [(S a.0, b, t, l), (S a.1, b, t, l)] | a == l - 1 => (S b, 0, (l - 1), 0) || a | l - 1 < a < 100 => a + t | _ => a # Performs the beta-reduction R = (a) -> switch | (isλ a) => [λ,R a.1] | (isA a) && (isλ a.0) => R(S(R(a.0),R(a.1)).1) | _ => a # Test a = [λ,[λ,[1 [1 0]]]] b = [λ,[λ,[1 [1 [1 0]]]]] console.log show R [a, b] ``` [Answer] # Waterhouse Arc - 140 characters ``` (= f[is cons?&car._'λ]n[if atom._ _ f._ `(λ,_.1,n:_.2)(= c n:_.0 e _)(if f.c(n:deep-map[if(is c.1 _)e.1 _]c.2)(map n _))]λ[n:read:rem #\._]) ``` [Answer] **C 1039 bytes** ``` #define F for #define R return #define E if(i>=M||j>=M)R-1; enum{O='(',C,M=3999};signed char Q[M],D[M],t[M],Z,v,*o=Q,*d=D,*T;int m,n,s,c,w,x,y;K(i,j,k){!Z&&(Z=t[O]=1)+(t[C]=-1);E;if(!o[i]){d[j]=0;R 0;}if((c=t[o[i]]+t[o[i+1]])!=2||o[i+2]!='\\'){d[j++]=o[i++];R K(i,j,i);}F(i+=2,y=w=0;i<M&&o[i]&&c;++i)c+=t[o[i]],!w&&c==1?w=i:0,!y&&o[i]=='.'?y=i+2:0;E;if(c){F(;d[j++]=o[i++];)E;R 0;}F(c=y;c<w;++c)if(o[c]=='\\')F(n=0,m=w+2;m<i;++m){if(o[m]==o[c+2]){F(x=0;o[m+x]&&isalpha(o[m+x])&&o[m+x]==o[c+2+x];++x);if(o[c+2+x]!='.'||isalpha(o[m+x]))continue;if(v>'Z')R-1;F(n=c+2;n<w;++n)if(o[n]==o[m]){F(x=0; o[m+x]&&isalpha(o[m+x])&&o[m+x]==o[n+x];++x);if(o[m+x]=='.'&&!isalpha(o[n+x]))F(;--x>=0;) o[n+x]=v;}++v;}}F(c=y;c<w&&j<M;++c){F(x=0;o[c+x]&&o[c+x]==o[k+4+x]&&isalpha(o[c+x]); ++x);if(o[k+4+x]=='.'&&!isalpha(o[c+x])){F(m=w+2;m<i-1&&j<M;++m)d[j++]=o[m];c+=x-1;}else d[j++]=o[c];}E;Z=2;R K(i,j,i);}char*L(char*a){F(s=n=0;n<M&&(o[n]=a[n]);++n);if(n==M)R 0;v='A';F(;++s<M;){Z=0;n=K(0,0,0);if(Z==2&&n!=-1)T=d,d=o,o=T;else break;}R n==-1||s>=M?0:d;} ``` Variables allow as input using lowercase letters [from a..z] the sys can generate variables using uppercase letters [from A..Z] if need in the output... Assume ascii character configuration. ``` #define P printf main() {char *r[]={ "((\\ abc. (\\ b. (abc (abc (abc b))))) (\\ cc. (\\ dd. (cc (cc dd)))))", "((\\ fa. (\\ abc. (fa abc))) (\\ yy. (\\ abc. yy)))", "((\\ x. x) z)", "((\\ x. x) (\\ y. (\\ z. z)))", "(\\ x. ((\\ y. y) x))", "((\\ x. (\\ y. x)) (\\ a. a))", "(((\\ x. (\\ y. x)) (\\ a. a)) (\\ b. b))", "((\\ x. (\\ y. y)) (\\ a. a))", "(((\\ x. (\\ y. y)) (\\ a. a)) (\\ b. b))", "((\\ x. (x x)) (\\ x. (x x)))", "(((\\ x. (\\ y. x)) (\\ a. a)) ((\\ x. (x x)) (\\ x. (x x))))", 0}, *p; int w; for(w=0; r[w] ;++w) {p=L(r[w]); P("o=%s d=%s\n", r[w], p==0?"Error ":p); } R 0; } /*1.039*/ ``` [Answer] **Python: 1266 characters** (measured using wc) ``` from collections import *;import re A,B,y,c=namedtuple('A',['l','r']),namedtuple('B',['i','b']),type,list.pop def ab(t):c(t,0);p=c(t,0);c(t,0);return B(p,tm(t)) def tm(t):return ab(t)if t[0]=='\\'else ap(t) def at(t): if t[0]=='(':c(t,0);r=tm(t);c(t,0);return r if 96<ord(t[0][0])<123:return c(t,0) if t[0]=='\\':return ab(t) def ap(t): l = at(t) while 1: r = at(t) if not r:return l l = A(l,r) def P(s):return tm(re.findall(r'(\(|\)|\\|[a-z]\w*|\.)',s)+['=']) def V(e):o=y(e);return V(e.b)-{e.i} if o==B else V(e.l)|V(e.r)if o==A else{e} def R(e,f,t):return B(e.i,R(e.b,f,t)) if y(e)==B else A(R(e.l,f,t),R(e.r,f,t))if y(e)==A else t if e==f else e def N(i,e):return N(chr(97+(ord(i[0])-96)%26),e) if i in V(e)else i def S(i,e,a): return A(S(i,e.l,a),S(i,e.r,a)) if y(e)==A else(e if e.i==i else B(N(e.i,a),S(i,R(e.b,e.i,N(e.i,a)),a)))if y(e)==B else a if e==i else e def T(e): if y(e)==A:l,r=e;return S(l.i,l.b,r)if y(l)==B else A(T(l),r)if y(l)==A else A(l,T(r)) if y(e)==B:return B(e.i,T(e.b)) q def F(e):o=y(e);return r'(\%s. %s)'%(e.i,F(e.b))if o==B else'(%s %s)'%(F(e.l),F(e.r)) if o==A else e def E(a): try: return E(T(a)) except NameError:print(F(a)) E(P(input())) ``` Not the shortest by a long shot, but it correctly handles alpha-renaming and all the examples listed in OPs post. [Answer] # Haskell 456 C It can be much shorter if the lazy evaluation feature of Haskell is fully utilized. Sadly, I don't know how to do it. Also, many characters are wasted in the parsing step. ``` data T=A[Char]|B[Char]T|C T T (!)=(++) s(A a)=a s(B a b)="(λ "!a!". "!s b!")" s(C a b)='(':s a!" "!s b!")" e d(A a)=maybe(A a)id(lookup a d) e d(B a b)=B a.e d$b e d(C a b)=f d(e d a)(e d b) f d(B x s)q=e((x,q):d)s f d p q=C p q d=tail p('(':'λ':s)=let(A c,t)=p(d s);(b,u)=p(d.d$t);in(B c b,d u) p('(':s)=let(a,t)=p s;(b,u)=p(d t)in(C a b,d u) p(c:s)|elem c" .)"=(A "",c:s)|1<2=let((A w),t)=p s in(A(c:w),t) r=s.e[].fst.p main=do l<-getLine;putStrLn$r l ``` ## Ungolfed version ``` data Expression = Literal String | Lambda String Expression | Apply Expression Expression deriving Show type Context = [(String, Expression)] show' :: Expression -> String show' (Literal a) = a show' (Lambda x e) = "(λ " ++ x ++ ". " ++ show' e ++ ")" show' (Apply e1 e2) = "(" ++ show' e1 ++ " " ++ show' e2 ++ ")" eval :: Context -> Expression -> Expression eval context e@(Literal a) = maybe e id (lookup a context) eval context (Lambda x e) = Lambda x (eval context e) eval context (Apply e1 e2) = apply context (eval context e1) (eval context e2) apply :: Context -> Expression -> Expression -> Expression apply context (Lambda x e) e2 = eval ((x, e2):context) e apply context e1 e2 = Apply e1 e2 parse :: String -> (Expression, String) parse ('(':'λ':s) = let (Literal a, s') = parse (tail s) (e, s'') = parse (drop 2 s') in (Lambda a e, tail s'') parse ('(':s) = let (e1, s') = parse s (e2, s'') = parse (tail s') in (Apply e1 e2, tail s'') parse (c:s) | elem c " .)" = (Literal "", c:s) | otherwise = let ((Literal a), s') = parse s in (Literal (c:a), s') run :: String -> String run = show' . eval [] . fst . parse main = do line <- getLine putStrLn$ run line ``` [Answer] Got 231 with JavaScript / no Regex ``` (function f(a){return a[0]?(a=a.map(f),1===a[0][0]?f(function d(b,a,e,c){return b[0]?1===b[0]?[1,d(b[1],a,e,c+1)]:2===b[0]?b[1]===c-1?d(a,0,c-1,0)||b:c-1<b[1]?[2,b[1]+e]:b:[d(b[0],a,e,c),d(b[1],a,e,c)]:b}(a[0],a[1],-1,0)[1]):a):a}) ``` Receives 2-elements arrays. `1` stands for `λ` and 2 stands for a bruijn index variable. Test: ``` zero = [1,[1,[2,0]]]; // λλ0 succ = [1,[1,[1,[[2,1],[[[2,2],[2,1]],[2,0]]]]]]; // λλλ(1 ((2 1) 0)) console.log(JSON.stringify(reduce([succ,[succ,[succ,zero]]]))); // 0+1+1+1 // Output: [1,[1,[[2,1],[[2,1],[[2,1],[2,0]]]]]] = λλ(1(1(1 0))) = number 3 ``` [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~782~~ ~~766~~ ~~758~~ 731 bytes ``` #include <string> #include <map> #define A return #define N new E using S=std::string;using C=char;using I=int;S V(I i){A(i>8?V(i/9):"")+C(97+i%9);}S W(C*&s){C*b=s;while(*++s>96);A{b,s};}struct E{I t,i;E*l,*r;E(E&o,I d,I e){t=o.t;i=o.i+(o.i>=d)*e;t?l=N{*o.l,d,e},t-1?r=N{*o.r,d,e}:0:0;}E(I d,std::map<S,I>m,C*&s){t=*s-40?i=m[W(s)],0:*++s-92?l=N{d,m,s},r=N{d,m,++s},++s,2:(m[W(s+=2)]=d,l=N{d+1,m,s+=2},++s,1);}I R(I d){A t?t-1?l->t==1?l->l->s(d,0,*r),*this=*l->l,1:l->R(d)||r->R(d):l->R(d+1):0;}I s(I d,I e,E&v){t?t-1?l->s(d,e,v),r->s(d,e,v):l->s(d,e+1,v):i==d?*this={v,d,e},0:i-=i>d;}S u(I d){A t?t-1?S{"("}+l->u(d)+' '+r->u(d)+')':S{"(\\ "}+V(d)+". "+l->u(d+1)+')':V(i);}};S f(C*s){E a{0,{},s};for(I c=999;a.R(0)&&c--;);A a.u(0);} ``` [Try it online!](https://tio.run/##hVNRb5swEH7PrzhlWmKDYaSatoFjoqriIS99aKT2YekDAZJYAlKB0yal/PbubEjaTesWOebuu/N3n48jeXhwNkny@vpJlkm@TzOY1qqS5SYcvCFF/IBumq1lmcElVJnaV@UZuIYye4JosK/xGCxErdIg6Eh4h12JZBtXvTMXslR8AbdkDpI2l0SGP2a3RH7xaTAcUvuK@N9t@dmnvF3AHbmyRjVtrqyVqPnTVuYZsWy7Dv1vlF82K1a3vMVa@0RB1MxBMckjK2dWxSMSjXZsDin@M9oosXMVl7hLm@AWipRaGVezXFw31s7NWcqylilnMqs6pDJI4AUebyOiiczNsBnTBZuHBeukKWHVzldvJkXx847U9J55gZbo@BeGO2UFqmRVb2Kk1Ru7CIg5YIsLei9SZnLtic5GqMuZYBPmcKOLY6dAzbS83AmVEOaJqyYp8/C@lFlqK2thaZhNAnzckJS@vFSd0QP2hOr7zKEmfWtYNHrEW5yoNV/GHimr3uzghKM89KQQ6ayr1jx2bfMC6QgZpvqd7X@Xu2iGZNjaSLFHGfYYxnZ1suk40OHlEjDjVkNDF4Z9Lko1GTgb2IYWR2aN04AdjyBuPNa0@uWvdxWWS4Tv@zx2b4hHR6PEcThOB8TuHn3evpttucNhyeIiHOAQQhHLklBoBoC/d2MLOTeQmTcgJrLJVI7T3jmJLBnklJqs8@Fkt1cwnaLMkZW7q2yj2alGxsty3FF23w54fNC@ErKEgwsHCmgcXb0/u/BMkbeLkA4/UsxBrAcNhoC2YhdiE/owpq2VC6s/CY7/IDj@h@BwKnF2/iPh43Mdaez2VUjcr5WOmdzExFLcE71Sej61dk9ca8P11saDuYMRhZ6SRVYbXD3tuue2yjLdXxPSMO2wU9HCpJVm12VKIAWs6VnU@9J99b8GTrFf "C++ (gcc) – Try It Online") The basic idea here is that the code uses an internal representation based on the idea of [de Bruijn indices](https://en.wikipedia.org/wiki/De_Bruijn_index) -- except that I reverse the indices to indicate the lambda-depth of the binding of the referred variable. In the code: * `E::t` represents the type of a node - 0 for a variable leaf node, 1 for a lambda node, and 2 for a function application node. (Chosen so that it coincides with the arity of the node, which just happens to be possible.) Then `E::l` and `E::r` are the children as appropriate (just `E::l` for a lambda node), and `E::i` is the lambda-depth index for a variable leaf node. * The constructor `E::E(E&o,int d,int e)` clones a subexpression which was initially at lambda-depth `d` for pasting into a new location at lambda-depth `d+e`. This involves preserving variables at lambda-depth less than `d` while incrementing variables at lambda-depth at least `d` by `e`. * `E::s` does a substitution of the subexpression `v` into variable number `d` in `*this` while decrementing variable numbers greater than `d` (and `e` is an internal detail tracking the lambda-depth increment for when it needs to call `E::c`). * `E::R` searches for a single beta-reduction to perform, preferring top-most or left-most instances according to a pre-order search through the AST. It returns nonzero if it found a reduction to perform or zero if it found none. * `E::u` is a `to_string` type operation which reconstitutes a "human readable" string using synthetic names for the variables. (Note that because of a little golfing of the `V` helper function it will only generate names containing `a` through `i`.) * The constructor `E::E(int d, std::map<std::string, int> m, char*&s)` does parsing of an input string `s` into an expression AST based on a mapping `m` of currently bound variable names into lambda-depth indices. * `f` is the main function answering the question. (As you can see at the TIO link, the code does handle variable names with multiple characters, and it also gets a correct answer of `(\ a. (\ b. a))` for `((\ f. (\ x. (f x))) (\ y. (\ x. y)))`. It also just so happens that the parsing code can handle variable shadowing at no extra cost.) --- -16 bytes partially due to idea by ceilingcat (which I had also come up with independently), and partially due to changing `E*a=new E;` to `E&a=*new E;` and then changing `a->` to `a.` -8 more bytes due to another comment by ceilingcat (factor out assignment of `a.t` from ternary) -27 bytes from converting parser and clone into constructors of `E` ]
[Question] [ *This is [Calvin](https://codegolf.stackexchange.com/users/26997/calvins-hobbies). Just trying to get 20 rep so this user can chat in the [PPCG Minecraft Server chatroom](https://chat.stackexchange.com/rooms/24544/ppcg-minecraft-server).* Write a program or function that takes in a positive integer. If the integer is even (2, 4, 6, ...), print or return this exact ASCII art string: ``` __ __ __ __ ___ /\ /\ | |\ | | / | | /\ | | / \/ \ | | \ | |-- | |--\ /__\ |-- | / \ | | \| |__ \__ | \ / \ | | ``` If the integer is odd (1, 3, 5, ...), print or return this exact ASCII art string: ``` __ __ \ / | | /| | / | / \ __ / | | \ /\ / | | / | |-- | |--/ \ / |-- | \/ \/ | |/ | |__ \__ |__| \/ |__ _|_ ``` You may assume the input is always a positive integer. In both output cases there may optionally be any number of trailing spaces up to the right edge of the "T" on each line, and/or a single trailing newline. Note how there are two columns of spaces between each letter. **The shortest code in bytes wins.** [Answer] # JavaScript (ES6), ~~343~~ ~~336~~ ~~289~~ ~~267~~ ~~265~~ 260 bytes Just for fun... :) (Thanks to Xufox for cutting off 46 bytes, and encouraging me to cut off another 37 on my own.) ``` n=>`887141${n%2?` 98/202/05/4|3/29 1 /2|5| 92/92/30 / 0--2|5|--/492/3|--3| 29/29/40/2013912|1|59/4|12_|_`:`3185121_ 2/92/9409205/405/94|5| /29/2930 9 0--2|5|--94/193|--3| /892029013912|392/492|5|`}`.replace(/\d/g,x=>+x?x<2?'__':x<9?' '.repeat(x):'\\':'| |') ``` Called as `a(4)` or similar. Try it here: ``` a=n=>`887141${n%2?` 98/202/05/4|3/29 1 /2|5| 92/92/30 / 0--2|5|--/492/3|--3| 29/29/40/2013912|1|59/4|12_|_`:`3185121_ 2/92/9409205/405/94|5| /29/2930 9 0--2|5|--94/193|--3| /892029013912|392/492|5|`}`.replace(/\d/g,x=>+x?x<2?'__':x<9?' '.repeat(x):'\\':'| |') document.getElementById("a").innerHTML = "<pre>"+a(2)+"</pre>"; document.getElementById("b").innerHTML = "<pre>"+a(3)+"</pre>"; ``` ``` <p id="a"></p> <p id="b"></p> ``` I've condensed the whitespace into strings of digits from `2` to `8` (e.g. `887` = 23 spaces). Each digit is then replaced with the corresponding number of spaces. `0` represents `| |`, and `1` represents `__`. All in all, this program is 170 bytes shorter than the two strings combined (203 + 227 = 430), so I'm happy. :) **Edit:** Somehow, it's exactly the same length as the only other entry at this point.... o\_o **Edit 2:** Saved some space by changing `n%2<1?` to `n%2?` and swapping the strings. Also took advantage of the fact that the beginnings of the two strings are the same to reduce another 5 bytes. **Edit 3:** `|2|` seemed to show up an awful lot, so simplified each occurence to `x`, saving 7 bytes. Xufox's suggestions cut off another 40 bytes. **Edit 4:** Xufox's suggestion to replace `\n` with actual line breaks paid off, removing 6 bytes from the total. Changing `x` to `0` and `__` to `1` (insert evil laugh here), then combining all of the (insert plural of Regex here), as he did in his entry, saved an extra 16 bytes. **Edit 5:** Since I've chosen to use the ES6 standards, I used custom template string interpolation to shave off 2 final bytes. [Answer] ## Matlab, ~~343~~ 341 ``` a=' -/\_|'; if mod(input(''),2) x='003C00E00E000L0005N5000I000005550I0000I0055N4UVYO26R4004400400U005300UUXO060O060003C00C30CO00IO00UUUS060S5B54000';else x='0I2000L0000L000E05H50C0000000555000C00C00H554UVYO26R4004400400U000250WUU006O006O0I2002I00O0I0O0C0UUU006S05BT0004';end disp(a(reshape(dec2base(base2dec(reshape(x,[],7),36),6),4,[])-47)) ``` The input number is provided from stdin. Sample run: ``` >> a=' -/\_|'; if mod(input(''),2) x='003C00E00E000L0005N5000I000005550I0000I0055N4UVYO26R4004400400U005300UUXO060O060003C00C30CO00IO00UUUS060S5B54000';else x='0I2000L0000L000E05H50C0000000555000C00C00H554UVYO26R4004400400U000250WUU006O006O0I2002I00O0I0O0C0UUU006S05BT0004';end disp(a(reshape(dec2base(base2dec(reshape(x,[],7),36),6),4,[])-47)) 1 __ __ __ __ ___ /\ /\ | |\ | | / | | /\ | | / \/ \ | | \ | |-- | |--\ /__\ |-- | / \ | | \| |__ \__ | \ / \ | | ``` [Answer] # CJam, ~~158~~ ~~149~~ ~~145~~ 138 bytes ``` li2%"A+×rµ^ÅÆÿ»£ºoU#ü T^U^ÝZe<ÄÊKÞÒ£^ÛWWø5Úí§¹T^Úêer^^°^Ã}Ã^A0R2"281b7b"/ -_\|"f=N/S3**_"_ ":T/TW%*4/zW%1m>N*1>"\/"_W%er"^W^]5OU"{i_32>T=t}/\4/zN*? ``` The above uses caret notation, since the code contains unprintable characters. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=li2%25%22A%2B%C3%97r%C2%B5%C2%85%C3%86%C3%BF%C2%BB%C2%A3%C2%BAoU%23%C3%BC%20T%15%C2%9DZe%3C%C3%84%C3%8AK%C3%9E%C3%92%C2%A3%C2%9BWW%C3%B85%C3%9A%C3%AD%C2%A7%C2%B9T%C2%9A%C3%AAer%1E%C2%B0%C2%83%7D%C3%83%010R2%22281b7b%22%2F%0A%20-_%5C%7C%22f%3DN%2FS3**_%22_%20%22%3AT%2FTW%25*4%2FzW%251m%3EN*1%3E%22%5C%2F%22_W%25er%22%17%1D5OU%22%7Bi_32%3ET%3Dt%7D%2F%5C4%2FzN*%3F&input=1). If the permalink doesn't work in your browser, you can copy the code from [this paste](http://pastebin.com/EQTLJbqR). ### Example run ``` $ LANG=en_US $ xxd -ps -r > minecraft.cjam <<< 6c69322522412bd772b585c6ffbba3ba6f5523fc2054159d5a653cc4ca4bded2a39b5757f835daeda7b9549aea65721eb0837dc30130523222323831623762222f0a202d5f5c7c22663d4e2f53332a2a5f225f20223a542f5457252a342f7a5725316d3e4e2a313e225c2f225f5725657222171d354f55227b695f33323e543d747d2f5c342f7a4e2a3f $ cjam minecraft.cjam <<< 2; echo __ __ __ __ ___ /\ /\ | |\ | | / | | /\ | | / \/ \ | | \ | |-- | |--\ /__\ |-- | / \ | | \| |__ \__ | \ / \ | | $ cjam minecraft.cjam <<< 1; echo __ __ \ / | | /| | / | / \ __ / | | \ /\ / | | / | |-- | |--/ \ / |-- | \/ \/ | |/ | |__ \__ |__| \/ |__ _|_ ``` ### Idea Instead of encoding the MINECRAFT string (padded to achieve a constant line length) directly, we'll encode a "zipped" version of it, where rows and columns have been transposed. After zipping and removing the linefeeds, this string (let's call it **R**) has to be encoded: ``` / / / \ \ / / \ \ \ ||| ||| \ \ \ ||| |||_ -__ -_ | / \_ __ _ |||_ - _ - |\ \ / / /_ \_ \ \ |||_ - _ - _ _|||_ ``` There are many runs of spaces, so we'll replace each occurrence of a space triplet with a linefeed. This leaves us with seven different characters (`\n -/\_|`), so we assign each of them a number from **0** to **6** and consider the resulting array digits of a base 7 number, which we then encode as a byte string. Decoding works by reversing the steps from above. The mirrored string can be constructed from the original one. If we reverse the order of the four rows and swap the soliduses, we obtain the following: ``` \ / | | /| |__ /__ | / \ / | | \ /\ / | | / | |-- | |--/ \__/ |-- | \/ \/ | |/ | | \ | | \/ | | __ __ __ __ ___ ``` Somehow similar, but we'll clearly have to rotate the rows to bring the bottom row to the top: ``` __ __ __ __ ___ \ / | | /| |__ /__ | / \ / | | \ /\ / | | / | |-- | |--/ \__/ |-- | \/ \/ | |/ | | \ | | \/ | | ``` That would be it if it wasn't for those pesky underscores. If we read the original string from top to bottom and ignore linefeeds (thus obtaining **R**) and replace each underscore followed by space with a space followed by an underscore before shifting the rows, this is the result: ``` _ _ _ \ / | | /| |_ /_ | / \ __ / | | \ /\ / | | / | |-- | |--/ \ / |-- | \/ \/ | |/ | |__ \__ |__| \/ |__ _|_ ``` Much better! All that's left to do is deleting the first space of the first row (shifting all underscores in the first row one character left), moving the misplaced underscores in **E** and **C** one row up and discarding the underscore over **T**. ### Code ``` li2% e# Read an integer from STDIN and push its parity. "A+×rµ^ÅÆÿ»£ºoU#ü T^U^ÝZe<ÄÊKÞÒ£^ÛWWø5Úí§¹T^Úêer^^°^Ã}Ã^A0R2" 281b7b e# Convert the byte string from base 281 to base 7. "/\n -_\\|"f= e# Replace each digit by its corresponding character. N/S3** e# Turn linefeeds into three spaces. _ e# Copy the resulting string. "_ ":T e# Define T. /TW%* e# Replace occurrences of T with T reversed. 4/z e# Split into chunks of length 4 and zip. W%1m> e# Reverse and rotate the rows. N* e# Join the rows, separating by linefeeds. 1> e# Discard the first character. "\/"_W%er e# Swap the soliduses. "^W^]5OU" e# Push the string that corresponds to [23 29 53 79 85]. { e# For each character: i e# Push its code point. _32> e# Push 1 iff the code point is larger than 32. T= e# Select the element at that index from T = "_ ". t e# Replace the element at the code point's index with that char. }/ e# \ e# Swap the partially generated MINECARFT string on top. 4/z e# Split into chunks of length 4 and zip. N* e# Join the rows, separating by linefeeds. ? e# Select the first string iff the input was odd. ``` [Answer] # Pyth - 182 bytes Uses base encoding approach. Since indexing is modular in Pyth, I don't even have to do anything for the even odd, just put it in the correct order, and use `@Q`. As a bonus this also works with negative numbers. ``` @mjbcs@L"_| /\\-"jCd6 56,"EWbòH\x00B)þK٣ĭIOõìæ«FFãbÐÄBØ\«¼,vã<RN>­º:w÷ò¾<éifP9e|ÉWf!FÔèà""EWbòH\x00B)þOHÿ$@ËþçX'D[¾«Â?°´=&£üá ¹»ázH×Æz3äkÕg{`!|ðY!ðGV"Q ``` I had tries only encoding the first one, then flipping and switching the slashes, but the first and last line were too hard. I could save 6 bytes by putting actual null bytes in the code, but that's too much trouble. [Try it online here](http://pyth.herokuapp.com?code=%40mjbcs%40L%22_%7C%20%2F%5C%5C-%22jCd6%2056%2C%22%03EWb%C3%B2H%5Cx00B%C2%8E)%C3%BEK%C3%99%C2%A3%C3%84%C2%AD%1AIO%C3%B5%C2%81%C3%AC%C3%A6%C2%ABF%15F%C3%A3b%C3%90%C3%84B%C2%92%C3%98%5C%C2%AB%C2%BC%2Cv%1D%C3%A3%3C%02R%1CN%C2%98%02%3E%C2%AD%C2%BA%3Aw%C3%B7%C3%B2%C2%BE%3C%C3%A9ifP9e%7C%C3%89W%12f!F%C3%94%C3%A8%C3%A0%22%22%03EWb%C3%B2H%5Cx00B%C2%8E)%C3%BEOH%C3%BF%24%40%C3%8B%C3%BE%0B%C3%A7X%06%01%27%C2%96%C2%85D%C2%91%5B%C2%BE%C2%AB%C3%82%3F%C2%B0%C2%B4%3D%26%C2%A3%C2%93%C3%BC%C3%A1%C2%87%20%C2%B9%C2%BB%02%C3%A1zH%C3%97%C3%86z%C2%8E3%C3%A4k%C3%95g%7B%60!%7C%C3%B0%C2%8D%1BY!%11%C3%B0%15%1CGV%22Q&input=4&debug=1). It looks really bad online because the output box is too small and wraps. I recommend fiddling with the dev-console and changing the `col-md-5` to a `col-md-7`. [Answer] # JavaScript (ES6), ~~312~~, ~~285~~, ~~281~~, ~~272~~, ~~270~~, ~~263~~, ~~262~~, 260 *For previous edits see the [edit history](https://codegolf.stackexchange.com/posts/53980/revisions).* **Edit 5:** In the conversion, I switched the number associated with `-` (now 0) and whitespace (now 1). In the resulting block, the numbers 1, 2 and 3 weren’t used as much anymore. This allowed me to use an array with the missing numbers. **Edit 6:** Improved the array literal. I tried this previously, but used `777` and `77` as strings instead of numbers and noticed only now that I had missed this. **Edit 7:** The “Golfed code” is a function, as specified by the question and there’s no need for `f=` to meet this specification. Thus, removing it, saving two bytes. --- Runnable in Firefox 39: ``` // Testing: f= // Golfed code: n=>[...`11111113ss17ss1pp11117pp3ppp 97dj3dj7822j78z213e17z3v8397gm78212 7f3kf3k1z27k7z20021200k17fppk1z001z d7983987j2287jz2ss1lss2aabj3d7987j2aa3aza`.replace(/[123]/g,x=>[,777,'77z',77][x])].map(a=>isNaN(i=parseInt(a,36))?a:'- /\\_|'[n%2?i%6:~~(i/6)]).join`` // Testing: ;document.body.appendChild(document.createElement('pre')).innerHTML=f(0); document.body.appendChild(document.createElement('pre')).innerHTML=f(1); document.body.appendChild(document.createElement('pre')).innerHTML=f(2); document.body.appendChild(document.createElement('pre')).innerHTML=f(35); ``` It’s based on the base 6 number system and each ASCII character stands for a number: ``` "-": 0 " ": 1 "/": 2 "\": 3 "_": 4 "|": 5 ``` Then, I’ve combined the number representation of each ASCII string. For example: when the first ASCII string contains a `/` at one position and the *other one* contains a `\` at *the same position*, that position becomes `32`, which is base 6 (`20` in decimal). If you convert this to base 36 (to get *one* base-36 number for every *two* base-6 numbers), you get `k`. All this was done beforehand and the function basically undoes this process. ~~Now the two JavaScript answers both have one other answer each, that has the same byte count…~~ --- PS: As a note to myself and a reference to others, this is the code I used: ``` // 1. ASCII here a=`|\\-/ _`; // 2. ASCII here b=`/|\\_ -`; // Note: the ASCII strings’ backslashes have to be escaped! [...a] .map((c,i)=>parseInt((c+b[i]) .replace(/-/g,'0') .replace(/ /g,'1') .replace(/\//g,'2') .replace(/\\/g,'3') .replace(/_/g,'4') .replace(/\|/g,'5'),6)) .map(c=>isNaN(c) ?` ` :c.toString(36)) .join`` // Returns "wn3g7o", which is then put into the function as the block at the top. ``` [Answer] # CJam, 136 bytes ``` "^ASÓ8¥È÷^K¯¾/^HÕ2^ÄË1jÒÝ^D^Á0îl;)HR§û|^Ê^Þ^ÇÝÅ^ßNlz^TfÑ^Øj>À^à 4#bH\¿^Äî·íì^E^A~(¿ø³(ú´,^È(¡j>è?#'»vçPïju87)×" 265b8b[S9*'|3*+S2*]"/-_\| "+f=s4/56/ri=zN* ``` The above uses caret notation, since the code contains unprintable characters. The linefeed is solely for "readability". Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22%01S%C3%938%C2%A5%C3%88%C3%B7%0B%C2%AF%C2%BE%2F%08%C3%952%C2%84%C3%8B1j%C3%92%C3%9D%04%C2%810%C3%AEl%3B)HR%C2%A7%C3%BB%7C%C2%8A%C2%9E%C2%87%C3%9D%C3%85%C2%9FNlz%14f%C3%91%C2%98j%3E%C3%80%C2%83%204%23bH%5C%C2%BF%C2%84%C3%AE%C2%B7%C3%AD%C3%AC%05%01~(%C2%BF%C3%B8%C2%B3(%C3%BA%C2%B4%2C%C2%88(%C2%A1j%3E%C3%A8%3F%23'%C2%BBv%C3%A7P%C3%AFju87)%C3%97%22265b8b%5BS9*'%7C3*%2BS2*%5D%22%2F-_%5C%7C%20%22%2Bf%3Ds4%2F56%2Fri%3DzN*&input=2). If the permalink doesn't work in your browser, you can copy the code from [this paste](http://pastebin.com/XA5WBE86). ### Example run ``` $ LANG=en_US $ xxd -ps -r > minecraft.cjam <<< 220153d338a5c8f70bafbe2f08d53284cb316ad2dd048130ee6c3b294852a7fb7c8a9e87ddc59f4e6c7a1466d1986a3ec08320342362485cbf84eeb7edec05017e28bff8b328fab42c8828a16a3ee83f2327bb76e750ef6a75383729d7223236356238625b53392a277c332a2b53322a5d222f2d5f5c7c20222b663d73342f35362f72693d7a4e2a $ cjam minecraft.cjam <<< 2; echo __ __ __ __ ___ /\ /\ | |\ | | / | | /\ | | / \/ \ | | \ | |-- | |--\ /__\ |-- | / \ | | \| |__ \__ | \ / \ | | $ cjam minecraft.cjam <<< 1; echo __ __ \ / | | /| | / | / \ __ / | | \ /\ / | | / | |-- | |--/ \ / |-- | \/ \/ | |/ | |__ \__ |__| \/ |__ _|_ ``` ### Idea This approach has some similarities to the one in [my other answer](https://codegolf.stackexchange.com/a/53973), but it is a lot simpler and (rather disappointingly) a bit shorter. We search for a way to encode the following string: ``` __ __ __ __ ___ __ __ /\ /\ | |\ | | / | | /\ | | \ / | | /| | / | / \ __ / | | / \/ \ | | \ | |-- | |--\ /__\ |-- | \ /\ / | | / | |-- | |--/ \ / |-- | / \ | | \| |__ \__ | \ / \ | | \/ \/ | |/ | |__ \__ |__| \/ |__ _|_ ``` After padding each row (to achieve a constant line length), zipping (transposing rows and columns) and removing the linefeeds, this string has to be encoded: ``` / / / \ \ / / \ \ \ ||| ||| \ \ \ ||| |||_ -__ -_ | / \_ __ _ |||_ - _ - |\ \ / / /_ \_ \ \ |||_ - _ - _ _|||_ \ \ \ / / \ \ / / / ||| ||| / / / ||| |||_ -__ -_ | / \_ __ _ ||| -_ -_ /| / \ \ _ \ _ / / / ||| -_ -_ _ ||| _ ``` We'll replace each substring `" |||"` with a **0**, each substring `" "` with a **1** and the characters of `"/-_\| "` with **2** to **7**, forming an array of base 8 digits, which can be encoded as a byte string. Decoding works by reversing the steps from above. ### Code ``` "^ASÓ8¥È÷^K¯¾/^HÕ2^ÄË1jÒÝ^D^Á0îl;)HR§û|^Ê^Þ^ÇÝÅ^ßNlz^TfÑ^Øj>À^à 4#bH\¿^Äî·íì^E^A~(¿ø³(ú´,^È(¡j>è?#'»vçPïju87)×" 265b8b e# Convert from base 265 to base 8. [S9*'|3*+S2*] e# Push [" |||" " "]. "/-_\| "+ e# Concatenate to push [" |||" " " '/' '-' '_' '\' '|' ' ']. f= e# Select the elements that correspond to the base 8 digits. s4/ e# Flatten and chop into chunks of length 4 (columns). 56/ e# Chop into two subarrays of 56 columns. ri e# Read an integer from STDIN. = e# Select the corresponding subarray. e# Arrays wrap around, so [A B]0= eq. [A B]2= and [A B]1= eq. [A B]3=. zN* e# Zip and join the rows, separating by linefeeds. ``` [Answer] # Racket, ~~443~~ ~~434~~ 386 Bytes ``` (require file/gunzip net/base64)(define(f n)(define o(open-output-bytes))(gunzip-through-ports(open-input-bytes(base64-decode #"H4sIAK8Lt1UAA22Q3Q3AIAiE352CBcwtRHLpHg7f8lubahRUDuVD5DjItrH9REgOEWgskfVMDeca1GWcSmN2WFBtlUTdzdmSOT0BpEpGnjxUAf2RmvPq1OyKGF6N5V1nvgYcWjeod/Hj8JotBRtH0qM48OeoWrBxJH23KL/dOMh4IDXe8MUbT1AqtKkBAAA="))o)(list-ref(string-split(get-output-string o)"a")(modulo n 2))) ``` Just for kicks. ``` (require file/gunzip net/base64) (define (f n) (define o (open-output-bytes)) (gunzip-through-ports (open-input-bytes (base64-decode #"H4sIAK8Lt1UAA22Q3Q3AIAiE352CBcwtRHLpHg7f8lubahRUDuVD5DjItrH9REgOEWgskfVMDeca1GWcSmN2WFBtlUTdzdmSOT0BpEpGnjxUAf2RmvPq1OyKGF6N5V1nvgYcWjeod/Hj8JotBRtH0qM48OeoWrBxJH23KL/dOMh4IDXe8MUbT1AqtKkBAAA=")) o) (list-ref (string-split (get-output-string o) "a") (modulo n 2))) ``` N.B. you may need the `#lang racket` line to run in DrRacket. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~179~~ ~~177~~ 176 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` " -/\_|"•ÿ%Ò´Åçδ’Üå·Äm…½µƵδø5)ǝ®∊∊Ý®þCĀ₆áÝoþ²ši¤Æ%ßû¤%¦Ï≠θĀ5¾₃ʒŸQ>Šn°η8±8d¸6':…é’b…÷‡ö©«&‡huѦ%λÁZÊJÌ₅ú∞°»ó₄ι«ÓW´×ƒ×ùqiò2D1āwθóÆ˲’ Tι#и∊²ý‚KʒFæΩZºÿÏ";ηiʒæøвøïž‚è°ć½∊•7вèJ2äIè ``` [Try it online.](https://tio.run/##FY9BSwJRFIX3/YowpmgRpWBKQZsiyFZBEEgQSUEuKlpEmxbjpGYWSNNCiiwVmxShbNTmqTjCPTMGLh7@hvdHpiecxQf3cM85S8HDmP/Y83xT0wuL@wfXPqGWMVCgUwspfPKWUJ/xig@ykDwVqkF9ag/bvAUWnP8r0JfIZKUgCfa6owotjRIK57DJdEtxqiCt4B09qihkICfuipw5apBsod2MdJftrLnFM2pwK0w/4SNiy3MrMgQ1mRqbgCXUEn6pRvVZSSeXeCRD4T0koshG8CC0FLoi80YN6qEptCTvUB1Pe7J8fqgjj85FHGZgw@8krjhDE2nckymfT@3yzsyYyepkoi/Ul@2RvgmD16LUxQA53yq34iMdBtjYBMO3a0sTqtRwbqk/Ga2WQ/JSjQRQ2ULV80L/) **Explanation:** ``` •ÿ%Ò´Åçδ’Üå·Äm…½µƵδø5)ǝ®∊∊Ý®þCĀ₆áÝoþ²ši¤Æ%ßû¤%¦Ï≠θĀ5¾₃ʒŸQ>Šn°η8±8d¸6':…é’b…÷‡ö©«&‡huѦ%λÁZÊJÌ₅ú∞°»ó₄ι«ÓW´×ƒ×ùqiò2D1āwθóÆ˲’ Tι#и∊²ý‚KʒFæΩZºÿÏ";ηiʒæøвøïž‚è°ć½∊• ``` is the [compressed number](https://codegolf.stackexchange.com/a/166851/52210): ``` 669530978249988431396781816197276307266403407188962925862194299697873953319419752813246251351417090709766331736351616127424760949905163941809417778114834562736028512279028673309866195447599979612590918985644583407413903825059942009898007791080822453262749380245316127735585410697701790387188175543639634091138422651942833048832372950797322005040161476426127678479662921265139425 ``` [Try it online.](https://tio.run/##FY/NSgJRHMX3PUYxRbsMLCloU7SoVRAE7pKCZlHRItpeJzWzQJoWUmSp2NQg1DSOzVVxhP@ZMXBx8Rnui0xXOIvf4nA@lpKHmcRxHEvWwFCDSR7y@BCeZE94wTv5yJ1KZtGAOqOO8MCTi39V@pLFkhIUIdgMmTQKqKN6joDcqK5TEwUNb@hTUyMLZXlbEzxkSQqkcT02I763EdXOyBF@in5SR8RXFtZUCWzVmpmCL1kdv2RTa17RySUeyNJEH9k0Sju4l0YePVl8JYf6aEsjJ7rUwuOBGl8Zmaige6HDXd5KhNkrwdFGAXfkqvCZfdGdm3A1nVwMJHveHZvbsISdph6GKM@uC18fm7DAJy44vqNAmfBJTnhDg@lp1ojj1X8) `7в` converts it to Base-7 as list, so we get the list of digits: ``` [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,5,5,1,1,1,1,5,5,1,1,1,5,5,1,1,1,1,1,1,1,1,1,1,1,1,1,5,5,1,1,5,5,5,0,1,1,3,4,1,1,3,4,1,1,1,1,6,1,1,6,4,1,1,6,1,1,6,1,1,1,1,1,3,1,1,1,1,6,1,1,6,1,1,1,1,1,3,4,1,1,1,1,6,1,1,1,1,1,6,0,1,3,1,1,4,3,1,1,4,1,1,1,6,1,1,6,1,4,1,6,1,1,6,2,2,1,1,6,1,1,1,1,1,6,2,2,4,1,1,1,1,3,5,5,4,1,1,1,6,2,2,1,1,1,6,0,3,1,1,1,1,1,1,1,1,4,1,1,6,1,1,6,1,1,4,6,1,1,6,5,5,1,1,1,4,5,5,1,1,6,1,1,1,4,1,1,3,1,1,1,1,4,1,1,6,1,1,1,1,1,6,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,5,5,1,1,1,1,5,5,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,4,1,1,1,1,1,1,1,1,3,1,1,6,1,1,6,1,1,3,6,1,1,6,1,1,1,1,1,3,1,1,1,1,6,1,1,1,3,1,1,4,1,5,5,1,3,1,1,6,1,1,1,1,1,6,0,1,4,1,1,3,4,1,1,3,1,1,1,6,1,1,6,1,3,1,6,1,1,6,2,2,1,1,6,1,1,1,1,1,6,2,2,3,1,1,1,1,4,1,1,3,1,1,1,6,2,2,1,1,1,6,0,1,1,4,3,1,1,4,3,1,1,1,1,6,1,1,6,3,1,1,6,1,1,6,5,5,1,1,1,4,5,5,1,1,6,5,5,6,1,1,1,1,1,4,3,1,1,1,1,6,5,5,1,1,5,6,5] ``` [Try it online.](https://tio.run/##FY/NSgJRHMX3PUYxRbsMTCloU7SoVRAE7pKCXFS0iLbXSSezQJoWUmSp6JQIZaM2d5QZ4X9mDFxcfIb7ItMVzuK3OJyPlfhROnYSRZLVMdJgUg95fIieZM94RZMc5M4ks8ij/rgveuDx5b8KfclCUQmK4G8FTOoGaqhcwCc7rGWoAUPDO4bU0MhCSd5VBQ9YnHyp30zMkO9vhtVz6ggnST/JY@JrS@uqBC3Vmp6BI1kNv9Si9qKi0ys8kqWJIbIpFHfxIPU8BrLwRh0aoiv1nHCpjadDNb48NlGGe5mBvbodC7LXgqMLA/dkq/C5A@EuTLmaTjY8yV72JuYOLNFK0QAjlOY3hJOZmLDApzY4vkNfmfBJneCWvNlpVk9M7ShK/AM) `è` indexes each digit in the string `"\n-/\_|"`, and `J` then joins the entire list together, which gives us the following: ``` __ __ __ __ ___ /\ /\ | |\ | | / | | /\ | | / \/ \ | | \ | |-- | |--\ /__\ |-- | / \ | | \| |__ \__ | \ / \ | | __ __ \ / | | /| | / | / \ __ / | | \ /\ / | | / | |-- | |--/ \ / |-- | \/ \/ | |/ | |__ \__ |__| \/ |__ _|_ ``` [Try it online.](https://tio.run/##FY9BSwJRFIX3/YowpmgRZWBKQZuiha2CIJAgkoJcVLSINi2ek5pZIE0LKbJUbFKEslHzqTjCPTMGLh7@hvdHpiecxQf3cM85S4HDqP/Y83xT0wuL@wfXPslKGGgwqIkkPkVTsme84oPaSJxKZlKfWsOWaIIH5v/y9CXTGSUogr3hMKmnUET@HDZZbjFGZaQ0vKNHZY1MZOVdQXCHBciW@s3IcPnOuls4o7poh@gndER8ZW5VhaCqUqMTaEtWxC9VqTar6OQSj2Rqood4BJkwHqSeRFem36hOPTSknhAdquFpT5XPDQ3k0LmIwVre9DvxK8HRQAr3ZKnnU7uiMzPmqjpZ6Ev2sj0ytmCKaoS6GCDrWxPt2MiACT62wPHt2sqECtWdW@pPRrNSUF0qYc8L/gM) `2ä` splits the string into two parts. `Iè` take the input, and indexes it (with automatic wrap-around) to get one of the two parts, which is then being output implicitly. Huge thanks to [*@MagicOctopusUrn*'s ASCII compressor](https://codegolf.stackexchange.com/a/120966/52210) which was used to generate the compressed number and Base-7 transliteral. [Try it online.](https://tio.run/##fVE7DsIwDN17iih7ZH69QMWEmJgjWSAhDsCaoVcpC4KhIwsSQyou0ouEOIlDUSui5jnNe4n9nFm5P8yPzhn7XHd3e3u/tru@bmx76h6LsqxkX1/kOaDfkxXxcrnqrrYl9EQjN86J6YGYMS5/GEQshAAdpxDGfzqGoAHejH@sISyI1DRZokNQKkuUCgcAUYvE@HPABeREmkKoThOayMFXk7P@9Tc5Cs0r4HQwshes0CUwsJeaAmwPxva4RBjYS03JnUtpB/YQ4wVJE97B4Ac) (After which the transliterate has been golfed by reversing the string and number on the stack, using `в` instead of `B` to make it a list of digits, and index into the string with `è`. [Answer] # C, 251 bytes ``` k(w){char*f="_-/\\|]^^^\0<&*&)&3&(&&WX&J&*&\0t_&/&3&\0`);35)I5M\0a).@7).8-;./.-\0j()(0(1+4()(*+4+4()(04+",*o=f+4,m[229]="",i=7,c=10,p;for(memset(m,32,228);i;c=*f++^(w%2&i--/2==2)*115)for(p=0;*++o;m[(w%2?4-i/6-p/57:p/57)*57+p%57]=c)p+=*o-37;printf(m);} ``` This is a function `k` that receives a parameter and prints the message to `stdout`. A more readable version: ``` k(w) { char*f="\n_-/\\|", // characters to fill in *o= " "// for each character, the list of positions to put it in, difference-encoded "]%%^^^\0" // for '\n' (newline) "<&*&)&3&(&&WX&J&*&\0" // for '_' (underscore) "t_&/&3&\0" // for '-' (minus) "`);35)I5M\0" // for '/' or '\' (slashes) "a).@7).8-;./.-\0" // for '\' or '/' (slashes) "j()(0(1+4()(*+4+4()(04+", // for '|' (vertical bar) m[229]="", // message to generate i, // index of character, running 7...1 c, // current character to fill in p, // where to place the character y; // y-coordinate of the character memset(m,32,228); // fill the message with spaces for(i=7;--i;) { c=*f++; c^=~w%2|i/2^1?0:115; // flip the direction of slashes, if needed for(p=0;*++o;) { p+=*o-37; // jump to next position y=p/57; // extract the y-coordinate y=w%2?4-i/5-y:y; // flip the y-coordinate, if needed m[y*57+p%57]=c; // place the character } } printf(m); // print the message } ``` First, it prepares an empty message (filled with spaces). For each character (e.g. `|` or `-`), it has a list of positions to place that character in. For each position, if the upside-down version should be printed, the position is flipped. That is, its vertical coordinate `y` is replaced by `4-y` or `3-y` (depending on whether the character is an underscore). Also, the directions of the slashes are flipped - this is performed by a `XOR` with `115`. This control structure is also used to place the newline characters - it seems more efficient to add 4 more coordinates to the list than to write an explicit loop. --- There are a few minor glitches with this system. First of all, the final letter T looks a bit different in the flipped version: ``` ___ | | | | | _|_ ``` To output it correctly, the code has to place the `|` characters after the `_` characters. In addition, in order to make sure the control string contains only ASCII characters, I encoded it: * It records the differences between the positions instead of the positions themselves - this reduces the range * The numbers in the string have `37` added to them, to shift them into the ASCII Range 32...127. I could add a smaller number, but `37` avoids characters like `"` and `\`, which have to be escaped inside string literals. * Two of the numbers were greater than 127 - for example, the first `-` character appears at position 137. To account for this, I added an artificial `-` character at another position (79), which is later overwritten - the character `|` also appears at position 79. --- Another funny thing was that I couldn't use `puts` to output the string - this would produce an extra trailing newline. So I used `printf` instead. Also, the number `57` appears 4 times in the golfed code - the seemingly long-winded expression `(w%2?4-i/6-p/57:p/57)*57+p%57` makes it possible to eliminate the variable `y`, making the code shorter. [Answer] # Perl, ~~292~~ ~~259~~ 246 bytes ``` $_="Svv __SS__S nnSv nnSnnn i kjSkj hw|j h|wS /SwrhSi pq hwS | mSlmSlS |S| l |S|--wS |--lSSmnnlS |--S | k ihSih jw|h j|S|__S g__S|oosjSk ih jS|ooSo|o";s/v/SSSSS/g;s/w/S|S/g;s/S/ /g;<>&1?y"g-s"\\/\\ /\\ ___ |":y"g-s"\\ \\/\\/_ /\\| ";print $_ ``` It takes advantage of the fact that the two strings are mostly similar (e.g. the entire I E and C) and makes the string out of characters that are displayed differently depending on which version is being displayed. e.g m means "a forward slash for the right-way-up string, a backward slash in the upside down one". It does a transliteration substitution to display the correct character. Spaces are also run-length encoded using string substitutions. multi-line: ``` $_="Svv __SS__S nnSv nnSnnn i kjSkj hS|S|j h|S|SS /SS|SrhSi pq hS|SS | mSlmSlS |S| l |S|--S|SS |--lSSmnnlS |--S | k ihSih jS|S|h j|S|__S g__S|oosjSk ih jS|ooSo|o"; s/v/SSSSS/g; s/w/S|S/g; s/S/ /g; <>&1? y"g-s"\\/\\ /\\ ___ |" : y"g-s"\\ \\/\\/_ /\\| "; print $_ ``` Idea: Since there are only 22 unique columns in the output, it should be possible to store it as 22\*4 = 88 characters with a range of 0-17 (all the possible "dual-meaning" characters), along with a 56 character lookup table with one entry in the range of 0-21 per column. In theory this could be encoded with < 100 bytes however it's hard to make this a net win because of the more complicated code to decode it. [Answer] # CJAM, 206 The two ascii pictures are base-216 encoded, one byte = 3 characters. ``` " _\/|-":A;S7*"!D!D"+:B;qi2%{B"h °°¤8 2 °2,J° °"",4# °³8=Ô° Ó\"# Ó °""\"z °Â89D-D·° z ·!¶"}{B"' '!J"+"#h °¼88 2 °° ° °""2/\" °²8=Ô° Óh#L Ó °"" h°°9D-D°,2 h° °"}?]{{i32-__36/A=@6/6%A=@6%A=}/N}/ ``` Test it [here](http://cjam.aditsu.net/#code=%22%20_%5C%2F%7C-%22%3AA%3BS7*%22!D!D%22%2B%3AB%3Bqi2%25%7BB%22h%20%20%C2%8C%C2%B0%C2%B0%C2%A48%202%20%C2%B02%2CJ%C2%8C%C2%B0%20%C2%B0%22%22%2C4%23%20%C2%B0%C2%B38%3D%C3%94%C2%B0%20%C3%93%C2%8C%5C%22%23%20%C3%93%20%C2%B0%22%22%5C%22%C2%8Cz%20%C2%B0%C3%8289D-D%C2%B7%C2%B0%20z%20%C2%B7!%C2%B6%22%7D%7BB%22'%20%20%20%20'!J%22%2B%22%23h%C2%98%20%C2%B0%C2%BC88%202%20%C2%B0%C2%B0%20%C2%98%20%C2%B0%20%C2%B0%22%222%2F%5C%22%20%C2%B0%C2%B28%3D%C3%94%C2%B0%20%C3%93h%23L%20%C3%93%20%C2%B0%22%22%C2%8C%20%20h%C2%B0%C2%B0%C2%809D-D%C2%B0%2C2%20h%C2%B0%20%C2%B0%22%7D%3F%5D%7B%7Bi32-__36%2FA%3D%406%2F6%25A%3D%406%25A%3D%7D%2FN%7D%2F&input=2) [Answer] # Powershell, ~~275~~ ~~253~~ 248 bytes ``` param($n)$d='8 \83484/7/484302 92984308 92918--118--128||6//0\16116129558| \/ |8 /02083\6/10018/6\302 955776_71 9_7_' '8\,__,777,/6 /,\6/6\,_8 -- _,88,888, ,||||||'-split','|%{$d=$d-replace+$i++,$_} 0..3|%{$l=$_;-join$d[(0..55|%{$_*8+$l*2+$n%2})]} ``` Test script: ``` $f = { param($n)$d='8 \83484/7/484302 92984308 92918--118--128||6//0\16116129558| \/ |8 /02083\6/10018/6\302 955776_71 9_7_' '8\,__,777,/6 /,\6/6\,_8 -- _,88,888, ,||||||'-split','|%{$d=$d-replace+$i++,$_} 0..3|%{$l=$_;-join$d[(0..55|%{$_*8+$l*2+$n%2})]} } &$f 2 &$f 1 ``` Output: ``` __ __ __ __ ___ /\ /\ | |\ | | / | | /\ | | / \/ \ | | \ | |-- | |--\ /__\ |-- | / \ | | \| |__ \__ | \ / \ | | __ __ \ / | | /| | / | / \ __ / | | \ /\ / | | / | |-- | |--/ \ / |-- | \/ \/ | |/ | |__ \__ |__| \/ |__ _|_ ``` ## Main ideas The compression method is extended method of [CJam](https://codegolf.stackexchange.com/a/53973/80745) by Dennis♦: 1. Create a string before compression: * chars of the first column of both ASCII arts, then * chars of the second column, then * chars of the third column and so on... 2. Compress using 10 consecutive replacements (10 because Powershell can use numbers 0..9 as strings, this makes the decompress algorithm shorter. Replacements found by brute force.) The script for compression: ``` $src = " __ __ __ __ ___", # line1, art1 " __ __ ", # line1, art2 " /\ /\ | |\ | | / | | /\ | | ", # line2, art1 "\ / | | /| | / | / \ __ / | | ", # line2, art2 " / \/ \ | | \ | |-- | |--\ /__\ |-- | ", # line3, art1 " \ /\ / | | / | |-- | |--/ \ / |-- | ", # line3, art2 "/ \ | | \| |__ \__ | \ / \ | | ", # line4, art1 " \/ \/ | |/ | |__ \__ |__| \/ |__ _|_" # line4, art2 $z=-join(0..$src[0].Length|%{ $p=$_ $src|%{$_[$p]} }) $z ``` The before compression string is: ``` \ / /\ / \ \ / \/ /\ / \ \ / \/ / \ |||||| |||||| \ / \/ / \ |||||| ||||||__ --____ --__ || // \\__ ____ __ ||||||_ -- __ -- _ | \/ | / \ \ / /\ /__ \ \__ / \/ / \ ||||||_ -- __ -- _ _ __ ||||||_ _ ``` [Answer] ## SAS, 442 bytes ``` %macro a(b);&b=tranwrd(&b,put(i,1.),repeat('A0'x,i));%mend;%macro b(z);length a b c d$99;if mod(&z,2)then do;a='992__3__';b='\7/1|1|1/|1|4/3|2/1\0__0/1|4|';c='0\1/\1/2|1|0/0|1|--1|4|--/3\1/2|--2|';d='1\/1\/3|1|/1|1|__2\__1|__|4\/3|__1_|_';end;else do;a='992__3__2__65__1___';b='1/\1/\3|1|\1|1|4/3|1|4/\3|4|';c='0/1\/1\2|1|0\0|1|--1|4|--\3/__\2|--2|';d='/7\1|1|1\|1|__2\__1|2\1/3\1|4|';end;do i=0to 9;%a(a)%a(b)%a(c)%a(d)end;put a/b/c/d;%mend;` ``` Non-golfed: ``` %macro a(b); &b=tranwrd(&b,put(i,1.),repeat('A0'x,i)); %mend; %macro b(z); length a b c d$99; if mod(&z,2)then do; a='992__3__'; b='\7/1|1|1/|1|4/3|2/1\0__0/1|4|'; c='0\1/\1/2|1|0/0|1|--1|4|--/3\1/2|--2|'; d='1\/1\/3|1|/1|1|__2\__1|__|4\/3|__1_|_'; end; else do; a='992__3__2__65__1___'; b='1/\1/\3|1|\1|1|4/3|1|4/\3|4|'; c='0/1\/1\2|1|0\0|1|--1|4|--\3/__\2|--2|'; d='/7\1|1|1\|1|__2\__1|2\1/3\1|4|'; end; do i=0to 9; %a(a) %a(b) %a(c) %a(d) end; put a/b/c/d; %mend; ``` Tests: ``` data a; %b(1) %b(2) %b(0) %b(35) run;                        __    __ \        /  |  |  /|  |     /    |   /  \ __ /  |     |  \  /\  /   |  | / |  |--  |     |--/    \  /   |--   |   \/  \/    |  |/  |  |__   \__  |__|     \/    |__  _|_                        __    __   __             __  ___   /\  /\    |  |\  |  |     /    |  |     /\    |     |  /  \/  \   |  | \ |  |--  |     |--\    /__\   |--   | /        \  |  |  \|  |__   \__  |   \  /    \  |     |                        __    __   __             __  ___   /\  /\    |  |\  |  |     /    |  |     /\    |     |  /  \/  \   |  | \ |  |--  |     |--\    /__\   |--   | /        \  |  |  \|  |__   \__  |   \  /    \  |     |                        __    __ \        /  |  |  /|  |     /    |   /  \ __ /  |     |  \  /\  /   |  | / |  |--  |     |--/    \  /   |--   |   \/  \/    |  |/  |  |__   \__  |__|     \/    |__  _|_ ``` Could possibly save a bit of code by putting them in input blocks, but that adds the restriction that the macro can only be once per datastep which I feel violates the spirit of writing it as a macro. (And I suspect adding a prompt to get input in the datastep adds more characters). [Answer] # bash, 247 bytes ``` (($1%2)) && c=tail || c=head base64 -d <<<H4sIAF/3uFUCA31Q2w3AIAj8ZwoWMLcQyS3i8JWXtWlTI6BwPA7Vz0Nunc9HhKSowlJU57qWJjBoZ/4a41o8aC4NsTBjbMgYkQDStCIrDz3AbmRuYjpzPTOGG5P9/gmKtQddFy8eMbOn4Khb7NE88ObRs+DgUez3iqrtwYPMAoWJhU/KBeJFPOCqAQAA | zcat | $c -n4 ``` Strings are concatenated and gziped. [Answer] # PHP, 225 bytes Ugly, brute-force solution. ``` echo str_split(gzinflate(base64_decode('dZDdDcAgCITfnYIFzC1Ecos4fOW3Nm2NgsohfIp8DrJtbB8RkkMEGktk7anhXIO6jFNpzA4Lqq2SqLs5WzKnJ4BUycjOQzXQhdScd6dmV8Rwa7rqP9/QukE9ixeGt2wpODASHoWBN0a1ggMj4fuHsuyBQcYDqfH/XrwA')),224)[$argv[1]%2]; ``` I compressed then base64 encoded the concatenated strings to be displayed. The code decodes, decompresses and splits it in pieces of 224 characters. The first string is 224 characters without a trailing newline, the second is 201 characters (also no newline after it). The parity of the command line argument (`$argv[1]%2`) is used as index in the array generated by `str_split()`. [Answer] # Haskell, 138 bytes ``` m x=do h<-readFile"a" return$take 225.drop(225*mod x 2)<$>find((==h).hash.pack)(replicateM 425"/\\|_- ") ``` This is a bit of a hack. I am bruteforcing the SHA256 hash of the concatination of the two minecraft texts, and then splitting them apart and choosing the appropriate text based on parameter x. This is of cource very impractical and cannot be computed in real time, and there may even be collisions along the way for all I know. Because Haskell cannot have the ASCII representation of that hash in a string, I am reading it from a file called "a", and has therefor added 32 bytes to my score. * readFile and pack is from Data.ByteString.Char8 * hash is from Crypto.Hash.SHA256 ## Explaination: ``` replicateM 425"/\\|_- " ``` Creates a list of every combination of the letters "/\|\_- " on 425 letters (the length of both minecraft texts combined) ``` find((==h).hash.pack) ``` Pick the first one that matches the hash ``` take 225.drop(225*mod x 2) ``` The first text is 225 letters long, the other one is exactly 200. [Answer] # Javascript (ES6), ~~403~~ 296 bytes (Moved from my [previous answer](https://codegolf.stackexchange.com/a/53943/42545)) Trying out a new method: ``` n=>`55555559Å9Å${n%2?`55555558556776}}5Y75Y¥Æ75786¡YAA[7ćA5Fï5¡YFéA8Y§5}\x83AEÅKÅ\x99}5§5\x999\x95`:`Q5555Q9Ý>6¡77¡}}5Y7756¡75768Y¡AA£7ćA5Fû5u¡FéAY55¡}}­EÅKÅ}G;5¡}5}`}`.replace(r=/./g,x=>(163+x.charCodeAt()).toString(6).slice(1)).replace(r,x=>' /|\\_-'[x]).match(/.{56}/g).join` ` ``` Note that there is a few unprintable character; these have been replaced with e.g. `\x83`. The encoding itself is about 40 bytes shorter than the other, but the decoding process is more elaborate. I used the base-216 system that others have used to encode the text. For reference, here's the code I used: ``` // normal MINECRAFT a='00000000000000000000000440000440004400000000000004400444'+ '00130013000020023002002000001000020020000013000020000020'+ '01003100300020020302002550020000025530000144300025500020'+ '100000000300200200320024400034400200030010000300200000200'; // upside-down MINECRAFT // un-comment this one to run it /* a='00000000000000000000000440000440000000000000000000000000'+ '30000000010020020012002000001000020001003044010020000020'+ '03001300100020020102002550020000025510000300100025500020'+ '003100310000200210020024400034400244200000310000244004240'; */ console.log(a.replace(/.../g,x=>String.fromCharCode(parseInt(b[i],6)+53))); ``` This basically takes the ASCII text (pre-converted to base 6) and triples it up on itself, changing it to base 216. 53 is then added to remove most non-printable characters. Suggestions welcome! --- Here's the original 403-byte code: ``` a=n=>{y=[' ','/','|','\\','_','-'],x=`55555559Å9Å${n%2?`55555555¡55Y}}eA5;5};GÝY}5}¡k;77;} 757Ĉ5G;7ć75§H5AB77Ý8ÝEÑ5H5EÅÕ`:`Q5555Q9Ý6¡k5}\u008FAA5;5}}5k5}5}Y§G77G} 757Ċ5?×7ć7;55GAAI7Ý8ÝA865GA5A`}`;b=x.split('').map(x=>x.charCodeAt(0)-53);for(c=[],i=b.length;i--;){c[i]=b[i].toString(6);while(c[i].length<3)c[i]='0'+c[i]}d=c.join('').replace(/\d/g,x=>y[x]).split('');d[56]=d[112]=d[168]=` `;return d.join('')}; ``` Using a `for` loop, a `while` loop, four variables that were only used once, and a ton of long algorithms for simple things. Boy, have I improved... [Answer] # Python, 312 bytes ``` def y(b): x=int(['4vwhclv10tuk4z18gf73aimn6zvwkrhxekphfn1lxocj9ezchd1cd1cv97p3f6k12s8hcjznnm5iq3om4vgxvugp3makgu4n3f6qxvdrtl4c0lva12hwt','8uzwdylhtrf6oqnwnck8pfxu25m5844tuo2700v3zoeuvossx1b47rnwyrmqodau3feu3spi9jydhyxvntv48vojx9iq9af78wufzn1'][b%2],36);x<<=69;s="";t=" /\\-|_\n" while x:s+=t[x&7];x>>=3 print s ``` Function prints output given an int [Answer] # C, 321 bytes Encoded the repetition and the character index into a string. ``` main(n,v,p,c)char**v,*p,*c;{c=" _/\\|-\n";for(p=atoi(v[1])%2?"8@8iXivs8rhththrthtPrXt`rhspiprhtPtvpshrshr`thtprpthtmhtPtmrXshr`tm`tvhsrhsrXthtrhthti`sihtitPsrXtihqtq":"8@8iXi`i8PihavhrshrsXthtshthtPrXthtPrsXtPtvprhsrhs`thtpspthtmhtPtmsXris`tm`tvr8shththsthti`siht`shrXshtPtw";*p;p++)for(n=*p/8^15;n--;)putchar(c[*p&7]);} ``` [Answer] # Python 3, 486 ~~533~~ ~~612~~ ``` r=str.replace;m,p=r(r(r('''YYYYY __YA AYY A___ /\ /\YX\ X Y/YX Y/\Y| Y| / \/ \ X \ X-- | Y|--\Y/__\ |-- | /YY\ X \XA \A| \ /Y\ | Y| ''','X','| |'),'Y',' '),'A','__ '),print; if int(input())%2==0:p(m) else: q,i,u=m.split('\n')[::-1],0,[[23,24,29,30],[42,43],[],[23,24,29,30,34,35,53,49,50,55]];q.insert(0,q.pop()) while i<len(q): x=list(r(q[i],'_',' '))+[' '] for a in u[i]:x[a]='_' p(r(r(r(r(''.join(x),'___',''),"\\",'t'),'/',"\\"),'t','/')) i+=1 ``` [Answer] # [PHP](https://php.net/), 263 bytes ``` <?=strtr('3333 20220'.['2 0332 020_ 2/\2/\211\113/2113/\212 1 /2\/2\ 11 \ |1412 14\22/0\ 14 1 /32 \112\|102 \012 \2/22\12 1', ' \32 /112/|13/212 /2\ 0 /12 1 \2/\2/ 11 / |1412 14/22\2/ 14 1 2\/2\/211/1102 \010|3\/2102_|_'][$argn&1],[__," |"," "," ","--"]); ``` [Try it online!](https://tio.run/##PY/LCsIwEEX3@YohiFFonUe68/UhTQkiYldaqsv8tus6E8Ew3CSXO2eSaZyWw3kaJ7e6zPfH0Xd@784n9Y6v9/yeNyHqAiERCrs@CFCMKkLZCSYr5sQcUUz0JsAOUJIWMEOCwp2ZXRJBUq/TACpDuyQVJj2RBpQlkiwZGhdc0gRqAktliyGB1Kr8OhiNj3@@tZtn/DrenqSI3wAq0QySXHIY@vrbNQ9Nn3PjAYo3rQJ1b1s/bPfL8nk82@vlOt6@ "PHP – Try It Online") [Answer] # Ruby, 290 bytes ``` $><<(gets.to_i%2<1?"xCeCdCnCcC_ c/Bc/Be|ABAAf/e|Af/Be|f| b/cB/cBd|AbBb|A--Af|--Be/CBd|--d| /iBAAcB|ACdBCAdBc/eBAf|":"xCeC Bi/AAc/|Af/e|d/cBbCb/Af| bBc/Bc/d|Ab/b|A--Af|--/eBc/d|--d| cB/cB/e|A/AACdBCAC|fB/e|Cc_|_").gsub(?C,'__').tr(?B,?\\).gsub(?A,'c|').gsub(/[a-z]/){|e|' '*(e.ord-97)} ``` Probably a weak and improvable entry. Basically a very simple (handcrafted) compression where lowercase letters mean that many spaces (actually ord(ch) - 'A' spaces) and uppercase letters are just some common terms that saved a few bytes. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~72~~ 71 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ═j;ΗD^⌡⁾yō⁶⅜┐≡¼τ~≡š┘,┼◄‚4øDqψ∫‛²′Ζdκ↓±ģ░○∙ΘΝ◄ōΞ06║⁶╗i-η}┌^JY³‘''n.2%?№↕ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTUwaiUzQiV1MDM5N0QlNUUldTIzMjEldTIwN0V5JXUwMTREJXUyMDc2JXUyMTVDJXUyNTEwJXUyMjYxJUJDJXUwM0M0JTdFJXUyMjYxJXUwMTYxJXUyNTE4JTJDJXUyNTNDJXUyNUM0JXUyMDFBNCVGOERxJXUwM0M4JXUyMjJCJXUyMDFCJUIyJXUyMDMyJXUwMzk2ZCV1MDNCQSV1MjE5MyVCMSV1MDEyMyV1MjU5MSV1MjVDQiV1MjIxOSV1MDM5OCV1MDM5RCV1MjVDNCV1MDE0RCV1MDM5RTA2JXUyNTUxJXUyMDc2JXUyNTU3aS0ldTAzQjclN0QldTI1MEMlNUVKWSVCMyV1MjAxOCUyNyUyN24uMiUyNSUzRiV1MjExNiV1MjE5NQ__,inputs=MQ__,v=0.12) SOGLs vertical mirroring worked perfectly for this. [Answer] # [Canvas](https://github.com/dzaima/Canvas), 70 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` C<aT[≤^5t‽◂6Zr!v↓[u0F∙OF-╫#t┬a*7ZfK1!&)y@½(+M⇵PV-¼G:Uju╋╷(╫:N‟‾)n⁸2%?↕ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjIzJXVGRjFDYVQldUZGM0IldTIyNjQldUZGM0UldUZGMTUldUZGNTQldTIwM0QldTI1QzI2JXVGRjNBJXVGRjUyJTIxJXVGRjU2JXUyMTkzJXVGRjNCJXVGRjU1MEYldTIyMTkldUZGMkYldUZGMjYldUZGMEQldTI1NkIldUZGMDMldUZGNTQldTI1MkMldUZGNDEqJXVGRjE3JXVGRjNBZksxJTIxJTI2JTI5eSV1RkYyMCVCRCV1RkYwOCV1RkYwQk0ldTIxRjUldUZGMzBWLSVCQ0clM0EldUZGMzVqdSV1MjU0QiV1MjU3NyUyOCV1MjU2QiUzQU4ldTIwMUYldTIwM0UlMjkldUZGNEUldTIwNzgldUZGMTIldUZGMDUldUZGMUYldTIxOTU_,i=Mg__,v=8) ]
[Question] [ A [zip bomb](https://en.wikipedia.org/wiki/Zip_bomb) is a compressed file, designed so that unpacking it yields the biggest file possible. These are fairly well known, and there are examples of 42 KB files which expand into multiple petabytes of data. In this challenge, the goal is reversed. Instead of providing a compressed file which is then unpacked, the goal is to provide an uncompressed file which is compressed in an unreasonably inefficient manner, ideally becoming larger than the original. **Rules:** You should provide a file between **10 KB** and **1 GB**, which will be compressed by your chosen algorithm. You should also specify a compression algorithm, such as gzip or PNG. If the algorithm allows things like a compression level to be set, different configurations count as different algorithms. The algorithm can be lossless or lossy, and can be application specific (like PNG or MP3). Submissions are scored based on the ratio of \$\frac{\text{compressed}}{\text{original}}\$. For example, an 80 KB file that "compresses" to 88 KB would get a score of \$1.1\$. The highest scoring solution, **per algorithm**, wins. [Answer] # [FFmpeg](https://ffmpeg.org/) `-crf 0 -preset ultrafast -tune film -vf format=yuv444p`, score 198.7425 Input is a 65535 × 1 [PBM](https://en.wikipedia.org/wiki/Netpbm) file: ``` P4 65535 1 IEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEI ``` This image consists of repetitions of the following 16-pixel pattern: [![enter image description here](https://i.stack.imgur.com/niELF.png)](https://i.stack.imgur.com/niELF.png) The input file is exactly 10,000 bytes: the first 8203 bytes encode the image (one bit per pixel plus the 11 byte header); the last 1797 bytes are padding. The input is 'compressed' into a single-frame lossless H.264 video using FFmpeg, yielding a 1,987,425 byte MP4 file as output. The following Ruby script generates both files: ``` #!/usr/bin/env ruby raw = 'raw.pbm' cmp = 'compressed.mp4' File.write(raw, 'P4 65535 1 ' + 'IE'*4994 + 'I') system("ffmpeg -i #{raw} -crf 0 -preset ultrafast -tune film -vf format=yuv444p -frames 1 #{cmp}") puts File.size(raw) puts File.size(cmp) ``` The compression/quality options passed to FFmpeg are: * `-crf 0` (constant rate factor 0). From the [docs](https://trac.ffmpeg.org/wiki/Encode/H.264): 'You can use `-crf 0` to create a lossless video . . . Note that lossless output files will likely be huge'. * `-preset ultrafast` 'A slower preset will provide better compression', so I chose the fastest one. (The next fastest option, `superfast`, reduces the file size more than fivefold.) * `-tune film` Adding this option ('use for high quality movie content; lowers deblocking') increased the file size by 2 bytes. * `-vf format=yuv444p` Adding this option (no chroma subsampling) increased the file size by 1 byte. For comparison, with the default compression/quality settings (`ffmpeg -i raw.pbm -frames 1 compressed.mp4`) the compression ratio is 4.44558. With maximum compression and lowest quality (`ffmpeg -i raw.pbm -crf 51 -preset veryslow -frames 1 compressed.mp4`) the compression ratio is 1.4147. ### Pattern selection Images encoded only by repetitions of one of `I`, `E`, `)`, `%`, `0x15`, or `Q` result in MP4 files that are at least 9.5 % larger than for any other byte. These six patterns all have a white:black pixel ratio of 5:3 with no two black pixels adjacent to each other. I tested all repeated permutations of these six bytes up to size six, finding that the pattern encoded by repetitions of `IE` yielded the largest file size. One might guess that a random image would result in a larger MP4 file than a regular pattern. I have found no such image. Across 10,000 trials with images encoded by random combinations of the six bytes identified above, the maximum file size was 1,961,715 bytes (average 1,961,005). Across 10,000 trials with completely random images, the maximum file size was only 1,514,853 bytes (average 1,499,010). --- In an older version of this answer I used `-filter:v fps=10000000` instead of `-frames 1`, resulting in a much higher compression ratio, without realising that the output contained thousands of frames (thanks to @MT0 for the comment). This seemed like an unfair advantage, as more frames containing the same image could be added to increase the file size at will. [Answer] # JPEG (4:4:4 Chroma subsampling), ~1584.35 Asking Redwolf about what the input file type for a PNG is, we hear that it's > > Any file you can get an implementation of a PNG converting program to accept. > > > I realized that this means we're essentially looking for a file which compresses really well in one format but really horribly in another. I initially looked for something PNG couldn't compress well but JPEG could, but I soon realized it was easier to go the other way around. To construct my image, I started with this 8x8 pattern: [![enter image description here](https://i.stack.imgur.com/HLRej.png)](https://i.stack.imgur.com/HLRej.png) Here, horizontal rows are either full green or no green, and vertical rows are either full red or no red. PNG's two compression steps are both *perfect* for this kind of pattern. The filter uses color data from the left and top pixels, while the interlacing groups into even-dimensioned checkerboard patterns. Better yet, this means that PNG will repeat this sequence for a while with relatively small changes to file size compared to image size. My final PNG is 3840x3840: [![enter image description here](https://i.stack.imgur.com/qmDMN.png)](https://i.stack.imgur.com/qmDMN.png) This takes up 11,198 bytes and has a CRC-32 of 4979FF24. I converted this to a JPEG in Paint.net, with 100% quality to make sure the exact same image came out and 4:4:4 chroma subsampling so it couldn't cheat a little with the colors, and received a 17,741,541 byte file with a CRC-32 of B6B4AC7D. The overall ratio between these two files is about 1584.35. [Answer] # [BSD Compress](https://www.freebsd.org/cgi/man.cgi?query=compress&sektion=1&format=html), 1.4746 Unlike `gzip`, [compress](https://en.wikipedia.org/wiki/Compress) doesn't check whether it would be cheaper to store an uncompressed block, so its worst case performance is much worse than `gzip`'s. If you give it a file of completely random bytes, without any patterns or redundancies to take advantage of, `compress` fails miserably. ``` python3 -c 'from numpy import random; random.seed(29597); f=open("raw_file","wb"); f.write(random.bytes(1024*10))' && cat raw_file | compress > compressed_file && wc -c *_file ``` This doesn't work on Try It Online, since the TIO shell doesn't have `compress` installed, but my Macbook has it installed by default. When I run this, I get the following file sizes: ``` 15100 compressed_file 10240 raw_file ``` For a ratio of 1.474609375 [Answer] # [BSD Compress](https://www.freebsd.org/cgi/man.cgi?query=compress&sektion=1&format=html), 1.5721 The following Python script constructs a file which compresses worse than a random file. It continually extends the current file by a random byte, samples 20 different random choices and continues with the file which compresses the worst. Running the script took 1.5 hours on my machine, because it tries the compression on more than 200 000 different files. I used the implementation [ncompress 5.0](https://github.com/vapier/ncompress/tree/v5.0) on Windows. ``` import random as rnd import subprocess as sp import numpy as np FILE_LEN = 10 * 1024 # 10 KiB BYTE_RANGE = 256 SAMPLES = 20 rnd.seed(0) with open("file.txt", 'wb+') as f: for pos in range(FILE_LEN): arr = np.zeros(BYTE_RANGE, dtype=np.int_) random_bytes = rnd.sample(range(BYTE_RANGE), SAMPLES) for b in random_bytes: f.seek(pos) f.write(bytes([b])) f.flush() result = sp.run(["compress.exe", "-fc", "file.txt"], capture_output=True) arr[b] = len(result.stdout) b_opt = np.argmax(arr) f.seek(pos) f.write(bytes([b_opt])) ``` Here are the stats: `raw - 10240 Bytes` `compressed - 16099 Bytes` [Answer] # gzip (RFC 1952), 10kb/9.976kb ≈ 1.0024057739 RFC 1952 represents the length of the name of the original file as a null-terminated string. Therefore, we can just use the following gzip of a 0-byte file with an arbitrarily long name: ``` 1F 8B 08 08 A7 53 62 60 04 FF 41 41 41 41 41 41 41 41 41 41... ...41 41 41 41 41 41 00 01 00 00 FF FF 00 00 00 00 00 00 00 00 ``` with enough As (0x41) to pad out our file to 10kb. Note that some header flags and settings can be modified as you please. I'm not certain if any programs handle this correctly. After a certain length, longer than the Windows file name limit but shorter than this, 7zip declares the archive invalid, likely due to some kind of technical limitations. The Linux utility `gz` successfully returns a 0-byte file, but uses the name of the gzipped file rather than the specified name. I didn't bother to look more into it, since I'm confident that this is a valid gzip by the simple and straightforward wording of RFC 1952. [Answer] # PCX (run length encoding of images). Ratio of 12 or 1131 depending on whether using uncompressed (though stored more efficiently) or compressed via different algorithm (e.g. png) Using the PNG attached (because imgur supported it), I go from: 4860 bytes to 5500128 bytes for a ratio of 1131.7. Using a portable bitmap file (which imgur doesn't support), I lose color but now go from actually uncompressed 12059 bytes to 1500897 bytes for a ratio of about 12. (What I had hoped to do was get it to have worst case RLE (basically: it works by storing each pixel as a 1 byte symbol but does run length encoding, but if the pixel in question is >= 192, you have to store the run length of 1 so the parsing can determine what is a run length indicator (high 2 bits set to 1, lower 6 bits determine the run length from 0 to 63) and what is a pixel, so each pixel would require 2 bytes (and then there's the metadata)... didn't quite do that but will take this for now) [![PNG version of input 1000x1000 pixel image with thin vertical stripes](https://i.stack.imgur.com/xzEaE.png)](https://i.stack.imgur.com/xzEaE.png) [Answer] # 10196469/10240=995.74892578125 wav source <https://paste.ubuntu.com/p/DfRCHqWBXC/> . There's no absolute reason the data look like this. compress command: `ffmpeg -i a.wav b.mp3` ffmpeg create 8kbps mp3 even for 8bps wav ]
[Question] [ > > There's a [500 rep unofficial bounty](https://codegolf.meta.stackexchange.com/a/17479/20260) for beating the [current best answer](https://codegolf.stackexchange.com/a/41314/20260). > > > **Goal** Your goal is to multiply two numbers using only a very limited set of arithmetic operations and variable assignment. 1. Addition `x,y -> x+y` 2. Reciprocal `x -> 1/x` (*not* division `x,y -> x/y`) 3. Negation `x -> -x` (*not* subtraction `x,y -> x-y`, though you can do it as two operations `x + (-y)`) 4. The constant `1` (no other constants allowed, except as produced by operations from `1`) 5. Variable assignment `[variable] = [expression]` **Scoring:** The values start in variables `a` and `b`. Your goal is to save their product `a*b` into the variable `c` using as few operations as possible. Each operation and assignment `+, -, /, =` costs a point (equivalently, each use of (1), (2), (3), or (4)). Constants `1` are free. The fewest-point solution wins. Tiebreak is earliest post. **Allowance:** Your expression has to be arithmetically correct for "random" reals `a` and `b`. It can fail on a measure-zero subset of **R**2, i.e. a set that has no area if plotted in the `a`-`b` Cartesian plane. (This is likely to be needed due to reciprocals of expressions that might be `0` like `1/a`.) **Grammar:** This is an [atomic-code-golf](/questions/tagged/atomic-code-golf "show questions tagged 'atomic-code-golf'"). No other operations may be used. In particular, this means no functions, conditionals, loops, or non-numerical data types. Here's a grammar for the allowed operations (possibilities are separated by `|`). A program is a sequence of `<statement>`s, where a `<statement>` is given as following. ``` <statement>: <variable> = <expr> <variable>: a | b | c | [string of letters of your choice] <expr>: <arith_expr> | <variable> | <constant> <arith_expr>: <addition_expr> | <reciprocal_expr> | <negation_expr> <addition_expr>: <expr> + <expr> <reciprocal_expr>: 1/(<expr>) <negation_expr>: -<expr> <constant>: 1 ``` You don't actually have to post code in this exact grammar, as long as it's clear what you're doing and your operation count is right. For example, you can write `a-b` for `a+(-b)` and count it as two operations, or define macros for brevity. (There was a previous question [Multiply without Multiply](https://codegolf.stackexchange.com/questions/655/multiply-without-multiply), but it allowed a much looser set of operations.) [Answer] ## 22 operations ``` itx = 1/(1+a+b) #4 nx = -1/(itx+itx) #4 c = -( 1/(itx + itx + 1/(1+nx)) + 1/(1/(a+nx) + 1/(b+nx)) ) #14 ``` [Try it online!](https://tio.run/##LYuxCsAgDET3fkXAJUGKiHb0Y9SlLlaKg/16a5oeJNy949rTz6u6GYPbUjhm6QMCWINWR50IWMpvlem@8Or1OhKcmSIIBw3yv3UdRL83GDlKStIQKOtnu0vtmGm@ "Python 3 – Try It Online") The ops are 10 additions, 7 inverses, 2 negations, and 3 assignments. So, how did I get this? I started with the promising-looking template of the sum of two double-decker fractions, a motif that had appeared in many previous attempts. ``` c = 1/(1/x + 1/y) + 1/(1/z + 1/w) ``` When we restrict the sum to `x+y+z+w=0`, a beautiful cancellations occur, giving: ``` c = (x+z)*(y+z)/(x+y) ``` which contains a product. (It's often easier to get `t*u/v` rather than `t*u` because the first has degree 1.) There's a more symmetric way to think about this expression. With the restriction `x+y+z+w=0`, their values are specified by three parameters `p,q,r` of their pairwise sums. ``` p = x+y -p = z+w q = x+z -q = y+w r = x+w -r = y+z ``` and we have `c=-q*r/p`. The sum `p` is distinguished as being in the denominator by corresponding to the pairs `(x,y)` and `(z,w)` of variables that are in the same fraction. This is a nice expression for `c` in `p,q,r`, but the double-decker fraction is in `x,y,z,w` so we must express the former in terms of the latter: ``` x = ( p + q + r)/2 y = ( p - q - r)/2 z = (-p + q - r)/2 w = (-p - q + r)/2 ``` Now, we want to choose `p,q,r` so that `c=-q*r/p` equals `a*b`. One choice is: ``` p = -4 q = 2*a r = 2*b ``` Then, the doubled values for `q` and `r` are conveniently halved in: ``` x = -2 + a + b y = -2 - a - b z = 2 + a - b w = 2 - a + b ``` Saving `2` as a variable `t` and plugging these into the equation for `c` gives a 24-op solution. ``` #24 ops t = 1+1 #2 c = 1/(1/(-t+a+b) + 1/-(t+a+b)) + 1/(1/(-b+t+a) + 1/(-a+b+t)) #1, 10, 1, 10 ``` There's 12 additions, 6 inverses, 4 negations, and 2 assignments. A lot of ops are spent expressing `x,y,z,w` in terms of `1,a,b`. To save ops, instead express `x` in `p,q,r` (and thus `a,b,1`) and then write `y,z,w` in terms of `x`. ``` y = -x + p z = -x + q w = -x + r ``` Choosing ``` p = 1 q = a r = b ``` and expressing `c` with a negation as `c=-q*r/p`, we get ``` x = (1+a+b)/2 y = -x + 1 z = -x + a w = -x + b ``` Unfortunately, halving in `x` is costly. It needs to be done by inverting, adding the result to itself, and inverting again. We also negate to produce `nx` for `-x`, since that's what `y,z,w` use. This gives us the 23-op solution: ``` #23 ops itx = 1/(1+a+b) #4 nx = -1/(itx+itx) #4 c = -( 1/(1/(-nx) + 1/(1+nx)) + 1/(1/(a+nx) + 1/(b+nx)) ) #15 ``` `itx` is `1/(2*x)` and `nx` is `-x`. A final optimization of expressing `1/x` as `itx+itx` instead of the templated`1/(-nx)` cuts a character and brings the solution down to 22 ops. [Answer] # 23 operations ``` z = 1/(1/(1/(1/(a+1)+1/(b+1))-1+1/(a+b+1+1))-(1/a+1/b)) res = z+z ``` proof by explosion: ``` z = 1/(1/(1/(1/(a+1)+1/(b+1))-1+1/(a+b+1+1))-(1/a+1/b)) 1/(a+1)+1/(b+1) == (a+b+2) / (ab+a+b+1) 1/(1/(a+1)+1/(b+1)) == (ab+a+b+1) / (a+b+2) 1/(1/(a+1)+1/(b+1))-1 == (ab - 1) / (a+b+2) 1/(1/(a+1)+1/(b+1))-1+1/(a+b+1+1) == ab / (a+b+2) 1/(1/(1/(a+1)+1/(b+1))-1+1/(a+b+1+1)) == (a+b+2) / ab 1/a+1/b == (a+b) / ab 1/(1/(1/(a+1)+1/(b+1))-1+1/(a+b+1+1))-(1/a+1/b) == 2 / ab 1/(1/(1/(1/(a+1)+1/(b+1))-1+1/(a+b+1+1))-(1/a+1/b)) == ab / 2 z = ab / 2 and therefore z+z = ab ``` I abused wolfram alpha to get this beautiful image (wolfram alpha tried to get me to subscribe to pro to save it, but then ctrl-c ctrl-v ;-)): ![](https://i.stack.imgur.com/UnNlp.gif) score (with added `+` on subtraction): ``` z = ////++/++-+/++++-/+/ res = + ``` [Answer] # 29 operations Does not work for the set \$\{(a,b) \in \mathbb{R}^2 : a\pm b=0 \text{ or } a\pm b = -1\}\$. That's probably measure zero? ``` sum = a+b nb = -b diff = a+nb rfc = 1/(1/(1/sum + -1/(sum+1)) + -1/(1/diff + -1/(diff+1)) + nb + nb) # rfc = 1/4c c = 1/(rfc + rfc + rfc + rfc) # sum is 2: =+ # nb is 2: =- # diff is 2: =+ # rfc is 18: =///+-/++-//+-/+++ # c is 5: =/+++ # total = 29 operations ``` The structure of `rfc` (Reciprocal-Four-C) is more evident if we define a macro: ``` s(x) = 1/(1/x + -1/(x+1)) # //+-/+ (no = in count, macros don't exist) rfc = 1/(s(sum) + - s(diff) + nb + nb) # =/s+-s++ (6+2*s = 18) ``` Let's do the math: * `s(x)`, mathematically, is `1/(1/x - 1/(x+1))` which is after a bit of algebra is `x*(x+1)` or `x*x + x`. * When you sub everything into `rfc`, it's really `1/((a+b)*(a+b) + a + b - (a-b)*(a-b) - a + b + (-b) + (-b))` which is just `1/((a+b)^2 - (a-b)^2)`. * After difference of squares, or just plain expansion, you get that `rfc` is `1/(4*a*b)`. * Finally, `c` is the reciprocal of 4 times `rfc`, so `1/(4/(4*a*b))` becomes `a*b`. [Answer] # 27 operations ``` tmp = 1/(1/(1+(-1/(1/(1+(-a))+1/(1+b))))+1/(1/(1/b+(-1/a))+1/(a+(-b)))) res = tmp+tmp+(-1) # tmp is 23: =//+-//+-+/++///+-/+/+- # res is 4: =++- ``` There is no theory behind this. I just tried to get `(const1+a*b)/const2` and started with `(1/(1-a)+1/(1+b))` and `(-1/a+1/b)`. [Answer] # 25 operations ``` two = 1+1 c = 1/(1/(a+b) + -1/(a+b+two)) + 1/(-1/a + 1/(a+two)) + 1/(-1/b + 1/(b+two)) ``` Definitely not optimal, but probably optimal when restricted to only two levels of nested inversions (i.e. not using `1/(1/(1/...`). There *might* be ways to optimize this... Uses the property $$ \frac{1}{\frac{1}{x}-\frac{1}{x+2}} = \frac{x(x+2)}{2} = \frac{x^2}{2}+x $$ If we substitute \$x\$ with \$a+b, a, b\$ respectively: $$ \begin{align} \frac{1}{\frac{1}{a+b}-\frac{1}{a+b+2}} &= \frac{(a+b)^2}{2}+(a+b) = \frac{a^2}{2} + ab + \frac{b^2}{2} + a + b \tag1 \\ \frac{1}{\frac{1}{a}-\frac{1}{a+2}} &= \frac{a^2}{2}+a \tag2 \\ \frac{1}{\frac{1}{b}-\frac{1}{b+2}} &= \frac{b^2}{2}+b \tag3 \\ \end{align} $$ We can easily see that \$(1)-(2)-(3)\$ conveniently gives \$ab\$. [Proof by Wolfram|Alpha](https://www.wolframalpha.com/input/?i=simplify+c+%3D+1%2F%281%2F%28a%2Bb%29+%2B+-1%2F%28a%2Bb%2B2%29%29+%2B+1%2F%28-1%2Fa+%2B+1%2F%28a%2B2%29%29+%2B+1%2F%28-1%2Fb+%2B+1%2F%28b%2B2%29%29): ``` > simplify c = 1/(1/(a+b) + -1/(a+b+2)) + 1/(-1/a + 1/(a+2)) + 1/(-1/b + 1/(b+2)) c = ab ``` ]
[Question] [ This challenge is to lift the spirits of our mod [Alex A.](https://codegolf.stackexchange.com/users/20469/alex-a), who is usually [wrong](http://meta.codegolf.stackexchange.com/a/7202/26997). --- Suppose you have a friend named Alex who needs help with basic logic and math, specifically [mathematical equivalence](https://en.wikipedia.org/wiki/Equality_(mathematics)). He gives you a list of equations of the form `[variable] = [variable]` where a `[variable]` is always a single uppercase letter A to Z (not a lowercase letter, not a number, nor anything else). There's one equation per line in the list except for a single line that only says `therefore`. All the equations above the `therefore` are [premises](https://en.wikipedia.org/wiki/Premise), facts that are assumed to be true. All the equations below the `therefore` are unverified propositions, facts that Alex is attempting to infer from the premises, and they may or may not be true. For example, in this equation list the single conclusionary proposition `A = C` happens to be true: ``` A = B B = C therefore A = C ``` It's your job to tell Alex if **all** of his propositions logically follow from the given premises. That is, you need to tell Alex if he is wrong or right in his conclusions. Write a program/function that takes in a string of a list of equations as described and prints/returns ``` Alex is right ``` if all the conclusions follow logically from the premises, and otherwise outputs ``` Alex is wrong ``` if any conclusion does not logically follow from the premises. **The shortest code in bytes wins.** Be sure to watch out for these cases: * Variable always equals themselves. e.g. ``` B = A therefore A = A X = X ``` results in `Alex is right`. * Variables with unknown relationships cannot be assumed to be equal. e.g. ``` P = Q therefore E = R ``` results in `Alex is wrong`. * When there are no equations after the `therefore` then the conclusions are [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth). e.g. ``` D = C therefore ``` and ``` therefore ``` both result in `Alex is right`. * When there are no equations before the `therefore` then only self-equality can be inferred. e.g. ``` therefore R = R ``` results in `Alex is right`, but ``` therefore R = W ``` results in `Alex is wrong`. ## More Examples **Alex is wrong cases:** (separated by empty lines) ``` A = B C = D therefore A = C A = L E = X A = I S = W R = O N = G therefore G = N L = I R = O S = A X = X X = E D = K D = Q L = P O = L M = O therefore K = L A = B therefore B = C Z = A S = S therefore A = Z A = A S = A A = S Z = A Z = A K = L K = X therefore X = P L = X L = P therefore A = B B = C A = C therefore A = A B = B C = C D = D E = E F = F G = G H = H I = I J = J K = K T = I L = L M = M N = N O = O P = P Q = Q R = R S = S T = T U = U V = V W = W X = X Y = Y Z = Z A = B B = C C = D D = E E = F F = G G = H H = I I = J J = K K = L L = M M = N N = O O = P P = O Q = R R = S S = T T = U U = V V = W W = X X = Y Y = Z therefore A = Z therefore C = D T = Y A = Z P = Q therefore E = R therefore R = W ``` **Alex is right cases:** ``` H = J therefore J = H K = L K = X therefore L = X C = B B = A therefore A = B K = L K = X K = P therefore L = X L = P X = P A = Y Y = Q Q = O therefore O = Y O = A C = C therefore C = C A = B B = A therefore A = B B = A A = B B = C C = D therefore A = A A = B A = C A = D B = A B = B B = C B = D C = A C = B C = C C = D D = A D = B D = C D = D therefore A = A B = B C = C D = D E = E F = F G = G H = H I = I J = J K = K L = L M = M N = N O = O P = P Q = Q R = R S = S T = T U = U V = V W = W X = X Y = Y Z = Z D = I F = H J = M therefore M = J D = I H = F A = B B = C C = D D = E E = F F = G G = H H = I I = J J = K K = L L = M M = N N = O O = P P = Q Q = R R = S S = T T = U U = V V = W W = X X = Y Y = Z therefore Z = A F = R G = I W = L A = B B = C therefore A = C B = A therefore A = A X = X P = P C = G M = C therefore D = C therefore therefore therefore R = R ``` [Answer] # Ruby, ~~80~~ 76 + 2 = 78 With command-line flags `p0`, run ``` gsub$1,$2%p=$`[/e/]while~/(.) = (?!\1)(.)/ $_="Alex is #{p ?:wrong: :right}" ``` Explanation: This uses pure string manipulation. `p0` reads the full input as a single string into the variable `$_`. Then, we repeatedly match that string against the regular expression `/(.) = (?!\1)(.)/`, which finds all strings of the form "X = Y" where X and Y aren't the same letter, and assigns X to $1 and Y to $2. When such a match is found, `gsub$1,$2` replaces all instances of X with Y in the string. We also check whether this match occurred before or after the "therefore" with ``` $`[/e/] ``` If it occurred after, it's an unjustified claim and Alex is wrong. We track whether any such occurrences have happened using `p=`. The use of `p` as a tracking variable prevents things from breaking if the loop never hits even once, since `p` will return nil if it's never been assigned to. As of this post, the CJam solution is longer. A proud, if no doubt fleeting moment. Edit: Yup, quickly dethroned. Also, to finish the explanation, with the `p` flag the final value of `$_` is output at the end of execution, so the last line is the output. [Answer] # CJam, 49 ``` "Alex is "qN%S{f{)er}(_el-}h;{)#},"wrong""right"? ``` Inspired from histocrat's Ruby solution. [Try it online](http://cjam.aditsu.net/#code=%22Alex%20is%20%22qN%25S%7Bf%7B)er%7D(_el-%7Dh%3B%7B)%23%7D%2C%22wrong%22%22right%22%3F&input=A%20%3D%20B%0AC%20%3D%20D%0Atherefore%0AA%20%3D%20C) 3 bytes obliterated thanks to jimmy23013 :) **Explanation:** For each premise, the program replaces the first variable with the 2nd variable in the rest of the text. It then checks if there's any conclusion with different variables. ``` "Alex is " first push the part we know qN% read the input and split into lines S push a space (initial no-op replacement string, see below) {…}h do-while f{…} for each line and the replacement string ) take out the last character er replace the remaining character(s) with that character ( afterwards, take out the first line _el duplicate and convert to lowercase - remove all the resulting characters from the line this removes all lowercase letters and non-letters "X = Y" becomes "XY" (new replacement string) and "therefore" becomes "" (ending the loop) this is the loop condition and is left on the stack every time ; after the loop, pop the empty string (from "therefore") {…}, filter the remaining (conclusion) lines using the condition block ) take out the last character # find its index in the remaining string this is 0 (false) iff the first character is the same as the last afterwards, we have an array of lines with non-equal variables "wrong" push "wrong" "right" push "right" ? choose "wrong" if the array was not empty, else choose "right" ``` **Old version, 85** ``` "Alex is "26,:A;{:i{{_A=_@-}g}%$~}:F;0q"= "-'t/Nf%~\{A\Ft:A;}/1>{F=}%-"right""wrong"? ``` This uses a union-find algorithm. [Try it online](http://cjam.aditsu.net/#code=%22Alex%20is%20%2226%2C%3AA%3B%7B%3Ai%7B%7B_A%3D_%40-%7Dg%7D%25%24~%7D%3AF%3B0q%22%3D%20%22-'t%2FNf%25~%5C%7BA%5CFt%3AA%3B%7D%2F1%3E%7BF%3D%7D%25-%22right%22%22wrong%22%3F&input=A%20%3D%20B%0AC%20%3D%20D%0Atherefore%0AA%20%3D%20C) [Answer] # CJam, ~~83~~ ~~75~~ ~~68~~ ~~67~~ 64 bytes *Thanks to Dennis for saving 1 byte.* ``` "Alex is "q_elN--N/:$La/~{)-},\{__m*{:&},::^|}5*-"wrong""right"? ``` [Test suite.](http://cjam.aditsu.net/#code=qN2*%2F%7B%3AQ%7B%0A%22Alex%20is%20%22Q_elN--N%2FLa%2F~%7B)-%7D%2C%5C%7B_Wf%25%7C__m*%7B%3A%26%7D%2C%3A%3A%5E%7C%7D5*-!%22wrriognhgt%22%3E2%25%0A%7D%26%5DoNo%7D%2F&input=) The test cases are too long for a permalink, so simply copy them in from the question. Note that this is fairly slow - it takes a minute or two in the online interpreter. You can make it much faster by changing `5*` to `2*` in which case it will finish almost instantly and solve all but one test case. ## Explanation *(Slightly outdated.)* The idea is to do a sort of "flood fill" of possible equalities and then remove all the equalities we obtained from the conclusion list. It can be shown that we need no more than 5 steps of the flood fill, because those would cover a distance (in the initial graph of inequalities) of `25 = 32` but the maximum distance is 25. ``` "Alex is " e# Push the string. q e# Read the input. _elN- e# Make a copy, convert to lower case, remove linefeeds. This gives us a string e# with all the characters we don't want from the input. - e# Remove them from the input. This leaves two upper-case letters on each line e# and an empty line between premises and conclusions. N/ e# Split into lines. La/ e# Split around the empty line. ~ e# Dump both halves on the stack. {)-}, e# Remove any "A = A"-type equalities from the conclusions. \ e# Swap with the premises. { e# Extend the premises 5 times... _Wf% e# Duplicate the premises and reverse each one, because = is symmetric. | e# Set union with the original premises. __m* e# Make two copies and get an array of every possible pair of premises. {:&}, e# Select those which have at least one character in common. ::^ e# For each such pair, take the mutual set difference, i.e. those characters e# that are in only one of the strings. | e# Set union with the original premises. }5* - e# Remove all the equalities we've obtained from the conclusions. If all e# conclusions were valid, the result will now be a empty array, which is falsy. ! e# Logical not. "wrong""right"? e# Select "wrong" or "right", respectively. ``` [Answer] ## R, 183 192 bytes *I have modified my answer to address a limitation pointed out by user2357112. There is still an extremely small probability of calling Alex out when he is in fact right (which itself does not seem to happen very often if I understand the context of the challenge :-). I hope he won't mind.* ``` i=grep("t",z<-scan(,"",,,"\n")) cat("Alex is",if(eval(parse(t=c(paste(LETTERS,"=",1:26),sample(rep(head(z,i-1),1e3)),paste(c(TRUE,sub("=","==",tail(z,-i))),collapse="&")))))"right"else"wrong") ``` I need to de-golf this a bit: ``` lines = scan(, what = "", sep = "\n") therefore_idx = grep("therefore", lines) setup = paste(LETTERS, "=", 1:26) premises = sample(rep(head(lines, therefore_idx - 1), 1000)) propositions = paste(c(TRUE, sub("=", "==", tail(lines, -therefore_idx))), collapse = "&") things_to_evaluate = c(setup, premises, propositions) boolean_result = eval(parse(text = things_to_evaluate)) cat("Alex is", if (boolean_result) "right" else "wrong") ``` For example, if the input is ``` A = B B = C therefore A = C B = C ``` it will first evaluate the `setup`: ``` A = 1 B = 2 ... Z = 26 ``` then the `premises` ``` A = B B = C ``` will be run 1,000 times each in a random order. This is to make sure ("almost sure") that all equalities are propagated. Finally, it will evaluate the `propositions`: ``` TRUE & A == B & B == C ``` [Answer] # Haskell, 208 bytes ``` import Data.Equivalence.Persistent c l=equate(l!!0)$last l r=foldr(c)$emptyEquivalence('A','Z') l#r=equiv r(l!!0)$last l f x|(h,_:t)<-span((<'t').head)$lines x="Alex is "++if all(#r h)t then"right"else"wrong" ``` I'm offloading the work to the `Data.Equivalence.Persistent` module, which provides functions for manipulating equivalence classes. All left to do is parsing the input and calling functions which sometimes have too long names for proper golfing. Usage example: ``` *Main> f "A = B\nB = C\ntherefore\nA = C" "Alex is right" *Main> f "A = B\nB = D\ntherefore\nA = C" "Alex is wrong" ``` [Answer] # Python 2, 264 bytes There's already a [remarkable Python 3 answer by mbomb007](https://codegolf.stackexchange.com/a/61494/36885). This answer steals flagrantly from that one (in particular the "Alex is wrriognhgt" trick). And this answer is also significantly longer than that one... Well, anyway, the idea in this answer is to maintain a dictionary of key-value pairs, where the keys are the 26 capital letter characters, and each key's corresponding value is the set of letters that are equivalent to the key. (If all 26 letters were equivalent, then each key would have a set of 26 letters for its corresponding value.) ``` def a(s): d={C:set(C)for C in map(chr,range(65,91))};p,c=s.split('t');c,p=[x.split('\n')for x in[c[9:],p]] for u in p[:-1]: g,h=u[::4];y=d[g]|d[h] for v in y: for w in y:d[v]|=d[w];d[w]|=d[v] print'Alex is','wrriognhgt'[all(u[0]in d[u[4]]for u in c if u)::2] ``` (To save bytes, this answer [mixes spaces and tabs](https://codegolf.stackexchange.com/a/58/36885), which is legal in Python 2.) This code is really pretty efficient, because the dictionary is limited to a maximum possible size (26 by 26 as described above) which doesn't depend on the number of lines of input. Now, as I was golfing this solution, I realized that I could **save four bytes** by using strings instead of sets for the dictionary values, by replacing ``` d={C:set(C)for C in map( ``` with ``` d={C:C for C in map( ``` Of course then you also have to replace (NOTE: DON'T DO THIS) the three instances of the set union operation `|` with string concatenation `+`, but that doesn't change the code length. The result is that everything should still work just the same, except it won't eliminate duplicates like you do with sets (it'll just keep adding onto the end of the string). Sounds OK--a little less efficient, sure, but 260 bytes instead of 264. Well, it turns out that **the 260-byte version is so inefficient** that it caused a `MemoryError` when I tested it with ``` A = B A = B therefore B = A ``` This was surprising to me. **Let's investigate the 260-byte "string concatenation" version!** Of course it would start out with the key-value pairs `A:A` and `B:B` (plus 24 others that don't matter). We'll write `d[A]` to mean the dictionary value corresponding to the key `A`, so at the beginning we'd have `d[A] = A`. Now, given the premise `A = B`, it would start by concatenating the values `d[A]=A` and `d[B]=B` to get `y = AB`. Then it'd loop over this string twice: `for v in AB: for w in AB:`... So, the first time through the loop, we have `v=A` and `w=A`. Applying `d[v] += d[w]` and `d[w] += d[v]` results in the following sequence of dictionaries: ``` {A:A, B:B} (start) {A:AA, B:B} (d[A] += d[A]) {A:AAAA, B:B} (d[A] += d[A]) ``` Next, with `v=A` and `w=B`: ``` {A:AAAA, B:B} (start) {A:AAAAB, B:B} (d[A] += d[B]) {A:AAAAB, B:BAAAAB} (d[B] += d[A]) ``` Next, `v=B, w=A`: ``` {A:AAAAB, B:BAAAAB} (start) {A:AAAAB, B:BAAAABAAAAB} (d[B] += d[A]) {A:AAAABBAAAABAAAAB, B:BAAAABAAAAB} (d[A] += d[B]) ``` And `v=B, w=B`: ``` {A:AAAABBAAAABAAAAB, B:BAAAABAAAAB} (start) {A:AAAABBAAAABAAAAB, B:BAAAABAAAABBAAAABAAAAB} (d[B] += d[B]) {A:AAAABBAAAABAAAAB, B:BAAAABAAAABBAAAABAAAABBAAAABAAAABBAAAABAAAAB} (d[B] += d[B]) ``` The above sequence of steps would implement the single premise `A = B`, with the conclusion that `A` is equal to every letter in the string `AAAABBAAAABAAAAB`, while `B` is equal to every letter in `BAAAABAAAABBAAAABAAAABBAAAABAAAABBAAAABAAAAB`. Now, suppose that the next premise is `A = B` **again**. You first calculate `y = d[A] + d[B] = AAAABBAAAABAAAABBAAAABAAAABBAAAABAAAABBAAAABAAAABBAAAABAAAAB`. Next, you loop over this string twice: `for v in y: for w in y:`... Yeah. Maybe that wouldn't be a very efficient implementation. [Answer] # Mathematica, 182 ``` f[s_]:="Alex is "<>If[True===And@@Simplify[#2,#1]&@@(StringSplit[s,"\n"]/.{a___,"therefore",b___}:>StringSplit/@{{a},{b}}/.{x_,_,y_}:>Symbol[x<>"$"]==Symbol[y<>"$"]),"right","wrong"] ``` Works on string input, as per the challenge. ``` In[]:= f["A = B B = C therefore A = C"] Out[]= Alex is right In[]:= f["D = K D = Q L = P O = L M = O therefore K = L"] Out[]= Alex is wrong ``` [Answer] # Retina, 90 bytes To run, place the following 12 lines of code in 12 separate files (+11 bytes counted for each file beyond the first). `<empty>` designates an empty file; `\n` designates a literal newline. Alternately, keep the `\n`s as they are, put all lines in a single file, and use the `-s` option. Make sure that all files use literal newlines, not Windows `\r\n`, and note the space at the end of the last line. ``` s+`^(.) = (.)(.*)\1 $1 = $2$3$2 )`^. .+\n <empty> ^.+|(.) = \1 <empty> ^\n*$ right ^[^r]+ wrong ^ Alex is ``` **How it works** The first replacement matches the first premise in the input, whenever the lhs of the premise occurs later on in the file. It replaces that later occurrence with the rhs of the premise. The `+` modifier ensures that the replacement is repeated until it doesn't match any more. Thus, if the first premise is `A = B`, all subsequent `A`s in the file get transmuted into `B`s. The second replacement removes the first premise from the input, since we're done with it now. Then the `)` modifier loops back to the first replacement, and repeats until there were no changes in a whole pass through the loop. This happens when all the premises have been substituted and removed, and the input starts with `therefore`. The third replacement matches the first line of input (which is `therefore`) or anything of the form `A = A`, and deletes it. If all propositions are supported by the premises, all of them will match this form, so what remains should consist solely of newlines. The fourth replacement changes this into `right`. Otherwise, the fifth replacement changes everything remaining (which doesn't contain `r` since `therefore` was deleted) into `wrong`. Finally, the last replacement adds `Alex is` at the beginning. [Answer] # ES6, 128 bytes Loosely based on the Ruby version. ``` r=s=>(m=/^[^e]*(.) = (?!\1)(.)/.exec(s))?r(s.replace(RegExp(m[1],'g'),m[2])):'Alex is '+(/(.) = (?!\1)/.test(s)?'wrong':'right') ``` Looks for any non-self-equality before the "therefore" and recurisvely replaces the variable throughout the string each time (this saves bytes over a while loop). [Answer] # C, 240 bytes ``` #define V[v-65] v[26];char*r[]={"wrong","right"};i=65;j;g(a){return a V^a?g(a V):a;}main(){char b[16];for(;i<91;++i)i V=i;while(gets(b)&&*b<99)b[0]V=b[4]V=b[0]V<b[4]V?b[0]V:b[4]V;while(gets(b))j|=g(*b)^g(b[4]);printf("Alex is %s\n",r[!j]);} ``` This works by combining values into set trees, so any equivalent values lead to the same set root. Ungolfed, with implicit types made explicit. ``` // Anything before `V` becomes an index into `v`, offset by -'A'. #define V [v-65] int v[26]; char* r[] = {"wrong", "right"}; int i=65; int j; // Finds a set identifier for a by recursing until some index points to itself. int g(int a) { return a V ^ a ? g(a V) : a; } int main() { char b[16]; // Initialize all entries to point to themselves. for(; i < 91; ++i) i V = i; // For each premise "A = B", set the entries for A and B to point to the // smaller of their current values. This exits after reading "therefore" // as 't' > 99. while (gets(b) && *b < 99) b[0]V = b[4]V = b[0]V < b[4]V ? b[0]V : b[4]V; // For each conclusion "A = B", OR j with non-zero if the set identifiers // for A and B are different. while (gets(b)) j |= g(*b) ^ g(b[4]); printf("Alex is %s\n", r[!j]); } ``` # 180 bytes This shorter version works for all cases from the OP, but for some other inputs incorrectly claims Alex is wrong. It uses a similar approach, but for each premise simply sets the second entry to the current value of the first entry. When comparing, it looks only at exact values instead of searching up a tree. ``` v[26];*V=v-65;char*r[]={"wrong","right"};i;j;main(){char b[16];for(;i<26;++i)v[i]=i;while(gets(b)&&*b<99)V[b[4]]=V[*b];while(gets(b))j|=V[*b]^V[b[4]];printf("Alex is %s\n",r[!j]);} ``` An example input for which this fails: > > A = B > > C = B > > therefore > > A = C > > > [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` …±º€ˆ „–у©#|€á[ćD.l#`:}\€ËPè«.ª ``` Inspired by [*@aditsu*'s CJam answer](https://codegolf.stackexchange.com/a/61488/52210). [Try it online](https://tio.run/##yy9OTMpM/f//UcOyQxsP7XrUtOZ0m8KjhnmPGiYfnnhs0qGVyjVAscMLo4@0u@jlKCdY1caA@N0Bh1ccWq13aNX//94Ktgo@XCAyAkwGcJVkpBalpuUXpXL5gEV9wKIRIBIA) or [verify all test cases](https://tio.run/##vZU/b9NAGMb391NEzppU6loJVT47tpM4sZ1/dlIGihQEUtWgkg4gIUUMMLDwZ0fqgmhhYenA6CAWvkW@iLl77mSf7ZYFleWR8/p97/3dc@85q2fHD58ss6Ptu/2oaXRPn56vDxpGq2UE52v5fJhepxezbLf5nH5Pf@xeffv9urHbfNptPm7f//qQXjbnPLa9OPr5xt47aT44eHlf/H4bbr@kX/fSq6yVXh9mhmGYjXsNRhZXm9aPl2fLR6uzJYmoxd@SyvCpwzVBvEtjrjGNuAY05OpqlS7/PSQfeTJDZJuUoF5oR61r8@c@CY2QH1KATgNUFSv2RVRjYdo7pnEu0Ed0G1d2soCaisREhsyGqnr0QbdEq09A5iMKSpVd7sAkScm3coaJDOm0hV3b8LRDDlcHvrnkcfWoC/d6XHvg6dMEET/3ZwDfh3AsoBCMEZwUno@UC6JqQlOuU5pxnVGMk5NnMec6hwOLkrtyJ3IibBB2QOiA0AWhB54uCHsglO75YBuAbQi2AGwhniOwjcA2BtsEbFOwzcAW53MyB@GiepY1dyXpBBV6Rgg/ijyxi1GtWtDEKuphP8U7sTPvr9OBuVAZVu6eWWFmN6zRhy@VldQ9SLQ5M3MnIvin34wA7wJthuV0lb2xaqdb45PRW6egOskyw8wn3larMq2SIW4hbmmTX8yVCWVQdSPu4Obc9Z2x0dFB9x66FPQDcMgMwef8l3sW/fM9k99GB6u4IIhr32BWmTT9y3fTjKl/AO1uhti7i11oK2m@1qO3/pZnKKL7Wbt9umqfHL94/gc). **Explanation:** ``` …±º€ˆ # Push dictionary string "alex is " „–у© # Push dictionary string "wrong right" # # Split by spaces: ["wrong","right"] | # Push all input-lines as list €à # Only leave the letters of each line [ # Start an infinite loop: ć # Extract the head of the list; pop and push remainder-list and head separately D # Duplicate the head .l # If it's a lowercase string: # # Stop the infinite loop ` # Push both letters in the string to the stack : # Replace all these letters in the remainder-list }\ # After the infinite loop: discard the duplicated "therefore" € # For each letter-pair in the remainder list of condition-lines: Ë # Check if both letters are equal (1 if truhy; 0 if falsey) P # Check if everything was truthy by taking the product è # Use this to index into the earlier ["wrong","right"]-list « # Append it to the "alex is " string .ª # Sentence capitalize it # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `…±º€ˆ` is `"alex is "` and `„–у©` is `"wrong right"`. [Answer] # [bash](https://www.gnu.org/software/bash/) + [awk](https://www.gnu.org/software/gawk/manual/gawk.html) + [SWI-Prolog](https://www.swi-prolog.org/), 167 bytes ``` head -n1 <(awk '/therefore/{s=1;next};{if(s)print"?=("$1","$3")";else print};END{print"write(\"Alex is right\");write(\"Alex is wrong\"). halt."}' -|paste -sd ,|swipl) ``` [Try it online!](https://tio.run/##XdBNa8JAEMbx@/MplkUwAaOEHtNQ1MR3o/Vd8ZLiapaGGHYXImg@e5xa6KGXHwP/OQzzFeukqhIRn5iTuezdiotvVm@ZRChxvirRumvf9TJxM6V3l2dL27mSmeEfvsVrLm/w2hu3uSdSLdirlF4YBfffpUJJI6wjb6fixqRmSl4Sc@S29z8U6ppdKDRZEqemycs6cx55rI1gjj6xxkMXMk/tqmozn3XQIbvokgECMkRI9tAj@@iTAwzIIYbkCCNyjDE5wYScYkpGiMgZZuQc89f8SS6wIJdYkiusyDXW5AYbcostucOO3GNPHvD3Lfzcd3gC "Bash – Try It Online") Originally, this was just going to be a Prolog answer, but the tools I could find to actually transform the input format into something usable were limited enough that I decided to do that part of it in bash, even though I had next to no experience doing anything in bash, and had never even touched awk. I ended up spending enough hours on it to want to post it even after it grew into this 167-byte, barely golfed at all monster. Essentially, what the awk program does is take the input from stdin, erase the line with `therefore`, replace every `A = B` after it with `?=(A,B)`, and append `write(\"Alex is right\");write(\"Alex is wrong\"). halt.`. Then, `paste -sd ,` replaces every newline but the last with a comma, transforming it into a valid two queries to the SWI-Prolog shell, which are then run with the printed result being truncated to one line by `head -n1`, which requires `<(...)` instead of a pipe for reasons beyond my understanding. All this, just to use [a builtin](https://www.swi-prolog.org/pldoc/doc_for?object=?%3D%20/%202)! ]
[Question] [ MS Paint was always a great time waster, but it was shunned by most graphic designers. Perhaps people lost interest because of the jarring color palette, or because of limited undo levels. Regardless, it's still possible to generate beautiful images with just the standard brush and default color palette. ## Challenge Using only the default brush (a 4x4 square with no corners) and the default color palette (the 28 colors below), attempt to replicate a source image using a technique based on [stochastic hill climbing](https://en.wikipedia.org/wiki/Stochastic_hill_climbing). ![enter image description here](https://i.stack.imgur.com/XLUWi.png) ## Algorithm Every answer must follow the same basic algorithm (stochastic hillclimb). Details can be tweaked within each step. A *movement* is considered to be a stroke of the brush (ie. clicking in paint). 1. **Guess next movement(s).** Make a guess (of coordinates and colors) for the next movement(s) however you'd like. However the guess must not reference the source image. 2. **Apply the guess.** Apply the brush to the painting to make the movement(s). 3. **Measure the benefit of movement(s).** By referencing the source image, determine whether the movement(s) benefited the painting (ie. the painting more closely resembles the source image). If it is beneficial, keep the movement(s), otherwise discard the movement(s). 4. **Repeat until convergence.** Go to Step 1 and try the next guess until the algorithm has converged sufficiently. The painting should heavily resemble the source image at this point. **If your program does not match these four steps, it is probably not a stochastic hillclimb.** I have tagged this as a popularity contest because the goal is to produce interesting painting algorithms based on the limited color palette and brush. ## Contraints * **The algorithm should be [stochastic](https://en.wikipedia.org/wiki/Stochastic) in some way.** * **The next guess should not be influenced by the source image. You are guessing each new movement, and then checking to see if it helped or not.** For example, you are not allowed to determine where to place the brush based on the source image colors (that is similar to dithering the source image, which is not the goal). * You are allowed to influence the placement by tweaking the steps of the algorithm however you'd like. For example, you could start your guesses at the edges and move inwards, drag the brush to create lines for each guess, or decide to paint dark colors first. You are allowed to reference previous iteration images (but not the source image) in order to calculate the next desired movement. These can be restrictive as you'd like (ie. only make guesses within the top-left quadrant for the current iteration). * The measure of "difference" between the source image and the current iteration can be measured however you'd like, **as long as it does not calculate other potential movements to determine whether this movement is considered to be the "best".** It shouldn't know whether the current movement is the "best", only whether it fits within the tolerance of the acceptance criteria. For example, it can be as simple as `abs(src.R - current.R) + abs(src.G - current.G) + abs(src.B - current.B)` for each affected pixel, or any of the well-known [color difference techniques](https://en.wikipedia.org/wiki/Color_difference). ## Palette You can [download the palette as a 28x1 image](https://i.stack.imgur.com/u9JAD.png) or create it directly in the code. ## Brush The brush is a 4x4 square without corners. This is a scaled version of it: ![enter image description here](https://i.stack.imgur.com/UYvlz.png) (Your code must use the 4x4 version) ## Example Input: ![Van Gogh - The Starry Night](https://i.stack.imgur.com/Qe7Jr.jpg) Output: ![The Starry Night generated](https://i.stack.imgur.com/zTF26.png) You can see how the basic algorithm progresses in a short video I made (each frame is 500 iterations): [The Starry Night](https://www.youtube.com/watch?v=J80Xo31luKE). The initial stages are interesting to watch: ![enter image description here](https://i.stack.imgur.com/R6cF5.png) [Answer] # JavaScript This solution uses the HTML5 canvas element to extract the image data, but without the need to use HTML, that means it can be run in your console. It access the color palette image as an array; I stored all the colors from the palette image in an array). It outputs to the console (after it finishes) and also stores the result in a variable. **The most updated version of the code is in the fiddle**. The fiddle also uses a better algorithm to reduce noise in the pictures. The improvement in the algorithm is mostly fixing a function (max to min) which caused the inverse color to be chosen. Code in the shape of the MS Paint Icon! (formatted code in fiddle or Stack Snippet) ``` eval(` function Paint(t){fun ction n(t){va r n=t.toString( 16);return 1==n. length?"0"+n:n}fu nction e(t){return "#"+n(t[0])+n(t[1] )+n(t[2])}var a=ne w Image,i=document. createElement("canv as"),h=null,o=docum ent.createElement( "canvas"),r= o.getContext("2d ") ,l=[],u=this,c =[[0,0,0],[255 ,2 55,255],[ 192,192, 192],[128,12 8 ,128],[126,3,8],[252,13,27] ,[255,25 3, 56],[128,127,23],[15,127,18],[ 41,253 , 46],[45,255,254],[17,128,127],[2 ,12,1 2 6],[ 11,36,2 51],[252,40,252],[12 7,15,1 2 6],[ 128,127 ,68],[255,253,136],[4 2,253, 1 33], [4,64,64],[23 ,131,251],[133,255,254], [ 129 ,132,252],[6,6 6,126],[127,37,2 51],[127, 6 4,1 3],[253,128,73],[252,22,129]];a.crossOrigin = "", a.src=t,this.done=this.done||function(){},a.o n load=function(){function t(t){var n=0,e=0,a=0;return t .forEach(function(t){n+=t[0],e+=t[1],a+=t[2]}),[n/t.leng t h,e /t.length,a/t.length]}function n(t){for(var n=[],e=0;e < t.l ength;e+=1)n.push(t[e]);return n}function g(t,n){retur n (Ma th.abs(t[0]-n[0])/255+Math.abs(t[1]-n[1])/255+Math.abs(t [ 2]- n[2])/255)/3}function f(t,n){for(var e=Math.floor(Math.ran do m()*n.length),a=n[e],i=(g(t,a),1-.8),h=56,o=[];o.length<=h& &g (t,a)>i;)if(o.push(a),a=n[Math.floor(Math.random()*n.length)] , o.length==h){var r=o.map(function(n){return g(t,n)});a=o[r.indexO f(Math.max.apply(Math,r))],o.push(a)}return a}function s(t,n){for( v ar e=[];t.length>0;)e.push(t.splice(0,n).slice(0,-1));return e}i.w i dth=a.width,i.height=2*a.height,h=i.getContext("2d"),h.drawImage(a,0 ,0,a.width,a.height);for(var d=(function(t){reduce=t.map(function(t){re turn(t[ 0]+t[1]+t[2])/3})}(c),0),m=0,v=i.width*i.height/4,p=0;v>p;p+=1)d >2*Mat h.ceil(a.width/2)&&(d=0,m+=1),l.push(f(t(s(n(h.getImageData(2*d,2 *m,4,4).data),4)),c)),d+=1;o.width=i.width,o.height=i.height;for(var d=0 ,m=0,v=i.width*i.height/4,p=0;v>p;p+=1)d>2*Math.ceil(a.width/2)&&(d=0,m+= 1),console.log("Filling point ("+d+", "+m+") : "+e(l[p])),r.fillStyle=e(l [p]),r.fillRect(2*d+1,2*m,2,1) ,r.fillRect(2*d,2*m+1,4,2),r.fillRect(2*d +1,2*m+3,2,1),d+=1;u.result=o .toDataURL("image/png"),u.resultCanvas =o,u.imageCanvas=i,u.image=a ,u.done(),console.log(u.result)},a.one rror=function(t){console.log ("The image failed to load. "+t)}}/*.. ............................ ...................................... . .......................... ..................................... ............................ ...................................... ............................. ....................................... ....................................................................... ....................................................................... .................. .................................................. ................ ................................................. .............. ................................................ ............. ................................................ ........... ................................................. ......... ................................................ ....... ................................................ .... ................................................ ................................................ ............................................... ............................................... .............................................. ............................................. ............................................ .......................................... ....................................... ..................................... ................................. ............................. ...................... ..... ..... ..... .... */` .replace(/\n/g,'')) ``` Usage: ``` Paint('DATA URI'); ``` # [Fiddle](https://jsfiddle.net/we4dkf9f/14/). The fiddle uses [crossorigin.me](http://crossorigin.me) so you don't need to worry about cross-origin-resource-sharing. I've also updated the fiddle so you can adjust some values to produce the best-looking painting. Some pictures' colors might be off, to avoid this, adjust the accept\_rate to adjust the algorithm. A lower number means better gradients, a higher number will result in sharper colors. --- Here's the fiddle as a Stack-Snippet (NOT updated, in case the fiddle doesn't work): ``` /* Options */ var accept_rate = 82, // 0 (low) - 100 (high) attempts = 16, // Attemps before giving up edge_multi = 2; // Contrast, 2-4 function Paint(image_url) { var image = new Image(), canvas = document.createElement('canvas'), context = null, result = document.createElement('canvas'), resultContext = result.getContext('2d'), final_colors = [], self = this, color_choices = [ [0,0,0], [255,255,255], [192,192,192], [128,128,128], [126,3,8], [252,13,27], [255,253,56], [128,127,23], [15,127,18], [41,253,46], [45,255,254], [17,128,127], [2,12,126], [11,36,251], [252,40,252], [127,15,126], [128,127,68], [255,253,136], [42,253,133], [4,64,64], [23,131,251], [133,255,254], [129,132,252], [6,66,126], [127,37,251], [127,64,13], [253,128,73], [252,22,129] ]; image.crossOrigin = ""; image.src = image_url; this.done = this.done || function () {}; function hex(c) { var res = c.toString(16); return res.length == 1 ? "0" + res : res; } function colorHex(r) { return '#' + hex(r[0]) + hex(r[1]) + hex(r[2]); } image.onload = function () { canvas.width = image.width; canvas.height = image.height * 2; context = canvas.getContext('2d'); context.drawImage(image, 0, 0, image.width, image.height); function averageColors(colors_ar) { var av_r = 0, av_g = 0, av_b = 0; colors_ar.forEach(function (color) { av_r += color[0]; av_g += color[1]; av_b += color[2]; }); return [av_r / colors_ar.length, av_g / colors_ar.length, av_b / colors_ar.length]; } function arrayFrom(ar) { var newar = []; for (var i = 0; i < ar.length; i += 1) { newar.push(ar[i]); } return newar; } function colorDif(c1,c2) { // Get's distance between two colors 0.0 - 1.0 return (Math.abs(c1[0] - c2[0]) / 255 + Math.abs(c1[1] - c2[1]) / 255 + Math.abs(c1[2] - c2[2]) / 255) / 3; } var furthest = (function (cc) { // Determines furthest color // Reduces RGB into a "single value" reduce = cc.map(function(color) { return ( color[0] + color [1] + color [2] ) / 3; }); }(color_choices)); function intDif(i1,i2,t) { return Math.abs(i1 - i2) / t } function arrayIs(ar, int,d) { return intDif(ar[0],int,255) <= d && intDif(ar[1],int,255) <= d && intDif(ar[2],int,255) <= d } function colorLoop(c1,c2) { var edgeCap = edge_multi * ((accept_rate / 100) / 50), values = c2.map(function (i) { return colorDif(c1,i); }); return arrayIs(c1,255,edgeCap)?[255,255,255]: arrayIs(c1,0,edgeCap) ?[0,0,0]: c2[values.indexOf(Math.min.apply(Math, values))]; } function colorFilter(c1, c2) { // Does the color stuff var rand = Math.floor( Math.random() * c2.length ), // Random number color = c2[rand], // Random color randdif = colorDif(c1, color), threshhold = 1 - accept_rate / 100, // If the color passes a threshhold maxTries = attempts, // To avoid infinite looping, 56 is the maximum tries to reach the threshold tries = []; // Repeat until max iterations have been reached or color is close enough while ( tries.length <= maxTries && colorDif( c1, color ) > threshhold ) { tries.push(color); color = c2[Math.floor(Math.random() * c2.length)]; // Tries again if (tries.length == maxTries) { // Used to hold color and location var refLayer = tries.map(function(guess) { return colorDif(c1, guess); }); color = tries[refLayer.indexOf(Math.min.apply(Math, refLayer))]; tries.push(color); } } var edgeCap = edge_multi * ((accept_rate / 100) / 50), loop = colorLoop(c1, c2); return arrayIs(c1,255,edgeCap)?[255,255,255]: arrayIs(c1,0,edgeCap) ?[0,0,0]: colorDif(c1,color)<accept_rate?color: loop; } function chunk(ar, len) { var arrays = []; while (ar.length > 0) arrays.push(ar.splice(0, len).slice(0, -1)); return arrays; } var x = 0, y = 0, total = (canvas.width * canvas.height) / 4; for (var i = 0; i < total; i += 1) { if (x > (Math.ceil(image.width / 2) * 2)) { x = 0; y += 1; } final_colors.push( colorFilter( averageColors( chunk( arrayFrom(context.getImageData(x * 2, y * 2, 4, 4).data), 4 ) ), color_choices) ); x += 1; } // Paint Image result.width = canvas.width; result.height = canvas.height; var x = 0, y = 0, total = (canvas.width * canvas.height) / 4; for (var i = 0; i < total; i += 1) { if (x > (Math.ceil(image.width / 2) * 2)) { x = 0; y += 1; } console.log("Filling point (" + x + ", " + y + ") : " + colorHex(final_colors[i])); resultContext.fillStyle = colorHex(final_colors[i]); resultContext.fillRect(x*2 + 1, y * 2, 2 , 1); // Top resultContext.fillRect(x * 2, y * 2 + 1, 4, 2); // Middle resultContext.fillRect(x * 2 + 1, y * 2 + 3, 2, 1); // Bottom x += 1; } self.result = result.toDataURL("image/png"); self.resultCanvas = result; self.imageCanvas = canvas; self.image = image; self.done(); console.log(self.result); }; image.onerror = function(error) { console.log("The image failed to load. " + error); } } // Demo document.getElementById('go').onclick = function () { var url = document.getElementById('image').value; if (!url.indexOf('data:') == 0) { url = 'http://crossorigin.me/' + url; } var example = new Paint(url); example.done = function () { document.getElementById('result').src = example.result; document.getElementById('result').width = example.resultCanvas.width; document.getElementById('result').height = example.resultCanvas.height; window.paint = example; }; }; ``` ``` <!--This might take a while--> Enter the image data URI or a URL, I've used crossorigin.me so it can perform CORS requests to the image. If you're inputting a URL, be sure to include the http(s) <input id="image" placeholder="Image URI or URL"><button id="go">Go</button> <hr/> You can get the image URI from a website like <a href="http://jpillora.com/base64-encoder/">this one</a> <hr/> Result: <img id="result"> <span id="error"></span><hr/> Check your console for any errors. After a second, you should see the colors that are being generated / printed getting outputted to the console. ``` --- To commemorate New Horizon's flyby of Pluto, I've inputted an image of Pluto: ![Original](https://i.stack.imgur.com/ARix3.jpg) ![Drawn](https://i.stack.imgur.com/5ypHF.png) ![Original](https://i.stack.imgur.com/P7X6g.jpg) ![Drawn](https://i.stack.imgur.com/JZ72p.png) For the following I've set it to make them resemble the original as close as possible: I ran this with OS X Yosemite's default wallpaper. After leaving it run for a bit, the results are absolutely stunning. The original file was huge (26 MB) so I resized and compressed it: ![enter image description here](https://i.stack.imgur.com/4YZZx.jpg) The starry night (I've used a higher resolution [image](https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/1280px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg) for better results) ![](https://i.stack.imgur.com/pbs16.png) A picture I found on google: ![enter image description here](https://i.stack.imgur.com/zr4O4.jpg) ![enter image description here](https://i.stack.imgur.com/oiQ2g.png) [Answer] # **JavaScript + HTML** ### Random: Random Point ### Random Aligned: Subdivides the canvas into 4x4 squares, and chooses a point randomly inside one of the squares. Offsets will move the grid, so you can fill in the little gaps. ### Loop: Creates a grid and Loops through all the points. Offsets moves the grid. Spacing determine the size of each cell. (They will start to overlap) ### Color difference: * RGB * HSL * HSV ``` var draw = document.getElementById("canvas").getContext("2d"); var data = document.getElementById("data").getContext("2d"); colors = [ [0, 0, 0], [255, 255, 255], [192, 192, 192], [128, 128, 128], [126, 3, 8], [252, 13, 27], [255, 253, 56], [128, 127, 23], [15, 127, 18], [41, 253, 46], [45, 255, 254], [17, 128, 127], [2, 12, 126], [11, 36, 251], [252, 40, 252], [127, 15, 126], [128, 127, 68], [255, 253, 136], [42, 253, 133], [4, 64, 64], [23, 131, 251], [133, 255, 254], [129, 132, 252], [6, 66, 126], [127, 37, 251], [127, 64, 13], [253, 128, 73], [252, 22, 129] ]; iteration = 0; fails = 0; success = 0; x = 0; y = 0; //Init when the Go! button is pressed document.getElementById("file").onchange = function (event) { document.getElementById("img").src = URL.createObjectURL(event.target.files[0]); filename = document.getElementById("file").value; /*if (getCookie("orginal") == filename) { console.log("Loading from Cookie"); reload = true; document.getElementById("reload").src = getCookie("picture"); }*/ }; /*function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1); if (c.indexOf(name) == 0) return c.substring(name.length, c.length); } return ""; }*/ //Run when the image has been loaded into memory document.getElementById("img").onload = function () { document.getElementById("file").disable = "true"; document.getElementById("canvas").hidden = ""; document.getElementById("canvas").height = document.getElementById("img").height; document.getElementById("data").height = document.getElementById("img").height; document.getElementById("canvas").width = document.getElementById("img").width; document.getElementById("data").width = document.getElementById("img").width; var imgData = draw.createImageData(document.getElementById("img").width, document.getElementById("img").height); for (var i = 0; i < imgData.data.length; i += 4) { imgData.data[i + 0] = 0; imgData.data[i + 1] = 0; imgData.data[i + 2] = 0; imgData.data[i + 3] = 255; } draw.putImageData(imgData, 0, 0); data.putImageData(imgData, 0, 0); if (reload == true) { draw.drawImage(document.getElementById("reload"), 0, 0); } data.drawImage(document.getElementById("img"), 0, 0); setInterval(function () { for (var u = 0; u < document.getElementById("selectColor").value; u++) { doThing(); } }, 0); }; //The core function. Every time this function is called, is checks/adds a dot. function doThing() { getCoords(); paintBucket(); console.count("Iteration"); if (compare(x, y)) { draw.putImageData(imgData, x, y); } } function getCoords() { switch (document.getElementById("selectCord").value) { case "1": x = Math.floor(Math.random() * (document.getElementById("img").width + 4)); y = Math.floor(Math.random() * (document.getElementById("img").height + 4)); break; case "2": x = Math.floor(Math.random() * ((document.getElementById("img").width + 4) / 4)) * 4; console.log(x); x += parseInt(document.getElementById("allignX").value); console.log(x); y = Math.floor(Math.random() * ((document.getElementById("img").height + 4) / 4)) * 4; y += parseInt(document.getElementById("allignY").value); break; case "3": x += parseInt(document.getElementById("loopX").value); if (x > document.getElementById("img").width + 5) { x = parseInt(document.getElementById("allignX").value); y += parseInt(document.getElementById("loopY").value); } if (y > document.getElementById("img").height + 5) { y = parseInt(document.getElementById("allignY").value); } } } function compare(arg1, arg2) { var arg3 = arg1 + 4; var arg4 = arg2 + 4; imgData2 = data.getImageData(arg1, arg2, 4, 4); imgData3 = draw.getImageData(arg1, arg2, 4, 4); N = 0; O = 0; i = 4; addCompare(); addCompare(); i += 4; for (l = 0; l < 8; l++) { addCompare(); } i += 4; addCompare(); addCompare(); i += 4; //console.log("New Score: " + N + " Old Score: " + O); iteration++; /*if(iteration>=1000){ document.cookie="orginal="+filename; document.cookie="picture length="+document.getElementById("canvas").toDataURL().length; document.cookie="picture="+document.getElementById("canvas").toDataURL(); }*/ if (N < O) { return true; } else { return false; } } function addCompare() { if (document.getElementById("colorDif").value == "HSL") { HSLCompare(); i += 4; return; } if (document.getElementById("colorDif").value == "HSV") { HSVCompare(); i += 4; return; } N += Math.abs(imgData.data[i] - imgData2.data[i]); N += Math.abs(imgData.data[i + 1] - imgData2.data[i + 1]); N += Math.abs(imgData.data[i + 2] - imgData2.data[i + 2]); O += Math.abs(imgData3.data[i] - imgData2.data[i]); O += Math.abs(imgData3.data[i + 1] - imgData2.data[i + 1]); O += Math.abs(imgData3.data[i + 2] - imgData2.data[i + 2]); i += 4; } function HSVCompare() { var NewHue = rgbToHsv(imgData.data[i], imgData.data[i + 1], imgData.data[i + 2])[0]; var PicHue = rgbToHsv(imgData2.data[i], imgData2.data[i + 1], imgData2.data[i + 2])[0]; var OldHue = rgbToHsv(imgData3.data[i], imgData3.data[i + 1], imgData3.data[i + 2])[0]; var NScore = [Math.abs(NewHue - PicHue), ((NewHue < PicHue) ? NewHue + (1 - PicHue) : PicHue + (1 - NewHue))]; var OScore = [Math.abs(OldHue - PicHue), ((OldHue < PicHue) ? OldHue + (1 - PicHue) : PicHue + (1 - OldHue))]; NScore = Math.min(NScore[0], NScore[1]); OScore = Math.min(OScore[0], OScore[1]); NewHue = rgbToHsv(imgData.data[i], imgData.data[i + 1], imgData.data[i + 2])[1]; PicHue = rgbToHsv(imgData2.data[i], imgData2.data[i + 1], imgData2.data[i + 2])[1]; OldHue = rgbToHsv(imgData3.data[i], imgData3.data[i + 1], imgData3.data[i + 2])[1]; NScore += Math.abs(NewHue-PicHue); OScore += Math.abs(OldHue-PicHue); NewHue = rgbToHsv(imgData.data[i], imgData.data[i + 1], imgData.data[i + 2])[2]; PicHue = rgbToHsv(imgData2.data[i], imgData2.data[i + 1], imgData2.data[i + 2])[2]; OldHue = rgbToHsv(imgData3.data[i], imgData3.data[i + 1], imgData3.data[i + 2])[2]; N += Math.abs(NewHue-PicHue) + NScore; O += Math.abs(OldHue-PicHue) + OScore; } function rgbToHsv(r, g, b){ r = r/255, g = g/255, b = b/255; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, v = max; var d = max - min; s = max == 0 ? 0 : d / max; if(max == min){ h = 0; // achromatic }else{ switch(max){ case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return [h, s, v]; } function HSLCompare() { var result = 0; rgb = false; var NewHue = rgbToHue(imgData.data[i], imgData.data[i + 1], imgData.data[i + 2])[0]; var PicHue = rgbToHue(imgData2.data[i], imgData2.data[i + 1], imgData2.data[i + 2])[0]; var OldHue = rgbToHue(imgData3.data[i], imgData3.data[i + 1], imgData3.data[i + 2])[0]; if (rgb == true) { N += Math.abs(imgData.data[i] - imgData2.data[i]); N += Math.abs(imgData.data[i + 1] - imgData2.data[i + 1]); N += Math.abs(imgData.data[i + 2] - imgData2.data[i + 2]); O += Math.abs(imgData3.data[i] - imgData2.data[i]); O += Math.abs(imgData3.data[i + 1] - imgData2.data[i + 1]); O += Math.abs(imgData3.data[i + 2] - imgData2.data[i + 2]); return; } var NScore = [Math.abs(NewHue - PicHue), ((NewHue < PicHue) ? NewHue + (1 - PicHue) : PicHue + (1 - NewHue))]; var OScore = [Math.abs(OldHue - PicHue), ((OldHue < PicHue) ? OldHue + (1 - PicHue) : PicHue + (1 - OldHue))]; NScore = Math.min(NScore[0], NScore[1]); OScore = Math.min(OScore[0], OScore[1]); NewHue = rgbToHue(imgData.data[i], imgData.data[i + 1], imgData.data[i + 2])[1]; PicHue = rgbToHue(imgData2.data[i], imgData2.data[i + 1], imgData2.data[i + 2])[1]; OldHue = rgbToHue(imgData3.data[i], imgData3.data[i + 1], imgData3.data[i + 2])[1]; NScore += Math.abs(NewHue-PicHue); OScore += Math.abs(OldHue-PicHue); NewHue = rgbToHue(imgData.data[i], imgData.data[i + 1], imgData.data[i + 2])[2]; PicHue = rgbToHue(imgData2.data[i], imgData2.data[i + 1], imgData2.data[i + 2])[2]; OldHue = rgbToHue(imgData3.data[i], imgData3.data[i + 1], imgData3.data[i + 2])[2]; N += Math.abs(NewHue-PicHue) + NScore; O += Math.abs(OldHue-PicHue) + OScore; } function rgbToHue(r, g, b) { if (Math.max(r, g, b) - Math.min(r, g, b) < 50) { rgb = true } r /= 255, g /= 255, b /= 255; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; if (max == min) { h = s = 0; // achromatic } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return [h,s,l]; } //Create a 4x4 ImageData object, random color selected from the colors var, transparent corners. function paintBucket() { color = Math.floor(Math.random() * 28); imgData = draw.createImageData(4, 4); imgData2 = draw.getImageData(x, y, 4, 4); i = 0; createCorn(); createColor(); createColor(); createCorn(); for (l = 0; l < 8; l++) { createColor(); } createCorn(); createColor(); createColor(); createCorn(); } function createCorn() { imgData.data[i] = imgData2.data[i]; imgData.data[i + 1] = imgData2.data[i + 1]; imgData.data[i + 2] = imgData2.data[i + 2]; imgData.data[i + 3] = 255; i += 4; } function createColor() { imgData.data[i] = colors[color][0]; imgData.data[i + 1] = colors[color][1]; imgData.data[i + 2] = colors[color][2]; imgData.data[i + 3] = 255; i += 4; } ``` ``` <canvas id="canvas" hidden></canvas> <br> <canvas id="data" hidden></canvas> <br> <input type="file" id="file"></input> <br> <img id="img"> <img id="reload" hidden> <p>Algorithms:</p> <select id="selectCord"> <option value="1">Random</option> <option value="2">Random Alligned</option> <option value="3" selected>Loop</option> </select> <select id="selectColor"> <option value="2000">Super Speedy</option> <option value="1000">Very Speedy</option> <option value="500" selected>Speedy</option> <option value="1">Visual</option> </select> <select id="colorDif"> <option value="RGB" selected>RGB</option> <option value="HSL">HSL</option> <option value="HSV">HSV</option> </select> <p>Algorithm Options: <br> </p> <p>X Offset: <input id="allignX" type="range" min="0" max="3" value="0"></input> </p> <p>Y Offset: <input id="allignY" type="range" min="0" max="3" value="0"></input> </p> <p>Spacing X: <input id="loopX" type="range" min="1" max="4" value="2"></input> </p> <p>Spacing Y: <input id="loopY" type="range" min="1" max="4" value="2"></input> </p> ``` ![enter image description here](https://i.stack.imgur.com/P7X6g.jpg) RGB: ![enter image description here](https://i.stack.imgur.com/ozxgy.png) HSL: ![enter image description here](https://i.stack.imgur.com/IEE82.png) HSV: ![enter image description here](https://i.stack.imgur.com/pGz8Z.png) [Answer] ## C# (reference implementation) This is the code used to generate the images in the question. I thought it would be useful to give some people a reference for organizing their algorithm. A completely random coordinate and color are selected each movement. It performs surprisingly well considering the limitations imposed by the brush size/acceptance criteria. I use the CIEDE2000 algorithm for measuring color differences, from the open source library [ColorMine](https://github.com/THEjoezack/ColorMine). This should give closer color matches (from a human perspective) but it doesn't seem to be a noticeable difference when used with this palette. ``` using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using ColorMine.ColorSpaces; using ColorMine.ColorSpaces.Comparisons; namespace Painter { public class Painter { private readonly Bitmap _source; private readonly Bitmap _painting; private readonly int _width; private readonly int _height; private readonly CieDe2000Comparison _comparison = new CieDe2000Comparison(); private const int BRUSHSIZE = 4; private readonly Random _random = new Random(); private readonly ColorPalette _palette; private static readonly int[][] BRUSH = { new[] {1, 0}, new[] {2, 0}, new[] {0, 1}, new[] {1, 1}, new[] {2, 1}, new[] {3, 1}, new[] {0, 2}, new[] {1, 2}, new[] {2, 2}, new[] {3, 2}, new[] {1, 3}, new[] {2, 3} }; public Painter(string sourceFilename, string paletteFilename) { _source = (Bitmap)Image.FromFile(sourceFilename); _width = _source.Width; _height = _source.Height; _palette = Image.FromFile(paletteFilename).Palette; _painting = new Bitmap(_width, _height, PixelFormat.Format8bppIndexed) {Palette = _palette}; // search for black in the color palette for (int i = 0; i < _painting.Palette.Entries.Length; i++) { Color color = _painting.Palette.Entries[i]; if (color.R != 0 || color.G != 0 || color.B != 0) continue; SetBackground((byte)i); } } public void Paint() { // pick a color from the palette int brushIndex = _random.Next(0, _palette.Entries.Length); Color brushColor = _palette.Entries[brushIndex]; // choose coordinate int x = _random.Next(0, _width - BRUSHSIZE + 1); int y = _random.Next(0, _height - BRUSHSIZE + 1); // determine whether to accept/reject brush if (GetBrushAcceptance(brushColor, x, y)) { BitmapData data = _painting.LockBits(new Rectangle(0, y, _width, BRUSHSIZE), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed); byte[] bytes = new byte[data.Height * data.Stride]; Marshal.Copy(data.Scan0, bytes, 0, bytes.Length); // apply 4x4 brush without corners foreach (int[] offset in BRUSH) { bytes[offset[1] * data.Stride + offset[0] + x] = (byte)brushIndex; } Marshal.Copy(bytes, 0, data.Scan0, bytes.Length); _painting.UnlockBits(data); } } public void Save(string filename) { _painting.Save(filename, ImageFormat.Png); } private void SetBackground(byte index) { BitmapData data = _painting.LockBits(new Rectangle(0, 0, _width, _height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); byte[] bytes = new byte[data.Height * data.Stride]; for (int i = 0; i < data.Height; i++) { for (int j = 0; j < data.Stride; j++) { bytes[i*data.Stride + j] = index; } } Marshal.Copy(bytes, 0, data.Scan0, bytes.Length); _painting.UnlockBits(data); } private bool GetBrushAcceptance(Color brushColor, int x, int y) { double currentDifference = 0.0; double brushDifference = 0.0; foreach (int[] offset in BRUSH) { Color sourceColor = _source.GetPixel(x + offset[0], y + offset[1]); Rgb sourceRgb = new Rgb {R = sourceColor.R, G = sourceColor.G, B = sourceColor.B}; Color currentColor = _painting.GetPixel(x + offset[0], y + offset[1]); currentDifference += sourceRgb.Compare(new Rgb {R = currentColor.R, G = currentColor.G, B = currentColor.B}, _comparison); brushDifference += sourceRgb.Compare(new Rgb {R = brushColor.R, G = brushColor.G, B = brushColor.B}, _comparison); } return brushDifference < currentDifference; } } } ``` Then you can generate series of images (like my video) by calling an instance in a way similar to the code below (tweak based on number of iterations/frames/name desired). The first argument is the file path to the source image, the second argument is the file path to the palette (linked in the question), and the third argument is the file path for output images. ``` namespace Painter { class Program { private static void Main(string[] args) { int i = 0; int counter = 1; Painter painter = new Painter(args[0], args[1]); while (true) { painter.Paint(); if (i%500000 == 0) { counter++; painter.Save(string.Format("{0}{1:D7}.png", args[2], counter)); } i++; } } } } ``` I searched for some colorful canvas paintings online and came across the images below, which seem to be great (complicated) test images. All copyrights belong to their respective owners. ![enter image description here](https://i.stack.imgur.com/TMCg2.jpg)![enter image description here](https://i.stack.imgur.com/OGrH9.png) [Source](http://afremov.com/MISTY-MOOD-PALETTE-KNIFE-Oil-Painting-On-Canvas-By-Leonid-Afremov-Size-24-x40.html) ![enter image description here](https://i.stack.imgur.com/19I5G.jpg)![enter image description here](https://i.stack.imgur.com/UXdm0.png) [Source](http://leonidafremov.deviantart.com/art/Original-oil-on-canvas-painting-360384649) ![enter image description here](https://i.stack.imgur.com/aFUEf.jpg)![enter image description here](https://i.stack.imgur.com/D25XL.png) [Source](http://leonidafremov.deviantart.com/art/Night-umbrellas-by-Leonid-Afremov-361873712) [Answer] # JavaScript Canvas **Update** Excellent suggestions in the comments. It's now faster and doesn't slow down the ui! ``` function previewFile() { var srcImage = document.getElementById('srcImage'); var file = document.querySelector('input[type=file]').files[0]; var reader = new FileReader(); reader.onloadend = function() { srcImage.src = reader.result; } if (file) { reader.readAsDataURL(file); } else { srcImage.src = ""; } } var buckets = []; // buckets / iterations var iter_per_focus = 5000; var pal = "00FFFF,0000FF,00FF00,FFFF00,\ C0C0C0,FF0000,FF00FF,FFFF78,\ FF0078,FF7848,7878FF,78FFFF,\ 00FF78,784800,007800,\ 007878,787800,780000,787878,\ 000078,780078,004878,7800FF,\ 0078FF,004848,787848,000000,FFFFFF".split(","); var pLen = pal.length; var p = 0; var _R = 0; var _G = 1; var _B = 2; var _CAN = 3; // Create fast access palette with r,g,b values and // brush image for color. function initPal() { for (var i = 0; i < pal.length; i++) { var r = parseInt(pal[i].substr(0, 2), 16); var g = parseInt(pal[i].substr(2, 2), 16); var b = parseInt(pal[i].substr(4, 2), 16); var pcan = document.createElement('canvas'); pcan.width = 4; pcan.height = 4; var pctx = pcan.getContext('2d'); pctx.fillStyle = '#' + pal[i]; pctx.beginPath(); pctx.rect(1, 0, 2, 4); pctx.rect(0, 1, 4, 2); pctx.fill(); pal[i] = [r,g,b,pcan]; } } initPal(); var score = []; var can = document.getElementById("canB"); var ctx = can.getContext('2d'); var mainDiv = document.getElementById("main"); var bCan = document.createElement('canvas'); bCan.width = can.width; bCan.height = can.height; var bCtx = bCan.getContext('2d'); var canA = document.getElementById("canA"); can.width = can.height = canA.width = canA.height = 200; var ctxA = canA.getContext('2d'); var imageData; var data; function getSrcImage() { var img = document.getElementById('srcImage'); can.width = canA.width = img.width; can.height = canA.height = img.height; ctxA.drawImage(img, 0, 0); imageData = ctxA.getImageData(0, 0, img.width, img.height); data = imageData.data; // adjust for brush offset var w = can.width - 2; var h = can.height - 2; var n = Math.floor((w * h) / iter_per_focus); buckets = []; for (var i = 0; i < n; i++) { var bucket = []; bucket.r = Math.floor(Math.random() * pLen); buckets.push(bucket); } var b = 0; var pt = 0; for (var y = 0; y < h; y++) { for (var x = 0; x < w; x++, pt+=4) { var r = Math.floor((Math.random() * n)); buckets[r].push([x,y,pt,256 * 12,Math.floor(Math.random()*pLen)]); b %= n; } pt += 8; // move past brush offset. } } var loopTimeout = null; function loopInit() { var r, y, x, pt, c, s; var row = can.width * 4; var b = 0; function loop() { clearTimeout(loopTimeout); var bucket = buckets[b++]; var len = bucket.length; // Stepping color //c = pal[p]; // Pulsing color; //c = pal[Math.floor(Math.random()*pLen)] // Pulsting step c = pal[bucket.r++]; bucket.r%=pLen; b %= buckets.length; if (b === 0) { p++; p%=pLen; } for (var i = 0; i < len; i++) { var x = bucket[i][0] var y = bucket[i][1]; var pt = bucket[i][2]; // Random color //c = pal[bucket[i][4]++]; //bucket[i][4]%=pLen; s = Math.abs(data[pt] - c[_R]) + Math.abs(data[pt + 1] - c[_G]) + Math.abs(data[pt + 2] - c[_B]) + Math.abs(data[pt + 4] - c[_R]) + Math.abs(data[pt + 5] - c[_G]) + Math.abs(data[pt + 6] - c[_B]) + Math.abs(data[pt + row] - c[_R]) + Math.abs(data[pt + row + 1] - c[_G]) + Math.abs(data[pt + row + 2] - c[_B]) + Math.abs(data[pt + row + 4] - c[_R]) + Math.abs(data[pt + row + 5] - c[_G]) + Math.abs(data[pt + row + 6] - c[_B]); if (bucket[i][3] > s) { bucket[i][3] = s; bCtx.drawImage(c[_CAN], x - 1, y - 1); } } loopTimeout = setTimeout(loop, 0); } loop(); } // Draw function is separate from rendering. We render // to a backing canvas first. function draw() { ctx.drawImage(bCan, 0, 0); setTimeout(draw, 100); } function start() { getSrcImage(); imageData = ctxA.getImageData(0, 0, can.width, can.height); data = imageData.data; bCan.width = can.width; bCan.height = can.height; bCtx.fillStyle = "black"; bCtx.fillRect(0, 0, can.width, can.height); loopInit(); draw(); } ``` ``` body { background-color: #444444; color: #DDDDEE; } #srcImage { display: none; } #testBtn { display: none; } #canA { display:none; } ``` ``` <input type="file" onchange="previewFile()"> <br> <img src="" height="200" alt="Upload Image for MS Painting"> <button onclick="genImage()" id="testBtn">Generate Image</button> <div id="main"> <img id="srcImage" src="" onload="start()"> <canvas id="canA"></canvas> <canvas id="canB"></canvas> </div> ``` [Answer] ## Mathematica It's not really all that fast though, but at least it makes vaguely recognisable images, so I'm happy. ``` img = Import["https://i.stack.imgur.com/P7X6g.jpg"] squigglesize = 20; squiggleterb = 35; colors = Import["https://i.stack.imgur.com/u9JAD.png"]; colist = Table[RGBColor[PixelValue[colors, {x, 1}]], {x, 28}]; imgdim0 = ImageDimensions[img]; curimg = Image[ConstantArray[0, Reverse[imgdim0]]]; rp := RandomInteger[squigglesize, 2] - squigglesize/2; i = 0; j = 0; Module[{imgdim = imgdim0, randimg, points, randcol, squigmid, st, randist, curdist = curdist0, i = 0, j = 0}, While[j < 10, squigmid = {RandomInteger[imgdim[[1]]], RandomInteger[imgdim[[1]]]}; While[i < 20, randcol = RandomChoice[colist]; st = RandomInteger[squiggleterb, 2] - squiggleterb/2; points = {rp + squigmid + st, rp + squigmid + st, rp + squigmid + st, rp + squigmid + st}; randimg = Rasterize[ Style[Graphics[{Inset[curimg, Center, Center, imgdim], {randcol, BezierCurve[Table[{-1, 0}, {4}] + points]}, {randcol, BezierCurve[Table[{-1, 1}, {4}] + points]}, {randcol, BezierCurve[Table[{0, -1}, {4}] + points]}, {randcol, BezierCurve[points]}, {randcol, BezierCurve[Table[{0, 1}, {4}] + points]}, {randcol, BezierCurve[Table[{0, 2}, {4}] + points]}, {randcol, BezierCurve[Table[{1, -1}, {4}] + points]}, {randcol, BezierCurve[Table[{1, 0}, {4}] + points]}, {randcol, BezierCurve[Table[{1, 1}, {4}] + points]}, {randcol, BezierCurve[Table[{1, 2}, {4}] + points]}, {randcol, BezierCurve[Table[{2, 0}, {4}] + points]}, {randcol, BezierCurve[Table[{2, 1}, {4}] + points]} }, ImageSize -> imgdim, PlotRange -> {{0, imgdim[[1]]}, {0, imgdim[[2]]}}], Antialiasing -> False], RasterSize -> imgdim]; randist = ImageDistance[img, randimg]; If[randist < curdist, curimg = randimg; curdist = randist; i = 0; j = 0;]; i += 1; ]; j += 1; i = 0;]; Print[curimg]] ``` Output: ![input](https://i.stack.imgur.com/P7X6g.jpg) ![Output](https://i.stack.imgur.com/lY6tw.png) ![input](https://i.stack.imgur.com/Qe7Jr.jpg) ![output](https://i.stack.imgur.com/36gx1.png) Output could probably be a bit better with more iterations, and there's still a lot that I can try to speed it up/improve convergence, but for now this seems good enough. [Answer] # SmileBASIC ``` OPTION STRICT OPTION DEFINT DEF MSPAINT(IMAGE,WIDTH,HEIGHT,STEPS) 'read color data DIM COLORS[28] COPY COLORS%,@COLORS @COLORS DATA &H000000,&H808080,&H800000 DATA &H808000,&H008000,&H008080 DATA &H000080,&H800080,&H808040 DATA &H004040,&H0080FF,&H004080 DATA &H8000FF,&H804000,&HFFFFFF DATA &HC0C0C0,&HFF0000,&HFFFF00 DATA &H00FF00,&H00FFFF,&H0000FF DATA &HFF00FF,&HFFFF80,&H00FF80 DATA &H80FFFF,&H8080FF,&HFF0080 DATA &HFF8040 'create output array and fill with white DIM OUTPUT[WIDTH,HEIGHT] FILL OUTPUT,&HFFFFFFFF VAR K FOR K=1 TO STEPS 'Pick random position/color VAR X=RND(WIDTH -3) VAR Y=RND(HEIGHT-3) VAR COLOR=COLORS[RND(28)] 'Extract average (really the sum) color in a 4x4 area. 'this is less detailed than checking the difference of every pixel 'but it's better in some ways... 'corners are included so it will do SOME dithering 'R1/G1/B1 = average color in original image 'R2/G2/B2 = average color in current drawing 'R3/G3/B3 = average color if brush is used VAR R1=0,G1=0,B1=0,R2=0,G2=0,B2=0,R3=0,G3=0,B3=0 VAR R,G,B VAR I,J FOR J=0 TO 3 FOR I=0 TO 3 'original image average RGBREAD IMAGE[Y+J,X+I] OUT R,G,B INC R1,R INC G1,G INC B1,B 'current drawing average RGBREAD OUTPUT[Y+J,X+I] OUT R,G,B INC R2,R INC G2,G INC B2,B 'add the old color to the brush average if we're in a corner IF (J==0||J==3)&&(I==0||I==3) THEN INC R3,R INC G3,G INC B3,B ENDIF NEXT NEXT 'brush covers 12 pixels RGBREAD COLOR OUT R,G,B INC R3,R*12 INC G3,G*12 INC B3,B*12 'Compare BEFORE=ABS(R1-R2)+ABS(G1-G2)+ABS(B1-B2) AFTER =ABS(R1-R3)+ABS(G1-G3)+ABS(B1-B3) 'Draw if better IF AFTER<BEFORE THEN FILL OUTPUT,COLOR, Y *WIDTH+X+1,2 ' ## FILL OUTPUT,COLOR,(Y+1)*WIDTH+X ,4 '#### FILL OUTPUT,COLOR,(Y+2)*WIDTH+X ,4 '#### FILL OUTPUT,COLOR,(Y+3)*WIDTH+X+1,2 ' ## ENDIF NEXT RETURN OUTPUT END ``` **MSPAINT** *image%[]* **,** *width%* **,** *height%* **,** *steps%* **OUT** *output%[]* * image% - 2D [y,x] integer array with the image data (32 bit ARGB format (alpha is ignored)) * width% - image width * height% - image height * steps% - number of iterations * output% - output array, same as image%. [![enter image description here](https://i.stack.imgur.com/9YUHf.jpg)](https://i.stack.imgur.com/9YUHf.jpg) [Answer] # Java + Processing I saw this challenge and immediately had to try it. My algorithm isn't too well optimized, so the output is a bit choppy. ``` color[] palette={#000000,#FFFFFF,#C0C0C0,#808080,#7E0308,#FC0D1B,#FFFD38,#807F17,#0F7F12,#29FD2E,#2DFFFE,#11807F,#020C7E,#0B24FB,#FC28FC,#7F0F7E,#807F44,#FFFD88,#2AFD85,#044040,#1783FB,#85FFFE,#8184FC,#06427E,#7F25FB,#7F400D,#FD8049,#FC1681}; PImage p; int currTime; int sTime=0; int yPix; void settings() { p=loadImage("arun-clarke-V-bkeYsTflY-unsplash.jpg"); yPix = 0; size(p.width,p.height); } void setup() { frameRate(p.width); noStroke(); rectMode(CENTER); //image(p,0,0); //for(int i=0; i<palette.length;i++) { // fill(palette[i]); // square(i*20,0, 20); //} } void draw() { int x = int(random(p.width)); int y = int(random(p.height)); color randPix = p.get(x,y); float[] d = new float[palette.length]; for(int k=0;k<palette.length;k++) { d[k]=abs(red(randPix)-red(palette[k]))+abs(blue(randPix)-blue(palette[k]))+abs(green(randPix)-green(palette[k])); }int b=0; for(int l=0;l<palette.length;l++){ if(d[l]<=d[b]){ b=l; } } fill(palette[b]); rect(x,y,2,4); rect(x,y,4,2); } void mouseClicked() { noLoop(); save("c.png"); } ``` # Examples [![enter image description here](https://i.stack.imgur.com/i3HQD.jpg)](https://i.stack.imgur.com/i3HQD.jpg)[![enter image description here](https://i.stack.imgur.com/hjxrp.png)](https://i.stack.imgur.com/hjxrp.png) [![enter image description here](https://i.stack.imgur.com/0ZV3o.jpg)](https://i.stack.imgur.com/0ZV3o.jpg)[![enter image description here](https://i.stack.imgur.com/u7O1U.png)](https://i.stack.imgur.com/u7O1U.png) ]
[Question] [ Consider the positive integer powers of five in decimal. Here are the first 25, right aligned: ``` X 5^X 1 5 2 25 3 125 4 625 5 3125 6 15625 7 78125 8 390625 9 1953125 10 9765625 11 48828125 12 244140625 13 1220703125 14 6103515625 15 30517578125 16 152587890625 17 762939453125 18 3814697265625 19 19073486328125 20 95367431640625 21 476837158203125 22 2384185791015625 23 11920928955078125 24 59604644775390625 25 298023223876953125 ``` Notice that the rightmost column of the powers is all `5`'s. The second column from the right is all `2`'s. The third column from the right, read from top to bottom, alternates `1`, `6`, `1`, `6`, etc. The next column starts `3`, `5`, `8`, `0` and then cycles. In fact, every column (if we go down far enough) has a cycling sequence of digits whose length is twice that of the previous cycle, except for the initial `5`'s and `2`'s cycles. Calling N the column number, starting with N = 1 at the right, the first few cycles are: ``` N cycle at column N 1 5 2 2 3 16 4 3580 5 17956240 6 3978175584236200 7 19840377976181556439582242163600 8 4420183983595778219796176036355599756384380402237642416215818000 ``` # Challenge Given a positive integer N, output the decimal digits of the cycle at column N, as described above. For example, the output for N = 4 would be `3580`. The digits may be output as a list such as `[3, 5, 8, 0]` or in another reasonable format so long as: * The digits are in order as read from top to bottom in the power columns. e.g. `0853` is invalid. * The cycle starts with the top number in its power column. e.g. `5803` is invalid as the 4th column starts with `3` not `5`. * Exactly one cycle is output. e.g. `358` or `35803` or `35803580` would all be invalid. Your code must work for at least N = 1 through 30. If desired you may assume the columns are 0-indexed instead of 1-indexed. So N = 0 gives `5`, N = 1 gives `2`, N = 2 gives `16`, N = 3 gives `3580`, etc. **The shortest code in bytes wins**. Thanks to [Downgoat](https://chat.stackexchange.com/transcript/message/35570305#35570305) and [DJ](https://chat.stackexchange.com/transcript/message/35570804#35570804) for challenge support. [Answer] # Python 2, ~~62~~ ~~61~~ 58 bytes Zero-based. I assume the L suffixes are acceptable. ``` lambda n:[5**(n*3/7-~i)/2**n%10for i in range(2**n/2or 1)] ``` Output: ``` 0 [5] 1 [2] 2 [1, 6] 3 [3, 5, 8, 0] 4 [1, 7, 9, 5, 6, 2, 4, 0] 5 [3, 9, 7, 8, 1, 7, 5, 5, 8, 4, 2, 3, 6, 2, 0, 0] 6 [1, 9, 8, 4, 0, 3, 7, 7, 9, 7, 6, 1, 8, 1, 5, 5, 6, 4, 3, 9, 5, 8, 2, 2, 4, 2L, 1L, 6L, 3 L, 6L, 0L, 0L] 7 [4, 4, 2, 0, 1, 8, 3, 9, 8, 3, 5, 9, 5, 7, 7, 8, 2, 1, 9, 7, 9, 6, 1, 7, 6L, 0L, 3L, 6L, 3L, 5L, 5L, 5L, 9L, 9L, 7L, 5L, 6L, 3L, 8L, 4L, 3L, 8L, 0L, 4L, 0L, 2L, 2L, 3L, 7L, 6L, 4L, 2L, 4L, 1L, 6L, 2L, 1L, 5L, 8L, 1L, 8L, 0L, 0L, 0L] ``` Previous solution: ``` lambda n:[5**int(n/.7-~i)/10**n%10for i in range(2**n/2or 1)] lambda n:[str(5**int(n/.7-~i))[~n]for i in range(2**n/2)]or 5 ``` --- Explanation: ``` def f(n): r = max(2**n / 2, 1) m = int(n/0.7 + 1) for i in range(r): yield (5**(m+i) / 10**n) % 10 ``` The `range(2**n/2)` uses the observation that [each cycle has length r = 2n-1](https://codegolf.stackexchange.com/questions/111247/5-2-16-3580-what-comes-next#comment270978_111247) except when n = 0, so we just compute the n-th digits for 5m to 5m + r - 1. The start of the cycle 5m is the first number larger than 10n. Solving 5m ≥ 10n gives m ≥ n / log10 5. Here we approximate log10 5 ≈ 0.7 which will break down when n = 72. We could add more digits to increase the accuracy: ``` | approximation | valid until | penalty | |---------------------------|--------------------|-----------| | .7 | n = 72 | +0 bytes | | .699 | n = 137 | +2 bytes | | .69897 | n = 9297 | +4 bytes | | .698970004 | n = 29384 | +8 bytes | | .6989700043 | n = 128326 | +9 bytes | | .6989700043360189 | too large to check | +15 bytes | | import math;math.log10(5) | same as above | +23 bytes | ``` The `/ 10**n % 10` in the loop simply extract the desired digit. Another alternative solution uses string manipulation. I used [the trick `~n == -n-1`](https://codegolf.stackexchange.com/a/37553/32353) here to remove 1 byte. An mentioned in the comment, the expression `5**(m+i) / 10**n` can further be simplified this way, which gives the current 58-byte answer. [![enter image description here](https://i.stack.imgur.com/WmTPr.png)](https://i.stack.imgur.com/WmTPr.png) (The division `x/2**n` can be done using bitwise right-shift `x>>n`. Unfortunately, due to Python's operator precedence this does not save any bytes.) The fraction 3/7 can also be improved in similar mannar: ``` | approximation | valid until | penalty | |---------------------------------|---------------------|-----------| | n*3/7 | n = 72 | +0 bytes | | n*31/72 | n = 137 | +2 bytes | | n*59/137 | n = 476 | +3 bytes | | n*351/815 | n = 1154 | +4 bytes | | n*643/1493 | n = 10790 | +5 bytes | | n*8651/20087 | n = 49471 | +7 bytes | | int(n*.43067655807339306) | too large to check | +20 bytes | | import math;int(n/math.log2(5)) | same as above | +26 bytes | ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 72 bytes ``` [3Q]sq2?dsa^1+2/dsusk[Ola^/O%plk1-dsk1>q]sp1[d5r^dOla^<psz1+d4/lu>t]dstx ``` 0-based indexing. This uses exact integer arithmetic -- no logarithm approximations. It will work up to the memory capacity of the computer. [Try the dc program online!](https://tio.run/nexus/dc#@x9tHBhbXGhkn1KcGGeobaSfUlxanB3tn5MYp@@vWpCTbaibUpxtaFcYW1xgGJ1iWhSXApKzKSiuMtROMdHPKbUriU0pLqn4/98EAA "dc – TIO Nexus") --- The dc code can be turned into a Bash solution: # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~96~~ ~~77~~ 75 bytes ``` u=$[(2**$1+1)/2] dc -e "[O$1^/O%p]sp1[d5r^dO$1^<psz1+d4/$u>t]dstx"|head -$u ``` [Try the Bash version online!](https://tio.run/nexus/bash#@19qqxKtYaSlpWKobaipbxTLlZKsoJuqoBTtr2IYp@@vWhBbXGAYnWJaFJcCErEpKK4y1E4x0VcptSuJTSkuqVCqyUhNTFHQVSn9//@/CQA "Bash – TIO Nexus") [Answer] # Mathematica, ~~66~~ ~~60~~ 52 bytes ``` Floor@Mod[5^Floor[Range@Max[2^#/2,1]+#/.7]/10^#,10]& ``` Anonymous function, 0-indexed. Uses approximation of log5(10) (≈ 0.7) ### How it works? ``` Range@Max[2^#/2,1] ``` Take larger of 2^(input)/2 and 1. Generate {1..that number} ``` ...+#/.7 ``` Add input/.7 ``` 5^Floor[...]/10^# ``` Raise 5 to the power of the result (generating powers of 5), divide by 10^input (getting rid of digits to the right of the desired column) ``` Mod[ ...,10] ``` Apply modulo 10, taking the one's digit (the desired column). ### Exact version, 58 bytes ``` Floor@Mod[5^Floor[Range@Max[2^#/2,1]+#/5~Log~10]/10^#,10]& ``` [Answer] # JavaScript (ES7), ~~78~~ 76 bytes ``` f=(N,z=5,s,X=2**N,q=z/10**N|0)=>s|q?X>0?q+f(N,z*5%10**-~N,1,X-2):"":f(N,z*5) ``` 0-indexed, i.e. `f(0)` gives `2`. ### Test snippet ``` f=(N,z=5,s,X=1<<N,q=z/Math.pow(10,N)|0)=>s|q?X>0?q+f(N,z*5%Math.pow(10,-~N),1,X-2):"":f(N,z*5) for (let i = 0; i < 10; i++) console.log(`f(${i}):`, f(i)); ``` The snippet uses `Math.pow` instead of `**` for cross-browser compatability. [Answer] # CJam, 35 ``` 5ri(:N.7/i)#2N(#mo{_AN#/o5*AN)#%}*; ``` [Try it online](http://cjam.aditsu.net/#code=5ri(%3AN.7%2Fi)%232N(%23mo%7B_AN%23%2Fo5*AN)%23%25%7D*%3B&input=8) It is space-efficient and not exceedingly slow, took several minutes for input 30 on my computer (using the java interpreter). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26~~ 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 bytes using kennytm's **0.7** approximation idea ``` 2*HĊR+÷.7$Ḟ*@5:⁵*⁸¤%⁵ ``` **[Try it online!](https://tio.run/nexus/jelly#@2@k5XGkK0j78HY9c5WHO@ZpOZhaPWrcqvWoccehJapA1v///80B)** (times out for **n>15**) Returns a list of integers, the digits. Zero based. Theoretically works for **n<=72** (replace `.7` with `5l⁵¤`, to get floating point accuracy). ### How? ``` 2*HĊR+÷.7$Ḟ*@5:⁵*⁸¤%⁵ - Main link: n 2* - 2 raised to the power of n H - halved: 2 raised to the power of n-1 Ċ - ceiling: adjust 2**-1 = 0.5 up to 1 for the n=0 edge case R - range: [1,2,...,ceiling(2**(n-1))] - has length of the period $ - last two links as a monad: ÷.7 - divide by 0.7 (approximation of log(5, 10), valid up to n=72) + - add (vectorises) Ḟ - floor (vectorises) 5 - 5 *@ - exponentiate (vectorises) with reversed @arguments ¤ - nilad followed by link(s) as a nilad ⁵ - 10 ⁸ - left argument, n * - exponentiate: 10 raised to the power of n : - integer division: strips off last n digits %⁵ - mod 10: extracts the last digit ``` *Locally:* the working set memory for **n=17** climbed to around **750MB** then spiked to around **1GB**; for **n=18** it slowly reached **2.5GB** then spiked to around **5GB**. [Answer] # [Perl 6](https://perl6.org), 52 bytes ``` ->\n{(map {.comb[*-n]//|()},(5 X**1..*))[^(2**n/4)]} ``` Works for arbitrarily high inputs, given sufficient memory *(i.e. no logarithm approximation)*. Returns a list of digits. [Try it online!](https://tio.run/nexus/perl6#y61UUEtTsP2vaxeTV62Rm1igUK2XnJ@bFK2lmxerr1@joVmro2GqEKGlZainp6WpGR2nYaSlladvohlb@7@gtEQhTUMlXlMvKz8zTyEtv0gBqMrS@j8A "Perl 6 – TIO Nexus") ### How it works ``` ->\n{ } # A lambda with argument n. (5 X**1..*) # The sequence 5, 25, 125, 625... map { }, # Transform each element as such: .comb[*-n] # Extract the n'th last digit, //|() # or skip it if that doesn't exist. ( )[^(2**n/4)] # Return the first 2^(n-2) elements. ``` The "element skipping" part works like this: * Indexing a list at an illegal index returns a [Failure](https://docs.perl6.org/type/Failure), which counts as an "undefined" value. * [`//`](https://docs.perl6.org/language/operators.html#infix_//) is the "defined or" operator. * `|()` returns an empty [Slip](https://docs.perl6.org/type/Slip), which dissolves into the outer list as 0 elements, essentially making sure that the current element is skipped. The edge-case `n=1` works out fine, because `2**n/4` becomes `0.5`, and `^(0.5)` means `0 ..^ 0.5` a.k.a. "integers between 0 (inclusive) and 0.5 (not inclusive)", i.e. a list with the single element 0. [Answer] # J, 50 bytes ``` (2^0>.2-~]){.' '-.~-{"1[:([:":[:|:[:,:5^[:>:i.)2^] ``` Note: must pass in extended number Usage: ``` q =: (2^0>.2-~]){.' '-.~-{"1[:([:":[:|:[:,:5^[:>:i.)2^] q 1x 5 q 2x 2 q 4x 3580 ``` [Answer] # [Haskell](https://www.haskell.org/), 73 bytes ``` f 0="5" f n=take(2^(n-1))[reverse x!!n|x<-show<$>iterate(*5)1,length x>n] ``` [Try it online!](https://tio.run/nexus/haskell#@5@mYGCrZKrElaaQZ1uSmJ2qYRSnkadrqKkZXZRallpUnKpQoaiYV1Nho1uckV9uo2KXWZJalFiSqqFlqmmok5Oal16SoVBhlxf7PzcxM0/BVqEoNTHFJ0/Bzs5WoaC0JLikSEFPIe2/CQA "Haskell – TIO Nexus") Uses 0-indexing. **Explanation:** ``` f 0="5" -- if the input is 0, return "5" f n= -- otherwise for input n take(2^(n-1)) -- return the first 2^(n-1) elements of the list [reverse x!!n -- of the nth column of x |x<-show<$> -- where x is the string representation iterate(*5)1 -- of the elements of the infinite list [5,25,125,...] ,length x>n -- if x has at least n+1 columns ] -- this yields a list of characters, which is equivalent to a string ``` [Answer] ## Batch, 294 bytes ``` @echo off if %1==1 echo 5 set/a"l=1<<%1-2,x=0,s=1 set t= for /l %%i in (2,1,%1)do call set t=%%t%%x :l if %l%==0 exit/b set t=%s%%t% set s= set c= :d set/ac+=%t:~,1%*5,r=c%%10,c/=10 set s=%s%%r% set t=%t:~1% if "%t%"=="" echo %r%&set/al-=1&goto l if %c%%t:~,1%==0x goto l goto d ``` Outputs each digit on its own line. Works by calculating the powers of 5 longhand, but only works up to `N=33` due to using 32-bit integers to keep count of how many digits to print. `s` contains the (reversed) last `N` digits of the current power of 5, while `t` contains `x`s used as padding, although the `x=0` makes them evaluate as zero when the next power is calculated. Example for `N=4`: ``` s t 1 xxx (initial values before the first power of 5 is calculated) 5 xxx 52 xx 521 x 526 x 5213 (print 3) 5265 (print 5) 5218 (print 8) 5260 (print 0) ``` [Answer] ## JavaScript (ES6), 73 bytes 1-indexed. Slightly shorter than the [ES7 answer](https://codegolf.stackexchange.com/a/111272/58563), but fails 3 steps earlier (at N=13). ``` n=>(g=x=>k>>n?'':(s=''+x*5%1e15)[n-1]?s.substr(-n,1)+g(s,k+=4):g(s))(k=1) ``` ### Demo ``` let f = n=>(g=x=>k>>n?'':(s=''+x*5%1e15)[n-1]?s.substr(-n,1)+g(s,k+=4):g(s))(k=1) console.log(f(1)) console.log(f(2)) console.log(f(3)) console.log(f(4)) console.log(f(5)) console.log(f(6)) console.log(f(7)) console.log(f(8)) ``` [Answer] # PHP>=7.1, 104 Bytes ``` for($s=1;$i++<2**(-1+$a=$argn);)~($s=bcmul($s,5))[-$a]?$g.=$s[-$a]:0;echo substr($g,0,max(2**($a-2),1)); ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/e42b2e197de989e2345fa75e5714d768a04ef7ef) [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes ``` !z↑+ḋ3İ2Tmod↔İ5 ``` [Try it online!](https://tio.run/##ASEA3v9odXNr//8heuKGkSvhuIszxLAyVG1vZOKGlMSwNf///zM "Husk – Try It Online") or [Verify first 10 values](https://tio.run/##AToAxf9odXNr/23CpysoYCsiIOKGkiAicykoc@KCgSnhuKMxMP8heuKGkSvhuIszxLAyVG1vZOKGlMSwNf// "Husk – Try It Online") ## Explanation ``` !z↑+ḋ3İ2Tmod↔İ5 İ5 list of powers of 5 mod↔ reverse each and convert to digits T transpose to get repeating columns z↑ zip with take using: +ḋ3İ2 powers of 2 with [1,1] added ! return the nth element ``` ]
[Question] [ The task is taken from an MIT lecture by Prof. Devadas called [You can read minds](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-s095-programming-for-the-puzzled-january-iap-2018/puzzle-3-you-can-read-minds/). A detailed explanation of the trick can be found in the linked video, or in [this document](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-s095-programming-for-the-puzzled-january-iap-2018/puzzle-3-you-can-read-minds/MIT6_S095IAP18_Puzzle_3.pdf). I'll try to explain it in simpler terms. It turns out this was invented in the 1930's, and is known as the **"Five-Card Trick of Fitch Cheney"**. --- The trick goes like this: * Five random cards are chosen from a deck of cards. The audience and your assistant get to see them, but you don't. * Your assistant (with whom you have practiced) will select four of those cards and show them to you in a specific order. Note that the hidden card is not randomly picked from the 5 cards. The assistant picks a/the card that will make the trick work. * You will deduce, based on the information you can gather from the four cards what the fifth card is. --- ## How? Keep the following two points in mind: 1. When choosing 5 random cards, you are guaranteed that *at least* two cards have the same suit1. 2. The image below shows a circle with all the ranks2. Since it's a circle, it's possible to count: **J, Q, K, A, 2, 3** (i.e. modular counting). You are guaranteed that the hidden card does not have the same rank as the first, since they will be of the same suit (explained below). It's always possible to choose the first card and the hidden cards such that the hidden card is between 1 and 6 ranks higher than the first (when counting in circles). If the first card is **1**, then the hidden card will be **2,3,4,5,6 or 7**. If the first card is **J**, then the hidden card will be **Q,K,A,2,3 or 4** and so on. [![card ranks from A up to K arranged in a circle](https://i.stack.imgur.com/gckLE.png)](https://i.stack.imgur.com/gckLE.png) --- ## The algorithm: **The first card:** This card will have the same suit as the hidden card. The card will also be the reference point you'll use when figuring out the rank of the hidden card. **The 2nd, 3rd and 4th cards** decodes a value in the inclusive range **1 ... 6**. We'll call the three cards **S, M, L** (smallest card, middle card, largest card). The values will be encoded like this (lexicographic order): ``` S M L -> 1 S L M -> 2 M S L -> 3 M L S -> 4 L S M -> 5 L M S -> 6 ``` So, if the rank of the first card is **5**, and the remaining three cards have ranks **4 Q 7** (they are ordered **S L M**), then the last card has rank **5+2=7**. You may choose if the ace should be the highest or lowest card, as long as it's consistent. If several cards share rank, then the suit will determine the order, where **C < D < H < S**. --- ### Input format: The four cards will be given as **H3** (three of hearts), **DK** (King of diamonds) and so on. You may choose to take the input the other way around as **3H** and **KD** instead. The input can be on any convenient format, but you can't combine the list of suits in one variable and the list of ranks in another. `'D5', 'H3' ..` and `[['D',5],['H',3] ...` are both OK, but `'DHCH',[5,3,1,5]` is not. You can't use numbers instead of letters, except for **T**. ### Output The hidden card, in the same format as the input. --- ### Example Let's do a walkthrough: ``` Input: D3 S6 H3 H9 ``` We know the hidden card is a diamond, since the first card is a diamond. We also know that the rank is **4,5,6,7,8 or 9** since the rank of the first card is **3**. The remaining cards are ordered **6,3,9 ==> M,S,L**, which encodes the value **3**. The hidden card is therefore **3+3=6** of diamonds, thus the output should be **D6**. ### Test cases: ``` C3 H6 C6 S2 C9 # The order is LMS (H6 > C6, and 2 < 6). 3+6=9 SQ S4 S3 ST # (ST = S10. Format is optional) S2 # The order is MSL. 12+3=2 HA CA DA SA H2 # The order is SML. 14+1=2 ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in each language wins. Explanations are encouraged! --- 1There are four suits (**C**lubs, **D**iamonds, **H**earts and **S**pades). 2There are 13 ranks, **2,3,4,5,6,7,8,9,10,J,Q,K,A**. You may choose to use **T** instead of **10**. [Answer] # JavaScript (ES6), [~~130~~](https://codegolf.stackexchange.com/revisions/165398/9) 102 bytes Takes input as an array of strings in `"Rs"` format, where **R** is the rank and **s** is the suit. Expects **"T"** for 10's. Aces are low. ``` a=>(s='A23456789TJQK')[([[R,[,S]],B,C,D]=a.map(c=>[s.search(c[0])+14,c]),R+=D<C|2*((D<B)+(C<B)))%13]+S ``` [Try it online!](https://tio.run/##Zcw7D4IwFIbh3V/hYnoqFZTiLbEkBSaduGxNh6aiaFQINU7@d6QxOujy5gzP@c7qoYxuT819cqv3ZXdgnWIhGIa4T4P5YrlaF9t0h7AAITIiSC4liUhMEsmUe1UNaBYK45pStboCLaYSO7OAaIlJ5rBkEz/9MUCyibADcV@MRzMqnbzT9c3Ul9K91Ec4gEBUI4IWlY29fIMkxkPPG6714NemphfUhtsUX@ubP8vtJLeTfP9@@NiqewE "JavaScript (Node.js) – Try It Online") ### How? We first convert each card into an array **[rank, card]** where **rank** is a numeric value in **[14...26]** and **card** is the original string. ``` [[R, [, S]], B, C, D] = a.map(c => ['A23456789TJQK'.search(c[0]) + 14, c]) ``` The rank and suit of the first card are stored in **R** and **S** respectively. The three other cards are stored in **B**, **C** and **D**. For instance, `['3c','6h','6c','2s']` becomes: ``` [ [ 16, '3c' ], [ 19, '6h' ], [ 19, '6c' ], [ 15, '2s' ] ] ^^ ^ <----------> <----------> <----------> R S B C D ``` We then compare each pair in **[ B, C, D ]**. These elements are implicitly coerced to strings when they are compared with each other: ``` [ 19, '6h' ] --> '19,6h' ``` Because both **rank** and **card** are guaranteed to consist of exactly two characters, it is safe to compare in lexicographical order. We compute: ``` (D < C) | 2 * ((D < B) + (C < B)) ``` Below are all the possible combinations: ``` B, C, D | v0 = D < B | v1 = C < B | v2 = D < C | v2|2*(v0+v1) ---------+-------------+-------------+-------------+-------------- S, M, L | false | false | false | 0 S, L, M | false | false | true | 1 M, S, L | false | true | false | 2 M, L, S | true | false | true | 3 L, S, M | true | true | false | 4 L, M, S | true | true | true | 5 ``` Finally, we build the output card using **R**, **S** and the above result: ``` 'A23456789TJQK'[(R += D < C | 2 * ((D < B) + (C < B))) % 13] + S ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~143~~ ~~140~~ ~~138~~ ~~136~~ ~~127~~ ~~125~~ ~~124~~ ~~123~~ 121 bytes ``` lambda(S,V),*l:S+N[F(V)+int(`map(sorted(l,key=lambda(s,v):(F(v),s)).index,l)`[1::3],3)*3/10] N='23456789TJQKA'*2;F=N.find ``` [Try it online!](https://tio.run/##Rc1dC4IwFIDh@36F0MV2bFRuZWl4IYpIgRCLbkrQUCnyCxWpX29uRN28HA7P2ep3d69KOmTWdcjj4pbEmJMzEDU3@Sy4ePgMs0fZ4aiIa9xWTZcmOCfP9G19dUt6MLGHeyAtwPxRJumL5BBdNNNkIWGgsoW2DCeBhShbrfXN1jjtjwcbqXTnWcE8Gy@Guhn/UDKMXIYI4voYX0y@gUCZKq4@@QlH7oVwRDiVwjH@gh/FXj6kiZyk4PQvfFuci7gi3JbCp8MH "Python 2 – Try It Online") Aces are high --- Encodes the three cards by finding their position in a sorted list of the cards (`0=smallest, 1=middle, 2=largest`): ``` cards: [SK, C4, H4] sorted: [C4, H4, SK] ranks: [ 2 index of SK in sorted ranks: [ 2, 0 index of C4 in sorted ranks: [ 2, 0, 1 index of H4 in sorted ranks: [ 2, 0, 1] = L,S,M ``` This is converted to an integer in base 3 and multiplied by 3, and divided by 10: ``` int('201',3) = 19 -> 19*3//10 = 5 ``` The different encodings are: ``` cards base3 *3 /10 [0, 1, 2] 012 5 15 1 [0, 2, 1] 021 7 21 2 [1, 0, 2] 102 11 33 3 [1, 2, 0] 120 15 45 4 [2, 0, 1] 201 19 57 5 [2, 1, 0] 210 21 63 6 ``` --- Saved: * -2 bytes, thanks to ovs [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 33 bytes ``` ØDḊḊ;“TJQKA”p“CDHS” ¢iⱮµḊŒ¿×4+Ḣị¢ ``` [Try it online!](https://tio.run/##y0rNyan8///wDJeHO7qAyPpRw5wQr0Bvx0cNcwuAbGcXj2Agk@vQosxHG9cd2gpUcnTSof2Hp5toP9yx6OHu7kOL/j/cselR05rQw@0gMvL//2gudWdjBQ8zBWczhWAjdR0u9eBAhWBjhWBDheAQENfDUcHZUcHFUSHYUZ0rFgA "Jelly – Try It Online") **Explanation** The first line is niladic. It yields a list of the 52 cards ``` ØDḊḊ;“TJQKA”p“CDHS” ØD Digits: '0123456789' ḊḊ Dequeue twice: '23456789' ; Append with... “TJQKA” ...the string 'TJQKA': '23456789TJQKA'. These are the ranks p Cartesian product with... “CDHS” ...the suits. This yields the list of all cards in lexicographic order: ['2C', '2D', '2H', '2S', '3C', ... 'AS'] ``` In the main link, `¢` calls the result of the first link which is the list of cards. ``` ¢iⱮµḊŒ¿×4+Ḣị¢ ¢ List of cards iⱮ Index of each (Ɱ) of the inputs in the list. µ New monadic link. The list of indices become this links argument. Ḋ Remove the first one. Œ¿ Index of the permutation of the last three items. Gives a number 1-6 as described in the problem statement. ×4 Multiply this by 4 so that when we add to the index of the first card we end up in the same suit. +Ḣ Add the first index. ị Use this number to index into... ¢ ...the list of cards. ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 49 [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") ``` ⊃x⌽⍨⊃i-4×2-⌊1.8⊥⍋1↓i←⎕⍳⍨x←,⍉'CDHS'∘.,2↓⎕D,'TJQKA' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862gv@P@pqrnjUs/dR7wogK1PX5PB0I91HPV2GehaPupY@6u02fNQ2OROoHKjtUe9moLIKIEfnUW@nurOLR7D6o44ZejpGQDVAeRcd9RCvQG9H9f9Ak/8rgEEBl7qzsbqCuocZkHAGEcFG6lxwueBAkIgJiACpCg5BkvNwBGkBES4gIthRHQA "APL (Dyalog Unicode) – Try It Online") Overview: `'CDHS'∘.,2↓⎕D,'TJQKA'` generates the outer product, so a 2d matrix with `(C2 C3 C4 ...), (D2 D3 D4 ...), ...`. We then transpose this matrix to get `(C2 D2 H2 ...), ...` and then flatten that. Thanks to @ngn for the `2-⌊1.8⊥`, which takes the order of cards (SML=1 2 3) and grades them (like the 1 to 6 in the OP). Code explanation: ``` ⊃x⌽⍨⊃i-4×2-⌊1.8⊥⍋1↓i←⎕⍳⍨x←,⍉'CDHS'∘.,2↓⎕D,'TJQKA' ⎕D,'TJQKA' ⍝ Concatenate a list of numbers with TJQKA 2↓ ⍝ Drop 2 (removes "01") ∘., ⍝ Generate the outer product of this prefixed with 'CDHS' ⍝ The suits ⍉ ⍝ Invert rows/columns , ⍝ Flatten (matrix -> array) x← ⍝ Store in x ⍳⍨ ⍝ Inverted ⍳⍨: find the indices, in our cards, ⎕ ⍝ of the argument cards i← ⍝ Store these indices in i 1↓ ⍝ Remove the first index ⍋ ⍝ Grade: get ordered indices 2-⌊1.8⊥ ⍝ The magic happens here: get the number from 1 to 6 4× ⍝ Multiply by 4 to get the same "back" on the card ⊃i- ⍝ Substract the result from our first index (which we had discarded) ⊃x⌽⍨ ⍝ (Modulated) Index into x (our cards) with this value ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~218~~ 208 bytes ``` [JQK] 1$& T`AJQK`1123 *' G0` \d+ 5** ' G, 1,` T`CD\HS`d \d * /^(_+)¶\1/(/¶(_+)¶\1/(K`1 /^(_+)¶_+¶\1/(K`2 ))K`4 /^(_+)¶_+¶\1/(K`3 /¶(_+)¶\1/(K`5 )))K`6 \d $+3-$& (\d+)-(\d+) $1*_$2* _{13}(_+)|(_{1,13}) $.($1$2 ``` [Try it online!](https://tio.run/##bU67DsIwDNz9FRkiyKOlddKyI5BAdKrCRiFBKgMLA2IDfqsf0B8LLhIgIRbrzndn3@V4PZ0PGON2XVc7QD6CTZgRDojGghqzZR6gaTWUSgGxhGESyDNfNCsXWpJAQbYXXsu@azATWd99CZ35iF6/dwakrELxR7HwEy/JSt7p8Idrm1I/QW1k@prAUXluFPgb2seQuwuCCRHSJoIjNzG6mrmCOcsc5k8 "Retina – Try It Online") **Explanation:** ``` [JQK] 1$& T`AJQK`1123 ``` Replaces Aces, Jacks, Queens and Kings with 1, 11, 12 and 13. The first two lines prepend a `1` before the letter, and the last transliterates the second digit. ``` *' G0` ``` The `*` indicates that this stage should not modify the working string. This may make the stage seem pointless, but it will be useful later. The `'` splits the working string at every space, and `G0` takes the first one (so it finds the first card). ``` \d+ 5** ' G, 1,`' ``` The first two lines multiply the numbers on the cards by 5, then turn them into unary (for example, 5 is represented as \_\_\_\_\_), so that we can add smaller amounts for suits later. The final line splits on spaces and keeps the last three cards. ``` T`CD\HS`d \d * ``` This converts Clubs, Diamonds, Hearts and Spades to 0, 1, 2 and 3 respectively, and turns the number into unary. Since it is now on the attached of the number part of the card, it will give a unique value for the card, determining how high it is. ``` /^(_+)¶\1/(/¶(_+)¶\1/(K`1 /^(_+)¶_+¶\1/(K`2 ))K`4 /^(_+)¶_+¶\1/(K`3 /¶(_+)¶\1/(K`5 )))K`6 ``` This finds the ordering of the cards, and the value to add to the first card. For example, on the first line `/^(_+)¶\1_+/(` matches orders that have the middle value larger than the first value. It creates an if-else loop for what to do (as this order matches permutations 1, 2 and 4). `K` marks a constant. ``` \d $+3-$& ``` Remember earlier when we used `*` to indicate that a stage wouldn't affect the working string? This is where we use it. This stage is a replace stage; it replaces the number to add by `$+3-$&`. `$+3` accesses the `*` stage, and gets the suit and number of the first card, `-` acts as a seperator, and `$&` is the match. So the working string is now `{suit}{original number}-{number to add}` ``` (\d+)-(\d+) $1*_$2* ``` This turns the two numbers into unary and adds them together. ``` _{13}(_+)|(_{1,13}) $.($1$2 ``` The top line captures either the number or the number - 13 (so that we don't get outputs of e.g S16). The bottom line turns the captured number back into base 10, and the result is printed implicitly. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~64~~ 62 bytes ``` ≔⪪⭆⁺⭆⁸⁺²ιTJQKA⭆CDHS⁺λι²δ≔E⟦ηζε⟧⌕διυ§δ⁺⌕δθ×⁴⊕⁺∧⌕υ⌊υ⊗⊕¬⌕υ⌈υ‹⊟υ⊟υ ``` [Try it online!](https://tio.run/##Tc7PC8IgFAfwe3/FYycHdqkdgk6jiH4tFu4WHdaUEpxbUyP65@3NFiWI@vz49VW3squaUnmfGiOvmrBWSUuY7aS@ZmVLcuXM33FGIVQmFGQcU4iK7XGXRrj7mWixXLNogCpAvJ/g5PF8NPzTw9ONwouCOFNYSc0JH0IdshzTLEntRnPx7G9C2pfdURWyFoYkFDa66kQttBX8026KKEhHIZNa1q4mrg9eNu6iUP2/ODT2h8vnF8eh6b0whuRNixXsIKzDmHvPjsASYFNghR8/1Bs "Charcoal – Try It Online") Link is to verbose version of code. Uses `T` for 10 and sorts `A` high. The permutation index was not very easily decoded; a different permutation order would have saved me at least three bytes. Explanation: ``` ⁺⭆⁸⁺²ιTJQKA ``` Add 2 to all the integers 0 to 7, then concatente them and suffix `TJQKA` for the picture cards and ace. This saves 2 bytes over a string literal, although it turns out that having `A` high would have saved a byte through string compression anyway. ``` ≔⪪⭆...⭆CDHS⁺λι²δ ``` Map over the cards and the suits, concatenting the two together. Since this would normally produce a nested array, the results are instead concatenated into a single string which is then split up into pairs of characters again. ``` ≔E⟦ηζε⟧⌕διυ ``` Find the positions of the second, third and fourth cards. ``` ⊕⁺∧⌕υ⌊υ⊗⊕¬⌕υ⌈υ‹⊟υ⊟υ ``` Compute the 1-indexed permutation index. The first two permutations have the smallest card first; this is tested via `⌕υ⌊υ`. The other two pairs of permutations are differentiated as to whether the largest card is first; this is tested via `⌕υ⌈υ`. Logical and arithmetic operations then map these tests to the values `0`, `2` and `4`; this is then increased by `1` depending on the comparison between the third and fourth cards, tested via `‹⊟υ⊟υ`. Finally the index is incremented to give the desired encoding. ``` §δ⁺⌕δθ×⁴... ``` Multiply that by 4 repesenting the distance between cards of the same suit, add on the position of the first card, and cyclically index and print the result. [Answer] # [Python 2](https://docs.python.org/2/), 147 bytes ``` lambda a:a[0][0]+R[h(map(a[1:].index,sorted(a[1:],key=lambda c:(I(c[1]),c))))+I(a[0][1])] R='A23456789TJQK'*2;I=R.index h=lambda(x,y,z):x*2+(y>z)+1 ``` [Try it online!](https://tio.run/##LYxNj4IwEIbPy6@YW1tpzFJW1G7YpMEDrCept9pD5SOQVSDIAfzzbP2YvId53sw83TRUbcPmMjzNF3M95wYMN@pT27ipqvDVdNgoj@tl3eTFSG9tPxT5q6J/xRS@vzKOE5wpTxOaETtugp8aW2gnDZFg/tcqWG@2x9/DHi3YdxKmL6VTvR14pBO9Ez4umIunnztxvblsezBQN6DQzgcZQOxDvEUUUGSXAKIAJHugPIC0BwLk8YGxgEjAzqJAmjsfXV83AxgKJTbLW3epB0zI/A8 "Python 2 – Try It Online") [Answer] # Pyth, 42 bytes ``` +hhQ@J+`M}2Tmk"JQKA"+hhKm,xJtdhdQhx.pStKtK ``` Really ugly... Try it online: [Demontration](https://pyth.herokuapp.com/?code=%2BhhQ%40J%2B%60M%7D2Tmk%22JQKA%22%2BhhKm%2CxJtdhdQhx.pStKtK&input=%22HA%22%2C%20%22CA%22%2C%20%22DA%22%2C%20%22SA%22&test_suite_input=%22HA%22%2C%20%22CA%22%2C%20%22DA%22%2C%20%22SA%22%0A%22C3%22%2C%20%22H6%22%2C%20%22C6%22%2C%20%22S2%22%0A%22SQ%22%2C%20%22S4%22%2C%20%22S3%22%2C%20%22S10%22&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=%2BhhQ%40J%2B%60M%7D2Tmk%22JQKA%22%2BhhKm%2CxJtdhdQhx.pStKtK&input=%22HA%22%2C%20%22CA%22%2C%20%22DA%22%2C%20%22SA%22&test_suite=1&test_suite_input=%22HA%22%2C%20%22CA%22%2C%20%22DA%22%2C%20%22SA%22%0A%22C3%22%2C%20%22H6%22%2C%20%22C6%22%2C%20%22S2%22%0A%22SQ%22%2C%20%22S4%22%2C%20%22S3%22%2C%20%22S10%22&debug=0) [Answer] # [J](http://jsoftware.com/), 68 bytes ``` r=.'23456789TJQKA' {:@{.,~0{r|.~1+(r i.0{{.)+(>,{r;'CDHS')A.@/:@i.}. ``` [Try it online!](https://tio.run/##Tcu9CsIwGEbhvVfxTn6K9fOnNdqUSkM6BJ1Kuok4iKW6CFmjvfXo4N924OFcQ3AF0yJJl2K1zpptvVMUtQV7WXqO@5l3d@7n46HDhWfe82g83MTe5aQrY2mkuJzK8sIPDl3B2Esccj7OQaBBHEXnU3cDiYowkWjRgZIKwiIxyAy9OdN/rCEMhMbCfvhVX64t0tdt0fzY/FgZKA1VQVkKTw "J – Try It Online") Note: -3 off TIO bytes because the `f=.` doesn't count. Will attempt to golf further and add explanation tomorrow. [Answer] # T-SQL, 200 bytes Input is a table variable. Using T for 10, aces are low Format for cards rank/suit KH,6D,TS ``` DECLARE @ TABLE(c char(2),i int identity(4,-1)) INSERT @ VALUES('2C'),('5H'),('4S'),('3C') SELECT substring(max(h+h),max(charindex(q,h)*w)+sum(power(3,i)*r)/10-4,1)+max(right(c,w))FROM(SELECT rank()over(order by w,charindex(q,h),c)%4r,*FROM(SELECT'A23456789TJQK'h,i/4w,left(c,1)q,*FROM @)d)y ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1205972/professor-at-mit-can-read-minds)** ungolfed Notice how the SML(1-6) value is calculated: Logically S,M,L(1,2,3) is converted to a numeric value > > first card is valued 27\*sequence value > > > second card is valued 9\*sequence value > > > third card is valued 3\*sequence value > > > [Answer] # [JavaScript (Node.js)](https://nodejs.org), 124 bytes ``` s=>(k='23456789TJQKA')[p=t=>k.search(s[t][0])+32+s[t][1],u=p(0),(u[0]+u[1]-2*(p(1)<p(2))-2*(p(1)<p(3))-(p(2)<p(3)))%13]+u[2] ``` [Try it online!](https://tio.run/##ZYxLD4IwEITv/gouprvyUFpFSSxJr3oi8UZ6IBXFR6Ch4N9HKsYYvUxmZ7@Za/7IjWouuvWr@lj0J94bnsCNE8qWq2i9iQ@7dC8IZpq3PLkFpsgbVYLJWpktJLqMui8fSq/jGhboQTc83G5IfDoDDSFuNVDEr4sNF9hw9DgNmW1Q2au6MvW9CO71GU6QEaaIR6LSinXUEInozOdOrCa/bGoGglkRVg4fVpg/VthJYSfFcSy8WVr2Tw "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 125 bytes ``` s=>(k='23456789TJQKA')[p=s.map(t=>k.search(t[0])+32+t[1]),u=p[0],(u[0]+u[1]-2*(p[1]<p[2])-2*(p[1]<p[3])-(p[2]<p[3]))%13]+u[2] ``` [Try it online!](https://tio.run/##ZYw9D4IwGIR3fwWLaStf0ipKYkm66kTC1jCQAqIgNBT8@9gGY4wu9753ee7u@TNXYrjJ0e36opwrOisaw4YCTHb78HCM0nNyYQBxSZX3yCUcadx4qswHUcORbzNkE2yPPMiQM1GpAwdOWu1JRy7eQKnvSXKcoS9HtIMmXH60Dohp4GwWfaf6tvTa/goryAERwAFhbcR8WAGNW75vRWL1yyZKE8QIM5J@WKb@WGYmmZlkxVJ4s7ieXw "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2TŸ.•3u§•S«.•ôì•âíJuDIkćsD{œJsJk>4*+è ``` Port of [*@dylnan*'s Jelly answer](https://codegolf.stackexchange.com/a/165395/52210), but unfortunately 05AB1E doesn't have the permutation index builtin.. [Try it online](https://tio.run/##yy9OTMpM/f/fKOToDr1HDYuMSw8tB1LBh1aDeIe3HF4DohYdXutV6uKZfaS92KX66GSvYq9sOxMt7cMr/v@PVgoOVNJRCjYGEY4gwtBAKRYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/o5CjO/QeNSwyLj20HEgFH1oN4h3ecngNiFp0eK1XqUtl9pH2Ypfqo5O9ir2y7Uy0tA@v@K/zPzpaydlYSUfJwwxIOIOIYCOlWJ1opeBAEBskFewIIgwNwMIeII4ziHBxhMjFxgIA). **Explanation:** ``` 2TŸ # Push the list [2,3,4,5,6,7,8,9,10] .•3u§•S # Push compressed string "jqka", converted to a list of characters « # Merge the lists together .•ôì• # Push compressed string "cdhs" â # Create each possible pair í # Reverse each pair Ju # Join each pair together, and convert to uppercase D # Duplicate the deck Ik # Get the index of the cards of the input-list in the deck ć # Extract head; pop and push remainder and head s # Swap to get the remainder D{ # Create a sorted copy œ # Get the permutations of that JsJk # Get the index of the unsorted permutation in this permutations list > # Increase it by 1 (since 05AB1E has 0-based indexing) 4* # Multiply it by 4 + # Add it to the extracted head è # And index it into the duplicated deck # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•3u§•` is `"jqka"` and `.•ôì•` is `"cdhs"`. ]
[Question] [ Drawing the Sierpinski triangle [has been](https://codegolf.stackexchange.com/q/38516/8478) [done to](https://codegolf.stackexchange.com/q/6281/8478) [death](https://codegolf.stackexchange.com/q/62859/8478). There's other interesting things we can do with it though. If we squint hard enough at the triangle, we can view upside-down triangles as nodes of a fractal graph. Let's find our way around that graph! First, let's assign a number to each node. The largest upside-down triangle will be node zero, and then we just go down layer by layer (breadth-first), assigning consecutive numbers in the order top-left-right: [![enter image description here](https://i.stack.imgur.com/SSNng.png)](https://i.stack.imgur.com/SSNng.png) Click for larger version where the small numbers are a bit less blurry. (Of course, this pattern continues ad infinitum inside the blue triangles.) Another way to define the numbering is that the centre node has index `0`, and the children of node `i` (adjacent triangles of the next-smaller scale) have indices `3i+1`, `3i+2`, and `3i+3`. How do we move around this graph? There are up to six natural steps one can take from any given triangle: * One can always move through the midpoint of one of the edges to one of the three children of the current node. We'll designate these moves as `N`, `SW` and `SE`. E.g. if we're currently on node `2`, these would lead to nodes `7`, `8`, `9`, respectively. Other moves through the edges (to indirect descendants) are disallowed. * One can also move through one of the three corners, provided it doesn't touch the edge of the triangle, to either the direct parent or one of two indirect ancestors. We'll designate these moves as `S`, `NE` and `NW`. E.g. if we're currently on node `31`, `S` would lead to `10`, `NE` would be invalid and `NW` would lead to `0`. ## The Challenge Given two non-negative integers `x` and `y`, find the shortest path from `x` to `y`, using only the six moves described above. If there are several shortest paths, output any one of them. Note that your code should work for more than just the 5 levels depicted in the above diagram. You may assume that `x, y < 1743392200`. This ensures that they fit inside a 32-bit signed integer. Note that this corresponds to 20 levels of the tree. Your code must process any valid input in **less than 5 seconds**. While this rules out a brute force breadth-first search, it should be a fairly loose constraint — my reference implementation handles arbitrary input for depth 1000 in half a second (that's ~480-digit numbers for the nodes). You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. The output should be a flat, unambiguous list of the strings `N`, `S`, `NE`, `NW`, `SE`, `SW`, using any reasonable separator (spaces, linefeeds, commas, `","`...). Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## Test Cases The first few test cases can be worked out by hand using the diagram above. The others ensure that answers are sufficiently efficient. For those, there may be other solutions of the same length that are not listed. ``` 0 40 => N N N N 66 67 => S SW N N N 30 2 => NW NW -or- NE SW 93 2 => NE SW 120 61 => NW NW NW NW N SE SW N 1493682877 0 => S S NW NW 0 368460408 => SW SW N N SW SW SE SW SW N SE N N SW SW N SE SE 1371432130 1242824 => NW NW NE NW N SE SW SW SW SE SE SW N N N N SW 520174 1675046339 => NE NW NE NE SE SE SW SW N SE N SW N SW SE N N N N SE SE SW SW 312602548 940907702 => NE NW S SW N N SW SE SE SE SW SE N N SW SE SE SE SW 1238153746 1371016873 => NE NE NE SE N N SW N N SW N SE SE SW N SW N N SE N SE N 547211529 1386725128 => S S S NE NW N N SE N SW N SE SW SE SW N SE SE N SE SW SW N 1162261466 1743392199 => NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE ``` [Answer] # Python 2, ~~208~~ ~~205~~ 200 bytes ``` A=lambda n:n and A(~-n/3)+[-n%3]or[] f=lambda x,y:f(A(x),A(y))if x<[]else["SSNEW"[m::3]for m in y[len(x):]]if x==y[:len(x)]else min([["NNSWE"[m::3]]+f(x[:~x[::-1].index(m)],y)for m in set(x)],key=len) ``` A function, `f`, taking a pair of node numbers, and returning the shortest path as a list of strings. ## Explanation We start by employing a different addressing scheme for the triangles; the address of each triangle is a string, defined as follows: * The address of the central triangle is the empty string. * The addresses of the north, south-west, and south-east children of each triangle are formed appending `0`, `1`, and `2`, respectively, to the address of the triangle. Essentially, the address of each triangle encodes the (shortest) path from the central triangle to it. The first thing our program does is translating the input triangle numbers to the corresponding addresses. [![Figure 1](https://i.stack.imgur.com/kZA3x.png)](https://i.stack.imgur.com/kZA3x.png) Click the image for a larger version. The possible moves at each triangle are easily determined from the address: * To move to the north, south-west, and south-east children, we simply append `0`, `1`, and `2`, respectively, to the address. * To move to the south, north-east, and north-west ancestors, we find the last (rightmost) occurrence of `0`, `1`, and `2`, respectively, and trim the address to the left of it. If there is no `0`, `1`, or `2` in the address, then the corresponding ancestor doesn't exist. For example, to move to the north-west ancestor of `112` (i.e., its parent), we find the last occurrence of `2` in `112`, which is the last character, and trim the address to the left of it, giving us `11`; to move to the north-east ancestor, we find the last occurrence of `1` in `112`, which is the second character, and trim the address to the left of it, giving us `1`; however, `112` has no south ancestor, since there is no `0` in its address. Note a few things about a pair of addresses, `x` and `y`: * If `x` is an initial substring of `y`, then `y` is a descendant of `x`, and therefore the shortest path from `x` to `y` simply follows the corresponding child of each triangle between `x` and `y`; in other words, we can replace each `0`, `1`, and `2` in `y[len(x):]` with `N`, `SW`, and `SE`, respectively. * Otherwise, let `i` be the index of the first mismatch between `x` and `y`. There is no path from `x` to `y` that doesn't pass through `x[:i]` (which is the same as `y[:i]`), i.e., the first common ancestor of `x` and `y`. Hence, any path from `x` to `y` must arrive at `x[:i]`, or one of its ancestors, let's call this triangle `z`, and then continue to `y`. To arrive from `x` to `z`, we follow the ancestors as described above. The shortest path from `z` to `y` is given by the previous bullet point. If `x` is an initial substring of `y`, then the shortest path from `x` to `y` is easily given by the first bullet point above. Otherwise, we let `j` be the smallest of the indices of the last occurrences of `0`, `1`, and `2` in `x`. If `j` is greater than, or equal to, the index of the first mismatch between `x` and `y`, `i`, we simply add the corresponding move (`S`, `NE`, or `NW`, respectively) to the path, trim `x` to the left of `j`, and continue. Things get trickier if `j` is less than `i`, since then we might get to `y` fastest by ascending to the common ancestor `x[:j]` directly and descending all the way to `y`, or we might be able to get to a different common ancestor of `x` and `y` that's closer to `y` by ascending to a different ancestor of `x` to the right of `i`, and get from there to `y` faster. For example, to get from `1222` to `1`, the shortest path is to first ascend to the central triangle (whose address is the empty string), and then descend to `1`, i.e., the first move takes us to the left of the point of mismatch. however, to get from `1222` to `12`, the shortest path is to ascend to `122`, and then to `12`, i.e., the first move keeps us to the right of the point of mismatch. So, how do we find the shortest path? The "official" program uses a brute-force-ish approach, trying all possible moves to any of the ancestors whenever `x` is not an initial substring of `y`. It's not as bad as it sounds! It solves all the test cases, combined, within a second or two. But then, again, we can do much better: If there is more than one directly reachable ancestor to the left of the point of mismatch, we only need to test the rightmost one, and if there is more than one directly reachable ancestor to the right of the point of mismatch, we only need to test the leftmost one. This yields a linear time algorithm, w.r.t. the length of `x` (i.e., the depth of the source triangle, or a time proportional to the logarithm of the source triangle number), which zooms through even much larger test cases. The following program implements this algorithm, at least in essence—due to golfing, its complexity is, in fact, worse than linear, but it's still very fast. **Python 2, ~~271~~ ~~266~~ 261 bytes** ``` def f(x,y): exec"g=f;f=[]\nwhile y:f=[-y%3]+f;y=~-y/3\ny=x;"*2;G=["SSNEW"[n::3]for n in g];P=G+f;p=[];s=0 while f[s:]: i=len(f)+~max(map(f[::-1].index,f[s:]));m=["NNSWE"[f[i]::3]] if f[:i]==g[:i]:P=min(p+m+G[i:],P,key=len);s=i+1 else:p+=m;f=f[:i] return P ``` Note that, unlike the shorter version, this version is written specifically not to use recursion in the conversion of the input values to their corresponding addresses, so that it can handle very large values without overflowing the stack. ## Results The following snippet can be used to run the tests, for either version, and generate the results: ``` def test(x, y, length): path = f(x, y) print "%10d %10d => %2d: %s" % (x, y, len(path), " ".join(path)) assert len(path) == length # x y Length test( 0, 40, 4 ) test( 66, 67, 5 ) test( 30, 2, 2 ) test( 93, 2, 2 ) test( 120, 61, 8 ) test( 1493682877, 0, 4 ) test( 0, 368460408, 18 ) test( 1371432130, 1242824, 17 ) test( 520174, 1675046339, 23 ) test( 312602548, 940907702, 19 ) test( 1238153746, 1371016873, 22 ) test( 547211529, 1386725128, 23 ) test( 1162261466, 1743392199, 38 ) ``` **Golfed Version** ``` 0 40 => 4: N N N N 66 67 => 5: S SW N N N 30 2 => 2: NE SW 93 2 => 2: NE SW 120 61 => 8: NW NW NW NW N SE SW N 1493682877 0 => 4: S S NW NW 0 368460408 => 18: SW SW N N SW SW SE SW SW N SE N N SW SW N SE SE 1371432130 1242824 => 17: NW NW NE NW N SE SW SW SW SE SE SW N N N N SW 520174 1675046339 => 23: NE NE NE NE SE SE SW SW N SE N SW N SW SE N N N N SE SE SW SW 312602548 940907702 => 19: NE NW S SW N N SW SE SE SE SW SE N N SW SE SE SE SW 1238153746 1371016873 => 22: NE NE NE SE N N SW N N SW N SE SE SW N SW N N SE N SE N 547211529 1386725128 => 23: S S S S NW N N SE N SW N SE SW SE SW N SE SE N SE SW SW N 1162261466 1743392199 => 38: NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE ``` **Efficient Version** ``` 0 40 => 4: N N N N 66 67 => 5: S SW N N N 30 2 => 2: NW NW 93 2 => 2: NE SW 120 61 => 8: NW NW NW NW N SE SW N 1493682877 0 => 4: NE S NW NW 0 368460408 => 18: SW SW N N SW SW SE SW SW N SE N N SW SW N SE SE 1371432130 1242824 => 17: NW NW NE NW N SE SW SW SW SE SE SW N N N N SW 520174 1675046339 => 23: NE NW NE NE SE SE SW SW N SE N SW N SW SE N N N N SE SE SW SW 312602548 940907702 => 19: NE NW S SW N N SW SE SE SE SW SE N N SW SE SE SE SW 1238153746 1371016873 => 22: NE NE NE SE N N SW N N SW N SE SE SW N SW N N SE N SE N 547211529 1386725128 => 23: S S S S NW N N SE N SW N SE SW SE SW N SE SE N SE SW SW N 1162261466 1743392199 => 38: NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE ``` [Answer] # Ruby, ~~195~~ ~~194~~ ~~190~~ 184 bytes **Original:** With apologies to [Ell](https://codegolf.stackexchange.com/users/31403/ell), as this is essentially a port of their answer and with many thanks to [Doorknob](https://codegolf.stackexchange.com/users/3808/doorknob) for their help in debugging this answer. There's probably another algorithm for this problem - something to do with `*f[x[0,**however far x matches with y**],y]` - but I will save that for another time. ``` a=->n{n<1?[]:a[~-n/3]+[-n%3]} f=->x,y{j=x.size (Array===x)?x==y[0,j]?y[j..-1].map{|m|%w[SE SW N][m]}:x.uniq.map{|m|[%w[NW NE S][m],*f[x[0,x.rindex(m)],y]]}.min_by(&:size):f[a[x],a[y]]} ``` **EDIT:** ~~The greedy algorithm doesn't work for `h[299792458, 1000000]`. I have returned the byte count to 195, while I repair my algorithm once more.~~ Fixed it only for the byte count to rise to 203. *Sigh* **Under construction:** This program uses a greedy algorithm to find common ancestors `x[0,j]==y[0,j]` (note: there may be several common ancestors). The algorithm is based very loosely on [Ell](https://codegolf.stackexchange.com/users/31403/ell)'s recursive ancestor search. The first half of the resulting instructions are how to get to this common ancestor, and the second half is getting to y based on `y[j..-1]`. Note: `a[n]` here returns a base-3 [bijective numeration](http://en.wikipedia.org/wiki/Bijective_numeration) using the digits `2,1,0` instead of `1,2,3`. As an example, let's run through `f[59,17]` or `f[[2,0,2,1],[2,1,1]]`. Here, `j == 1`. To get to `x[0,j]`, we go `0` or `NW`. Then, to get to `y`, go `[1,1]` or `SW SW` ``` a=->n{n<1?[]:a[~-n/3]+[-n%3]} h=->m,n{x=a[m];y=a[n];c=[];j=x.size (j=x.uniq.map{|m|k=x.rindex(m);x[0..k]==y[0..k]?j:k}.min c<<%w[NW NE S][x[j]];x=x[0,j])until x==y[0,j] c+y[j..-1].map{|m|%w[SE SW N][m]}} ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~144~~ ~~132~~ ~~129~~ ~~118~~ ~~133~~ ~~132~~ ~~130~~ ~~124~~ 117 [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") Thank you very much to Ven and ngn for their help in golfing this in [The APL Orchard](https://chat.stackexchange.com/rooms/52405/the-apl-orchard), a great place to learn the APL language. `⎕IO←0`. Golfing suggestions welcome. **Edit:** -12 bytes thanks to Ven and ngn by changing how `n` is defined and switching from 1-indexing to 0-indexing. -3 due to fixing a bug where not everything was switched to 0-indexing. -11 bytes due to changing how `P` and `Q` are defined. +15 bytes due to fixing a problem where my algorithm was incorrect with many thanks to ngn for help with figuring the `s[⊃⍋|M-s]` section. -2 bytes from rearranging the method of finding the backtracking path and +1 byte to bug fixing. -2 bytes thanks to Adám from rearranging the definition of `I`. -6 bytes thanks to ngn from rearranging the definition of `'S' 'NE' 'NW' 'N' 'SW' 'SE'` and from rearranging how `t` is defined (it is no longer a separate variable). -7 bytes thanks to ngn from golfing how `s` is defined. ``` {M←⊃⍸≠⌿↑1+P Q←⍵{(⍵/3)⊤⍺-+/3*⍳⍵}¨⌊3⍟1+⍵×2⋄(∪¨↓6 2⍴'SSNENWNNSWSE')[P[I],3+Q↓⍨⊃⌽I←⍬{M≥≢⍵:⍺⋄(⍺∘,∇↑∘⍵)s[⊃⍋|M-s←⌽⊢.⊢⌸⍵]}P]} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6t9gdSjruZHvTsedS541LP/UdtEQ@0AhUCQcO/Wag0goW@s@ahryaPeXbra@sZaj3o3A8VqD6141NNl/Kh3vqE2kHt4utGj7haNRx2rgOJtk80UjB71blEPDvZz9Qv38wsOD3ZV14wOiPaM1THWBho9@VHvCpClPXs9wfasATqjc@mjzkVAo6yAFoHNAlIdM3QedbQDnQRkAaU0i6PBTu2u8dUtBmns2fuoa5EeED/q2QGUj60NiK39nwY2sg/ix67mQ@uNQQb0TQ0OcgaSIR6ewf/TFIwsLc0tjUxMLRQMDQwMuJAFQDwDBB/IMzNTMIRQpigqTUzNLMyBIoaGZkZGZoYmIHXmJsbGlkaGlpYA "APL (Dyalog Unicode) – Try It Online") ### An explanation of the bug in the algorithm The basic problem is that I went thought the shortest path went directly through the common ancestor, and could not, in fact, go through an ancestor of the common ancestor. This is incorrect as the following examples will demonstrate. **From 66 to 5** ``` 66 → 0 2 2 2 → 0 2 2 2 5 → 0 1 → 0 1 ↑ common ancestor The two ancestors of 0 2 2 2 are: 0 2 2 (empty) (empty) has the shorter path back to 0 1 as it only needs two forward moves, while 0 2 2 requires two more backtracks and one more forward move. ``` **From 299792458 to 45687** ``` 299792458 → 0 2 1 1 0 1 1 2 1 1 1 2 1 0 2 2 2 0 45687 → 0 2 1 1 0 1 1 1 2 2 ↑ common ancestor The three ancestors of 299792458 are: 0 2 1 1 0 1 1 2 1 1 1 2 1 0 2 2 2 0 2 1 1 0 1 1 2 1 1 1 2 ← choose this one 0 2 1 1 0 1 1 2 1 1 1 2 1 0 2 2 And the three ancestors of 0 2 1 1 0 1 1 2 1 1 1 2 are: 0 2 1 1 0 2 1 1 0 1 1 2 1 1 0 2 1 1 0 1 1 2 1 1 1 0 2 1 1 0 1 1 1 2 2 ← 45687 for reference ↑ common ancestor While it seems like `0 2 1 1` is the shorter path, it actually results in a path that is 8 steps long (2 backtracks, 6 forward steps to 45687). Meanwhile, `0 2 1 1 0 1 1 2 1 1` is at an equal distance to the common ancestor and has the following ancestors: 0 2 1 1 0 2 1 1 0 1 1 2 1 0 2 1 1 0 1 1 0 2 1 1 0 1 1 1 2 2 ← 45687 for reference ↑ common ancestor Clearly, this is the superior path, as with three backtracks, we have reached the point of the common ancestor. With 3 backtracks and 3 forward moves, we have a path that is 6 steps long. ``` ## Explanation of the code ``` ⍝ ⍵ should be an array of 2 integers, x y SierpinskiPath←{⎕IO←0 ⍝ 0-indexing ⍝ P Q←{...}¨⍵ ⍝ First, the bijective base-3 numeration of x and y P Q←{ n←⌊3⍟1+⍵×2 ⍝ The number of digits in the numeration z←+/3*⍳n ⍝ The number of numerations with ≤ n digits (n/3)⊤⍵-z ⍝ And a simple decode ⊤ (base conversion) of ⍵-z }¨⍵ ⍝ gets us our numerations, our paths A←↑1+P Q ⍝ We turn (1+P Q) into an 2-by-longest-path-length array ⍝ ↑ pads with 0s and our alphabet also uses 0s ⍝ So we add 1 first to avoid erroneous common ancestor matches Common←⊃⍸≠⌿A ⍝ We find the length of the common ancestor, Common ⍝ I←⍬{...}P ⍝ Now we get the shortest backtracking path from P I←⍬{ Common=≢⍵:⍺ ⍝ If P is shorter than Common, return our backtrack path s←⌽⊢.⊢⌸⍵ ⍝ Get the indices of the most recent N SW SE t←s[⊃⍋|Common-s] ⍝ and keep the index that is closest to Common ⍝ and favoring the ancestors to the right of ⍝ Common in a tiebreaker (which is why we reverse ⊢.⊢⌸⍵) (⍺,t)∇t↑⍵ ⍝ Then repeat this with each new index to backtrack }P ⍝ and the path left to backtrack through Backtrack←P[I] ⍝ We get our backtrack directions Forward←(⊃⌽I)↓Q ⍝ and our forward moves to Q ⍝ starting from the appropriate ancestor (∪¨↓6 2⍴'SSNENWNNSWSE')[Backtrack,Forward] ⍝ 'S' 'NE' 'NW' 'N' 'SW' 'SE' } ⍝ and return those directions ``` ## Alternative solution using Dyalog Extended and dfns If we use `⎕CY 'dfns'`'s `adic` function, it implements our bijective base-n numeration (which was the inspiration for the version I use) for far fewer bytes. Switching to Dyalog Extended also saves quite a number of bytes and so here we are. Many thanks to Adám for his help in golfing this. Golfing suggestions welcome! **Edit:** -8 bytes due to changing how `P` and `Q` are defined. -14 bytes due to switching to Dyalog Extended. -2 due to using a full program to remove the dfn brackets `{}`. +17 bytes due to fixing a problem where my algorithm was incorrect with many thanks to ngn for help with figuring the `s[⊃⍋|M-s]` section. +1 byte to bug fixing. -2 bytes thanks to Adám from rearranging the definition of `I` ~~and -1 byte from remembering to put my golfs in both solutions~~. -3 bytes thanks to ngn by rearranging the generation of the cardinal directions, +1 byte from correcting a buggy golf, and -3 bytes thanks to ngn by rearranging how `t` is defined (it is no longer a separate variable). -7 bytes thanks to ngn by rearranging how `s` is defined. ### [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~123~~ ~~115~~ ~~101~~ ~~99~~ ~~116~~ ~~117~~ ~~114~~ ~~109~~ 102 bytes ``` M←⊃⍸≠⌿↑1+P Q←(⍳3)∘⌂adic¨⎕⋄(∪¨↓6 2⍴'SSNENWNNSWSE')[P[I],3+Q↓⍨⊃⌽I←⍬{M≥≢⍵:⍺⋄(⍺∘,∇↑∘⍵){⍵[⊃⍋|M-⍵]}⌽⊢.⊢⌸⍵}P] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXI862gv@@wKZj7qaH/XueNS54FHP/kdtEw21AxQCgcIaj3o3G2s@6pjxqKcpMSUz@dAKoN5H3S0ajzpWAdltk80UjB71blEPDvZz9Qv38wsOD3ZV14wOiPaM1THWBpow@VHvCpDZPXs9Qbb0rqn2fdS59FHnoke9W60e9e4CmwWkOmboAN0CtBlkV@9WzWogEQ12VHeNry6QE1sLNONR1yI9IH7UswMoUhsQ@x@o578CGBRwGVlamlsamZhaKBgaGBhwYQojxAwU4KJwMTMzBUNkjikWE0xMzSzM4eKGhmZGRmaGJiCd5ibGxpZGhpaWAA "APL (Dyalog Extended) – Try It Online") ]
[Question] [ ### Introduction You have the misfortune of being stuck in a runaway car on an obstacle course. All of the car's features are non-responsive, save for the steering system, which is damaged. It can drive straight, or it can turn right. Can the car be guided to safety? ### Mechanics Your car begins in the upper-left corner of an 8x8 map, and is trying to get to safety in the lower-right corner. The car has an orientation (initially to the right), measured in 90-degree increments. The car can perform one of two actions: 1. Drive one square forward, or 2. Turn 90 degrees clockwise, then drive one square forward Note that the car is unable to turn sharply enough to perform a 180-degree turn on a single square. Some of the squares are obstacles. If the car enters an obstacle square, it crashes. Everything outside the 8x8 course is assumed to be obstacles, so driving off the course is equivalent to crashing. The lower-right square is the safe square, which allows the car to escape the obstacle course. The starting square and safe square are assumed not to be obstacles. ### Task You must write a program or function which takes as its input an 8x8 array (matrix, list of lists, etc.), representing the obstacle course. The program returns or prints a Boolean, or something similarly truthy. If it's possible for the car to make it to the safe square without crashing (i.e., if the map is solvable), the output is `True`, otherwise, it's `False`. ### Scoring Standard code golf rules - the winner is the code with the fewest bytes. Bonuses: * If, for a solvable map, your code outputs a valid series of driver inputs which guide the car to the safe square, deduct 10 percentage points from your score. An example output format might be `SRSSR` (indicating Straight, Right, Straight, Straight, Right). This output would replace the standard `True` output. * If, for an unsolvable map, your code's output distinguishes between situations where a crash is unavoidable, and situations where it's possible to drive around the obstacle course forever, deduct 10 percentage points from your score. An example output might be `Crash` if a crash is unavoidable, or `Stuck` if the car is stuck in the obstacle course forever. These outputs would replace the standard `False` output for an unsolvable map. ### Example If the program is given an 8x8 array such as this: ``` [[0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 1, 0, 0, 0, 1, 0]] ``` It would be interpreted as a map like this, with black squares indicating obstacles: ![enter image description here](https://i.stack.imgur.com/j51T0.png) And a possible solution might be: ![enter image description here](https://i.stack.imgur.com/PRNBq.png) Since a solution exists, the program should return/print `True` for this map. The sequence of moves shown here is `SSSSRSRRRSRSSRRRSSRSSS`. [Answer] # JavaScript (ES6) - 122 124 148 162 172 178 187 190 193 208 bytes Many thanks to Optimizer and DocMax for helpful suggestions on how to improve this code: ``` F=a=>(D=(x,y,d)=>!D[i=[x,y,d]]&&(D[i]=1,x-=~d%2,y-=~-~d%2,x*y==49||!((x|y)&8||a[y][x])&&(D(x,y,d)||D(x,y,~-d%4))),D(-1,0)) ``` Returns `true` (truthy) for solvable and `false` (falsy) for unsolvable. Works only in Firefox as of today becasue of JavaScript 1.7 features. [**Test Board**](http://jsfiddle.net/f5h4jrdm/3/) [Answer] # C (GNU-C), 163 bytes \* 0.9 = 146.7 #C (GNU-C), 186 bytes \* 0.9 = 167.4 My new version uses a signed rather than unsigned integer. Earlier I was afraid of signed right shift, but I realized since the sign bit is the goal square, it doesn't matter what happens after that. The function takes an array of bits (ones represent blocked squares) in the form of a 64-bit integer. The bits are arranged least to most significant in the same way you would read a book. It returns -1 for a crash, 0 for driving forever, or 1 for escaping to the bottom right corner. ``` g(long long o) { typeof(o) a=0,i=255,r=1,u=0,l=0,d=0,M=~0LLU/i,D; for( ;i--;d = D<<8&~o) a |= D = d|r, r = (r|u)*2&~M&~o, u = (u|l)>>8&~o, l = ((l|d)&~M)/2&~o; return a<0?:-!(d|r|u|l); } ``` **Test program** ``` f(long long o){typeof(o)a=0,i=255,r=1,u=0,l=0,d=0,M=~0LLU/i,D;for(;i--;d=D<<8&~o)a|=D=d|r,r=(r|u)*2&~M&~o,u=(u|l)>>8&~o,l=((l|d)&~M)/2&~o;return a<0?:-!(d|r|u|l);} { char* s[] = {"Crash", "Stuck", "Escape"}; #define P(x) puts(s[f(x)+1]) L ex = 0x4640500C0A034020; P(ex); L blocked = 0x4040404040404040; P(blocked); L dead = 0x10002; P(dead); return 0; } ``` **Output** ``` Escape Stuck Crash ``` Python array-to-hex converter: ``` a2b=lambda(A):"0x%X"%sum(A[i/8][i%8]<<i for i in range(64)) ``` [Answer] ## Python 2 - 123 ~~125 133 146 148 150 154 160~~ `True` on success, `False` on failure. ``` def f(h=1,v=0,b=0,x=0,y=0,c=[]):s=x,y,h,v;a=b,x+h,y+v,c+[s];return(s in c)==(x|y)&8==b[y][x]<(x&y>6or f(h,v,*a)|f(-v,h,*a)) ``` You must supply input like `f(b=var_containing_board)`. ### Lambda version - 154 Returns `0` (falsy) for failure, `True` for success. ``` F=lambda b,x=0,y=0,h=1,v=0,c=[]:0if[x,y,h,v]in c or x|y>7or x|y<0 or b[y][x]else x&y==7or F(b,x+h,y+v,h,v,c+[[x,y,h,v]])or F(b,x+h,y+v,-v,h,c+[[x,y,h,v]]) ``` Thanks to Will and Brandon for making the function shorter than the lambda. Also for adding more horizontal scrolling :D Thanks to xnor for superior bit-bashing and logic! Edit note: I am reasonably confident that `b[y][x]` will never be executed when going out of range. Since we are outside of the board, the history check `s in c` will be `False`. Then the boundary check `(x|y)&8` will be `8`. Then python will not even check the last value of `==` because the first two are already different. [Answer] # Python, 187 ~~213~~ ## 207 chars, 10% bonus for printing path ``` b=map(ord," "*9+" ".join("".join("o "[i]for i in j)for j in input())+" "*9) def r(p,d,s): p+=(1,9,-1,-9)[d] if b[p]&1<<d:b[p]^=1<<d;return(s+"S")*(p==79)or r(p,d,s+"S")or r(p,(d+1)%4,s+"R") print r(8,0,"") ``` On the test input it finds a slightly different path: `SSSSRSRSRRSSRSSRRSRSSRSSSSS` The general approach is to first turn the input into a spaces and `o`s. Spaces have a hex of `20`, so all four lower bits are unset. `o` has a hex of `6F`, so the low four bits are all set. A border of `o`s is placed around the board so we don't have to worry about bad indices. As we walk over the board, we use the bits in each tile to see if we are allowed to pass when coming from that side. In this way, we avoid infinite loops. Its not enough to have a single boolean per tile, as your exit direction depends on your entry direction, so tiles can be visited twice. We then do a recursive search for a safe path. [Answer] # Javascript - ~~270 - 20% = 216~~ 262 - 20% = 210 bytes Since there ought to be at least one solution that earns both bonuses (and doesn't lead to a ridiculous stack depth ;)... Minified: ``` V=I=>{n=[N=[0,0,0]];v={};v[N]='';O='C';for(S='';n[0];){m=[];n.map(h=>{[x,y,d]=h;D=i=>[1,0,-1,0][d+i&3];p=v[h];for(j=2;j--;){O=v[c=[X=x+D(j),Y=y+D(3-3*j)),d+j&3]]?'K':O;J=X|Y;J<0||J>7||I[Y][X]||v[c]?O:(m.push(c),v[c]=p+'SR'[j])}S=(x&y)>6?p:S});n=m;}return S||O;}; ``` Expanded: ``` V = I => { n = [N=[0,0,0]]; v = {}; v[N] = ''; O = 'C'; for( S = ''; n[0]; ) { m = []; n.map( h => { [x,y,d] = h; D = i => [1,0,-1,0][d+i&3]; p = v[h]; for( j = 2; j--; ) { O = v[c = [X = x+D(j),Y = y+D(3-3*j),d+j&3]] ? 'K' : O; J = X|Y; J<0 || J>7 || I[Y][X] || v[c] ? O : ( m.push( c ), v[c] = p + 'SR'[j] ); } S = (x&y) > 6 ? p : S; } ); n = m; } return S || O; }; ``` `v` is a hashtable with keys that are state triples `(x,y,d)` corresponding to (x,y) coordinate and direction of entry `d`. Each key has an associated value that is the string of `S` (straight) and `R` (turn right) moves required to reach the state represented by the key. The code also maintains a stack of triples (in variable `n`) that have not been processed yet. The stack initially contains only the triple (0,0,0), corresponding to the state where the car faces right in the (0,0) cell. In the outer loop, `for( S = ... )`, the routine checks if any unprocessed triples remain. If so, it runs each unprocessed triple through the inner loop, `n.map( ...`. The inner loop does five things: 1. computes the two possible moves (driving straight, turning right) out of the current state 2. if either of these moves leads to a state already registered in the hashtable, it is ignored for further processing. We flag the FALSE output as `K` (stuck), however, since we have found at least one loop where the car can continue to circle forever without crashing. 3. if a state is legal and novel, it is added to the hashtable (`v`) and to the stack of unprocessed triples (`m`) for the next pass of the outer loop 4. when the new state is registered in `v`, its value is set to the value of the originating state (the sequence of moves) plus `R` or `S` based on the current move 5. if `x` and `y` are `7`, the value of the originating state (the sequence of moves taken to reach the originating state) is copied to `S`, since this move sequence is a solution to the problem After the inner loop terminates, `n` (the stack) is replaced by `m` (the new stack). After the outer loop terminates (no new states were reached), the function returns its output. If the (7,7) cell was reached, `S` will contain a sequence of moves leading to this cell, and this is outputted. If the cell was not reached, `S` will be the empty string, and the routine falls through to outputting `O`, which will contain `K` (stuck) if and only if a loop was found, or `C` (crash) if the car will inevitably crash. [Answer] ## Python 339 - 10% = 305 bytes I used a recursive depth-first search, which is terminated early on success via `exit`. Also printing path on success in the form of `00001010101010101010101110100111001000`, `0` for straight, `1` for right. The answer will be longer than optimal, since it is depth-first. I'm sure some optimizations to the algorithm could bring the byte count down quite a bit. ``` b=input() D=[(-1,0),(0,-1),(1,0),(0,1)] def a(l): x,y=0,0 v=2 for d in l: if d=='1':v=(v+1) % 4 x+=D[v][0] y+=D[v][1] if x<0 or x>7 or y<0 or y>7:return 0,x,y if b[y][x]:return -1,x,y return 1,x,y def c(l): if len(l) < 39: t,x,y=a(l) if t==1: if (x,y)==(7,7): print l;exit(0) c(l+"0") c(l+"1") c("") print 0 ``` ]
[Question] [ Cut a boolean matrix in 4x2 blocks and render them as Braille characters `U+2800`...`U+28FF`. ``` [[0,1,0,0,1,0], [1,0,0,0,0,0], [1,0,0,0,1,0], [1,1,1,1,0,0]] ⣎⣀⠅ ``` Pad with 0-s if dimensions are not multiples of 4 and 2. ``` [[0,1,0], [1,0,0], [1,1,1]] ⠮⠄ ``` Usual golfing rules apply, flexible on input format. Output should either have the structure of a matrix or look like a matrix, e.g. list of strings; single string with newlines. Hint: `chr(0x2800 + 128*b7 + 64*b6 + 32*b5 + 16*b4 + 8*b3 + 4*b2 + 2*b1 + b0)` is the dot pattern ``` b0 b3 b1 b4 b2 b5 b6 b7 ``` Larger test: ``` [[0,0,1,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,0], [0,1,1,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,1,1,1,1,1], [0,1,1,0,0,1,1,1,0,0,0,1,1,1,1,0,0,1,1,0,0,0,1], [1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,1,1,0,0,1,1], [1,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,1,1,1,0,1,0], [1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0], [1,1,0,1,1,1,1,1,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0], [1,1,0,1,1,1,1,1,0,0,1,1,0,0,1,0,0,1,1,1,1,1,1], [1,1,0,1,1,1,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,1,0], [1,1,0,1,0,1,1,0,1,1,0,1,1,0,1,0,0,0,0,1,1,0,0], [1,1,0,0,0,1,1,0,1,0,0,0,1,0,1,1,0,0,0,1,1,0,0], [1,1,0,0,0,1,1,0,1,0,0,0,1,0,1,1,1,0,0,1,1,0,0], [0,1,1,0,1,1,1,0,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,1,1,1,1,1,0,0,1,1,1,1,1,0,0,1,1,0,1,1,1,0,0], [0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,0,1,1,1,1,0]] ⣰⠟⠻⣦⠀⠠⠾⡇⢠⡞⢛⡆ ⣿⢠⣬⣥⠄⣀⠀⡇⢈⣻⣈⡀ ⣿⠘⢹⡇⡞⠙⡇⣧⡉⢹⡏⠀ ⠘⠷⠟⠁⠳⠾⠃⠘⠇⠾⠧⠀ ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~31~~ 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` sz0Z ç€2ZF€ç€8Zœ?@€€-36Ḅ+⁽$ṁỌY ``` **[Try it online!](https://tio.run/##y0rNyan8/7@4yiCK6/DyR01rjKLcgCSYaRF1dLK9A5ABRLrGZg93tGg/atyr8nBn48PdPZH///@PjjbQMdAxhEIDFIgsApWP1eFSiEaoR9WDzIfLI@nApQbVLogOdLtR3YUsaoihA5tPkO2G@QNTHboOJLOQdODyPRoLqw5UlxugmoZFB2o4YdiOosNAxxALiRaKWMPKEMnlGOFIlA5DDB3I7jDEFms4dGD62xDFXlQdBmjxgM5DCr3YWAA "Jelly – Try It Online")** ### How? ``` sz0Z - Link 1, split & right-pad with zeros: list, items; number, chunkSize s - split items into chunks of length chunkSize z0 - transpose with filler zero Z - transpose ç€2ZF€ç€8Zœ?@€€-36Ḅ+⁽$ṁỌY - Main link: list of lists of numbers (1s & 0s), M ç€2 - call the last link (1) as a dyad for €ach (left=M, right=2) - ((left,right) bits read left-right then top-bottom) Z - transpose the resulting list of lists of lists - ((left, right) bits read top-bottom then left-right) F€ - flatten €ach ç€8 - call the last link (1) as a dyad for €ach (left=^, right=8) Z - transpose the resulting list of lists of lists - ("blocks" each and all read left-right top-to bottom) -36 - literal -36 €€ - for €ach (block-wise row) for €ach (block) œ?@ - lexicographical permutation with reversed arguments - (get the permutation at index -36 (modular) in a list of - all permutations of the indexes sorted lexicographically. - That is the 8!-36 = 40284th - equivalently the values at - indexes [8,7,6,4,2,5,3,1]) Ḅ - convert from binary list to integer (vectorises) ⁽$ṁ - base 250 literal = 10240 + - add Ọ - cast to character (vectorises) Y - join with newlines - implicit print ``` [Answer] # Mathematica, ~~126~~ ~~110~~ ~~97~~ 90 ``` FromCharacterCode[10240+ListCorrelate[2^{{0,3},{1,4},{2,5},{6,7}},#,1,0][[;;;;4,;;;;2]]]& ``` --- This solution takes advantage of [`ListCorrelate`](http://reference.wolfram.com/language/ref/ListCorrelate.html) to [convolve a (reversed) kernel over a matrix](https://en.wikipedia.org/wiki/Kernel_(image_processing)#Convolution), which is essentially a sliding matrix multiplication (or dot product). See a visual explanation [here](https://mathematica.stackexchange.com/questions/64925/how-do-i-understand-listcorrelatecontains-k-l-k-r-when-it-works-for-2-di?noredirect=1&lq=1). Padding is done by using `0` as the fourth argument. In the following example, we expect the result to match the hint above: ``` ListCorrelate[ 2^{{0, 3}, {1, 4}, {2, 5}, {6, 7}}, {{b0, b3}, {b1, b4}, {b2, b5}, {b6, b7}} ] (* returns {{b0 + 2 b1 + 4 b2 + 8 b3 + 16 b4 + 32 b5 + 64 b6 + 128 b7}} *) ``` Note that `ListConvolve` is not any shorter, since the third argument would be `-1`. Since this applies the kernel at every position of the matrix, we just need to extract the elements in every fourth row and second column. We use shorthands for [`Span`](http://reference.wolfram.com/language/ref/Span.html) and [`Part`](http://reference.wolfram.com/language/ref/Part.html): `[[;;;;4,;;;;2]]`. Helpfully, [`FromCharacterCode`](http://reference.wolfram.com/language/ref/FromCharacterCode.html) can take a matrix of character codes and return a list of strings. --- This solution returns a list of strings, which is one of the allowed output formats. Simply prepend `Column@` for the output to “look like a matrix.” --- You can play around with this in a free online Mathematica notebook. [Go here](https://develop.open.wolframcloud.com/app/), click Create a New Notebook, wait a moment, paste in this code, then press `shift+enter`. ``` m1={{0,1,0,0,1,0},{1,0,0,0,0,0},{1,0,0,0,1,0},{1,1,1,1,0,0}}; m2={{0,1,0},{1,0,0},{1,1,1}}; m3={{0,0,1,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,0},{0,1,1,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,1,1,1,1,1},{0,1,1,0,0,1,1,1,0,0,0,1,1,1,1,0,0,1,1,0,0,0,1},{1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,1,1,0,0,1,1},{1,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,1,1,1,0,1,0},{1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0},{1,1,0,1,1,1,1,1,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0},{1,1,0,1,1,1,1,1,0,0,1,1,0,0,1,0,0,1,1,1,1,1,1},{1,1,0,1,1,1,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,1,0},{1,1,0,1,0,1,1,0,1,1,0,1,1,0,1,0,0,0,0,1,1,0,0},{1,1,0,0,0,1,1,0,1,0,0,0,1,0,1,1,0,0,0,1,1,0,0},{1,1,0,0,0,1,1,0,1,0,0,0,1,0,1,1,1,0,0,1,1,0,0},{0,1,1,0,1,1,1,0,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0},{0,1,1,1,1,1,0,0,1,1,1,1,1,0,0,1,1,0,1,1,1,0,0},{0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,0,1,1,1,1,0}}; MatrixToBraille := Column@ FromCharacterCode[10240+ListCorrelate[2^{{0,3},{1,4},{2,5},{6,7}},#,1,0][[;;;;4,;;;;2]]]& MatrixToBraille/@{m1,m2,m3} ``` Then you should see this: > > ![](https://i.stack.imgur.com/Gm4YA.png) > > > [Answer] # JavaScript ES7 ~~210~~ ~~207~~ ~~201~~ ~~200~~ ~~198~~ ~~194~~ ~~185~~ 183 bytes ``` a=>eval('for(y=0,c="";A=a[y];y+=4,c+=`\n`)for(x=0;A[x]+1;x+=2)c+=String.fromCharCode(10240+eval("for(N=k=0;k<6;k++)N+=(g=(X,Y=3)=>(a[Y+y]||0)[X+x]|0)(k>2,k%3)*2**k")|g(0)+g(1)*2<<6)') ``` 4 bytes saved thanks to ngn 3 bytes saved thanks to Luke # How it works I'm going to split the code up into parts and speak about them separately: ``` for(y=x=0, c=""; a[y]; x+=2) !((a[y] || [])[x]+1) && (y+=4,x=0,c+=`\n`) ``` This is where every variable gets declared. `x` and `y` is the position of the "cursor" (the upper left edge of the current braille character). The x coordinate increases by 2 every iteration, and it stops, when there's no row with the index `y` (a[x] returns `undefined` if it doesn't exist, which gets converted to false). There are multiple tricks in the second row. `(a[y] || [])[x]` ensures that looking up the value at the `(x, y)` position doesn't throw an error. The `&&` is the usual and operator, and it only checks the right side of the expression, if the left was true. This can be translated to ``` if (!((a[y] || [])[x] + 1)) y+=4,x=0,c+=`\n` ``` The next part: ``` c+=String.fromCharCode(10240+eval("for(N=k=0;k<6;k++)N+=(g=(x,y)=>(a[y]||[])[x]||0)(~~(k/3)+x,k%3+y)*2**k,N")+g(x,y+3)*64+g(x+1,y+3)*128) ``` `String.fromCharCode` simply converts the passed number to a unicode character with the same character code. The expression in the parentheses calculates the index of the Braille character: ``` for(N=k=0;k<6;k++)N+=(g=(x,y)=>(a[y]||[])[x]||0)(~~(k/3)+x,k%3+y)*2**k ``` Goes through the position in the ``` 1 4 2 5 3 6 ``` order, multiplies the values at those positions with 2i, where i is the index and adds them together. The ``` g=(x,y)=>(a[y]||[])[x]||0 ``` part declares a lambda function called `g`, which given an `x` and `y` coordinate returns either the value at the `(x, y)` position or 0 if the position lies outside the bounds of the array. ``` +g(x,y+3)*64+g(x+1,y+3)*128 ``` This part adds up the last two positions with the correct weights using the function defined a bit earlier. Last but not least, the ``` a=>eval('...') ``` part has 2 functions. It defines an anonymous lambda and ensures, that the for loop doesn't cause any problems (a single line lambda such as this one can't contain a single for loop only, an evaluation circumvents this). [Answer] # Dyalog APL, ~~133~~ ~~122~~ ~~114~~ ~~112~~ ~~101~~ ~~100~~ ~~98~~ ~~95~~ ~~94~~ ~~93~~ ~~90~~ ~~88~~ 86 bytes Assumes `⎕IO←0` ``` {C⍴{⎕UCS 10240+2⊥(∊S⌷⍨⍵+⍳¨A)[⍎¨⍕76531420]}¨(,b)/,⍳⍴b←{0 0≡A|⍵}¨⍳⍴S←⍵↑⍨A×C←⌈(⍴⍵)÷A←4 2} ``` -~~8~~ ~~9~~ 12 bytes thanks to @Adám in chat -2 bytes thanks to @ngn [Try it online!](https://tio.run/##RU87CsJAEO33FFsmuOLko9YhELCyCKIgFopgI2grmlaiuKKFWFsI6VXSx5vMReKLwcjA7vvMm9kdL@f16Wo8X8zynI@XTpe3JxKij8uVLdZPUpYiVZ4loor/9bLAxQBJRzpV8pdGCSECuGsf5hrLen4oLbJdqtm8vxsc70M@pKwT1q8a60eWeOaQ9TGDcGm3mo7l2jSKssRQE7Oh0IFBk2IiSeLdzdsgGBXdhRHCAOftGRO999Uv@CE2YEE236n3/aMdCTwFMJD9Cg1Enn8A) ## How (input is `⍵`)? * `A←4 2`, store the vector `4 2` in variable `A` * `(⍴⍵)÷`, the dimensions of `⍵` divided by `A` * `⌈`, ceiling * `C←`, stored in `C` * `A×`, multiplied by `A` * `⍵↑⍨`, fit `⍵` to those dimensions * `S←`, stored in `S` * `⍳⍴`, indexes of `S` * `{0 0≡A|⍵}¨`, `1` where the top left of a cell is, `0` everywhere else * `(,b)/,⍳⍴b←`, truthy indexes * `{⎕UCS 10240+2⊥(∊S⌷⍨⍵+⍳¨A)[⍎¨⍕76531420]}¨`, turn each element into braille * `C⍴`, reshape the dimensions to `C` [Answer] # JavaScript, 136 bytes ``` a=>(b=a.map(x=>[]),a.map((l,i)=>l.map((c,j)=>b[i>>2][j>>1]|=c<<'01263457'[i%4+j*4%8])),b.map(l=>l.map(c=>String.fromCharCode(10240+c)))) ``` Thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn), using bit shifts save 4 bytes. [Answer] # [Python 2](https://docs.python.org/2/) + [drawille](https://github.com/asciimoo/drawille), ~~141~~ ~~125~~ ~~120~~ 116 bytes Saved 16 bytes thanks to ngn and L3viathan Saved 5 bytes thanks to L3viathan Saved 4 bytes thanks to ngn ``` from drawille import* def a(d,c=Canvas(),e=enumerate):[c.set(j,i)for i,x in e(d)for j,y in e(x)if y];print c.frame() ``` [Try it online!](https://tio.run/##Jcc7DsIwDADQnVN4jFHUgRHUiWMgBiuxhavmIzeU5vRBgre92tur5MsYYiVBNProujJoqsXa@RRZgFz0Yb5T3mlz6Hnm/E5s1BivjzBt3NziFaUYqD9AM7CLvy6@/3ugCvTnrZrmBmESo8QOx/gC "Python 2 – Try It Online") tio does not have drawille installed so it does not work [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~57~~ 54 bytes\* -3 thanks to OP. Prompts for Boolean matrix. Prints character matrix. ``` 1↓⎕UCS{2⊥40,⌽(,⍉3↑⍵),⊢⌿⍵}⌺(2 2⍴4 2)⊢0⍪⍣3⍪∘0⍣3⊢⎕,0 ``` [Try it online!](https://tio.run/##jVLBSsQwEL33K3LchQhJW39Abx7qYfFUeihskUKpy@4KStlrraUpihS86EERxKt6EWTBT5kfqW123SZpCjKQzmTmvZl5qT@L9qaXfnR2WkN2dTD3wygKagrpHZTVyeEkMSF/sQmG4nuEgV1bkN4C@xxjyJ@gWDfuCoqvkYlMYB82MsfNPQH2BuzZaj/ZPeFuU11WmLRNDCe4WEJ6k7RUZXU0OXYgyxNgj6ufV2DvLScC9oDmgT9FcVOMHBSFcbBA/gKF8ex8WW8H5VTINlyXYIoJ5qeHDeRuIm5S3OU31uY9Q6Kz/ug6YAdRi@k@ryZYIBRMvNnmOVdXL2PEeJcXEEM1ci@6m1c3x1YGLDEqCN0mYm9RRjJgPS4BMbS94mkR8uREZtMgZJ163SUEwVRzKipqtRJ@MNzT8V8I2kOIc1Ddqw0g@ntTqa@MIMo7qJGgnuf9Ag "APL (Dyalog Unicode) – Try It Online") `⎕,0` append a zero on right (ignored if even number of columns) `⊢` yield that (to separate `3` and `⎕`) `⍪∘0⍣3` append zeros on bottom thrice (because `⌺` drops partial windows) `0⍪⍣3` stack zeros on top thrice (because `⌺` starts in the top left corner) `⊢` yield that (separates the parenthesis and the `0`) `{`…`}⌺(2 2⍴4 2)` on each 4-row 2-column window, with 4-row vertical and 2 row horizontal step:  `⊢⌿⍵` last row (lit. vertical right reduction); `[b6,b7]`  `(`…`),` prepend:   `3↑` take three rows; `[[b0,b3],[b1,b4],[b2,b5]]`   `⍉` transpose; `[[b0,b1,b2],[b3,b4,b5]]`   `,` ravel; `[b0,b1,b2,b3,b4,b5]`  now we have `[b0,b1,b2,b3,b4,b5,b6,b7]`  `⌽` reverse; `[b7,b6,b5,b4,b3,b2,b1,b0]`  `40,` prepend 40 (for 40×29 = 10240); `[40,b7,b6,b5,b4,b3,b2,b1,b0]`  `2⊥` evaluate as base-2 (binary) `⎕UCS` convert to character `1↓` drop the first row (all-zero because of `⌺`'s padding) --- \* In Classic, counting `⌺` as `⎕U233A`. [Answer] # [Haskell](https://www.haskell.org/), 145 bytes ``` (a!b)c=take b$c++repeat a r([]:_)=[] r l=['⠀'..]!!(sum.zipWith(*)[1,8,2,16,4,32,64,128]$l>>=0!2):r(drop 2<$>l) b[]=[] b s=r(([]!4)s):b(drop 4s) ``` [Try it online!](https://tio.run/##jZPPaoQwEMbvPsUIwibdIImVZZHGe8899BBCiVvblc26EvXSUx@lz9YXsS6VbRIVSiDkz/zmm/lCjqo9lVoP7xf9BjwAEIISStg0qDPsk@lejggRf4AL2fvbvY2sBblqE@LLu6XZp2yOLHVjq996mQf6iJXMRtYs8FbLiFs9ddMtIa5bM30XoYQtzJ6Xy44xq/qZm/9D2ByxS2FLz7eGzJtnjrKHUO89/J3loZSQZUI81p2UA1JhgQ@8U6cSiuiw3ZqyKVUHKjBIyOwFcyEDA5qLzffX5yaOZRiitj/HH1XzXHVHdIdHW/YkIWxHUnKfkF1KWLKXkc5zTsMEZwa9mksDyUOUaxwUQl5TFtByg0aJMMUtzorfmLTFw1lVNXBATd89dSbua13VZYsBFXD9u3j4AQ "Haskell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~168~~ ~~165~~ 161 bytes ``` def f(m): while m: r,m,s=[*zip(*m)],m[4:],'' while r:s+=chr(10240+sum(q<<int(w)for(q,w)in zip((r[0]+(0,)*3)[:4]+(r+[()])[1],'01263457')));r=r[2:] print(s) ``` [Try it online!](https://tio.run/##nVTNboMwDL7zFNyalBzslm0SKw/QZ4g4bUNFGv0Jnart5RmFDuLYcJgQKMH@/DmfHZ@/r4fTcdu27x9lXKpaZ1F8O1SfH3HdrWJnatPkdv1TndW61oWpbZoVZrXqbIOby5okfzs4hbBJIWm@anXZ7arjVd10eXLqYm66Osb3AMpZKBIFRq@32mZpt3aJVbrQFruYgJvnbfr0stJav7rc2U1WdDRndw/W6HafWwsGDZj@W5gotsOuf8h@sg/P3V5EUan2OoqGiN1ijDhhJ9SMP/bRh@8fF3p/0H/6aODZkfiDh5Kynrx8f8oT6oCyl48fswIhvpSdnxWEZwxYH/agGsg0YNwLWUmKw8gRVoRnJPcMkpfmOtofWfFKh/7jH3IOKX@kSnldAkJ3ANPa50BBnbCetK8oP1cBSQUh6GyYqTqSmmOgi8y6dCchPDHRkZyS3DFkPMjuKQrq8btMquepx/MAVllkCOkktHuAcYCICDsN2dThCFhE0MyDjhMQyzOPcgCbfMBVFLWitxT/gUCGANaTQdVmEPPzEYUJBkEdwp0/ux/93/4C "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 169 bytes ``` a=[] y=0 for l in eval(input()): y-=1;a+=y%4//3*[-~len(l)//2*[10240]];x=0 for v in l:a[-1][x//2]|=v<<(6429374>>y%4*6+x%2*3&7);x+=1 for l in a:print(*map(chr,l),sep='') ``` [Try it online!](https://tio.run/##nZLfaoMwFMbvfYrcdE38g4lKS7Xpi4RchOGokFmxThTGXt3Zweg0J1kpnAuN5/zO5/elGbvzpU6nSXEhvZFT7@3SIo2qGpW90riqm48OE5J7aIw4K1TAx00Wx6kvoi9d1liTOE58wWiSUSmLYSagG6K/IXSuRMSkGOYe@cn74xHvsuSQ7rPTacb4u2DYJH76sifFEHB2363ypq3qDvvvqsGv5zbUJLyWDd9uyTQJQUM0F/tTFCrz071fhkisGCDJPF/0LzCPTIDKfjA2teB/mQ0MxrjtMRX/euOYs2HW2xaYR4yGX10Y0AYKLrRiwIysotcYuhwyH@BAXUkxwwZrps9gGIwx9TP3ZfsH4/CXQVoNDLXcFdvhOkQpvwE "Python 3 – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 53 bytes ``` 4 2∘{⎕ucs 2⊥40⍪(⍎¨⍕76531420)∘.⊃,¨⍺∘↑¨↓∘⍵¨⍺∘ר⍳⌈⍺÷⍨⍴⍵} ``` [Try it online!](https://tio.run/##jVLLSsNAFN3nK2apMMpMm@o/uIgLlyGLYFMJhLSYFpTQlRBCcIoiRTe6E8StiuDS/sn9kXjzaDOTTEAuDPdxzrmPxJ0FB@NrN5he5LBa@1NI7lg@wZeYZADpU4zZxXmEfvZqMhDveyBWv28g1sdHoyE3B2wfUYeQ3dAi@4MBJPfoJg@FK7622c1j4X3AbYrx5hsERp9YX@aWdzXHhjHysNnJ2akFaRaDeFlWDMQQEM/k0nPHJEQwsUjgh15E3Ij44WwxzyekECGmYduMcspo@TrUIHYVlabETb2you4YtdBwK9RQGnAD46MSx6gkIpmcqeulSoNXOXK8q0uMPozai@8m1c1Rr04VxRZDt4ncWz4d67GOlsTo277laRnq5ExV0zDUO3W6KwxGueZtXVF7K@mnop07/ovBOwx5Dq77aj2M7t5c6asyWOs7tCPpeo7zBw "APL (Dyalog Unicode) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 164 bytes 163 bytes of code + 1 flag `-p` ``` @a=eval}{for(;$r<@a;$r+=4){for($c=0;$c<@{$a[0]};$c+=2){$n="0b";map$n.=0|$a[$r+3][$c+$_],1,0;for$y(1,0){map$n.=0|$a[$r+$_][$c+$y],2,1,0}$\.=chr 0x2800+oct$n}$\.=$/} ``` [Try it online!](https://tio.run/##jZH/SsMwEMdfRcb90dKsXqoDoQv0BXyCGiSWicJsSx3iqH11462TevkxkEC43H3u1zf9bthvrK2M2n2Y/TQ@d0NSwrCtDN2Zuk1nDzQKS2i21QimRj2RnakiHaFVK3xalW@mhzZX@EVhSrvRNQHwqIUUWFIBOCZkpaPHETGDRy2KEzrBQ66al@EKP4s7xKxrDtDOTrierE1qFEjc@aBzuOc3rkX9R7sZ/L3EF/4S4fY58X5XdyLulR4f24D3Pc8fUj7PKi38pZ09K8K7E6NbK@BdbYLOjEchI7enXEQfySYOtPsHLz2eTyBjfxTlw22l05Pz6Onuv5hiOv3u@sNr177b9f0mR4l23f8A "Perl 5 – Try It Online") Takes each row comma separated on one line. ]
[Question] [ ## Background In typography, [*rivers*](http://en.wikipedia.org/wiki/River_(typography)) are visual gaps in a block of text, which occur due to coincidental alignment of spaces. These are particularly annoying since your brain seems to pick them up more easily in peripheral vision, which constantly distracts your eyes. As an example, take the following block of text, lines broken such that the line width does not exceed **82 characters**: ``` Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eismod tempor incididunt ut labore et dolore maga aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eismod tempor incididunt ut labore et dolore maga aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ``` There is a river spanning six lines in the bottom right part, which I've highlighted in the following block: ``` Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eismod tempor incididunt ut labore et dolore maga aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem█ipsum dolor sit amet, consectetur adipisicing elit, sed do eismod tempor█incididunt ut labore et dolore maga aliqua. Ut enim ad minim veniam, quis nostrud█exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute█irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla█pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui█officia deserunt mollit anim id est laborum. ``` We can mitigate this by choosing a slightly different column width. E.g. if we layout the same text using lines no longer than **78 characters**, there is no river longer than two lines: ``` Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eismod tempor incididunt ut labore et dolore maga aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eismod tempor incididunt ut labore et dolore maga aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ``` Note that for the purpose of this question we're only considering monospaced fonts, such that rivers are simply vertical columns of spaces. The length of a river is the number of lines it spans. Aside: If you're interesting in river detection in proportional fonts, there are some [interesting](https://tex.stackexchange.com/q/29049/18957) [posts](https://dsp.stackexchange.com/q/374/11608) around the network. ## The Challenge You're given a string of printable ASCII characters (code point 0x20 to 0x7E) - i.e. a single line. Print this text, with a line width between 70 and 90 characters (inclusive), such that the *maximum* length of any river in the text is minimised. If there are multiple text widths with the same (minimal) maximum river length, choose the narrower width. The above example with 78 characters is the correct output for that text. To break lines, you should replace space characters (0x20) with line breaks, such that the resulting lines have as many characters as possible, but not more than the chosen text width. Note that the resulting line break itself is not part of that count. As an example, in the last block above, `Lorem[...]tempor` contains 78 characters, which is also the text's width. You may assume that the input will not contain consecutive spaces, and won't have leading or trailing spaces. You may also assume that no word (consecutive substring of non-spaces) will contain more than 70 characters. You may write a program or function, taking input via STDIN, command-line argument or function argument and printing the result to STDOUT. This is code golf, so the shortest answer (in bytes) wins. [Answer] ## Ruby ~~162 160 158 152 160~~ 157 ([demo](http://ideone.com/1UN9kk)) ``` i=gets+' ' (69..s=r=89).map{|c|w=i.scan(/(.{1,#{c}}\S) /).flatten m=(0..c).map{|i|w.map{|l|l[i]}+[?x]}.join.scan(/ +/).map(&:size).max m<s&&(s=m;r=w)} puts r ``` The un-golfed version: ``` input = gets+' ' result = '' (69..smallest_max=89).each{|w| #split text into words of at most w characters wrap = (input+' ').scan(/(.{1,#{w}}\S) /).flatten #transpose lines and find biggest "river" max_crt_river = (0..99).map{|i| wrap.map{|l|l[i]} }.flatten.join.scan(/ +/).max_by(&:size).size if max_crt_river < smallest_max smallest_max = max_crt_river result = wrap.join ?\n end } puts result ``` [Answer] ## APL (105) ``` {∊{1↓∊⍵,3⊃⎕TC}¨⊃G/⍨V=⌊/V←{⌈/≢¨⊂⍨¨↓⍉2≠⌿+\↑≢¨¨⍵}¨G←(K⊂⍨' '=K←' ',⍵)∘{×⍴⍺:(⊂z/⍺),⍵∇⍨⍺/⍨~z←⍵>+\≢¨⍺⋄⍺}¨70+⍳21} ``` Explanation: * `(K⊂⍨' '=K←' ',⍵)`: Add a space in front of `⍵`, then split `⍵` on the spaces. Each word retains the space it begins with. * `∘{`...`}¨70+⍳21`: with that value, for each number in the range `[71, 91]`: (Because of the way the words are split, each 'line' ends up with an extra space on the beginning, which will be removed later. The range is shifted by one to compensate for the extra space.) + `×⍴⍺:`: if there are still words left, - `z←⍵>+\≢¨⍺`: get the length for each word, and calculate a running total of the length, per word. Mark with a `1` all the words that can be taken to fill up the next line, and store this in `z`. - `(⊂z/⍺),⍵∇⍨⍺⍨~z`: take those words, and then process what's left of the list. + `⋄⍺`: if not, return `⍺` (which is now empty). * `G←`: store the list of lists of lines in `G` (one for each possible line length). * `V←{`...`}¨G`: for each possibility, calculate the length of the longest river and store it in `V`: + `+\↑≢¨¨⍵`: get the length of each word (again), and make a matrix out of the lengths. Calculate the running total for each line on the rows of the matrix. (Thus, the extra space at the beginning of each line is ignored.) + `2≠⌿`: for each *column* of the matrix, see if the current length of the line at that point does not match the line after it. If so, there is *not* a river there. + `⊂⍨¨↓⍉`: split each column of the matrix by itself (on the `1`s). This gives a list of lists, where for each river there will be a list `[1, 0, 0, ...]`, depending on the length of the river. If there is no river, the list will be `[1]`. + `⌈/≢¨`: get the length of each river, and get the maximum value of that. * `⊃G/⍨V=⌊/V`: from `G`, select the first item for which the length of the longest river is equal to the minimum for all items. * `{1↓∊⍵,3⊃⎕TC}¨`: for each line, join all of the words together, remove the fist item (the extra space from the beginning), and add a newline to the end. * `∊`: join all the lines together. [Answer] # Bash+coreutils, 236 157 bytes Edited with a different approach - quite a bit shorter than before: ``` a=(`for i in {71..91};{ for((b=1;b++<i;));{ fold -s$i<<<$@|cut -b$b|uniq -c|sort -nr|grep -m1 "[0-9] " }|sort -nr|sed q }|nl -v71|sort -nk2`) fold -s$a<<<$@ ``` Reads the input string from the command line. With 3 nested sorts, I shudder to think what the big-O time complexity is for this, but it does complete the example in under 10 seconds on my machine. [Answer] # CJam, ~~116 106 99 84 77~~ 72 bytes ``` l:X;93,72>{:D;OOXS/{S+_2$+,D<{+}{@@);a+\}?}/a+}%{z'K*S/:!0a/1fb$W=}$0=N* ``` Takes the single line input and prints the correct output to STDOUT. *UPDATE* : Improved a lot and removed redundant loops by doing all calculations in the sorting loop itself. Also fixed a bug in river length calculation. Explanation soon (after I golf it even further) [Try it here](http://cjam.aditsu.net/) [Answer] # Python 3, 329 bytes ``` import re,itertools as s def b(t,n): l=0;o="" for i in t.split(): if l+len(i)>n:o=o[:-1]+'\n';l=0 l+=len(i)+1;o+=i+' ' return o t=input();o={} for n in range(90,69,-1):o[max([len(max(re.findall('\s+',x),default='')) for x in ["".join(i) for i in s.zip_longest(*b(t,n).split('\n'),fillvalue='')]])]=n print(b(t,o[min(o)])) ``` Ungolfed version: ``` # Iterates over words until length > n, then replaces ' ' with '\n' def b(t,n): l = 0 o = "" for i in t.split(): if l + len(i) > n: o = o[:-1] + '\n' l = 0 l += len(i) + 1 o += i + ' ' return o t = input() o = {} # range from 90 to 70, to add to dict in right order for n in range(90,69,-1): # break text at length n and split text into lines temp = b(t,n).split('\n') # convert columns into rows temp = itertools.zip_longest(*temp, fillvalue='') # convert the char tuples to strings temp = ["".join(i) for i in temp] # findall runs of spaces, get longest run and get length temp = [len(max(re.findall('\s+',x),default='')) for x in temp] # add max river length as dict key, with line length as value o[max(temp)] = n print(b(t,o[min(o)])) ``` [Answer] # Python, 314 bytes Many thanks to SP3000, grc, and FryAmTheEggman: ``` b=range;x=len def p(i): l=[];z='' for n in t: if x(z)+x(n)<=i:z+=n+' ' else:l+=[z];z=n+' ' return l+[z]*(z!=l[x(l)-1]) t=input().split();q=[] for i in b(70,91):l=p(i);q+=[max(sum(x(l[k+1])>j<x(l[k])and l[k][j]is' '==l[k+1][j]for k in b(x(l)-1))for j in b(i))] print(*p(q.index(min(q))+70),sep='\n') ``` [Answer] # JavaScript (ES6) 194 ~~202~~ Iterative solution, maybe shorter if made recursive ``` F=s=>{ for(m=1e6,b=' ',n=70;n<91;n++) l=b+'x'.repeat(n),x=r=q='', (s+l).split(b).map(w=> (t=l,l+=b+w)[n]&&( l=w,r=r?[...t].map((c,p)=>x<(v=c>b?0:-~r[p])?x=v:v,q+=t+'\n'):[] ) ),x<m&&(o=q,m=x); alert(o) } ``` **Explained** ``` F=s=> { m = 1e9; // global max river length, start at high value for(n=70; n < 91; n++) // loop on line length { l=' '+'x'.repeat(n), // a too long first word, to force a split and start x=0, // current max river length q='', // current line splitted text r=0, // current river length for each column (start 0 to mark first loop) (s+l) // add a too long word to force a last split. Last and first row will not be managed .split(' ').map(w=> // repeat for each word ( t=l, // current partial row in t (first one will be dropped) (l += ' '+w)[n] // add word to partial row and check if too long && ( l = w, // start a new partial row with current word r=r? // update array r if not at first loop ( q+=t+'\n', // current row + newline added to complete text [...t].map((c,p)=>( // for each char c at position p in row t v = c != ' ' ? 0 // if c is not space, reset river length at 0 : -~r[p], // if c is space, increment river length x<v ? x=v : v // if current > max, update max )) ):[] ) ) ) x < m && ( // if current max less than global max, save current text and current max o = q, m = x ) } console.log(o,m) } ``` **Test** in FireFox/FireBug console. ``` F('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eismod tempor incididunt ut labore et dolore maga aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eismod tempor incididunt ut labore et dolore maga aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.') ``` *Output* ``` Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eismod tempor incididunt ut labore et dolore maga aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eismod tempor incididunt ut labore et dolore maga aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes ``` Z=⁶ŒgẎ§Ṁ KƤẈ>Tị⁸ðƬœ-ƝK€ ḲçⱮ70r90¤ÑÞḢY ``` [Try it online!](https://tio.run/##7ZG/TtRBEMd7nmIeAC50xkIqrLDUQrthd@4Ys//YnSHQgZWJiQlaS0FIaAhRC3Nix4V7j9@9yM9ZTx/ChG53Z@Y73@9n31IIJ@P45tnq7MfDp9lw9/H@evh5urG3vBru3u@8HH59WJ3NF1@XNw@ft5Zf9lbvbjaG@ffF9erb7ZPt@nT7/mpxvrgY5pevx3F8kStF4NI0gs8hV2gsgJFkE1xOjZyQaAX0XLix4zQDCmzVRt4mgLjF7EEoFhvm5Niz1ySgAgH3TR5I1tIEEWcIGPhQcQKvBChxNGmI3A9HdsW4CYfKDVJuUtUDHVN1LCicE2gIGF1eC/cms9QX/ZHkYs1AaL6jWcpr/7ZKJrDbJVGFgKuakXVUTlCpVDqg5Klabns4ykGLrSOzYzmBWiNwHMI/QJZHYaozRoHUDUHBahetE3h@7KgIaadoCLJzSM76nBb2KH3CUpSa2VPqDDsoW@o0FOy5IU@nBhnBU6PaqzGHbgM7IDYc7S9WjRN4/Lz/9/N@Aw "Jelly – Try It Online") ## How it works ``` Z=⁶ŒgẎ§Ṁ - Link 1: Calculating max river length - Takes a list of lines on the left Z - Transpose =⁶ - Map spaces to 1 and everything else to 0 Œg - Over each row, group adjacent equal values Ẏ - Tighten, removing the rows § - Sum each The groups of adjacent elements are either runs of 0 or 1 The sums map runs of 0s to 0, and runs of 1 to their lengths Ṁ - Yield the maximum KƤẈ>Tị⁸ðƬœ-ƝK€ - Link 2: Breaks a string into a line width limited paragraph - Takes a list of words W on the left and a width N on the right ð - Group into a dyad f(W, N): Ƥ - Over each prefix of W: K - Join it by spaces Ẉ - Length of each > - Greater than N? T - Indices of truthy elements ị⁸ - Index into W This removes elements from W up the width N Ƭ - Repeatedly apply f(W, N) until a fixed point Ɲ - Over each overlapping pair [a, b]: œ- - Remove each element of b from a K€ - Join by spaces ḲçⱮ70r90¤ÑÞḢY - Main link. Takes a string S on the left Ḳ - Split S into words, W ¤ - Create a nilad: 70 - 70 90 - 90 r - Inclusive range; [70, 71, ..., 89, 90] Ɱ - Over each element i in the range: ç - Call Link 2 with W on the left and i on the right Þ - Sort by: Ñ - Max river length (Link 1) Ḣ - First element (the narrowest width, and shortest river) Y - Join by newlines ``` ]
[Question] [ ![enter image description here](https://i.stack.imgur.com/6dfRm.png) > > Your life could depend on this. Don't blink. Don't even blink. Blink and you're dead. They are fast. Faster than you can believe. Don't turn your back, don't look away, and don't blink! **Good luck.** > > > [Weeping Angels](http://en.wikipedia.org/wiki/Weeping_Angel) are an alien race that cannot move while being observed by another being (even another Angel). They feed by sending their victims back in time. You ([The Doctor](http://en.wikipedia.org/wiki/Doctor_(Doctor_Who))) are trapped in a room with some, and you need to get to your TARDIS. --- ### Task Write a program that will, given an ASCII representation of a rectangular room, output a path that will lead you to safety. If any Angel can attack — *at any time during your progress* — then that path is not safe. An Angel can attack if it can see you while not being seen by you or another Angel. ### Input Input is two parts. First, the direction you're facing (NSEW). Then on succeeding lines, a representation of the room, showing start/end locations, and the location/facing of all Angels. The sample below shows that there is one angel facing west, and you start facing south. ``` S .......... ....D..... .......... .......... .......... .......... .......... .......... .........W .......... ...T...... ``` * **`.`** - Empty space * **`D`** - The Doctor (starting position) * **`T`** - The TARDIS (end position) * **`N,S,E,W`** - An Angel, facing the direction specified (north, south, east, west) ### Line of sight You can see any space withing 45 degrees of the direction you're facing. Line of sight is obstructed if there is another entity along a direct horizontal, vertical, or 45-degree diagonal. Any other diagonal does **not** obstruct the view. Angels' line of sight works in the same way. For example, in the following, `-` represents your field of view, assuming you're facing south. ``` ........ ...D.... ..---... .-----.. -------. ---N---- ---.--N- ---.---- ``` ### Output The output is a string representing the path you will take to exit. If there are multiple safe paths, choose any one. If no path is safe, output `0`. If the map is malformed, do whatever you like, including crashing out. Consider it malformed if the room is not rectangular, there is no exit, etc. If there are no Angels, it's not malformed, simply easy. For each step, you can do one of two things: move in a NSEW direction, or turn to a NSEW direction (without changing positions). To move, simply output the letter for that direction. To turn to face a direction, output `F` followed by the appropriate letter. For example, the following output: ``` SSFESSSSSSSW ``` is a safe path for the sample given in the input section. You move south twice, face east to keep the angel in sight, then move south seven more times and west once to enter the TARDIS. ### Test Cases 1) You can go around the east-facing Angel to get to the TARDIS. Unless you step directly between them, they lock each other in place, so it doesn't matter which way you're facing at any point. ``` W ...D.... ........ ........ ........ .E.....W ........ ........ ...T.... ``` 2) You lose. There's no way to get past them. They can see each other until you step between them. At that point, you can't face them both and you're done. Might as well just shut your eyes and get it over with. ``` S ...D.... ........ ........ ........ E......W ........ ........ ...T.... ``` ### Winning Standard golf rules and [loopholes](https://codegolf.meta.stackexchange.com/q/1061/14215) apply, least bytes wins. I'll try to get some more test cases soon, but feel free to suggest your own in the meantime. Image and quote from Doctor Who. [Answer] ## C# ~~1771~~ ~~2034~~ ~~1962~~ ~~1887~~ 1347bytes *Re-wrote the blocking LOS checking in 1 loop, making it much tidier, and about 450bytes shorter* ``` using C=System.Console;using T=System.Math;struct P{int x,y,d;static void Main(){int v=C.ReadLine()[0],w,h,i,o=0,x=0,y=0,O,E,F,e=46;var R=C.In.ReadToEnd().Replace("\r","");var M=new int[w=R.IndexOf("\n"),h=(R.Length+1)/(w+1)];for(;o<h;o++)for(i=0;i<w;i++)if((M[i,o]=R[o+o*w+i])==68)M[x=i,y=o]=e;System.Func<int,int,int,bool>S=null;S=(X,Y,D)=>{var Z="SSSE_WNNNE_W___E_W";int I=0,H=0,L=0,J=Y,K=M[X,Y],B;M[X,Y]=D>0?D:K;for(H=0;H<9;H++)for(I=X,J=Y;H!=4&(I+=H%3-1)<w&I>=0&(J+=H/3-1)<h&&J>=0;){if(((B=M[I,J])==Z[H]|B==Z[H+9])&(D<1||!S(I,J,0)))goto W;if(B!=e)break;}for(B=I=-1;++I<w;B=1)for(J=0;J<h;J++)if(I!=X&J!=Y&(((B=M[I,J])==87&I>X&(H=T.Abs(J-Y))<I-X)|(B==69&I<X&H<X-I)|(B==78&J>Y&(L=T.Abs(I-X))<J-Y)|(B==83&J<Y&L<Y-J))&(D<1||!S(I,J,0)))goto W;W:M[X,Y]=K;return B>1;};P a,p=new P{x=x,y=y,d=v};var A=new System.Collections.Generic.List<P>();System.Action q=()=>{if(((E=M[p.x,p.y])==e|E==84)&!A.Contains(p)&!S(p.x,p.y,p.d))A.Add(p);};q();for(o=0;(O=A.Count)!=o;o=O)for(i=O;i-->o;){p=A[i];if((E=M[p.x,p.y])==84)for(R="";;p=a){i=0;n:a=A[i++];O=T.Abs(p.y-a.y)+T.Abs(a.x-p.x);if(O==1&p.d==a.d)R=(a.y-p.y==1?"N":p.y-a.y==1?"S":a.x-p.x==1?"W":"E")+R;else if(O<1)R="F"+(char)p.d+R;else goto n;if(i<2)goto Z;}if(E==e){if(p.x-->0)q();p.x+=2;if(p.x<w)q();p.x--;if(p.y-->0)q();p.y+=2;if(p.y<h)q();p.y--;for(F=0;F<4;q())p.d="NESW"[F++];}}R="0";Z:C.WriteLine(R);}} ``` This is a complete program that expects the input to terminate with an EOF and be passed to STDIN. It (hopefully) prints the shortest path to the TARDIS, or "0" if no path exists. It uses a shoddy Breadth First Search to follow all possible routes, then it backtracks from the TARDIS to The Doctor to assemble the output. Formatted code: ``` using C=System.Console; using T=System.Math; struct P { int x,y,d; static void Main() { int v=C.ReadLine()[0],w,h,i,o=0,x=0,y=0,O,E,F,e=46; var R=C.In.ReadToEnd().Replace("\r",""); var M=new int[w=R.IndexOf("\n"),h=(R.Length+1)/(w+1)]; for(;o<h;o++) for(i=0;i<w;i++) if((M[i,o]=R[o+o*w+i])==68) M[x=i,y=o]=e; System.Func<int,int,int,bool>S=null; S=(X,Y,D)=> { var Z="SSSE_WNNNE_W___E_W"; int I=0,H=0,L=0,J=Y,K=M[X,Y],B; M[X,Y]=D>0?D:K; for(H=0;H<9;H++) for(I=X,J=Y;H!=4&(I+=H%3-1)<w&I>=0&(J+=H/3-1)<h&&J>=0;) { if(((B=M[I,J])==Z[H]|B==Z[H+9])&(D<1||!S(I,J,0))) goto W; if(B!=e) break; } for(B=I=-1;++I<w;B=1) for(J=0;J<h;J++) if(I!=X&J!=Y&(((B=M[I,J])==87&I>X&(H=T.Abs(J-Y))<I-X)|(B==69&I<X&H<X-I)|(B==78&J>Y&(L=T.Abs(I-X))<J-Y)|(B==83&J<Y&L<Y-J))&(D<1||!S(I,J,0))) goto W; W: M[X,Y]=K; return B>1; }; P a,p=new P{x=x,y=y,d=v}; var A=new System.Collections.Generic.List<P>(); System.Action q=()=>{if(((E=M[p.x,p.y])==e|E==84)&!A.Contains(p)&!S(p.x,p.y,p.d))A.Add(p);}; q(); for(o=0;(O=A.Count)!=o;o=O) for(i=O;i-->o;) { p=A[i]; if((E=M[p.x,p.y])==84) for(R="";;p=a) { i=0; n: a=A[i++]; O=T.Abs(p.y-a.y)+T.Abs(a.x-p.x); if(O==1&p.d==a.d) R=(a.y-p.y==1?"N":p.y-a.y==1?"S":a.x-p.x==1?"W":"E")+R; else if(O<1) R="F"+(char)p.d+R; else goto n; if(i<2) goto Z; } if(E==e) { if(p.x-->0)q(); p.x+=2;if(p.x<w)q();p.x--; if(p.y-->0)q(); p.y+=2;if(p.y<h)q();p.y--; for(F=0;F<4;q()) p.d="NESW"[F++]; } } R="0"; Z: C.WriteLine(R); } } ``` Output for example input ``` SFESWSSSSSSS ``` Output for test case 1) ``` WSWSWSSSESESE ``` Output for test case 2) ``` 0 ``` I present, as requested, a new test case: ``` S ..E..DS.... ........... ........... ........... ........... ........... ........... ........... ....SSSSS.W .......T... ``` My program outputs ``` SESESESESFNSSSSWW ``` WozzeC's Test Case 1: ``` EEEEFWSSSFNWWN ``` WozzeC's Test Case 2: ``` FSEEEESFWSSSSWFNWWWNFENNEES ``` [Answer] # Python – ~~559 565 644~~ 633 ``` M=input() I=1j Q={"S":I,"N":-I,"E":1,"W":-1} A=[] e=enumerate for y,l in e(M[2:].split()): for x,c in e(l): P=x+y*1j if c=="D":D=(P,Q[M[0]]) elif c=="T":T=P elif c!=".":A+=[(P,Q[c])] def s(D,h,r=[]): def L(X,p,d): S=[p+d*(i+j*I)for i in range(x+y)for j in range(-i+1,i)if j] for f in[1,1+I,1-I]: i=0 while i<x+y>1>(S[-1]in[a[0]for a in[D]+A]+[T])*i:i+=1;S+=[p+i*f*d] return X[0]in S if y>=D[0].imag>=(D[0]in[a[0]for a in A])<all(any(L(a,*b)for b in[D]+A)for a in A if L(D,*a))>(D in r)<=D[0].real<=x: r+=[D] if D[0]==T:print h;exit() for n in"SWEN":s((D[0]+Q[n],D[1]),h+n,r);s((D[0],Q[n]),h+"F"+n,r) s(D,"") print"0" ``` Input has to be provided like this: ``` "W\n...D....\n........\n........\n........\nE......W\n........\n........\n...T....\n" ``` Essentially it’s [this approach](https://codegolf.stackexchange.com/a/26157/11354) applied to finding all states (position and direction) the Doctor can safely reach, storing how he got there and printing the way in case of success. Positions and directions are realised with complex numbers. I could probably safe some chars using Sage’s complex number arithmetics, but that would run extremely long. I first thought I could save six characters by having the Doctor turn into a specific direction after reaching the Tardis, but I realised that this could result in wrong solutions. Also I first misread the rules. Here is a mostly ungolfed version: ``` Map = input() I = 1j string_to_dir = {"S":I,"N":-I,"E":1,"W":-1} Angels = [] Pos = 0 direction = string_to_dir[Map[0]] for y,line in enumerate(Map[2:].split()): for x,char in enumerate(line): Pos = x+y*1j if char == "D": Doctor = (Pos, direction) elif char == "T": Tardis = (Pos, direction) elif char != ".": Angels += [(Pos,string_to_dir[char])] reachables = [] def display(LoS, Doctor): string = "" for y,line in enumerate(Map[2:].split()): for x,char in enumerate(line): if x+y*1j == Doctor[0]: string += "D" elif x+y*1j in LoS: if char in ".D": string += "*" else: string += "X" elif char != "D": string += char else: string += "." string += "\n" print string def LoS(angel,Doctor): p,d = angel Sight = [] for i in range(x+y): for j in set(range(-i+1,i))-{0}: Sight += [p+d*i+d*j*I] for line in [d, (1+I)*d, (1-I)*d]: for i in range(1,x+y): Pos = p + i*line Sight += [Pos] if Pos in [angel[0] for angel in Angels+[Doctor, Tardis]]: break return Sight def search(Doctor, history): global reachables Sight = sum([LoS(angel, Doctor) for angel in [Doctor]+Angels],[]) if ( all(angel[0] in Sight for angel in Angels if Doctor[0] in LoS(angel, Doctor)) and not (Doctor in reachables) and (0<=Doctor[0].imag<=y) and (0<=Doctor[0].real<=x) and (Doctor[0] not in [angel[0] for angel in Angels]) ): reachables += [Doctor] if Doctor[0] == Tardis[0]: print history exit() for new_direction in "SWEN": search((Doctor[0]+string_to_dir[new_direction], Doctor[1]), history + new_direction) search((Doctor[0], string_to_dir[new_direction]), history + "F" + new_direction) search(Doctor, "") print "0" ``` # Test Cases Test case 1: ``` SSSFSWWWSSSSFWEFSEFWE ``` Test case 2: ``` 0 ``` VisualMelon’s test case: ``` SSFWSSSSSFSWWSSWWWFWEEEEFSEFWEFSE ``` [Answer] # C# ~~1454, 1396, 1373, 1303~~ 1279 ``` class P{static int x,d,y=x=d=55,o=170,X=0,Y=0,u,k=3;static string[,]t=new string[o,o];static int[,]m=new int[o,o];static string e=" NS ETD W .",q="0";static void Main(string[]s){m[0,1]=m[1,8]=-1;m[0,2]=m[1,4]=1;u=e.IndexOf(s[0][0]);for(;k<s[0].Length;k++){var c=s[0][k];if(c=='D'){X=x;Y=y;}if(c=='\\'){y++;x=d;k++;}else m[y,x++]=e.IndexOf(c);}k=A(X,Y,1);if((k&u)!=0){W(X,Y,k,"");}System.Console.Write(q);}static void W(int x,int y,int h,string s){t[y,x]=s;for(int i=1;i<9;i*=2){int l=y+m[0,i],g=x+m[1,i];if(m[l,g]==5)q=t[l,g]=s+e[i];else if(m[l,g]==15){m[l,g]=6;m[y,x]=15;int n=A(g,l,1),U;for(int j=1;j<9;j*=2){var z=t[l,g]??s;if((n&h&j)!=0&z.Length>=s.Length){U=u;u=j;W(g,l,n,s+((u!=j)?"F"+e[j]:"")+e[i]);u=U;}}m[y,x]=6;m[l,g]=0;}}}static int A(int x,int y,int L){int r=15,a,b,c,f=0,g,h,R,B;for(a=1;a<d-5;a++){g=1;for(b=y-a;b<=y+a;b++)for(c=x-a;c<=x+a;c++){B=m[b,c];R=0;bool W=(c+a-x)%a==0,V=(b+a-y)%a==0,z=W&V;if(B>0&B<9&B!=6&B!=5&g!=16&!((W|V)&(f&g)!=0)){h=R;if(b==y-a){R=1;if(c==x-a){h=4;R=9;}else if(c==x+a){h=8;R=5;}B&=h&2;}else if(b==y+a){R=2;if(c==x-a){h=4;R=10;}else if(c==x+a){h=8;R=6;}B&=h&1;}else if(c==x-a){B&=4;R=8;}else if(c==x+a){B&=8;R=4;}else B=0;if(B!=0){if(L==1&&A(c,b,0)==15)r&=R;if(L==0)return R;}}if(z){if(B<9&B>0&!(c==x&y==b))f|=g;g*=2;}}}return r;}} ``` Right. So I decided to give this a go, and boy did it take a while. It's built up mostly using logical operators. * North = 1 = N * South = 2 = S * East = 4 = E * West = 8 = W * Doctor = 6 = D * TARDIS = 5 = T * 15 = . <-All free spaces To avoid having to check for Null etc. I decided to use a field of [MAX\_SIZE\*3]\*[MAX\_SIZE]\*3 and put the game board close to the center. Loop checks are done inside and out all the way to 50(MAX\_SIZE). So something like this: ``` 22222 21112 21D12 21112 22222 ``` When a E W S or N is found I do the same check on their part. If anything is found looking at the Angels (Not the Doctor) they return 15 as free passage. If they are not looked upon they return in which way the Doctor should face to be safe. i.e N would return 2 for south. Unless it is NW or NE in which case it would return 6(2+4) and 10(2+8) respectively. If two angels are watching the Doctor the return values from these would be "ANDed" so in the test example 2 crunchpositions 4 AND 8 would turn into 0. Meaning that the position is bad and should be avoided. Expanded code: ``` class P { static int x,d,y=x=d=55,o=170,X=0,Y=0,u,k=3; static string[,] t = new string[o, o]; static int[,] m = new int[o, o]; static string e = " NS ETD W .", q="0"; static void Main(string[]s) { m[0, 1]=m[1, 8]=-1; m[0, 2]=m[1, 4]=1; u=e.IndexOf(s[0][0]); for (;k<s[0].Length;k++) { var c = s[0][k]; if (c == 'D') { X = x; Y = y; } if (c == '\\') { y++; x = d; k++; } else m[y, x++] = e.IndexOf(c); } k=A(X,Y,1); if ((k&u)!=0) { W(X, Y, k,""); } System.Console.Write(q); } static void W(int x,int y,int h,string s){ t[y, x] = s; for (int i = 1; i < 9; i*=2) { int l = y+m[0, i], g = x+m[1, i]; if (m[l, g] == 5) q = t[l, g] = s + e[i]; else if (m[l, g] == 15) { m[l, g] = 6; m[y, x] = 15; int n = A(g, l,1),U; for (int j = 1; j < 9; j *= 2) { var z = t[l, g]??s; if ((n & h & j) != 0 & z.Length>=s.Length) { U = u; u = j; W(g, l, n,s+((u != j) ? "F" + e[j] : "") + e[i]); u = U; } } m[y, x] = 6; m[l, g] = 0; } } } static int A(int x, int y,int L) { int r = 15,a,b,c,f=0,g,h,R,B; for (a = 1; a < d - 5; a++) { g = 1; for (b = y - a; b <= y + a; b++) for (c = x - a; c <= x + a; c++) { B=m[b, c]; R=0; bool W=(c+a-x)%a==0,V=(b+a-y)%a==0,z=W&V; if (B>0&B<9&B!=6&B!=5&g!=16&!((W|V)&(f&g)!=0)) { h=R; if (b==y-a) { R=1; if(c==x-a){h=4;R=9;} else if(c==x+a){h=8;R=5;} B&=h&2; } else if (b==y+a) { R=2; if(c==x-a){h=4;R=10;} else if (c==x+a){h=8;R=6;} B&=h&1; } else if(c==x-a){B&=4;R=8;} else if(c==x+a){B&=8;R=4;} else B=0; if (B!=0) { if(L==1&&A(c,b,0)==15)r&=R; if (L==0)return R; } } if (z) { if (B < 9 & B > 0 & !(c==x&y==b)) f |= g; g *= 2; } } } return r; } } ``` # Test results 1 Example: FNSSSWNNNWSSSWSSSSENNESES 2 Example: No way out VisualMelon Example: FNSSSSSSSWNNNNNNNWSSSSSSSSSEEEE My Test case1: FSSENEEEFWSSFNSWWN My Test case2: FSEEEESFWSSSSFNWWWWNFENNFSEES As can be seen my Doctor loves strutting around like a douche to show the Angels how fun it is to move around. I can make the software find the shortest path, but it takes longer and needs more code. # Test cases for you guys ``` S D.... ..NE. .WTS. .S... ``` Another one: ``` E D.... WNNN. ...E. .WTE. .SSE. ..... ``` ]
[Question] [ You've recently made an account on a dodgy gambling site, where for a fee of 25 dollars, they will pay you back a random amount between 0 and 50 dollars. After getting around 5 dollars twice, you decide to prove the site is a scam. After accessing their external firewall with the default password, you find your way onto their database server, and find where the values for the minimum and maximum amounts are held. You decide to plug 25 '9's in as the maximum value, but get an error message saying the maximum value must be of type 'uint64'. However it is now that you notice some number keys don't seem to type into the remote console correctly. The challenge appears before you almost as if typed up on a Q+A site. using only the conveniently installed programs for testing and executing your particular language, output the maximum size of an unsigned 64-bit integer value, however almost everything except the programming tools are broken on this machine, leaving you without the use of the numbers 1,2,4,6,8 - in either source code or literals, you also notice that it seems to take an exponentially longer amount of time to execute the program for each additional piece of code, so you'd better keep it short if you want to get rich before the drawing! --- # The Challenge * Write a program which outputs 18446744073709551615, the maximum value of an unsigned 64-bit integer, as either a number, or a single string. * Your source code cannot contain any of the characters '1','2','4','6' or '8' * if your language does not have an unsigned 64-bit integer or equivalent, the output can be in string format or otherwise, but must be the above number. * this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in each language wins! [Answer] # C, 26 bytes ``` main(){printf("%lu",~0l);} ``` Prints a `unsigned long` value. Requires the size of `long` to be 64 bits. [Answer] ## 64-bit SBCL Common Lisp, 18 bytes `most-positive-word` Most positive word on 64-bit compiler is 64uint. It's something. [Answer] ## CJam (4 bytes) ``` GG#( ``` [Online demo](http://cjam.aditsu.net/#code=GG%23() This calculates 1616 - 1 using builtin `G` for 16 and the decrement operator `(`. [Answer] # [Beeswax](https://github.com/m-lohmann/BeeswaxEsolang.jl), 3 bytes ``` _M{ ``` Explanation: ``` _ # Create a bee going horizontally across the line, reading the code M # Decrement the bee's counter, which starts at 0. # This will set the counter to 2^64-1, because as bees don't have a concept of # negative numbers, all values that are negative are translated to 2^64-n, # and in this case, n = -1, as we are calculating 0 - 1. { # Print the value ``` [Try it online!](https://tio.run/nexus/beeswax#@x/vW/3/PwA "Beeswax – TIO Nexus") This language is *perfect* for this challenge. Here is an extract from the [Esolang page on Beeswax](https://esolangs.org/wiki/Beeswax): > > As everyone knows, bees don’t have a concept of negative numbers, but they discovered that they can use the most significant bit of an address to get around that. Thus, coordinates relative to a bee’s position are realized by the [two’s complements](https://en.wikipedia.org/wiki/Two%27s_complement) of the coordinates. This way, half of the 64-bit address space is available for local addressing without wraparound in each direction. > > > The maximum positive 64-bit two’s complement address is 9223372036854775807 or 0x7fffffffffffffff in 64 bit hex. All values from 0 up to this value translate identically to the same 64 bit value. All values n in the opposite (negative) direction translate to 2^64-n. For example: n=-1 is addressed by 18446744073709551615. n=-9223372036854775808 is addressed by 9223372036854775808. > > > This is basically unsigned longs. EDIT: I'm still expecting Dennis to outgolf me with a 2-byte solution. [Answer] # Python3 REPL, 12 bytes In REPL: `~-(~-3<<9*7)` Outside of REPL: `print~-(~-3<<9*7)` <--> Python2! Here's another one at 17 bytes: `~-(~-3<<ord("?"))`. ## Explanation Nothing super fancy. Here's it broken down: ``` ~- | Subtract 1 from the next value. ( | ~-3 | Subtract 1 from 3, resulting in 2 << | Binary shift 2's digits to left, 9*7 | by 9*7 (63). ) | The value inside the parentheses is now 2**64. ``` The resulting expression is roughly (but not quite) `~-(2<<63)` -> `(2**64)-1`. I use the [tadpole operator](https://blogs.msdn.microsoft.com/oldnewthing/20150525-00/?p=45044) twice here. A golfing tip about it is [here](https://codegolf.stackexchange.com/a/37553/41754). There is also `sys.maxint` in Python2 which can be used, but I won't be looking at that. [repl.it](https://repl.it/Fr7H/0) <- testing link. [Answer] # bc, ~~15~~ 13 bytes *Saved 2 bytes thanks to manatwork.* ``` (a=9+7)^a-3/3 ``` Nothing fancy, just (16^16)-1. [Answer] ## [dc](https://en.wikipedia.org/wiki/Dc_(computer_program)), 7 bytes I think it's allowed for stack based languages to leave the answer on the top cell of the stack, similar to a return value for functions. If explicit printing is needed, add `p` at the end of the code. ``` AZ5E^z- ``` [**Try it online!**](https://tio.run/nexus/dc#@@8YZeoaV6Vb8P8/AA) It computes (2 64 - 1) using several tricks: * `2` is given as the number of digits (`Z`) found in integer 10 (`A`) * `64` is given as `5E`. By default dc uses 10 as the input radix. Even so, it can accept numbers in hexadecimal notation, but they will be converted differently than you'd expect. Example: (5E)default = (5E)(input radix = 10) = (5 \* 10 1) + (14(E) \* 10 0) = 50 + 14 = 64 * `1` is given as the stack's depth (`z`), since only (2 64) was present then ### Alternative story: > > However it is now that you notice some number keys don't seem to type > into the remote console correctly. You take a deep breath and start > testing each numerical key. It is worse than you thought! Not a single > one works, and you're left with the task to produce your desired > integer by using only letters and symbols. > > > **Solution in dc:** computing (16 16 - 1), still 7 bytes! ``` Fz+d^z- # push 15, push 1, add, duplicate, exponentiate, push 1, subtract ``` [**Try it online!**](https://tio.run/nexus/dc#@@9WpZ0SV6Vb8P8/AA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` žJn< ``` Explanation: ``` žJ # Push 4294967296 n # Squared < # Decreased by one ``` Finally! A chance to use `05AB1E`'s builtins for powers of two! [Try it online!](https://tio.run/nexus/05ab1e#@390n1eezf//AA "05AB1E – TIO Nexus") Another 4 byte answer: ``` žxo< ``` Explanation: ``` o # 2 to the power of žx # 64 < # Decreased by one ``` [Try it online!](https://tio.run/nexus/05ab1e#@390X0W@zf//AA "05AB1E – TIO Nexus") (if anyone is wondering, this question is older than all the other 4-byte answers) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ⁴*`’ ``` [Try it online!](https://tio.run/nexus/jelly#@/@ocYtWwqOGmf//AwA "Jelly – TIO Nexus") **Explanation** ``` ⁴ # 16 * # exponentiate ` # last link as a monad, repeating the argument ’ # decrement ``` [Answer] # MATLAB / Octave, 5 bytes @Sanchises posted an excellent MATLAB answer, however this one is a considerably different approach, so I'll post it anyway: ``` tic/0 ``` In MATLAB, `tic` returns the number of milliseconds past since the program was opened. Crucially the value it returns is a `uint64` type. This gets away from having to cast a number to `uint64` from MATLABs default type of `double`. Any number divided by 0 in MATLAB is considered as infinity which for non-floating point types, MATLAB represents this as the maximum integer value for that type. --- This also works with **Octave** though depending on which interpreter you use it may spit out a "division by zero" warning as well. You can try the code [online here](http://octave-online.net/) though as I say you get a /0 warning that doesn't appear in MATLAB. [Answer] # [Java (JDK)](http://jdk.java.net/), 28 bytes ``` v->Long.toUnsignedString(~0) ``` [Try it online!](https://tio.run/##NYw9D4IwEIZ3fsWNNJHGHWV00onoYhwqH02xXBt6JSEG/3qtgNPde8/zXidGkXX1K6jemoGgi5l7Upq3HitSBvlpW/LE@qdWFVRaOAcXoRDeCcB2dSQojtGoGvrI0pIGhfL@ADFIxxYV4P/scIveblUKaOEIYcyKs0HJyVzRKYlNveL0s2chX9rl5KjpufHEbUSkMW25sFZPKXqtGftpczKHLw "Java (JDK) – Try It Online") [Answer] # [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html), ~~18~~, 16 bytes * Saved 2 bytes, thx @MrScapegrace ``` (9-7)^(55+9)-3/3 ``` [Answer] ### PHP, 16 bytes This is much like the answer from Ven: <https://codegolf.stackexchange.com/a/110751/38505> ``` printf("%u",~0); ``` <https://repl.it/Frcy/0> > > For this to work, you need to be in a 64-bit architecture. This is because ~0 is -1, which is 111111111111111111111111111111111111111111111111111111111111‌​1111 in binary, in 64 bits, compared to 11111111111111111111111111111111 in 32-bits, and the numbers are plataform-dependent - [Ismael Miguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel) > > > [Answer] ## MATLAB / Octave, 22 bytes ``` eye(['~rw}?='-9 ''])/0 ``` [Try it online!](https://tio.run/nexus/octave#@59amaoRrV5XVF5rb6uua6mgrh6rqW/w/z8A "Octave – TIO Nexus") `eye` is used to create a unit matrix (matrix with `1` on the diagonal, zero otherwise). Without arguments, this creates a `1x1` unit matrix, or in other words, just a `1`. It takes an optional argument, which is the data type ('class' in MATLAB terminology) of the created matrix. We thus ask for a `1` of class `uint64` , and divide it by zero which results in `Inf` in MATLAB, which gets clipped at `intmax('uint64')`. The vector `['~rw}?='-9 '']` evaluates to `'uint64'`. Concatenating an empty char to a vector is 1 byte shorter than using `char('~rw}?='-9)`. Reasoning towards this answer: the built-in `intmax` sadly evaluates to the maximum of a 32 bit signed integer. The obvious next option is `uint64()`, which contains the forbidden characters. The alternative is to use a function that takes a string as a data type. Obvious candidates are `intmax` and `cast`, but alternatives include `zeros`, `ones` and `eye`. ``` eye(['~rw}?='-9 ''])/0 % Winning version! 22 bytes. intmax(['~rw}?='-9 '']) % Obvious candidate. 23 bytes. 1/zeros(['~rw}?='-9 '']) % 24 bytes cast(Inf,['~rw}?='-9 '']) % 25 bytes. Also an obvious candidate, but actually very long. ``` Note: MATLAB is installed by default on virtually all dodgy gambling sites. [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), ~~29~~ 14 bytes ``` 0xC000PB/3-3/3 ``` [Try it online!](https://tio.run/nexus/powershell#@29Q4WxgYBDgpG@sa6xv/P8/AA "PowerShell – TIO Nexus") *Thanks to @n0rd for essentially golfing this in half.* This leverages the inbuilt unary `PB` operator that basically functions as "multiply the preceding number by `1125899906842624`" (i.e., how many bytes are in a pebibyte). That's coupled with the hex `0xC000`, or `49152`, so `49152 pebibytes`. We divide that by `3`, yielding `18446744073709551616`, and subtract `3/3` to get the final value. [Answer] # BF, 108 bytes ``` -[----->+<]>--.+++++++.----..++.+.---..----.+++++++.----.++++.-------.+++++++++.----..----.+++++.-----.++++. ``` If each command is considered as 3 bits, this is potentially 41 bytes. [Answer] # [Retina](https://github.com/m-ender/retina), ~~28~~ 27 bytes *Saved 1 byte thanks to Kritixi Lithos* ``` bieegheeahdhajffbgbf T`l`d ``` [Try it online!](https://tio.run/nexus/retina#@8@VlJmamp6RmpqYkZKRmJWWlpSelMYVkpCTkPL/PwA "Retina – TIO Nexus") **Explanation** ``` bieegheeahdhajffbgbf ``` Replaces the non-existent/empty input with this string. This particular string was generated by the "inverse" of this program. It encodes `a` through `j` as `0` through `9`, respectively. ``` T`l`d ``` This is a `T`ransliteration stage. The `l` and `d` are character sets used for transliteration. `l` represents the lowercase alphabet, `d` is all digits. So, it maps `abcdefghij` back to `0123456789`. [Answer] ## JavaScript, ~~39~~ ~~38~~ ~~33~~ 32 bytes ``` alert(0xafebff0+'737095'+0xc99f) ``` Edit: Saved 5 bytes thanks to @Arnauld. [Answer] ## Python3 REPL, 11 bytes ``` ~0^~0>>~077 ``` ### How it works * ~0 is -1 (two's complement, an infinite sequence of '1's) * 077 is 63 in octal, so ~077 is -64 * Shift right with negative parameter is a shift to the left * Putting all together, -1 xor (-1 << 64) is the number we are looking for [Answer] # JavaScript (ES6), 50 bytes ``` [...'䠎ᴐIF╏ɧ'].map(s=>s.charCodeAt()).join`` ``` [Answer] # C++, 46 bytes. ``` int m(){std::cout<<unsigned long long(5+3-9);} ``` First time ever doing a code golf, but I'm fairly happy with myself. Will happily take any critique/suggestions :) [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~64, 62, 58~~, 54 bytes ``` (((((()()()()){}){}){}){}){({}<(({}()){}[()])>[()])}{} ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XwMMNCFQs7oWCWlU19poAAmweLSGZqymHZisra79/x8A "Brain-Flak – Try It Online") [Try it online!] *Four bytes saved thanks to @Riley!* Explanation: ``` #Push a 64 (((((()()()()){}){}){}){}) #While true { #Pop the top of the stack. We'll store this value for later, but first ({} #Before pushing the value < #Push (N + 1) * 2 - 1 # (where N is the number underneath, originally 0) (({}()){}[()]) > #And push the TOS minus one back on [()]) #endwhile } #Pop the zero left over {} #And decrement the number underneath ({}[()]) ``` For the record, I tried pushing 32 and quadrupling, but it's the same byte count. [Answer] # C# 6, 31 bytes ``` ()=>System.Console.Write(~0UL); ``` Pretty much the same as Java. # C# 5, 56 bytes ``` class P{static void Main(){System.Console.Write(~0UL);}} ``` [Answer] # Forth (gforth), ~~11~~ ~~9~~ 7 bytes ``` true U. ``` [**Try it online**](https://tio.run/nexus/forth-gforth#@19SVJqqEKr3/z8A) `true` is the same as `-1`. `U.` prints a number as an unsigned integer. This works on TIO, possibly because it has a 64-bit architecture? I'm not sure. If I run `-1 U.` on repl.it, for example, I get 2\*\*32-1. If repl.it supported double-length integers, outputting them would use `UD.` instead. [Answer] # R, 58 bytes R has only 32-bit integers, and with 64-bit doubles, the number 18446744073709551615 [is not accurately represented](https://tio.run/nexus/r#FctNCoAgEEDhfacYaFM7JX9y4WHEJhoIR3A2nt5s@eB7XIW4tK1lqlhiCGGHFRoKyINwUatv6iAMhWEaLEI35VmS/nH0qE9jnDdG@cOrYK122i59jA8), hence this will return a string. I can't even use 64-bit integer packages, because many of them have `64` in the names. Probably not the right tool for the job. ``` x=as.character((9+7)^(9+7)) n=nchar(x) substr(x,n,n)='5';x ``` computes `16^16` and replaces the last character with a `5`. [Try it online!](https://tio.run/nexus/r#@19hm1isl5yRWJSYXJJapKFhqW2uGQcmNbnybPNAMhoVmlzFpUnFJUCWTp5Onqatuqm6dcX//wA) [Answer] # Swift, 8 bytes ``` UInt.max ``` ### outside playground / repl - 15 bytes ``` print(UInt.max) ``` [Answer] # TI-Basic, 10 bytes ``` 9+7 Ans^Ans-0! ``` [Answer] # x64 Assembly, 7 bytes hex (assembled): 4831C048FFC8C3 disassembled, commented: `XOR RAX,RAX ;Zero the value of 64 bit register RAX DEC RAX ;Decrement the value of RAX RET ;Return this value` RAX is a 64 bit register, and is most often used to return integer arguments (eg, C). By decrementing 1, its value rolls over from 0 to... 2^64-1, which is exactly needed. Though, the assembled binary contains ones and fours and eights, the assembly doesn't, but the assembled file is counted in assembly, so does it count? Ow, my head. Also, output is return value in this case. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~223~~ 193 bytes Includes +1 for `-A` -30 thanks to DJMcMayhem ``` ((((((((((((((((((((((((()()()){}){}()){}){}())[()()()()])[][]())[[]()()])[]))()()()())[[]()()])[][()])[()()()()])()()()())[(()()()){}()])()()()()))()()())[()])[()()]))()()()())[(()()()){}()]) ``` [Try it online!](https://tio.run/nexus/brain-flak#@6@BC2iCoGZ1LRAh0dEQcQ3NWM3o2OhYkAiIhPA1NWGyyKLRYAqhD6EGYQmKOEIephHFZFRd////13UEAA "Brain-Flak – TIO Nexus") This just pushed the ASCII values of and prints as characters. For reference, it takes 338 bytes to generate the actual number using the [Integer meta golfer](https://brain-flak.github.io/integer/). ``` ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((()()()){}()){}){}()){}()){({}[()])}{}()){}()){}())){}{})){}{})()){}{})){}{})){}{})()){}{})){}{})){}{}){}){}())){}{}){}())()){}{})){}{}){}){}){}())()){}{})()){}{})){}{}){}())){}{})()){}{})){}{})){}{})){}{})()){}{})()){}{})){}{}){}())){}{}){}){}())()){}{})()){}{})){}{}) ``` [Try it Online!](https://tio.run/nexus/brain-flak#@69BHaAJgprVtWACRoMIjeraaA3NWM1aJDEQASSBCiGkBgoPtxjMZBgPyNTAVIAqga4Arh2bBagyOLXit@P/fwA) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 6 bytes ``` C*h7"ÿ ``` [Try it online!](https://pyth.herokuapp.com/?code=C%2ah7%22%C3%BF&debug=0) ## How it works ``` C*h7"ÿ "ÿ creates the string "ÿ" (U+00FF) h7 creates 8 (7+1) * generates "ÿÿÿÿÿÿÿÿ" C convert to integer from base 256 ``` This works because `18446744073709551615 = 0xFFFFFFFFFFFFFFFF`. ]
[Question] [ In [this question](https://codereview.stackexchange.com/q/245978/105327) at Code Review they tried to find the fastest way to return the unique element in an array where all the elements are the same except one. But what is the shortest code that accomplish the same thing? ### Goal Find the unique element in an array and return it. ### Rules * The input array will contain only integer, strictly positive numbers, so you can use 0 as the end of the input if your language needs it. * The size of the array will be at least 3 and will have a finite size. You can limit the size of the array to any limit your language has. * Every element in the array will be the same, except for one which will be different. * You must output the value (not the position) of the unique element in any standard format. You can output leading or trailing spaces or newlines. * You can take the input array in any accepted format. ### Examples ``` Input Output ------------------------------ [ 1, 1, 1, 2, 1, 1 ] 2 [ 3, 5, 5, 5, 5 ] 3 [ 9, 2, 9, 9, 9, 9, 9 ] 2 [ 4, 4, 4, 6 ] 6 [ 5, 8, 8 ] 5 [ 8, 5, 8 ] 5 [ 8, 8, 5 ] 5 ``` ### Winner This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win! [Answer] # [Python 3](https://docs.python.org/3/), 27 bytes ``` lambda x:min(x,key=x.count) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCKjczT6NCJzu10rZCLzm/NK9E839BUWZeiUaaRrShjgIEGUEYsZqaXHBJYx0FUzhCkbEEa7BERijyJjoKEGSGImwBNsoCJPYfAA "Python 3 ‚Äì Try It Online") [Answer] # [R](https://www.r-project.org/), 24 bytes ``` a=scan();a[a!=median(a)] ``` [Try it online!](https://tio.run/##K/r/P9G2ODkxT0PTOjE6UdE2NzUlE8hL1Iz9b6gAgkYg8j8A "R ‚Äì Try It Online") [Answer] # JavaScript (ES6), ~~¬†32¬†~~ 27 bytes *Saved 5 bytes thanks to @xnor* ``` a=>a.sort()[0]+a.pop()-a[1] ``` [Try it online!](https://tio.run/##dc5NCoMwEIbhvaeYZUJjrL/owl4kZDFYLYo4wYjXTyG1QSqFdzGLh4@ZcEfbraPZ4oWevRtah@0DpaV1Y1zd9Q2lIcN4jCrVrqPF0tzLmV5sYApScZR9DtAAwDkkCWTRL84FlCEvA84vuPGbzTnQ/5YLcVR9Z8NydcG1f6A@yYBL9wY "JavaScript (Node.js) ‚Äì Try It Online") ### How? `a.sort()` sorts the input array in lexicographical order. We know for sure that this is going to put the unique element either at the first or the last position, but we don't know which one: ``` [ x, ..., y, ..., x ].sort() -> [ y, x, ..., x ] or [ x, x, ..., y ] ``` Either way, the sum of the first and the last elements minus the 2nd one gives the expected result: ``` [ y, x, ..., x ] -> y + x - x = y [ x, x, ..., y ] -> x + y - x = y ``` We could also XOR all of them: ``` a=>a.sort()[0]^a.pop()^a[1] ``` [Try it online!](https://tio.run/##dc5BCoMwEIXhvaeYZQJprFpFF/YiIcJgtVQkE4x4/RRSG6RS@Bez@HjMhBu6fnnZ9WLoMfix9djeUTpaVsbVVXcoLVnGO1SZ9j0ZR/MgZ3qykSnIxF7@OUADAOeQppAnv7gQUMaCjLg44SZsNsdA/1u@ib3qOxuXqxOuwwP1QUZc@jc "JavaScript (Node.js) ‚Äì Try It Online") [Answer] # x86-16 machine code, 14 bytes **Binary:** ``` 00000000: 498d 7c01 f3a6 e305 4ea6 7401 4ec3 I.|.....N.t.N. ``` **Listing:** ``` 49 DEC CX ; only do length-1 compares 8D 7C 01 LEA DI, [SI+1] ; DI pointer to next value F3 A6 REPE CMPSB ; while( [SI++] == [DI++] ); E3 05 JCXZ DONE ; if end of array, result is second value 4E DEC SI ; SI back to first value A6 CMPSB ; [SI++] == [DI++]? 74 01 JE DONE ; if so, result is second value 4E DEC SI ; otherwise, result is first value DONE: C3 RET ; return to caller ``` Callable function, input array in `[SI]`, length in `CX`. Result in `[SI]`. **Explanation:** Loop through the array until two different adjacent values are found. Compare the first to the third value. If they are the same, the "odd value out" must be the second, otherwise it is the first. *Example:* Input `[ 1, 1, 1, 2, 1, 1 ]`, reduce until different adjacent values are found `a = [ 1, 2, 1, 1 ]`. If `a[0] == a[2]` then result is `a[1]`, otherwise result is `a[0]`. **Tests using DOS DEBUG:** [![enter image description here](https://i.stack.imgur.com/X1ee5.png)](https://i.stack.imgur.com/X1ee5.png) [![enter image description here](https://i.stack.imgur.com/VpQ5P.png)](https://i.stack.imgur.com/VpQ5P.png) [![enter image description here](https://i.stack.imgur.com/YkjXd.png)](https://i.stack.imgur.com/YkjXd.png) [![enter image description here](https://i.stack.imgur.com/8Hu9y.png)](https://i.stack.imgur.com/8Hu9y.png) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ```  í¬¢ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//1KRDi/7/jzbUUTDSUQCShrEA "05AB1E ‚Äì Try It Online") Since `1` is the only truthy integer in 05AB1E, we can just filter (`í`) on the `¬¢`ount. There is also the Counter-Mode builtin, which returns the least frequent element in a list at the same bytecount: ``` .m ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fL/f//2hDHQUIMoIwYgE "05AB1E ‚Äì Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 5 bytes ``` ‚ç∏1=¬Ø‚ç∏ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HvDkPbQ@uB1P@0R20THvX2PepqPrTe@FHbxEd9U4ODnIFkiIdn8P80BUMwNAKRXGkKxgqmEAhkWwJFLWEQyDcBQzMgywKowgIA "APL (Dyalog Extended) ‚Äì Try It Online") Regular Dyalog APL 18.0 has `‚ç∏‚磬Ø1`, but it doesn't work here because it requires the input array to be sorted, unlike Extended's `¬Ø‚ç∏` which allows unsorted input arrays. ### How it works ``` ‚ç∏1=¬Ø‚ç∏ ‚çù Input: a vector N of positive integers ‚çù (Example: 4 4 6 4) ¬Ø‚ç∏ ‚çù Whence; generate a vector V where V[i] is the count of i in N ‚çù (¬Ø‚ç∏ 4 4 6 4 ‚Üí 0 0 0 3 0 1) 1= ‚çù Keep 1s intact and change anything else to zero (V1) ‚çù (1= 0 0 0 3 0 1 ‚Üí 0 0 0 0 0 1) ‚ç∏ ‚çù Where; generate a vector W from V1, where i appears V1[i] times in W ‚çù (‚ç∏ 0 0 0 0 0 1 ‚Üí 6) ``` [Answer] # [Haskell](https://www.haskell.org/), 32 bytes ``` f(x:y)|[e]<-filter(/=x)y=e|1<3=x ``` [Try it online!](https://tio.run/##hc7RCoMgFAbg@z3FuTTQjXJFjXyEPUHI8EKZzCJaFwW9uxN1Q6@m/4VwPn/OU7xf0hhrFdpue3EMkvdEabPKBV3YVuxMHmVP2WZHoSdgMIr5/gA0L3pa4QyqOAEM7pY4pgoP4OAPIVA5gh2hGOpfvvNAaCSd/9@l8TBpueKYJqkIpInE9bcu@TyQOpLWb/GPtPmiGeH2Aw "Haskell ‚Äì Try It Online") # Explanation The code, expanded with variables renamed to be more descriptive. ``` f (first:rest) | [unique] <- filter (/=first) rest = unique | 1 < 3 = first ``` `(first:rest)` is a pattern match on a list that destructures it into its first element (`first`) and the list without the first element (`rest`). Each line with a `|` at the front is a case in the function (known as "guards" in Haskell). The syntax looks like `functionName args | condition1 = result1 | condition2 = result2 ...`. There are two cases: 1. `[unique] <- filter (/=first) rest`. This asserts that `filter (/=first) rest` produces a list containing only one element, which we name `unique`. `filter (/=first) rest` filters out all elements in `rest` not equal to `first`. If we are in this case, then we know that `unique` is the unique element, and we return it. 2. `1 < 3`. This asserts that 1 is less than 3. Since it's always true, this is a "fallthrough" case. If we reach it, we know that there are at least 2 elements not equal to the first element, so we return `first`. [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, 12 bytes ``` sort|uniq -u ``` [Try it online!](https://tio.run/##S0oszvj/vzi/qKSmNC@zUEG39P9/Qy4YNILQAA "Bash ‚Äì Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ·∏ü√Ü·πÉ ``` Explanation: `·∏ü` (probably) removes all elements that are not the most common element (returned by `√Ü·πÉ`). I don't know why isn't the result a single-element list (perhaps it's a feature I didn't know about?), but that makes this even better. [Try it online!](https://tio.run/##y0rNyan8///hjvmH2x7ubP7//3@0iQ4ImsUCAA "Jelly ‚Äì Try It Online") [Answer] # [J](http://jsoftware.com/), 10 8 bytes ``` 1#.|//.~ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1avT19er@a/7nSlMw1IEiIwhDAShmrKNgCkcKIAAUtAQrsURGIGETHSgyA/EswHosFAA "J ‚Äì Try It Online") ### How it works ``` 1#.|//.~ input: 1 1 1 2 1 /.~ group by itself: 1 1 1 1 2 |/ insert | (remainder) into both groups: 1 | 1 | 1 | 1 = 0 2 = 2 1#. sum: 2 ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 17 bytes ``` @(x)x(x!=mode(x)) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzQqNC0TY3PyUVyNb8n6YRrWCoA0VGEIZCrCYXSNxYR8EUjmCClmBllsgIJmWiA0VmMBELsF4LIPc/AA "Octave ‚Äì Try It Online") 2 bytes golfed thanks to [Luis Mendo](https://codegolf.stackexchange.com/a/207749/67312)! [Answer] # [Ruby](https://www.ruby-lang.org/), 18 bytes ``` ->a{a-[a.sort[1]]} ``` [Try it online!](https://tio.run/##TYu7CoNAEEV7v@IiLBgYBTURLfRHhikmothl8VGI@u0ruCKBU9znuHxX19cubnTTmDWZfuPMqcjhmJHSTeYFhAJGTvg8@Ki6JtU/vnjTTeF9eb1KiCSdtgM27LrDLvMUhcaibmBsCANWQs8q8sLhTg "Ruby ‚Äì Try It Online") The unique element will always be the largest or smallest, so remove all copies of the second element. [Answer] # [Octave](https://www.gnu.org/software/octave/) / MATLAB, 19 bytes ``` @(x)x(sum(x==x')<2) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzQqO4NFejwta2Ql3Txkjzf5pGtIKhDhQZQRgKsZpcIHFjHQVTOIIJWoKVWSIjmJSJDhSZwUQswHotgNz/AA "Octave ‚Äì Try It Online") ### How it works ``` @(x) % Define a function of x x==x' % Square matrix of all pairwise comparisons (non-complex x) sum( ) % Sum of each column <2 % Less than 2? This will be true for only one column x( ) % Take that entry from x ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~21~~ ~~19~~ 17 bytes ``` f[c=a_...,b_,c]=b ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z8tOtk2MV5PT08nKV4nOdY26X9AUWZeSbSyrl2ag4NyrFpdcHJiXl01V7WhDggagchaHa5qYx1TCARxLIHiljAIEjDRAUEzENMCqMiilqv2PwA "Wolfram Language (Mathematica) ‚Äì Try It Online") [Answer] # [R](https://www.r-project.org/), 25 bytes ``` a=sort(scan());a[a!=a[2]] ``` [Try it online!](https://tio.run/##K/r/P9G2OL@oRKM4OTFPQ1PTOjE6UdE2MdooNva/sYIpCP4HAA "R ‚Äì Try It Online") Sort the input, giving `a`. Now `a[2]` is one of the repeated values. Keep only the element not equal to `a[2]`. This ends up 4 bytes shorter than my best shot with a contingency table: ``` names(which(table(scan())<2)) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 4 bytes -1 byte thanks to @FryAmTheEggman ``` ho/Q ``` [Try it online!](https://tio.run/##K6gsyfj/PyNfP/D//2gFCx0FUx0FC4VYAA "Pyth ‚Äì Try It Online") ## Explanation ``` o : Order implicit input /Q : by count of the element h : then take the first element ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 23 bytes ``` $args-ne($args|sort)[1] ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V8lsSi9WDcvVQPMqCnOLyrRjDaM/V/LxaVSklpcomCroMGloWCoA0VGEIaCpo4CGCgbAWWNdRRM4QguBZI1BspagnVZIiOIGrBeEx0oMkPWCJI1A8oCDbQAIjQpkKwpUNYCbCNIFsKxAFvPpQl1e41qNZdKFdAHKvFcaippCg5VXLX/AQ "PowerShell ‚Äì Try It Online") Takes input by splatting. We apply a filter to the original array getting rid of the dupes by sorting it and taking the 2nd element. [Answer] # T-SQL, 40 bytes Input is a table variable ``` DECLARE @ table(v int) INSERT @ values(1),(1),(2),(1) SELECT*FROM @ GROUP BY v HAVING SUM(1)=1 ``` Another variation # T-SQL, 54 bytes ``` DECLARE @ table(v real) INSERT @ values(1),(1),(2),(1) SELECT iif(max(v)+min(v)<avg(v)*2,min(v),max(v))FROM @ ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes ``` o·∏Ö‚àã‚↠``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P//hjtZHHd2POhf8/x9tomOiY6xjEvs/CgA "Brachylog ‚Äì Try It Online") Takes a list and returns a singleton list. ## Explanation ``` o·∏Ö‚àã‚↠Input is a list, say [4,4,3,4]. o Sort: [3,4,4,4] ·∏Ö Blocks of equal elements: [[3],[4,4,4]] ‚àã Pick a block: [3] ‚↠This block must have distinct elements (in this case, must have just one). Output it implicitly. ``` [Answer] # [RAD](https://bitbucket.org/zacharyjtaylor/rad), 13 bytes ``` ‚çµ[1‚ç≥‚ç®+/‚終àò=¬®‚çµ] ``` The lack of a need for `{}` in this language really helps. [Try it online!](https://tio.run/##K0pM@f//Ue/WaMNHvZsf9a7Q1gdyHnXMsD20AsiI/f//v6ECBBoBAA "RAD ‚Äì Try It Online") ## Explanation ``` ‚çµ[1‚ç≥‚ç®+/‚終àò=¬®‚çµ] +/‚終àò=¬®‚çµ count of each element's # of occurrences 1‚ç≥‚ç® first occurrence of a 1 ‚çµ[ ] the argument at that index ``` [Answer] # [Haskell](https://www.haskell.org/), 30 bytes ``` f(x:y)|elem x y=f$y++[x]|1>0=x ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02jwqpSsyY1JzVXoUKh0jZNpVJbO7oitsbQzsC24n9uYmaegq1CbmKBb7yCRkFRZl6Jgp5CmiaXgkI0EBrqQJERhKEQqwAGuroKRkAlOkAlxjoKpnAEk4coMYYqsQTrt0RGYIVIppjoQJEZkhEQJWZQJUDzLYAIVR6ixBSqxALsCkJKLFAdiqIk9j8A "Haskell ‚Äì Try It Online") Footer stolen from [coles answer](https://codegolf.stackexchange.com/a/207784/64121). If the first element is not in the remaining list, return it, otherwise rotate it to the end and try again. [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~8~~ 6 bytes **Solution:** ``` *<#'=: ``` [Try it online!](https://tio.run/##y9bNS8/7n2alZaOsbmv1P01dw1ABBI1ApLWxgikEWlsCRSxh0FrBBAzNrE0VLBQsrC2ASkAkkNb8/x8A "K (ngn/k) ‚Äì Try It Online") **Explanation:** ``` *<#'=: / the solution =: / group the input #' / count length of each < / sort ascending * / take the first ``` **Extra:** * **-2 bytes** thanks to `ngn` by dropping the lambda [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes ``` Tr[#/.Median@#->0]& ``` Inspired by [Kirill L.'s R submission](https://codegolf.stackexchange.com/a/207747/86341) [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6QoWllfzzc1JTMxz0FZ184gVu1/cHJiXnRAUWZeSbSygq6dQlq0cmysmo5CdbWhDggagchaIN9YxxQCQRxLoLglDIIETHRA0AzENNWx0LEAMSyAqqEMILO2NvY/AA "Wolfram Language (Mathematica) ‚Äì Try It Online") Finds the median, replaces its occurrences in the list with 0, and sums the list. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~3~~ 2 bytes *-1 byte thanks to [Razetime](https://codegolf.stackexchange.com/users/80214)!* ``` ‚óÑ= ``` [Try it online!](https://tio.run/##yygtzv7//9H0Ftv///9HG@uYQmAsAA "Husk ‚Äì Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 3 bytes ``` ƒä‚Üìh ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C4%8A%E2%86%93h&inputs=%5B9%2C%202%2C%209%2C%209%2C%209%2C%209%2C%209%5D&header=&footer=) ## Explained ``` ƒä‚Üìh ƒä # Get the counts of all items ‚Üì # Get the smallest item based on last item h # Output the head of that list ``` Also, according to code-golf's statistics, only a small percentage of people who view my answers actually upvote them. So if you enjoy this answer, consider upvoting, it's free, and you can change your mind at any time (given you have ‚â•2k rep). Enjoy the answer. [Answer] # [Julia 1.0](http://julialang.org/), 24 bytes ``` ~d=d[@.sum(==(d),[d])<2] ``` [Try it online!](https://tio.run/##fY7LCsMgEEX3fsUsFaQQ0wQDFfIfgwuDLaT0ATGBrvLr1o5BQha9nMXA8c54Xx6jqz4xrt547E9heXJjuBcSvRUXZaM3yDhCJTdUHsBKoCjx07WEplBcSk26o163Jz/K7bPcaPfVlJZ02qkTB5fSkNZ09Z/Wh08VbRnD3oVwnWZYnTE4WLi9J@BODgLGF3gbvw "Julia 1.0 ‚Äì Try It Online") [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 2 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md "Thunno 2 Codepage") ``` ·πÄo ``` Note that [output as a singleton list is a default](https://codegolf.meta.stackexchange.com/a/11884/114446). #### Explanation ``` ·πÄo # Implicit input o # Remove all instances of from the input ·πÄ # the mode of the input # Implicit output ``` #### Screenshot [![Screeshot](https://i.stack.imgur.com/wRU1vm.png)](https://i.stack.imgur.com/wRU1v.png) [Answer] # [ATOM](https://github.com/SanRenSei/ATOM), 15 chars, 18 bytes ### Code: ``` *üîç2>üßµ($1üîç$1==*) ``` ### Usage: ``` [1,1,1,2,1,1] INTO *üîç2>üßµ($1üîç$1==*) ``` ## [Try it live here](https://sanrensei.github.io/ATOM/) ### Explanation: The ATOM language implicitly treats the expression as a function, where \* is the parameter. Therefore, it interprets the expression as ``` [1,1,1,2,1,1] üîç2>üßµ($1üîç$1==*) ``` The üîç operator is an array filter, which takes an array on the left, and a function on the right. The expression to the right is implicitly parsed into a function. Therefore, it is searching the values in the input array for all values where the following returns true ``` 2>üßµ($1üîç$1==*) ``` The üßµ operator is array length, so it is searching for elements in the original input where ($1üîç$1==\*) evaluates to an array of length 1 i.e. the unique element. The first $1 looks for the variable on the stack at index 1, which is the original array (index 0 is the element in the array that is being iterated through, since we are inside the where operator). Another üîç operator is performed on the array. $1==\* is now parsed to a new function, and $1 refers to the variable on the stack at index 1, which is the number being iterated through in the outer üîç. The \* refers to the immediate stack variable, which is the number being iterated through in the inner üîç. Matches are returned, so if there are multiple instances of a number in the original array, the resulting array will be of length greater than or equal to 2. As such, only the unique element in the array will satisfy the 2>üßµ($1üîç$1==\*) clause. [Answer] # [Uiua](https://uiua.org), 4 [bytes](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==) ``` ‚äó1‚çò‚äö ``` [Try it!](https://uiua.org/pad?src=RiDihpAg4oqXMeKNmOKKmgoKRiBbMSAxIDEgMiAxIDFdCkYgWzggOCA1XQpGIFs1IDggOF0=) ``` ‚äó1‚çò‚äö ‚çò‚äö # inverse where, i.e. how many times does each element occur? ‚äó1 # index of 1 ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/), 34 bytes ``` {a[$0]++?c=$0:b+=$0}END{print b-c} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m704sTx7wYKlpSVpuhY3laoTo1UMYrW17ZNtVQyskrSBZK2rn0t1QVFmXolCkm5yLUQlVMOC1cZcMGgEEQIA) Takes positive integers separated by newlines. Let's call the unique number `u` and duplicates `d`. * `{a[$0]++?c=$0:b+=$0}`: Executed for each line. `$0` contains the number on the line. + `a` is used as a dict that counts the occurrences of each number. `a[$0]++` increments the count, and evaluates to falsy if it was encountered the first time, truthy otherwise. + `b+=$0` is run exactly twice, when each of `u` and `d` is read the first time. Therefore, `b` is equal to `u+d` at the end. + `c=$0` is run for the rest of the time, and `$0` in this case is always `d`. * `END{print b-c}` is run after all inputs are processed. `b-c` is `u`, and it is printed. ]
[Question] [ This challenge, while probably trivial in most "standard" languages, is addressed to those languages which are so esoteric, low-level, and/or difficult to use that are very rarely seen on this site. It should provide an interesting problem to solve, so this is your occasion to try that weird language you've read about! ### The task Take two natural numbers `a` and `b` as input, and output two other numbers: the result of the integer division `a/b`, and the remainder of such division (`a%b`). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): shortest answer (in bytes), for each language, wins! ### Input/Output * 0<=`a`<=255, 1<=`b`<=255. Each of your inputs (and outputs too) will fit in a single byte. * You may choose any format you like for both input and output, as long as the two numbers are clearly distinguishable (e.g. no printing the two results together without a delimiter) ### Examples ``` a,b->division,remainder 5,7->0,5 5,1->5,0 18,4->4,2 255,25->10,5 ``` **Note:** Builtins that return both the result of the division and the remainder are *forbidden*. At least show us how your language deals with applying two functions to the same arguments. **Note 2:** As always, an explanation of how your code works is very welcome, even if it looks readable to you it may not be so for someone else! --- ## The Catalogue 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: ``` ## [><>](https://esolangs.org/wiki/Fish), 121 bytes ``` ``` /* Configuration */ var QUESTION_ID = 114003; // 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 = 8478; // 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,<]*(?:<(?:[^\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; display: block !important; } #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 500px; 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="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f"> <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] # [BitCycle](https://github.com/dloscutoff/Esolangs/tree/master/BitCycle), ~~146~~ ~~79~~ 64 bytes *Just realized a whole section of my original code was unneccessary. Huge reduction!* ``` v <>! A\B^^= ? D^>^< >\v^~ D@ >/ C/ > C ^ A/B v ^ < ? D^ ``` The program takes input in unary from the command line, with the divisor first. It outputs the quotient and remainder in unary, separated by a `0`. For example, here's `a=11`, `b=4`, `a/b=2`, `a%b=3`: ``` C:\>python bitcycle.py divmod.btc 1111 11111111111 110111 ``` ### Ungolfed, in action Here's my ungolfed version computing `a=3`, `b=5` with animation turned on (sorry about the glitchiness): [![Divmod running in BitCycle](https://i.stack.imgur.com/TDukU.gif)](https://i.stack.imgur.com/TDukU.gif) ### Attempt at an explanation *The explanation applies to the ungolfed version. Before you tackle it, I highly recommend you read the [Esolangs page](http://esolangs.org/wiki/BitCycle) to get a feel for how the language works.* The algorithm goes like this: * Run an outer loop until the program is terminated. + Run an inner loop over the bits of the divisor, pairing them off with bits from the dividend. - If all bits of the divisor have matching dividend bits, output a single bit. - If not all bits of the divisor have matching dividend bits, output the separator `0` followed by what dividend bits there were, then terminate. The heart of the code is the relationships among the collectors (the uppercase letters). Since there are multiple separate collectors with each letter, let's refer to them as `A1`, `A2`, `B1`, `B2`, etc., numbering from top to bottom. * `A1` and `A2` hold the divisor and dividend, respectively, at the beginning of the main loop. * The inner loop peels off one bit at a time from the divisor and the dividend. + The rest of the divisor, if any, always goes into `B1`. + If both the divisor and dividend were nonempty, one bit goes into `C1` and one into `C3`. The rest of the dividend goes into `B2`. + If only the divisor was nonempty, we've reached the end of the dividend, and it's time to print the remainder. The bit from the divisor goes into `C2`. + If only the dividend was nonempty, we've reached the end of the divisor; it's time to process the bits in `C3` or `C2` for output. The rest of the dividend goes into `C4`. * If there are any bits in the `B` collectors, they cycle their contents back around to the `A` collectors and continue in the inner loop. * Once the `A` and `B` collectors are all empty, the `C` collectors open and we proceed to the processing stage: + `C1` and `C4` dump their contents (the divisor and the remaining dividend, respectively) into `D1` and `D3`. + If `C2` is empty, we're still printing the quotient. - The contents of `C3` go up to the top right `=` switch. The first `1` bit passes straight through to `!` and is output. - When the `1` bit passes through, it activates the switch to point rightward, which sends all the subsequent bits off the board. + If `C2` is not empty, we're printing the remainder. - The first bit of `C2` is negated to a `0` and passed through the switch. The `0` goes on to `!` and is output. - When the `0` bit passes through, it activates the switch to point leftward. Now all the bits from `C3` go leftward from the switch and are redirected around into the `!`, outputting the entire remainder. - A copy of the first bit from `C2` is also sent into `D2`. * Now the `D` collectors open. + If there is anything in `D2`, that means we just printed the remainder. The bit from `D2` hits the `@`, which terminates the program. + Otherwise, the contents of `D1` and `D3` loop back into `A1` and `A2` respectively, and the main loop starts over. [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), ~~43~~ 41 bytes ``` ,<,[>->+<[>]>>>>+<<<[<+>-]<<[<]>-]>>.>>>. ``` This uses a modified version of my [destructive modulus algorithm on Esolangs](https://esolangs.org/wiki/Brainfuck_algorithms#Modulus_algorithm). The program reads two bytes ‚Äì **d** and **n**, in that order ‚Äì from STDIN and prints two bytes ‚Äì **n%d** and **n/d**, in that order ‚Äì to STDOUT. It requires a brainfuck interpreter with a doubly infinite or circular tape, such as the one on TIO. [Try it online!](https://tio.run/nexus/bash#TY5PC4JAEMXP@SkGMyz8R4JdWpYudgqKbqF7UHcXl8yVdSsPfXdbq0PDwJvf4z2YqtCAgYrHTdKw5IAQpMf96CM/wwH2UIYJNuMhhDLk4YBMSoxiHBo/HE3asjolWs3BWf4ON8@HxeCC7ezsFeTW7AWR7HSkhQy0Ktq@Ew1TfVSqQrT8Xl3/Pvikh4FC0PVf4LIxFH/hWZsqKFbQLVAJrKolONl6M3fO6elwIZPbsnGME7PJGw "Bash ‚Äì TIO Nexus") ### How it works Before the program starts, all cells hold the value **0**. After reading **d** from STDIN (`,`), moving one step left (`<`) and reading **n** from STDIN (`,`), the tape looks as follows. ``` v A B C D E F G H J 0 n d 0 0 0 0 0 0 ``` Next, assuming that **n > 0**, we enter the while loop ``` [>->+<[>]>>>>+<<<[<+>-]<<[<]>-] ``` which transforms the tape as follows. First, `>->+<` advances to cell **C** and decrements it, then advances to cell **D** and increments it, and finally goes back to cell **C**. What happens next depends on whether the value of cell **C** is zero or not. * If cell **C** hold a positive value, `[>]` (go right while the cell is non-zero) will advance to cell **E**. `>>>>+<<<` advances to cell **J** to increment it, then goes back to cell **F**. Since cell **F** will always hold **0**, the while loop `[<+>-]` is skipped entirely, and `<<` goes back to cell **D**. Finally, since neither **D** nor **C** hold **0**, `[<]` (go left while the cell is non-zero) will retrocede to cell **A**. * If cell **C** holds **0**, the loop `[>]` is skipped entirely; `>>>>+<<<` advances to cell **G** to increment it, then goes back to cell **D**. At this point, **D** will hold **d** (in fact, the sum of the values in **C** and **D** will always be **d**), so `[<+>-]` (while **D** is positive, increment **C** and decrement **D**) will set **C** to **d** and **D** to **0**. Finally, `<<` retrocedes to cell **B**, `[<]` (go left while the cell is non-zero) further left to cell **A**. In both cases, `>-` advances to cell **B** and decrements it, and the loop starts over unless this zeroes it out. After **k** iterations, the tape looks as follows. ``` v A B C D E F G H J 0 n-k d-k%d k%d 0 0 k/d 0 k-k/d ``` After **n** iterations **B** is zeroed out and we break out of the loop. The desired values (**n%d** and **n/d**) will be stored in cells **D** and **G**, so `>>.>>>.` prints them. [Answer] ## [Funciton](https://github.com/Timwi/Funciton), ~~224~~ 108 bytes Byte count assumes UTF-16 encoding with BOM. ``` ‚îå‚îÄ‚îĂîÄ‚îÄ‚îÄ‚îê ‚îå‚ïñ‚ïì‚ïñ ‚îå‚ïñ ‚îÇ%‚ïü‚ïëf‚ïü‚îê‚îÇ√∑‚ïü‚îò ‚ïò‚蓼ïù‚ïô‚îÄ‚ïú‚îÇ‚ïò‚蓼ïù ‚îî‚îÄ‚îÄ‚îÄ‚îĂîÄ‚îò ``` [Try it online!](https://tio.run/nexus/funciton#fVMxbsMwDNz1Ci7diyD9UoAsHdI8wPCQKYPdionaRggQGOiSpUCAPKBT8wx@xJFoS6ZkIwZhSSR9vCOtFkhvSRds57BxVikOXAh3hB/dBqLLBcsnwiNhvfCLrpzj78pbowgNYUNoCT89GB5cNDqVg9GiUuEh/du0EB5CTVgJ2ysRq2H24hfp@@K0JuTbIeaiulQjRA8KUT0z8LoY3KMfA7kGFvIoO9RXlWY9GSPI2EghZdSvafnJlBJoW6d6RTgtlqeI6RbdBDMeutd4O0eRRmY8rCCJ5NAjcVOOB2MO2P@/6TBuVpzxBPN53pqJCQSHmFE2uildOWhH9offmLMP1JOOD60/cegwHJ872qP0S/rdLvu3v3PufJ9KWL6uafP@tl7x/ejpp7Ll/YiNEDpH11Kaae8 "Funciton ‚Äì TIO Nexus") The above defines a function `f`, which takes two integers and returns both their division and their product (functions in Funciton can have multiple outputs as long as the sum of inputs and outputs doesn't exceed 4). Using two input values for multiple purposes is actually quite trivial: you simply split off the connector with a T-junction at the value will be duplicated along both branches, which we can then feed separately to the built-ins for division and modulo. It actually took me twice as long to figure out how to display the result to the user than just to implement the solution. Also, Funciton has a built-in divmod, `√∑%`, and amusingly the built-ins `√∑` and `%` that my solution uses are implemented *in terms of* `√∑%`. However, my function `f` above isn't *quite* identical to `√∑%`: I had to swap the order of the inputs and although it seems like it should be easy to change that, so far I haven't been able to do so without increasing the byte count. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 5 bytes -2 bytes thanks to @ngn ``` ‚åä√∑,|‚ç® ``` This is an atop (2-train) of a fork (3-train), where the atop's right tine is a derived function (the result of an operator applied to a function): ``` result ‚Üë‚îå‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îê ‚îÇ‚îÇ ‚îå‚îÄ‚îÄ‚îÄ‚îÄ‚îê‚îÇ‚îå‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îê (derived function) ‚îÇ‚Üì ‚îÇ ‚Üì‚îÇ‚Üì ‚îÇ‚ï± ‚îå‚îÄ‚îÄ‚îÄ‚îê ‚îå‚îÄ‚îÄ‚îÄ‚îê ‚îå‚îÄ‚îÄ‚îÄ‚îê ‚ïî‚ïê‚ïê‚ïê‚蓼ïê‚ïê‚ïê‚ïó ‚îÇ ‚åä ‚îÇ ‚îÇ √∑ ‚îÇ ‚îÇ , ‚îÇ ‚ïë | ‚îÇ ‚ç® ‚ïë ‚îî‚îÄ‚îÄ‚îÄ‚îò ‚îî‚îÄ‚îÄ‚îÄ‚îò ‚îî‚îÄ‚îÄ‚îÄ‚îò ‚ïö‚ïê‚ïê‚ïê‚ïß‚ïê‚ïê‚ïê‚ïù ‚Üë ‚Üë ‚Üë ‚Üë ‚ï≤ left argument ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îò (operator) ‚îî‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚î¥ right argument ``` `‚åä` floor of `√∑` division `,` catenated to `|` division remainder `‚ç®` with swapped arguments (APL modulus is "backwards") [Try it online!](https://tio.run/nexus/apl-dyalog#@5/2qG3Co56uw9t1ah71rvj/31QhTcGcC0QachlaACkTLiNTENfIFAA "APL (Dyalog Unicode) ‚Äì TIO Nexus") [Answer] # Regex (ECMAScript / Python), 57 bytes ``` (x(x*)),(x*?)(?=\1*$)(x?(x*))(?=\4*$)((?=\2+$)\2\5*$|$\4) ``` [Try it online!](https://tio.run/##TZBNU8IwEIbv/RXbGWSTBgoCegBjT44ndQYPHiyHDgRI7dckUavCb8eEFmUPSfbZzfsmmyYfiV4qWZm@ruRKqLws3sTXQfFCfMJcbO7qipBvfjsIDqQmdUBpz64RJRGPL4MOJXV0pC6fuNwdRqxD41F8FXR2nXhCD8Hgm4amfDZKFhtCQ53JpSDXvf6E0plXJVqLFXAYzjyhVKl0c16XCojkwxnIGz4aup0x2uDU4bTFqcXw44ENdxVrDJWoRGJISoEB9tCt/1RaU9ec22Yd5olZbolqmVw7cT6EyJan4Oew20H@Ol6EmSg2Zgs@B3mRNnRyTh8Ssw3XWVkqIgcpPb3IRWX/bW0ZwgCQpXbn8IrsTIBhDxwY/4MF9OFl/vR472P7NhfNgBhryB5EpsW503GWf2Vv71XvRhtF2gKCEdoga3OfX0aocYpIbalhzq1x8e0Yul1oFTAukLX2fzKnxnOZdSKzo8zhFw "JavaScript (SpiderMonkey) ‚Äì Try It Online") - ECMAScript [Try it online!](https://tio.run/##dVFNb8IwDL3zK1zUyUlboAV2AUUcd2PSLjtQDtUIkArSKglakfbfmdOifcF8sGw/2@/Fqc9uX@nJRR3ryjiwZ5sYOQcjTL/fv7CGNRHnCfkFZwuRZ1HIWbNoqz6f@twH4zjk@Th/jMKPMJ/yC02vstkgW89BibRXF9bKDQhIe9KYytg23FYGFCgNptA7ydJknKZxxmc9IPNg@R/o7Ug7jBxaWZi3PTMJYINRCTFggt5TpvhXt9rSALlSiBTkwUrQlaMSsRykZsfhzlSn2jK@mqx5INRoVN7Bxi32UH6r8FYbpR1TCY4wKRMUJGCFsXWG3Y7zGEnpPXDSgmvspLYScVlpSdsG8PryvHwKkP/ivZ4yFpB91f3cH3Xd7dsu@t@hdZvq5IbvRjnJvI6ugbjBSeswvhYCkUGhN4AW/SUQfUcHkQ4SeaUP6Cs7xpvtmOvuqV3rD4qucJdiW6iDp7h8Ag "Python 3 ‚Äì Try It Online") - Python Takes its arguments in unary, as two strings of `x` characters whose lengths represent the numbers. The divisor comes first, followed by a `,` delimiter, followed by the dividend. The quotient and remainder are returned in the capture groups `\4` and `\3`, respectively. I developed the basic form of this on 2014-04-03 while working on my [abundant numbers regex](https://codegolf.stackexchange.com/a/178952/17216). It had been a month earlier that teukon and I had independently come up with the multiplication algorithm [described here](https://codegolf.stackexchange.com/questions/179239/find-a-rocco-number/179420#179420), but up until this point we hadn't written or golfed any regex to find the unknown quotient of a known dividend and divisor. And it wasn't until [dividing by \$\sqrt 2\$](https://codegolf.stackexchange.com/questions/198427/shift-right-by-half-a-bit/198428#198428) that I adapted it to handle a dividend of zero correctly. It is used, in its various forms (shown above or below), by these other regexes: * [Abundant numbers](https://codegolf.stackexchange.com/questions/110708/an-abundance-of-integers/178952#178952) * [Fibonacci numbers](https://codegolf.stackexchange.com/questions/126373/am-i-a-fibonacci-number/178956#178956) - the version that returns the index * [OEIS A033286 (\$np\_n)\$](https://github.com/Davidebyzero/RegexGolf/blob/master/regex%20for%20matching%20OEIS%20A033286.txt) * [Factorial numbers](https://codegolf.stackexchange.com/questions/121731/is-this-number-a-factorial/178979#178979) * [Proth numbers](https://codegolf.stackexchange.com/questions/89436/is-it-a-proth-number/179076#179076) * [Consecutive-prime/constant-exponent numbers](https://codegolf.stackexchange.com/questions/164911/is-this-a-consecutive-prime-constant-exponent-number/179412#179412) * [Is the number binary-heavy?](https://codegolf.stackexchange.com/questions/132243/is-the-number-binary-heavy/179436#179436) * [Euler's totient function](https://codegolf.stackexchange.com/questions/83533/calculate-eulers-totient-function/180255#180255) by Grimmy * [Shift right by half a bit](https://codegolf.stackexchange.com/questions/198427/shift-right-by-half-a-bit/198428#198428) * [Decompose a number!](https://codegolf.stackexchange.com/questions/78961/decompose-a-number/249369#249369) Commented and indented: ``` (x(x*)), # \1 = divisor; \2 = \1-1; tail = dividend (x*?)(?=\1*$) # \3 = remainder of division; tail -= \3 (x?(x*)) # \4 = conjectured quotient - find the largest one that matches the # following assertions; \5 = \4-1, or 0 if \4==0; tail -= \4 (?=\4*$) # assert tail is divisible by quotient ( (?=\2+$) # assert tail is positive and divisible by divisor-1 \2\5*$ # assert tail-(divisor-1) is divisible by quotient-1 | $\4 # if dividend == 0, assert that quotient == dividend ) ``` To show what's going on, here is a Python function that does division using the regex's algorithm: ``` def modulo_is_zero(n, modulus): return n==0 if modulus==0 else n>=0 and n % modulus == 0 def divide(dividend, divisor): if divisor==0: return remainder = dividend % divisor dividend -= remainder quotient = dividend if dividend != 0: while 1: if modulo_is_zero(dividend - quotient, quotient) and \ modulo_is_zero(dividend - quotient, divisor-1) and \ modulo_is_zero(dividend - quotient - (divisor-1), quotient-1): break quotient -= 1 if quotient == 0: return return [quotient, remainder] ``` [Try it online!](https://tio.run/##nVM9T8MwEN3zKy4DcqK6bQIbklnZQGJhAISC7FCH1m5thwr@fPFX46R0QHjJ3bvze3fny/bLrKS4Ohwoa2Ejab@Wr1y/fjMlC4ED0uvyOgN7FDO9EiAIqYC3x6Dz2FozEDfWagQFARfHIBACVZY5dso/OWVF@AiKPaCliuS8PQKWMEBJM8pvGi4oU0DgyGKV4i2fMsBzktJ9ZNdLw5kwo7tjWX8pt7Um5f2KrxnUCYjpJ1NKkoMGHqzSz@N5QmHPXyhiW/P63xzWLBJLKso616ds8KZY8zFBEw2B@nQIaZyTmZ19Nb80T6mz4WFeDnyzlcqA/tLZttGaUXDrwpSSSnuzlQo4cAGqEe@sqPBlVcXqXag7H/LlDy9dcNyV2bj4nNxJwZzZDdu7IwG0rLun6iUnfLnsglc776KbtrlVXBhLjZYIdxgRhHcYzeHx4f7uNkflJDc2NBsP0omeMIYJ@Cw7kYU2VPZmsVfcsEIbVYSEcobAMG3QLAI5qf2KII1cvQi5jBCyddgmo3xa71/s6FmgmZMIqSOJAJyVaBv7g1iJww8 "Python 3 ‚Äì Try It Online") Notice that in regex, \$0 \equiv 0 \pmod 0\$. This is very convenient, as it allows a quotient of \$1\$ to be returned with no special case. The only special case we actually need to handle is when the dividend is zero. First, to demonstrate that the correct answer satisfies the assertions used ‚Äì assume the remainder has already been subtracted away, and we are dividing \$B=C/A\$: \$\begin{aligned} C &= AB \\ C-B &= (A-1)B \\ C-B-(A-1) &= (A-1)(B-1) \end{aligned}\$ Thus, \$\begin{aligned} C &\equiv 0 \pmod A \\ C &\equiv 0 \pmod B \\ C-B &\equiv 0 \pmod {A-1} \\ C-B-(A-1) &\equiv 0 \pmod {B-1} \end{aligned}\$ The last two can be simplified to: \$\begin{aligned} C &\equiv B \pmod {A-1} \\ C &\equiv A \pmod {B-1} \end{aligned}\$ At this point it becomes apparent why neither of these two alone would be enough. If \$A<B\$, it looks like the first one could yield false positives, and if \$B<A\$, it looks like the second one could. It turns out that only one of them is needed if we're guaranteed the input meets certain constraints, but until recently I simply accepted this intuitively and from testing the algorithm up to large numbers. Unlike the [multiplication algorithm](https://codegolf.stackexchange.com/questions/179239/find-a-rocco-number/179420#179420), this division algorithm can't simply be proved correct from the Chinese remainder theorem, because \$C\$ is now constant while \$B\$, which defines one of the moduli, is the unknown. But [thanks to H.PWiz](https://chat.stackexchange.com/transcript/message/57537223#57537223), we finally have a rigorous proof for why the generalized form of division always works, and rigorously defined thresholds for when the division works in its two shortened forms. Now let's look at ways to shorten the regex. First, if we assume \$C\ge A\$, it becomes **50 bytes**: ``` (x(x*)),(x*?)(?=\1*$)(x(x*))(?=\4*$)(?=\2+$)\2\5*$ ``` [Try it online!](https://tio.run/##TZFNU8IwEIbv/RXbGXSTBgoiegAiJ8eTOoMHD@KhgwES@zVJVFT47Zg0VdlD0n128747W5W9Z2apZW17ppYvQhdV@So@D5qX4gPmYn29rQn54lf95EC2ZJtQ2nXnjJIZX5wlHdpCn4586u4h69DFcHGRdA5J/4umtnqwWpZrQlOTy6Ugl93eiNJJVGfGiBfgMJhEQutKm/C9qjQQyQcTkFM@HPibMRqw8li1WDkM3xG4kCv3BKagaJP6WFalleWbmDTEa@MWUy1qkVmiKDDALvrzn0oamgvXbNIis8sN0S3zDorzAcxceQxxAbsdFE/nz2kuyrXdQMxBnqhAR8f0NrObdJVXlSayr@jvyD5qtxhnyxD6gEy5203JSOFM8AnZkRDDLnhw/g@e0c2Bd1UpkLqXPXic39/dxNgO7COslbFA9iByI47tmz/wV472Uf1mjdWkLSBYYawbKOQxP5uhwTE2foF5t@ASu92cnkKrgIsSWWv/J/PbeCyzymTeyBx@AA "JavaScript (SpiderMonkey) ‚Äì Try It Online") - ECMAScript [Try it online!](https://tio.run/##dVHBbsIwDL3zFQYxOaGhtLBdYBHH3Zi0yw6UQwUBUkFSJUGDr@@SttoYMB/c@j3b77UuL26v1aSSx1IbB/ZimREzMNz0er2KnMl5QCnzeU7JnGfpoE9bMJTPofTPcdSn2Th7GfQrP7ZMp8N0NQPJk06ZWys2wCHpCGO0sfXrVhuQIBWYXO0ESdg4SaKUTjvgI5DFf2QIufXDr1D8IiHWWjmpTuIHPHopI2IrcrPeE8MAzzgoIAJkGLKvJL1eegyp4DwBcbAClHYe8mYOQpFjvDP6VFpCl5MV7XI5GhUPuHHNPd1YK41UjkiGI2QFQ45seb@TPdi1amzVdhZaCYZD@Px4X7x1kf5RaP9txCH9wcPUjY/mGHWXv3Rs3UafXPxlpBPEOkOaBhohOGEdRi3Q5SnkagNoMXwzYuhoKO/DW2zlu/62jeLddswURkGiab2SaICHEttcHoJE9Q0 "Python 3 ‚Äì Try It Online") - Python [Try it online!](https://tio.run/##nVPBjpswEL3nKwZVkUGQDbS3qu61t63USw@7qxUbho1pYie26Xb78@nYBgxpK1VFSNgzz@@9mTGnV7tX8t3l0mALR9X0B/UozONP1CqVRYj0Jnu/Ano02l5LkJyXINox6XZ4MAjyI61q2YCE9ZgEzqFcrRx7I76LBtPwkU3hA0bpgVyMCCL4MOZCyj1DAHhEwRvAY3@oLYLdI9RPBuUOQbVkgt7dnuBC@pzGZ/wxlyEq8h3pQ2lDlcdayAYXWuvx1Go048MbHuE@c@6VFSjt7KyPv@zFAaGKguQjYqlHMXNlZwBfzSY6mGiKaZX5KdzPGf/l@FDhpvqv87RMI0M0Q5tlbU8a629TJB7nUM1v2V00NrX44SKOJ6UtmFezOtXGYAPufqHWShu/bN3Q3dh1LZ8xLYu3ZZmPFlyy@1tyaLSg29ctHe@UtEL2GE1P401F0WWLoSb8Vkl0y276M848BEn@fFc@JFxst13YVW63vhI8aSEtUbMtK7qCcVacC7aBr18@335KWLbADrXnY/t8jESvGEOzPIqad2Nso3p786KFxdRYnQZAljOwaCzLh0DCK38ZmGHOL2MOEVLkg4oc5JPpCv/Gzu4ly51EgM4kQuCPEm1N/wtJXH4B "Python 3 ‚Äì Try It Online") - Python equivalent If we know that all divisors will be in the required range, the division regex can be shortened further. With \$C \equiv A \pmod {B-1}\$ and \$C \equiv 0 \pmod B\$, we need to find the *largest* matching quotient. With \$C \equiv B \pmod {A-1}\$, we need to find the *smallest* matching quotient. --- Coming in at **42 bytes**, here is the case of using only \$C \equiv A \pmod {B-1}\$ and \$C \equiv 0 \pmod B\$: ``` (x(x*)),(x*?)(?=\1*$)(x(x*))(?=\4*$)\2\5*$ ``` [Try it online!](https://tio.run/##XVJNU9swEL3nV6xnAElW4nyQ9oAROXV6ajsDBw6EYdygJBKxrEhKEyj57enKNiTTPWilt6v3nrzWxZ/Cz5yyoeetepaurMyLfD04YeQWbuXi285S@iZu@umB7uguZayL64TRiZgO0zPWgvE4xuN0NP2Snh3S/hvLQnUXnDILyjK/UjNJv3Z7Y8byznxjZkFVBpR/sk6V8slWW@moYfC3AxjzygG1YtSFtfhRhGU2X1WVo/XWr13ATpbnYDnHG2oO1JxbIQYMfjtZvOQQIXsj1gycDBtnILiNzPc193apVvJ4w/SFzT/ajBDDvLPv2MJ7@QwCBnlHOlc53@xrX0oMUOFajAYxo4UG1hHWLaxrZ7Ve9KITMYCLC1CJ0DGPU6qgB@pcM7gWoFMNHEZpXUMibH5/RwkdU/LfR9KMsZo4xqwyQRl8W41El2RHMietLAJ2IivpkrgeUcWa5hKbfVYWYbakrsVqr1F@guUrSMpooHy4fMxW0izCEhIRTTfo@BQ9mZLqo8X28THQvEFZTqAPhGvMAh4IPyHgpAsRuDwCj/h57m9//fyekNZbjGYWnDfIHuTKy1Olemyf5TjITfDB0bZAIEgfCG/PiRhOiCdXhDAsNVhUa1TakbUMZGoIb@U/aT4aT2nmBf5ekebwDw "JavaScript (SpiderMonkey) ‚Äì Try It Online") - ECMAScript This can be shortened further, thanks to a trick [found by Grimmy](https://chat.stackexchange.com/transcript/message/49138588#49138588) (and used in [this post](https://codegolf.stackexchange.com/questions/83533/calculate-eulers-totient-function/180255#180255)). I've used it to shorten [factorial](https://codegolf.stackexchange.com/questions/121731/is-this-number-a-factorial/178979#178979), [Proth](https://codegolf.stackexchange.com/questions/89436/is-it-a-proth-number/179076#179076), [\$np\_n\$](https://github.com/Davidebyzero/RegexGolf/blob/master/regex%20for%20matching%20OEIS%20A033286.txt), and [consecutive-prime/constant-exponent](https://codegolf.stackexchange.com/questions/164911/is-this-a-consecutive-prime-constant-exponent-number/179412#179412) regexes. As a standalone division regex, it comes in at **39 bytes**: ``` (x+),(x*?)(?=\1*$)((x*)(?=\1\4*$)x)\3*$ ``` [Try it online!](https://tio.run/##XVJNc9sgEL37V6xmkgDClj/i6SEK8anTU9uZ9NBDnMmoDrYhFsKAazWNf7u7SErs6R4E@3Z578FKF78Lv3DKhoG36lm6sjIv8s/RCSP3cC9Xn2tL6au4G6ZHWnPWp3U6Y3Qm5uP0glHM2mQ@xbRm8@v04pgOX1kWqh/BKbOiLPMbtZD0U38wZSzvLXdmEVRlQPkn61Qpn2y1l44aBn97gLGsHFArJn3Yiq9FWGfLTVU52mz91gXsZHkOlnM8oZZAzaUVYsTgl5PFSw4Rsndiy8DJsHMGgtvJ/NBw79dqI08nzFDY/L3NCDHOe4eeLbyXzyBglPekc5Xz7b7xpcQIFW7FZBRXtNDCOsK6g3XjrNGLXnQiRnB1BSoROq7TlCoYgLrUDG4F6FQDh0na1JAIm9/eUELHJfnvkTRjrCGOsahMUAbv1iDRJalJ5qSVRcBOZCV9Er8nVLG2ucRmn5VFWKyp67DGa5SfYfkGkjIaKB8mj9lGmlVYQyKi6Ra9PkfPpqSGaLG7fAw0b1CWExgC4RpXAQ@EnxFw0ocITE7AIz7Pz/vv374kpPMWo50F5y1yALnx8lypGdtHOQ5yF3xwtCsQCNIHwrs8EeMZ8eSGEIalFotqrUo3so6BzA3hnfwHzXvjOc2ywN8r0hz/AQ "JavaScript (SpiderMonkey) ‚Äì Try It Online") - ECMAScript [Try it online!](https://tio.run/##dVLBbuIwEL3zFZOqyHYSIKE9Qb097q0rrVbqAVCVLabYS@wwNoJ@PWs7WZS2rA@JZ96bec/2NO9ua/TdWdaNQQf23eYo5oAcb25uzvSUsZye0kdGH/myTG8Z9VEbLO99eGLLu/T27LmLcjYqV/NBr1Fdue1gLTYg7UuDshYvjTkKpJrNBuBXw6dz2PNAG292xiCNW7tH5zksco5buRNQtgVhyQ3oYcN5MYPfKKo/faD5xvczQOEOqOEXHsQFbDJe9vr966AnvInprkZzT2sqa8UaOBQDgWjQxu3GIEiQGrDSb4IW@bQosrI7SQDV/8DOnEp4AZVeg0y4ipv7lEoYgRwqBg8cVKogg2naglR5hxBEH1T4aeM@36NiPYWwXo12Uh/E/JKtvXcUYysqfN1SzIGcSJQhOQlfH0nWd1lHq0Fa7KyIqnWQ3wlN6/EbmkNjKVtMVyzhcjJRV7AyYkP10Zs3rh2VOZmQXOWEewMLklmH9Gs5y4h3eg2cRnBFWqvRInkyWvhuI3j@@ePpe0LYB93uCTMO5SUf6j65a988svzojq1bm4MbH1E6QYOPluC1wQnrSNYlEl7G1yKWhJsgJDBayPvwJjv5xI9Qq/ilO1nq9qgttSfRJq5KbCo/xl7i/Bc "Python 3 ‚Äì Try It Online") - Python [Try it online!](https://tio.run/##hVNNc5swEL37VywHj4TBH7g9JVGuvaUznc70kGQ8pIhaqi2BJOpJ/7yrL8CmyYQLq7er9x67S/Nq9lJ8Op8rWsNRVt1B7pje/aVKYpEHpNPpzQzso6jplABByAZY3SfdiR40BXFvo1JUIGDeJ4EQ2Mxmjr1if1hFcXiJKveAliqSs7oHLGGARs0ofyyZqKgCAj2LVYq3fMkAL8lY7jNtJw2jwlzc9fhpzw4UilHQ@hhrrfkxM7ETiydNGx0MNPkQpb49T5eMH1@3IY7fuCzSkcwerr29KFr@HpDxOoHicnyPo6@hRc9ndmykMqBfdX4szd5PzJpqFDvSXSNPVGER9RqyvYWWuLJVfZBSYR/qVhlbk77bVjFv3GgnPm2iuSftTW/vu@rokGwyUlzw9QxiTZrJRhazptSaVuD2jSollfZhLRUwYAJUKX5RvMm3m75vLsXfTkVjPIkbzRLCffB5gZkdCJvzFO4I8AWHDLaLkMTc/QtO8I67l5Bm2kOeTob2UwrDREdvx8ENK4pZztOrxUzIgxTUWxt@u5YE0Aq2j5vnhLD1modT4U5zfq1o7QhjqdEa5TxHBOVtjpbw49vXhy8JSq9qYyOzfoU8ZkUnjKHzvsou0EqbSnZmdVLMUKyNwqEgzRAYqg3KIpCQwvcNaeT8IuQqQsr6sB8Z5ZPhN/yPHT0JlDmJUHohEYA3JerSLpOVOP8D "Python 3 ‚Äì Try It Online") - Python non-regex equivalent ``` (x+), # \1 = divisor (x*?)(?=\1*$) # \2 = remainder of division; tail -= \2 ( # \3 = conjectured quotient - find the largest one that matches (x*) # \4 = \3-1; tail -= \4 (?=\1\4*$) # assert tail-(quotient-1)-divisor is divisible by quotient-1 x # tail -= 1 ) \3*$ # assert both tail and dividend are divisible by quotient ``` The above algorithm is guaranteed to return the correct quotient if at least one of the following constraints is met (along with \$C \equiv 0 \pmod A\$): * \$A^2+2A < 4C\$ ¬†or equivalently¬† \$A+2 < 4B\$ * \$A=C\$ ¬†or equivalently¬† \$B=1\$ + This works because the regex subtracts \$C-(B-1)-A\$ in order to assert that it is \$\equiv 0 \pmod {B-1}\$, and that subtraction will always result in a non-match (as it can't have a negative result) if \$A=C\$, unless \$B=1\$. * \$A\$ is a prime power + One of the cases in which this must be true, is when \$C\$ is semi-prime and neither of the two other conditions are met. It also must be true if \$C\$ is a prime power. The proof of the first constraint follows. We start from the assertions made by the regex: \$\begin{aligned} \qquad C &\equiv 0 \pmod B \\ C &\equiv A \pmod {B-1} \end{aligned}\$ Suppose the algorithm finds a \$B'\$ satisfying these moduli, with \$C=A'B'\$. Since the search for \$B\$ is done from largest to smallest, the only way for it to first find a \$B'\ne B\$ is with \$B<B'\$. Then: \$\begin{aligned} \qquad C &\equiv 0 \pmod {B'} \\ C &\equiv A \pmod {B'-1} \\ A'B' &\equiv A \pmod {B'-1} \\ B' &\equiv 1 \pmod {B'-1} \end{aligned}\$ So, by modular division of \$A'B'/B'\$, \$\qquad A' \equiv A \pmod {B'-1}\$ Due to \$AB=A'B'\$ and \$B<B'\$, \$\begin{aligned} \qquad A &> A' \\ A &\ge A'+B'-1 \end{aligned}\$ Due to the [AM-GM inequality](https://en.wikipedia.org/wiki/Inequality_of_arithmetic_and_geometric_means), we have: \$\begin{aligned} A'+B' &\ge 2\sqrt C \\ A'+B'-1 &\ge 2\sqrt C-1 \\ A &\ge 2\sqrt C-1 \\ {(A+1)}^2 &\ge {(2\sqrt C)}^2 \\ A^2+2A+1 &\ge 4C \end{aligned}\$ So for a \$B'\$ to be found, \$A^2+2A+1 \ge 4C\$ must be true. Therefore, if \$A^2+2A+1 < 4C\$, no such \$B'\$ will be found. But \$A^2+2A+1 = 4AB\$ has no solutions: \$\begin{aligned} A^2+2A+1 &\stackrel?= 4AB \\ A &> 0 \\ A+2+{1\over A} &\ne 4B \end{aligned}\$ So we can simplify the inequality that guarantees no \$B'\$ will be found: \$\begin{aligned} A^2+2A+1 &\le 4C \\ A^2+2A &< 4C \end{aligned}\$ And now the proof of the prime power constraint. Suppose that \$A\$ is a prime power and the algorithm has found a \$B'\$: \$\begin{aligned} \qquad A&=p^n \\ A'B'&=C\\ B'&>B \\ A'&<A \\ A' &= p^{n-k},\ k>0 \end{aligned}\$ So \$B'\$ must have gained the prime power factor that \$A'\$ lost: \$\begin{aligned} \qquad B' &= xp^k\\ B' &\equiv 0 \pmod p \\ A &\equiv 0 \pmod p \end{aligned}\$ So \$A\$ and \$B'-1\$ are coprime, and we can do modular division by \$A\$, since it is not \$\equiv 0 \pmod {B'-1}\$: \$\begin{aligned} \qquad C &\equiv A \pmod {B'-1} \\ AB &= A\pmod {B'-1} \\ A &\equiv A \pmod {B'-1} \\ B &\equiv 1 \pmod {B'-1} \\ B &< B' \\ B &\le B'-1 \\ B &= 1 \end{aligned}\$ So for a \$B'\$ to be found when \$A=p^n\$, it must be the case that \$B=1\$, meaning \$A=C\$. But we already know that the algorithm works properly when \$A=C\$. --- [Answer] # JavaScript (ES6), 17 bytes Thanks to @Arnauld for golfing off one byte ``` x=>y=>[x/y|0,x%y] ``` Receives input in format (x)(y) Gets floor of x/y by performing bitwise or Gets remainder by x%y Puts both values in an array so that they can both be returned [Try it online!](https://tio.run/nexus/javascript-node#S7P9X2FrV2lrF12hX1ljoFOhWhn7Pzk/rzg/J1UvJz9dI03D0EBTw0RT8z8A) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` {√∑|%}·∂† ``` [Try it online!](https://tio.run/nexus/brachylog2#@199eHuNau3DbQv@/482MjXVMTKN/R8FAA "Brachylog ‚Äì TIO Nexus") ### Explanation We abuse the metapredicate `·∂† findall` to apply two different predicates to the Input list of two arguments: ``` { }·∂† Findall for the Input [A,B] : √∑ Integer division | Or‚Ķ % Modulo ``` [Answer] # Java 8, 18 Bytes `(a,b)->a/b+","+a%b` This is a lambda expression of the type `BiFunction<Integer, Integer, String>`. I'm surprised... this is actually a fairly concise solution for Java. Go lambda expressions! [Answer] # [MATL](https://github.com/lmendo/MATL), ~~12~~ 10 bytes ``` Qt:ie=&fhq ``` Input is `a`, then `b`. Output is remainder, then quotient. [Try it online!](https://tio.run/nexus/matl#@x9YYpWZaquWllH4/7@RqSmXkSkA "MATL ‚Äì TIO Nexus") ### Explanation This avoids both modulo and division. Instead it uses *array reshaping*: 1. Build an array of `a+1` nonzero elements. 2. Reshape as a 2D array of `b` rows. This automatically pads with zeros if needed. 3. The row and column indices of the last nonzero entry, minus `1`, are respectively the remainder and quotient. Consider for example `a=7`, `b=3`. ``` Q % Input a implicitly. Push a+1 % STACK: 8 t: % Duplicate. Range from 1 to that % STACK: 8, [1 2 3 4 5 6 7 8] ie % Input b. Reshape as a matrix with b rows (in column major order) % STACK: 8, [1 4 7; 2 5 8] 3 6 0] = % Compare for equality % STACK: [0 0 0; 0 0 1; 0 0 0] &f % Row and column indices (1-based) of nonzero element % STACK: 2, 3 hq % Concatenate. Subtract 1. Implicitly display % STACK: [1 2] ``` [Answer] # Regex (Perl / PCRE), ~~36~~ 35 bytes ``` x(x*),((x(?=((?(4)\4)\1)))*)\4?(x*) ``` [Try it online!](https://tio.run/##VVFRb4IwEH7nVxyks6040ExfxA5NXPbmkmXJHtQQs9UNg2AKDyyO/XV2BWq0IU3v@@6@@7g7SZVM6uMPEBXAOck@dgkQP8BQzJaLt8VjZVnktMtz@QkChoFFpFKZyttgnylgJBZDLIhn4mHSPFyXw7njDg13MNyh5QAP0RqMlhRKxDl4QAcUbwPFPGjy5kfM08l/4BPlt2C8b7TFEEKdMAUb799fSGT6VXyz@XE93nKwsTCGO5S/5UYtF6cFmgdftzeu9DkpZMDpKOzueFiFnRhdU@9GxqMDuIbGGtpSjo7oKksl5Z4D9/D@@rJ6tjepE1yadHN03RaqQCa5vDLRDf3CW1VlGWPdPgqZF2itC20xCmlOp7Tp2WLOZV82jqrXM7@2Sc0ajYbJutbY7@Kk0Yiip9UyiuqSlX0@YKxkoWAsZGO@wW/EOe/jK9RsXf8D "Perl 5 ‚Äì Try It Online") Takes its arguments in unary, as two strings of `x` characters whose lengths represent the numbers. The divisor comes first, followed by a `,` delimiter, followed by the dividend. The quotient and remainder are returned in the capture groups `\2` and `\5`, respectively. In contrast to the [ECMAScript regex solution](https://codegolf.stackexchange.com/questions/114003/division-and-remainder/222932#222932), this one doesn't have to do anything anywhere near as fancy or mathematically interesting. Just count the number of times \$divisor\$ fits into \$dividend\$ by splitting the divisor to keep two tandem running totals that are both subtracted from \$dividend\$, one that keeps subtracting \$divisor-1\$, and one that keeps subtracting \$1\$ and adding it to the total quotient. We must do a split like this, because regex refuses to repeat a zero-width group more than once (this, along with the limited space to work in, is exactly what prevents it from being Turing-complete). I never wrote a division algorithm in any regex flavor besides ECMAScript before. So it's interesting to now know how they compare in golfed size. ``` x(x*), # \1 = divisor-1; tail = dividend ( # \2 = what will be the quotient ( x # tail -= 1 (?= ( # \4 = running total (?(4)\4) # recall the previous contents of \4, if any \1 # \4 += divisor-1 ) ) )* # Loop the above as many times as possible (zero or more); if # it loops zero times, \4 will be unset (we'll treat that as 0) ) \4? # tail -= \4, or leave tail unchanged if \4 is unset (x*) # \5 = remainder ``` # Regex (Java), ~~41~~ ~~40~~ 38 bytes ``` x(x*),((x(?=(\4\1|(?!\3)\1)))*)\4?(x*) ``` [Try it online!](https://tio.run/##fVNNc9owEL3zKxbPMEjgmNAkl7oapum0vTRJJzn0gDkILIOMLbuSCM4k/Ha6wiaBhKlmQKt9b7/XKX/kZ2m83Mq8LLSFFN@BLIJeCIealZXZSZ0Wc1Eh0hr0er1tRaoe9QmpyIiR6DIavpBRO7qg0ZBS2qPR5cgRtkgdtMrVNJMzmGXcGLjhUsEzNDpjucXrsZAx5IiQB6ulmgPXczOeULALXawNfK9morSyQMsW4PkhMwEJU2K9E4kXzIpYBMjwaHi9ShKhRXwveCw0THe0YyXZWzbPhNKwiWx8G64Xzj8hhk2xbB7/kkoQSttMrbKMyoSYQPxd8cwQzzXDo/T5mFp7IMSedPCMHuyrB9ci9DBF3jI0fdaNVNfdNtzUus1vbq3QCjRrJKw2L10AQ8NdP6SyUGJ3RczOfRBaF9qw8xpLpOLZjpHzSrKLK2SglDqpZswWXI8nFTBwbdm9HAH6MMSfs5qE8FVr/mSCRGYZqfxu1W1CJ4UG4rxLDAjyC3N8FPp9eoynDk93eIoC4s0w3anG6QTjd/1u@Kq74Xa2wAHmCOggr19kt5AK9/Yb5llPNVhrXpImwVlRPt0l91zNBeYJWOy@EImb@eb9uigywRUs0XuOZamYHKAyAZIydg4jJHyG9hJeXpA218WqJJ9okAk1twuCE5WD9BC7OsI66WGR7jw8GSvyoFjZoMR9swnxOjEMAP8YeD5IzPcgj30uS3rKctyJfbScoN2J3PxTSdEQRGbEKW@3hRLeu9gnaHAGf@7vbn@2I/WeXS9ev/@m3dTRjntQb@oR7cMiVM0i1MjprllhbMc07rAHtbC/22yI0/OMh/Pz9pm6XtZZQpvBOW39p9BIvcVIOH5uLkZtvL8/xNhstv8A "Java (JDK) ‚Äì Try It Online") This is a port of the Perl/PCRE regex to a flavor that has no conditionals. Emulating a conditional costs ~~5~~ 3 bytes here. The quotient and remainder are returned in the capture groups `\2` and `\5`, respectively. ``` x(x*), # \1 = divisor-1; tail = dividend ( # \2 = what will be the quotient ( # \3 = the following (after the first iteration has finished), # which is always 1 x # tail -= 1 (?= ( # \4 = running total \4 # recall the previous contents of \4 (only if it is set) \1 # \4 += divisor-1 | (?!\3) # Match this alternative only if this is the first iteration of # the loop, meaning \4 is unset; \3 can never not match here if # \3 is set (because \3==1) unless \1==0, in which case it # doesn't matter if this alternative is taken instead of the # above ‚Äì in that case, the value of \4 isn't changed anyway. \1 # \4 = divisor-1 ) ) )* # Loop the above as many times as possible (zero or more); if # it loops zero times, \4 will be unset (we'll treat that as 0) ) \4? # tail -= \4, or leave tail unchanged if \4 is unset (x*) # \5 = remainder ``` # Regex (Python[`regex`](https://github.com/mrabarnett/mrab-regex) / Ruby), 43 bytes ``` x(x*),((x(?=((?(5)\5)\1))(?=(\4)))*)\4?(x*) ``` [Try it online!](https://tio.run/##dVFNb8IwDL3zK1ykyQktpRVwAUUcd2PSLjtQDtUIkArSKgla@fWd06B9wawoSvye/V6c5uqOtZ526tzUxoG92sTIg2yXYIQZDoddy9oRTxhr2UowtmJzXtDKOff3YsY5H/FitvKsjvibfDHOt0tQIhs0pbVyBwKygTSmNrY/7msDCpQGU@qDZFkyzbI454sBUHiw@g/0caYevcHUytK8H5lJAFscVRADJuh3uin@VaD2VENbJUQG8mQl6NpRioROUrNzejD1pbGMb/Itj4SaTKoH2LzHnqpvIz4ao7RjKsEJJlWCggxsMLbOsPvWPEZy@gic9@AWg9XeIq5rLanbGN5eX9bPEfJfurdpxgLyr7yv@@MujL9n0b@m1u3qi0s/jHKSeR@BQNrgpHUY3xKRyKHUO0CLfhKInhEg8kEmb/IR/WZQvOuOhQ5PDdQfEiHxUGJfqpOX6D4B "Python 3 ‚Äì Try It Online") - Python `import regex` [Try it online!](https://tio.run/##ZVDRSsMwFH3vV9wWJck6u06nD45QBhPfJgzBByulsmymbGlJOqww/PV6m3SbaGhKzrkn555cvX//ajVwWIqNaKpIiU@Yz55nkRb5agqSx16VGyNWKIk9oXWpjT2uSw0SpII4im5ih4tfGHDtUEmDJhgUEEIwDLo/IsmAf4O2ErmGgvMYEhTfg7@DwwEurqOtUJv6w@dyVFjm7sxcFvZit6p9bUBGdZmZkMAISFgcAUdAd2hLXkl4MuyrQyyeLHvujWB/siiVIAzvX8HL8mnx6JNTs/7tIYex5cTWiHMSN6NzUa083FN7qLRUdS855quFqTGhI30@7pIaG8G2dzzxcDx9Xx@HPgVnFaQqCB3/x8@R//3Wudyin8uTZQ@LeZa1DW0GbEhpQxNOaUJvWYrfmLEOpxPG2IClk6RTte0P "Ruby ‚Äì Try It Online") - Ruby This is a port of the Perl/PCRE regex to flavors that have no support for nested backreferences. Python's built-in `re` module does not even support forward backreferences, so for Python this requires [`regex`](https://github.com/mrabarnett/mrab-regex). Emulating a nested backreference by copying the group back and forth costs 8 bytes here. The quotient and remainder are returned in the capture groups `\2` and `\6`, respectively. ``` x(x*), # \1 = divisor-1; tail = dividend ( # \2 = what will be the quotient ( x # tail -= 1 (?= ( # \4 = running total (?(5)\5) # recall the previous contents of \4 (as copied into \5) if any \1 # \4 += divisor-1 ) ) (?=(\4)) # \5 = \4, to make up for Python's lack of nested backreferences )* # Loop the above as many times as possible (zero or more); if # it loops zero times, \4 will be unset (we'll treat that as 0) ) \4? # tail -= \4, or leave tail unchanged if \4 is unset (x*) # \6 = remainder ``` # Regex (.NET), 29 bytes ``` (x+),(?=(\1)*(x*))((?<-2>x)*) ``` [Try it online!](https://tio.run/##bVI9b8IwEN3zK66WK9skodB2gqYgdehGpS4dKAMqB0mUxKmdKpFQfju180FArQfLuvfu3bs757JEpUNMkhNVwVrhAavNbJZhyZfsxCtXeHwR8M@pGPFqJATniyf//rkSI3FiS4@8yDSPEtwRMXdovtUadxDAxKGolFS6ee@lAk6jYDIHGvkJwnTSPF1XwLFD4waNBzRuUTCHWhnOKjaisQAXmMfM3QYi0VJSQ6FqnG6LrxA1p7qNR3ujzZs7Bh@/YWJEaVoDJhrheGPyfFOfpuODkj@5Xj9sxglmhyIEP0PjEW7BZl5xHq84a1MzNCPbJ1Iq0ybcmQxRi969PaWKCvRDqQsgHcP6bY2lhknWlP9TQHhwGT@bExvSt0BWMkNSC/Dh4/1t9XpDzlW7HbhuE@kTBrhdVw87de1c@PQzo1smkemQ9IstUBfWNO8Ctv2pODLNaqt9ZMz4aCHiNL21DizPDn6Qn1@PpPssg/6Q90d/v23@W336BQ "PowerShell ‚Äì Try It Online") This uses .NET's Balanced Groups feature. It returns the quotient and remainder in the lengths of `\4` and `\3`, respectively. ``` (x+), # \1 = divisor; assert \1 > 0; tail = dividend (?= (\1)* # push \2 onto the stack for each time \1 fits into dividend (x*) # \3 = remainder ) ((?<-2>x)*) # \4 = quotient: pop all \2 from stack, doing \4 += 1 for each ``` # Regex `üêò` (.NET), 14 bytes ``` (x+),(\1)*(x*) ``` [Try it online!](https://tio.run/##tVOxboMwFNz5ilfkynYIlLRbokiROnRrpS4dUoYoeQQQYGKDEini21PbkJC0HbrUg2W9O9/de5hK7FGqBPP8ROR8KXGLh2g6LXHPFvTEDh4fs88JH7HDiJ/oYuw@i6JKc9y4fOaQaqUUbmAOoUNQSiGVPcdCAiPpPJwBSf0cYRLao@dxOPZoZtFsQLMOBb2IkWH0QEck4@ABHVO9d4WUW0oaa41C04gMilW9TlAxovhZwarsGmEIRbCVoqnU8jEK1quqbiSqYC2ash6oEosb6lMU5Fhu6@RCsYYZ@LiDEHzdgr3jl6j7gnswkCkaT1Nc6lCJHmScCyH1LOBBU27imbWXaY1@IlQNbs/RMZZGZWwNIvDh4/3t9eXOvbnYT9vzLtUWMFf4Tb//QNc051fyuTudPPxbyFehuf8Tzmlb58rUL7XVPk@1n3t@cTWqmrA0Zn3BBJ/wI1W0NU5HSlsOHeQ6trku07nBQX5221//igf94d4P/Xhlf4T29AU "PowerShell ‚Äì Try It Online") This uses .NET's Balanced Groups feature. It returns the quotient in the capture count of `\2`, and remainder in the length of `\3`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` :,% ``` [Try it online!](https://tio.run/nexus/jelly#@2@lo/r//38jU1MgBgA "Jelly ‚Äì TIO Nexus") [Answer] ## Mathematica, ~~20~~ 18 bytes ``` ‚åä#/#2‚åã@Mod@##& ``` Minor abuse of the flexible output rules: the result is given as `div[mod]`, which will remain unevaluated. The individual numbers can be extracted with `result[[0]]` and `result[[1]]`. And hey, it's only one byte longer than the ridiculously named built-in `QuotientRemainder`. Mathematica, actually has a neat way to apply multiple functions to the same input, but it's three bytes longer: ``` Through@*{Quotient,Mod} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` √∑¬≤¬π%‚Äö ``` [Try it online!](https://tio.run/nexus/05ab1e#@394@6FNh3aqPmqY9f@/kSmXkakpAA "05AB1E ‚Äì TIO Nexus") ~~05AB1E has a bug, so implicit input doesn't work :(~~ [Emigna](/users/47066) noted that inputs are often pushed in reverse. [Answer] ## [Jellyfish](https://github.com/iatorm/jellyfish), 14 bytes ``` p m ,|S % i Ei ``` [Try it online!](https://tio.run/nexus/jellyfish#@1/AlculUxPMpaqQyeWa@f@/kakpl5EpAA "Jellyfish ‚Äì TIO Nexus") ### Explanation Jellyfish is a beautiful language when it comes to applying multiple functions to the same input. The language is 2D and all binary functions look south for one input and east for another. So by approaching one value from the west and from the north, we can feed it to two functions without having to duplicate it in the code. The two `i`s in the program are replaced with the two input values when the program starts. Now `%` is division. It takes one input directly from the east, and when going south it hits the `E` which redirects that search east as well. So both inputs get fed to `%` as arguments. `|` is the built-in for modulo, which basically does the same thing, but ends up looking south for both in puts. We concatenate both results into a pair with `,`. Then `m` is the floor function (which we need because `%` is floating-point division) and finally we print the result with `p`. [Answer] # sed, 36 bytes 35 bytes of code, +1 for the `-r` flag. ``` :a;s/^(1+)( 1*)\1/\1\2x/;ta;s/.* // ``` Takes input in unary, space-separated, with the smaller number first. Outputs as unary, with the quotient first in `1`s and the remainder second in `x`s. (If this isn't acceptable, let me know and I'll change it to space-separated `1`s like the input.) ### Explanation ``` :a; Define label a s/ / /; Perform this substitution: ^(1+) Match the first unary number... ( 1*) ... followed by a space and 0 or more 1s... \1 ... followed by the the first group again \1\2x Keep the first two parts unchanged; replace the third with an x ta; If the substitution succeeded, goto a s/.* // After the loop is over, remove the first number ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 12 ~~13~~ bytes ``` ;W@o,I|\S%;O ``` Which maps onto the following cube ``` ; W @ o , I | \ S % ; O . . . . . . . . . . . . ``` [Try it here](https://ethproductions.github.io/cubix/?code=O1dAbyxJfFxTJTtP&input=NywzCg==&speed=20) Explanation with steps as executed `,I|I,` - starts with an superflous integer divide, gets the first integer from input, reflects back and gets the next integer from input, then divides again `O;` - Output the result of the integer division and pop it `%` - do the mod. This could be done later, but ended up here `S\o` - Add space character to stack, redirect up and output space `W;` - Shift left and pop the space from the stack `O|@` - Output the mod previously calculated, pass through the horizontal reflector and halt. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~56~~ 54 bytes ``` ({}<>)<>([()]{()<(({})){({}[()])<>}{}>}<><([{}()]{})>) ``` [Try it online!](https://tio.run/nexus/brain-flak#FYrBDQBACMLWgR0Mi5ibhDC7p58@2g6cEkto8BksrCG9PLMljvYptHNPKM58 "Brain-Flak ‚Äì TIO Nexus") *-2 bytes thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/)* ## Explanation The current best known [integer division](https://github.com/DJMcMayhem/Brain-Flak/wiki/Basic-Arithmetic-Operations#integer-division-positive-only) and [modulo](https://github.com/DJMcMayhem/Brain-Flak/wiki/Basic-Arithmetic-Operations#modulo-positive-only) in Brain-Flak are very similar (in fact the currently used integer division is just a modification I made on [feersum](https://codegolf.stackexchange.com/users/30688/)'s modulo). **Comparison of modulo and integer division:** ``` Modulo: ({}(<>))<> { (({})){({}[()])<>}{} }{}<> ([{}()]{}) Division: ({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<>< {} {} >) ``` Conveniently, the integer division program uses only the [third stack](https://codegolf.stackexchange.com/a/109859/20059) for storing data while the modulo program uses only the normal two stacks for storing data. Thus by simply running them both at the same time they do not collide at each other. **Combination of modulo and integer division:** ``` Modulo: ({}(<>))<> { (({})){({}[()])<>}{} }{}<> ([{}()]{}) Division: ({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<>< {} {} >) Combined: ({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><([{}()]{})>) ``` Finally, both the integer division and modulo programs used in this combination were designed to be stack clean (not leave garbage on the stacks/not depend on the (non)existence of values on the stacks other than their input) but that is not necessary for this problem. Thus we can save two bytes by not bothering to pop the zero at the end of the main loop and another two bytes by not pushing zero at the start, instead relying on the zero padding on the bottom of the stacks. **This gives us the final program:** ``` ({}<>)<>([()]{()<(({})){({}[()])<>}{}>}<><([{}()]{})>) ``` For the explanation for the integer division program see [feersum's answer](https://codegolf.stackexchange.com/a/98312/20059) ### Integer Division Explanation Coming Soon... [Answer] # [Python 2](https://docs.python.org/2/), 20 bytes ``` lambda a,b:(a/b,a%b) ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQqJNkpZGon6STqJqk@b@gKDOvRCFNw1THXPM/AA "Python 2 ‚Äì TIO Nexus") ### Built-in, 6 bytes ``` divmod ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@SWZabn/K/oCgzr0QhTcNUx1zzPwA "Python 2 ‚Äì TIO Nexus") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~168 148~~ 110 bytes I guess I should have checked the [Wiki](https://github.com/DJMcMayhem/Brain-Flak/wiki/Basic-Arithmetic-Operations) first ``` (({})(<({}(<(({})<>)>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}<>) ``` ## Format: ``` Input: Output: A (18) remainder (2) B (4) division (4) ``` [Try it online!](https://tio.run/nexus/brain-flak#bYyxCcBADAP7TCKVgRQpjBd5Monw7I6cb1P4OGShBlREmMZ4JJMmFvgI3CllTuJPqeYiQ6O7rr/a18Lytqes7D7v43oB "Brain-Flak ‚Äì TIO Nexus") ``` (({})(< # Copy A ({}(< # Pick up A (({})<>) # Copy B to the other stack >)) # Put A on top of a 0 on the second stack # At this point the stacks look like this: A 0 B B ^ <>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>) # Positive division from the wiki >)) # Put down A on top of a 0 # The stack now: A 0 Div B ^ <>{(({})){({}[()])<>}{}}{}<>([{}()]{}<>) # Modulo from the wiki ``` [Answer] # [OIL](https://github.com/L3viathan/OIL), ~~134~~ ~~106~~ ~~103~~ 102 bytes Takes the input from stdin, the two numbers seperated by a newline. Outputs the result of the integer division, then a newline, and then the remainder. This is one of the most complicated OIL programs I've ever written, as OIL lacks builtins for division, remainder, addition, substraction, and so on. It works with the primitive way of doing division: repeated nested decrementation. I present the code in an annotated format, with comments in the style of scripting languages. Before executing, the comments have to be removed. ``` 5 # read input into lines 0 and 2 5 2 0 # the zero to compare to (nops) 1 # make a backup of the second input at line 3 2 3 10 # check if the second input is 0. % 4 2 24 # if so, jump to 24 (marked with ¬ß) 13 # else, go on 10 # check if the first input is zero & 4 31 # if so, jump to 31 (marked with $) 18 # else, go on 9 # decrement both numbers 9 2 6 # jump to line 8 (marked with %) 8 8 # increment the value in line 1 (initially a zero) ¬ß 1 1 # "restore the backup" 3 2 6 # jump to line 13 (marked with &) 13 10 # is the second number zero? $ 4 2 42 # if so, jump to 42 (marked with +) 36 # else go on 9 # decrement both the second number and the backup 2 9 3 6 # jump to 31 (marked with $) 31 4 # print the division + 1 11 # a newline 4 3 # and the remainder (from the backup) ``` edit: Shaved off 3 more bytes by moving a "constant" to a one-digit location (less bytes to reference), and then implicit-ing 2 zero-locations (By using an empty line instead. One of them I could have done before). edit: And another byte by making the initial zero implicit. We really only need a single literal zero. [Answer] # [Retina](https://github.com/m-ender/retina), 14 bytes Let's abuse the input/output formats! ``` (.*)¬∂(\1)* $#2 ``` Takes input as `b\na`, in unary, using for unary digit any single non-digit, non-newline character. Outputs the quotient in decimal, immediately followed by the remainder in unary, using the same character as the input. [Try it online!](https://tio.run/nexus/retina#@6@hp6V5aJtGjKGmFpeKstH//xVAwFWBAQA "Retina ‚Äì TIO Nexus") `(.*) ¬∂(\1)*` matches the first number , then a newline (¬∂ is Retina's shorthand for \n), then the first number again as many times as possible. The number of matches of the second group will be the result of the division, and the part not matched will be the remainder. With `$#2`, we replace everything that was matched in the previous line with the number of captures of the second group, and get then our result. [Answer] # Excel 2013, ~~31 30~~ 26 bytes ``` =INT(A1/B1)&","&MOD(A1;B1) ``` # Explanation Input is in cell `A1` and `B1`. This simply returns the return values of the `FLOOR` and `MOD` function, which are for flooring the division and for the remainder. These values are separated by a comma. [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), 11 bytes ``` ?:?:}/!\{%! ``` [Try it online!](https://tio.run/nexus/labyrinth#@29vZW9Vq68YU62q@P@/kampgpEpAA "Labyrinth ‚Äì TIO Nexus") ### Explanation ``` ?: Read a and duplicate. ?: Read b and duplicate. } Move a copy of b over to the auxiliary stage. / Compute a/b. ! Print it. \ Print a linefeed. { Get back the other copy of b. % Compute a%b. ! Print it. ``` The IP then hits a dead end, turns around and the program terminates due to the attempted division by zero when `%` is executed again. [Answer] # C, 32 bytes ``` f(a,b){printf("%d %d",a/b,a%b);} ``` [Try it online!](https://tio.run/nexus/c-clang#DchLCoAgEADQqwyFoGCfTW2M7jL@UKgxzFbRsVtbb/naSGa7rFvOYmPqw1o9R6nFfeRIxfOGWWC2kThoiUwL9dT/YcdIXNzg@SRnoSC7cmWCUcFTX0qdQRPcBw "C (clang) ‚Äì TIO Nexus") [Answer] # [ArnoldC](https://lhartikk.github.io/ArnoldC/), ~~286~~ 283 bytes ``` HEY CHRISTMAS TREE c YOU SET US UP 0 HEY CHRISTMAS TREE d YOU SET US UP 0 GET TO THE CHOPPER c HERE IS MY INVITATION a HE HAD TO SPLIT b ENOUGH TALK GET TO THE CHOPPER d HERE IS MY INVITATION a I LET HIM GO b ENOUGH TALK TALK TO THE HAND c TALK TO THE HAND d YOU HAVE BEEN TERMINATED ``` [Try it online!](https://tio.run/nexus/arnoldc#dc87DsIwEEXRPqt4HS1IFLSGjDIj4o8846CUQPa/heAI0SShsWTr6OpZ7KBQjg8TTw3TiBtnUfNOYZkIz2aMBUqGoigJp8ueeq3Ued5B7xU67pWmDWq6erEIY6o4pkS5ppgyQRR@hIRBzJnEUNdWxK5dvKZerC6jEEvHMNffd1vT35agr5zFo4vr0HL@SuxCWydtnr5/YTcQrkQBRtlLcEbtPH8A "ArnoldC ‚Äì TIO Nexus") ### How It Works ``` HEY CHRISTMAS TREE c //DECLARE VARIABLE c = 0 YOU SET US UP 0 HEY CHRISTMAS TREE d //DECLARE VARIABLE d = 0 YOU SET US UP 0 GET TO THE CHOPPER c /* HERE IS MY INVITATION a SET c = a/b HE HAD TO SPLIT b ENOUGH TALK */ GET TO THE CHOPPER d /* HERE IS MY INVITATION a SET d = a mod b I LET HIM GO b ENOUGH TALK */ TALK TO THE HAND c // PRINT c TALK TO THE HAND d // PRINT d YOU HAVE BEEN TERMINATED //END ``` ### Output Format ``` a/b a mod b ``` [Answer] # [Quipu](https://esolangs.org/wiki/Quipu), 54 bytes ``` \/\/[]\n[] 1&/\1& [] [] // %% /\ /\ ``` [Try it online!](https://tio.run/##zVltU9tGEP6uX7FRBpBCsHHbTy6mDaSdps3bNJnpB0w7h3y2lciSqjsDHo9/O93duxOSX8CCMNNkAOtu79ndZ1d7d2sViUTctNsfhdISZtm0gCgbSIhT0GNpPisZ6ThLQaQDHozTfKqdhHmwIi14nSWJKEDFo1TBWFxK0BlcSJAqErkcwFWsxzCoCHnxJM8KhMtan1B7JN1AhEIWdTLV4iKRrVdFIWYn0@FQFl528QVn4Z1AO@S1lulAwas8n@tiNn@TalnkhcTfwUdRKPxTwreGRTY5mWmpgpNEjlt5kY1aI6l5KAzDRSR0NJ5HQknIZdcs/@U6kjmZ0jvOizjVSRr4ZgZkUWRFF/z9XBLMO6mUGMnQY4BYdqFiTAkDvWMogSoCJRrs49pVvH8IbiCvP0z1h@FJNkWn12O@z2xghjHy5oeLhRclQilY8ieYGPwufNK4dhSWXK6IhI5yAzHXs1zC53EhxQB6UAnN2R9pps@9gRyCyPNkFigmHlXw37BrhM/MbxY@R4S5d4k5oRlQdeFtrPQZUkNT7@ME2m2YKkwgTKd4IFOtWFzpwih1oMaNc2dRELIYslIXs8BVmUKqaaK7NU@Me@d1/1DeeETxeRunUsEwQ7loDHNIMAwIl0CCE@iy/PfsdCwKgkisKRg/fDr04iEE1l3osZMhkkCjtLaVyHSE78oxHMLuLsMFhyE864Hf9338SMJXYwwvBAbzCCrrwrsmS0CeC1ux@mscY/rnAsNjLdzvQYeNMY@ot4rO0UpAoyOpvLJpgMRoWkcj76eTC1lQcNFUz3BLc9orXXaxhu6@0emVmr/DfC1D69hvYS4njrHSTd9feGV47xY96CwQ142isjiqxi7GyLnoWKEgDo2fLs2NIzS8GidrPXSInQq9MKGKgmP8Cu@d7VGKDKaT3NiMSpz5iPvyNqX5yWgOrdXEzZ8S52QaSSLXq65F@w46XnU9jvi@1fv3I/V@ksmwmcqoC5T7gFRFmGOv41GsyYZbbgxbdX522U6TeVVFpIlfkLr6Q29RH0JTo5bOTCHAD/iqW@Sf70Jegb0PFF5A59Ai73x7mxne4T9/AP6yML7Bh2tka4/s0ra2kaQxr79H9tUyiJYtxdkJ9/fuT4J0LeBeP92zAnqDgHYC7Uem@5t022R3LOw/UiOVzQ@5LATtulw5g@uXMAvJUSJpFjZ42w@e1JiDZsa8eFJjXjQzpr1F@tkcfbjFeEBrWJ7bT8pRe1uOFrWK9lTm7DQLWe8bGHOa4X5PxojkdwSyJhlzelQamxj00yMNchY0UHm0RdoePTFPRw1peuq4HW0fN5fXx1vQePzEZh//z2g8bk7jjw8yaXuXu490@TeRNC3Azx@p8jTLZw1VwoNUrqKtalzY/@6mGiWZkng/8/AaTfpAJAlcGKWbb0QQu9vsmgtQU7PRGEISdD/b0AKgRDVXcqPG3dzs/XGTgQxpXC/Nw4MqI5HaQuppkRrN9JwX8aXQEqhDUfOCmzVov@uGOOO7q@0Nd1WP6VxtDuH1F65yAY5Dex5XfH33V4WNOhZWoQudadisax816tq4tk21zTT3Ku0Z6vGtC0joxJDULLmUVDeCFCXTWchMUcTqpdMwCIaYI@4elh0DLDWx7WLRZyQgu2Ln13pIHSw1RWQXgb5PTbEUf/y@3/JtPhWQZzGt51sPPY/xzZeUqRXlvMF7riHyzIige9RUyi5l2XWqpzoBBBY@9Gy7SURfbW8KaTgvOwXUmqkxUQl/yr6n0O1Sj8dM1wLONxk3bd36ilOuC8bhKFVhZtNoSwvTFVNf41xxK1bhDZ0XMsIXDBcTMRSJkjw0jNNYjXmQ8e@ih3pEz8oF9GAAq7QxiGegxkRajYJao8IVkgLzqWd4XOHsnuzheMThFlRv4thtX49IwNLySh7yGBefIUWRHzk8G@xz8mkpvclgK6iWBW0rpibDWrFk6CVhty@tCJMXddH6gX3I1nq6mCHTgVnS4fJuFi@FIRC2fF7w35oDwzQQOLGsb6s4fKY@8yRWirUZxhcQVVXLu9vi3v2h1iDTbDoa4yYxmk6ovUybDGSOEKPW8rl6ksrDcqNEAKkrFHv1AHFa3Jn@ttGTY6pTBS5fY11MpXdb7apF2SgNG6X3qUj3tNkBuFQASuDuSvuizsw3EGWgHbDzt5GzTRxgLabz4nTgYQLocJWitGzRq0gtd2o1c17eKixsb6pMsdUkMW/ir1mBvNe@N6mgVNbbl8Jc5UnMWcFfswS39LCcO3KSYLkJsc9Y0rlGlmWXeakU48BOmy8BSJ4ywBZcrr3llmVyw5KIdxdaVCuUc29JOUgs/zh8y3xluTlpsLZbFbdb2j2VmmrtylGHBcojlJNZd8Kh/@ICORd4PDGnHT5Am@YxP1egMRmm0pYWd9xZFq9oseLLB6TlFcslrwsBFzFXwe5Ut7YUGARefJJhtoh0HYA9lNX3yI1i5Yu3UcK@NBvnXRZvFCjTd6NEuetslCi3mpqEnaRvW@d0nKRvXHuFuPJ9/6bf7rfPzvvp2bkH@K@z2@53dvnj2Tn98Ec8bsDOjvnYp58bXLq46Xzv/fAf "Scala ‚Äì Try It Online") ### Explanation Each pair of columns constitutes a "thread." Threads are executed one at a time, top to bottom, left to right. Each thread also stores a value (initially 0). Each of **threads 0 and 1** uses the `\/` knot to read a number from stdin and stores that number as its value. **Thread 2** does the following: * `[]`: Get the value of thread N, where N is the previous value of this thread. Here, there is no previous value, so we get the value of thread 0. * `1&`: Push a 1. * `[]`: Get the value of thread N, where N is the 1 we just pushed. * `//`: Integer-divide the last two values. * `/\`: Output the result. **Thread 3** sets its value to a string containing a newline (`\n`) and then outputs it (`/\`). **Thread 4** does the same thing as thread 2, but with modulo (`%%`) instead of division. [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~27 26~~ 16 + 1 = 17 bytes ``` :r:{%:n','o-$,n; ``` # Note * Input using the `-v` flag, see TIO for an example. * This outputs the remainder first, then a comma and lastly the integer division. [Try it online!](https://tio.run/nexus/fish#@29VZFWtapWnrqOer6uik2f9//9/3TJDYyBhDAA "><> ‚Äì TIO Nexus") # Explanation Note that the stack starts as `A, B`, where `A` and `B` represent the first and second input, because of the `-v` flag used. ``` :r:{%:n','o-$,n; # Explanation :r:{ # Do some stack modifications to prepare it for # next part # (Stack: B, A, A, B) % # Take the modulo of the top two items # (Stack: B, A, A%B) : # Duplicate it # (Stack: B, A, A%B, A%B) n # Pop once and output as number # (Stack: B, A, A%B) ','o # Print separator # (Stack: B, A, A%B) - # Subtract the modulo from the first input # (Stack: B, A-A%B) $, # Swap the two inputs so they are back in order # and divide, so we get an integer # (Stack: floor(A/B)) n; # Output that as a number and finish. ``` [Answer] # C, 21 bytes ``` #define f(a,b)a/b,a%b ``` A macro that replaces f(a,b) with the 2 terms comma separated. Though you'd better be passing it to a function or else there's no way to pick the 2 apart. [Try It Online](https://tio.run/nexus/c-clang#DcdLCoAgEADQtZ5CCkFB@qxaGJ2kjTZKAzWF2So6u/V2r9QQIlIQUTnjtWu9cdKXGmnZbgjjlQGPZp04Uha7Q1L64exMf6OqJAgJM1Umqn4wg9aWsxTynUh0lr/lAw) [Answer] # [Haskell](https://www.haskell.org/), 21 bytes ``` a#b=(div a b,mod a b) ``` [Try it online!](https://tio.run/nexus/haskell#@5@onGSrkZJZppCokKSTm58CojX/5yZm5inYKhQUZeaVKKgomJgbGiooK1gYmv4HAA) Example usage: `13#2` returns `(6,1)`. Yes, this is pretty boring, however slightly more interesting than the `divMod` build-in which works the same. While we are at it, there is also `quot`, `rem` and `quotRem` which behave the same on natural numbers as `div`, `mod` and `divMod`. However, for negative inputs the result of `mod` has the same sign as the divisor, while the result of `rem` has the same sign as the dividend. Or, as it is put in the [Prelude documentation](http://hackage.haskell.org/package/base-4.9.1.0/docs/Prelude.html#v:quot), `quot` is integer division truncated toward zero and `div` is integer division truncated toward negative infinity. --- How about no `div` or `mod` build-ins? ### No build-ins, ~~36 32~~ 31 bytes ``` a#b|a<b=(a,0)|m<-a-b=(+1)<$>m#b ``` [Try it online!](https://tio.run/nexus/haskell#@5@onFSTaJNkq5GoY6BZk2ujm6gL5Ggbatqo2OUqJ/3PTczMU7BVKCjKzCtRUFEwMjVTtvwPAA "Haskell ‚Äì TIO Nexus") Example usage: `13#2` returns `(1,6)`, that is the `mod` result is first and the `div` result second. If `a` is smaller `b`, then `a mod b` is `a` and `a div b` is `0`, so `(a,0)` is returned. Otherwise recursively compute `mod` and `div` of `a-b` and `b`, add `1` to the division result and keep the remainder. Adding 1 to the division result is achieved by using `<$>`, which is commonly used as `map` to map functions over lists, but works on tuples too, however the function is applied to the second tuple element only. Edit: Saved one byte thanks to xnor! [Answer] # SWI Prolog, 109 bytes ``` p(A):-print(A). d(F,S,0,F):-S>F. d(F,S,D,R):-G is F-S,d(G,S,E,R),D is E+1. d(F,S):-d(F,S,D,R),p(D),p(-),p(R). ``` Output: ``` ?- d(255,25). 10-5 true . ?- d(5,7). 0-5 true . ``` Description: Simple recursive algorithm without builtin division or modulo. It simply counts "how many times fits the Second number into the First one?" and reports the result (unified to D) with the remainder (R). //edit: removed unnecessary spaces ]
[Question] [ ### Your Programs: You'll write two programs (both in the same language). The storage program takes a string from STDIN and stores it somewhere *persistent* (see below) and then exits without error. The retrieval program takes no input, retrieves the string that was stored, and prints it to STDOUT. ### Objective test of Persistence: You should be able to run the storage program on your local machine, then power-cycle your local machine, then call the retrieval program on your local machine. You can stash the string however you want (even on the web) as long as you pass this reboot test. ### Test Cases: Storage then retrieval: ``` echo foo | Store Retrieve foo ``` Repeated Stores should overwrite (like a set() method): ``` echo foo | Store echo bar | Store Retrieve bar ``` Repeated Retrieval is non-destructive (like a get() method): ``` echo foo | Store Retrieve foo Retrieve foo ``` Retrieval before any invocation of Storage: You don't need to worry about this. Your retrieval program can assume that the storage program has been run at some point in the past. ### Input/Output flexibility. People have asked me to expand this from strict STDIN/STDOUT to the standard IO rules. I can't because it would introduce too many loopholes. Some standard IO options already have the input stored in a persistent way, eg "programs may take input from a file". I'd like to be more flexible than just strict STDIN and STDOUT, but without opening the floodgates. From the standard IO rules thread I'm cherry-picking the ones that don't break the challenge: * [Programs may take input via GUI prompts](https://codegolf.meta.stackexchange.com/a/2459/69304) and command-line prompts if you want * [Programs may output by displaying it on screen](https://codegolf.meta.stackexchange.com/a/7139/69304) This includes GUI dialogs * [Programs may take input via command-line arguments](https://codegolf.meta.stackexchange.com/a/2449/69304) * [Programs may output to STDERR](https://codegolf.meta.stackexchange.com/a/2451/69304) but still can't actually throw errors. If you use an alternate it must be user-interactive. The user shouldn't have to do any other work besides piping their input to your program, typing it into a prompt your program provides, or typing input as a command-line-arg of your program. The user shouldn't have to do anything other than running your retrieve program to see the output displayed on screen or sent to STDOUT or STDERR. ### Allowed assumptions: * Your two programs will be run in the same directory * Your programs have read-write permissions for that directory * Files you create will survive the reboot (not in a temp dir) * One trailing newline that wasn't part of the string is allowed. No other trailing whitespace ### This is code-golf, and your score is the sum of bytes from both programs. [Answer] ## zsh, 4 bytes Store: `>f` (reads from STDIN and writes to a file called `f`) Retrieve: `<f` (writes the contents of `f` to STDOUT) [Answer] # TI-BASIC (Z80), 1 [byte](https://codegolf.meta.stackexchange.com/a/4764/43319 "TI-Basic is tokenized")? Store:  (just enter the string) Retrieve: `Ans` (byte 27) But if that isn't valid: # TI-BASIC (Z80), ~~7~~ 6 [bytes](https://codegolf.meta.stackexchange.com/a/4764/43319 "TI-Basic is tokenized") -1 thanks to Jakob. Store: `Prompt Str0` (bytes DD AA 09) Retrieve: `disp Str0` (bytes ED AA 09) [Answer] # Browser JS, 44 bytes **Store**: ``` localStorage.a=prompt() ``` **Retrieve**: ``` alert(localStorage.a) ``` [Answer] # POSIX shell sh/bash/... 8 bytes store: ``` dd>f ``` get: ``` dd<f ``` [Answer] # [Python 3](https://docs.python.org/3/), 46 bytes ### store, 45 bytes: ``` open(*'fw').write('print(%r)'%open(0).read()) ``` The retrieve program is built by the store command, a file named `f`. ([1 byte for the file name](http://codegolf.meta.stackexchange.com/questions/12819/what-assumptions-about-the-file-system-layout-can-be-made)) [Answer] # Batch, 16 bytes ``` COPY CON A TYPE A ``` [Answer] # Powershell - 4 Bytes Storage: ``` ac ``` (alternative also `sc`) Retrieval ``` gc ``` Edit: I just noticed the output is not allowed any user input... so it jumps from 4 to either 6 or 8 bytes Storage: ``` ac f ``` (alternative also `sc f`) for the 8 byte version ``` ac ``` (and specify `f` as path) for the 6 byte Version Retrieval ``` gc f ``` [Answer] # Rust, 136 bytes ## Store (84 bytes) ``` use std::{fs::*,io::*}; ``` ``` ||{let mut v=vec![];stdin().read_to_end(&mut v);write("a",v)} ``` ## Retrieve (52 bytes) ``` ||print!("{}",std::fs::read_to_string("a").unwrap()) ``` ## Acknowledgments * -1 byte thanks to [Esolanging Fruit](https://codegolf.stackexchange.com/users/61384) [Answer] # Bash, ~~12 11~~ 10 bytes ## store, ~~7 6~~ 5 bytes ~~`cat ->f`~~ # no need for `-`, stdin is default ~~`cat >f`~~ # no need for space, `>` separates as well ``` cat>f ``` ## retrieve, 5 bytes ``` cat f ``` [Answer] # HP 49G RPL, 48 bytes To save: `:2: A DUP PURGE STO`, 26.5 bytes To restore: `:2: A RCL`, 21.5 bytes If we can leave in the backup battery, we get: # HP 49G RPL, 0 bytes To save: , 0 bytes To restore: , 0 bytes, since the HP 49G leaves the stack untouched across reboots. [Answer] # [APL (APLX)](https://www.dyalog.com/aplx.htm), 5 [bytes](https://codegolf.meta.stackexchange.com/q/9428/43319) Store: `⍞⍈1` Retrieve: `⍇1` `⍞` get line from stdin `⍈1` write to next available component of file number 1 `⍇1` read the ~~first~~\* last component of file number 1 [![APLX Store session](https://i.stack.imgur.com/d8JTl.png)](https://i.stack.imgur.com/d8JTl.png)[![APLX Retrieve session](https://i.stack.imgur.com/VrBz0.png)](https://i.stack.imgur.com/VrBz0.png) \* Documentation says *first* but experimentation shows *last*. [Answer] # bash, 10 bytes (non-competing) ``` touch $@ ls ``` Unix filenames [can contain](https://unix.stackexchange.com/a/230299/43499) any character except `NUL` and `/`, and their names can be [upto 255 bytes long](https://serverfault.com/a/9548/188067) so this will be able to store only strings up to that length (consider that a limitation of the storage medium), and that don't contain '/' in them. That's one reason this is non-competing, another is that this assumes the directory it's run on is empty (or that extraneous output from `ls` is allowed). I still wanted to post this because it just seemed a cool and non-obvious way to store information. Another on a similar vein, which wouldn't have the same length and character limitations would be: ## ~~35~~ 33 bytes ``` mkdir -p $@ find|sed '$!d;s/..//' ``` This allows the `/` character in the string, and supports many more characters (exactly how many depends on implementation). *(-2 bytes on this thanks to @Cows quack)* [Answer] # Python 3, 56 bytes ## Store (33 bytes) ``` open(*'aw').write(open(0).read()) ``` ## Retrieve (23 bytes) ``` print(open('a').read()) ``` Prints with a trailing newline. [Answer] # Japt, ~~46~~ 30 bytes *-16 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974).* One of the first times I've tried using Japt. The JS eval can be fidgety sometimes. Uses the browser's `window.localStorage`. ## Store (16 bytes) ``` Ox`lo¯lSÈSge.P=U ``` ## Retrieve (14 bytes) ``` Ox`lo¯lSÈSge.P ``` [Answer] ## Haskell, 46 bytes Store (26 bytes): ``` getContents>>=writeFile"t" ``` Retrieve (20 bytes): ``` readFile"t">>=putStr ``` [Answer] # Ruby (26 Bytes) ## Set (16 Bytes) ``` IO.write'a',gets ``` ## Get (10 Bytes) ``` IO.read'a' ``` [Answer] # MATLAB (30 Bytes) ## Set (22 Bytes) ``` a=input('','s');save a ``` Can shave off 4 bytes by changing to `input('')`, but this will require input to be in single quotes: `'input string'` ## Get (8 Bytes) ``` load a;a ``` [Answer] # C (GCC), 98 bytes ## Store (46 bytes) Input is via first command line argument. ``` main(c,v)char**v;{fputs(v[1],fopen("a","w"));} ``` ## Retrieve (52 bytes) ``` c,d;r(){for(d=open("a",0);read(d,&c,1);)putchar(c);} ``` ## Unportability * Requires that several pointer types fit in `int`. ## Acknowledgments * -2 bytes thanks to [*ceilingcat*](https://codegolf.stackexchange.com/users/52904) * -10 bytes thanks to [Peter Cordes](https://codegolf.stackexchange.com/users/30206) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 bytes Store: `⍞⎕NPUT⎕A 1` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9uCS/KPX/o955j/qm@gWEhgApRwVDkAwXEAellhRlppalcj3qagYpcHcFKwBJ/VcAA7B@rrT8fC5kflJiEZQPMwEA "APL (Dyalog Unicode) – Try It Online") Retrieve: `⊃⎕NGET⎕A` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9uCS/KJXrUe@8R31T/QJCQ4CUIxdQHISDUkuKMlPLUv8/6moGSbu7gqVB2v4rgAFEd1p@PheED9OBxgUA "APL (Dyalog Unicode) – Try It Online") `⍞` get line from stdin `⎕NPUT` put it in a native file called `⎕A` the uppercase alphabet `1` and overwrite if the file exists `⊃` the first part (the data, the next parts are encoding and line ending type) of `⎕NGET` get the native file `⎕A` the uppercase alphabet [Answer] # R (27 bytes) ## store (21 bytes) ``` x=readLines('stdin') ``` ## load (6 bytes) ``` cat(x) ``` For this to work, the first script needs to be invoked with the command line option `--save`, and the second one with `--restore` (though in interactive mode this isn’t necessary: these options are the default). This could be shortened by 7 bytes were it not for the fact that a bug in R prevents the default argument of `readLine` from working in non-interactive mode. In interactive mode, it is *not* necessary, and the solution therefore only uses **20 bytes**. [Answer] # [Java (JDK 10)](http://jdk.java.net/), 204 Bytes **Warning:** Overwrites any preferences that any java programs have stored for your username! ### Store, 94 Bytes: ``` interface S{static void main(String[]a){java.util.prefs.Preferences.userRoot().put("",a[0]);}} ``` [Try it online!](https://tio.run/##DcsxDoMwDADAr0RMidRa3fsJVEbE4AaDnLYxShwWxNtdltsu4Y73NH/MOCuVBSO54aiKytHtwrP7IWc/aOG8jhOGI10DmvIXtkJLhf6SCuVIFVql8hJRH2Br6rvuhuNjCs/zNLO3yB8 "Java (JDK 10) – Try It Online") ### Retrieve 110 Bytes: ``` interface R{static void main(String[]a){System.out.print(java.util.prefs.Preferences.userRoot().get("",""));}} ``` [Try it online!](https://tio.run/##DYxBCsMgEAC/Ip4U2v1APxGSY@lhazZhbeMWXQMl5O3Gy8DMYSLueI/zpzVOSnnBQGY8iqJyMLvwbDbk5CbNnNbnC/0x/YvSBlIVfj2qi30BVfnbnZYCQydlSoEK1EJ5FFHnYSV11t6s9f5xnq21t8gF "Java (JDK 10) – Try It Online") ``` java S foo java R foo ``` This works by taking input as an arg and storing it in the user preferences backing-store provided by [java.util.prefs](https://docs.oracle.com/javase/8/docs/technotes/guides/preferences/index.html). It overwrites the user's root node to save one byte on naming a node. If you want to test it non-deestructively, either run it from a throwaway username or change the key from "" to a node name. [Answer] # C#, 157 Bytes **Set, 74 Bytes:** ``` class P{static void Main(string[]a){System.IO.File.WriteAllLines("a",a);}} ``` **Get, 83 Bytes:** ``` class P{static void Main(){System.Console.Write(System.IO.File.ReadAllText("a"));}} ``` -1 Bytes thanks to VisualMelon -2 Bytes thanks to LiefdeWen [Answer] # Perl 5, 48 26 23 bytes ### Write, 20+1(-n) bytes *-3 bytes thanks to mob* ``` open f,">>f";print f ``` I'm actually not certain about this one points-wise, but it meets the criteria. For past entries, only the cli options were counted, so that's what I'm going with. ### Read, 0+2 bytes ``` perl -pe "" f ``` [Answer] # Sed, 2+2 bytes: Stores to file `f`: ``` wf ``` Reads from file `f`: ``` rf ``` [Try a demo online!](https://tio.run/##LctBCoAgEEDRfaf4EOS@A3QXUSdtoeBMuOnuRtDqrV70mudMITecR62XejoeNEWGLB9dZvCGcGw7rFy3GtbQ3AaW078YXikVmS8) [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 23 + 16 = 39 bytes Simply writes STDIN to file `A`, then reads file `A`. `store.@`: ``` $A&FileWrite!AllInput[] ``` `retrieve.@`: ``` Echo!FileRead!$A ``` ## Testing ``` C:\Users\conorob\Programming\attache (master -> origin) λ echo testing | attache store.@ C:\Users\conorob\Programming\attache (master -> origin) λ attache retrieve.@ testing ``` [Answer] # Lua, 57 53 51 bytes **Store, 27 bytes** ``` io.open("x","w"):write(...) ``` **Retrieve, 24 bytes** ``` print(io.open"x":read()) ``` [Answer] **RUBY** **Store** *(24 bytes)* ``` File.write('a', ARGV[0]) ``` **Retrieve** *(16 bytes)* ``` p File.read('a') ``` [Answer] # C (Unix/GNU), 23+23 = 46 bytes ## Store, ~~27~~23 bytes ``` main(){system("dd>f");} ``` ## Retrieve, ~~27~~23 bytes ``` main(){system("dd<f");} ``` This basically wraps [jofel's answer](https://codegolf.stackexchange.com/a/168074/63856) into a C program. Note: The `dd` commands outputs some statistics to `stderr`, so you will see some additional output when you naively run it in the shell. However, since the challenge only says that the stored string must be presented on `stdout`, not `stderr`, I take it that it is allowed to have additional output on `stderr`... Anyway, suppressing `stderr` output is as easy as replacing `dd` with `cat`, increasing the byte counts of the two programs by one, each. [Answer] # PHP, 26+1 + 21 = 48 bytes Store.php: ``` <?fputs(fopen(s,w),$argn); ``` Run with `echo <input> | php -nF Store.php`. Retrieve.php: ``` <?=fgets(fopen(s,r)); ``` Run with `php -n Retrieve.php`. [Answer] # [C (gcc)](https://gcc.gnu.org), ~~77~~ 67 + 25 = 92 bytes Compiles with only a few warnings on my gcc. **store.c** ``` #include<stdio.h> main(int c,char**v){fputs(v[1],fopen("f","w"));} ``` Can probably golf out the include, but I couldn't figure out how. Segfaults if you don't pass it anything, but whatever. Peter Cordes: -1 **read.c** ``` main(){system("cat f");} ``` ]
[Question] [ We live in a wonderful age of technology where we can have beautifully detailed 8K screens on our TVs, and even 2K displays on our phones for our mobile browsing pleasure. We've come a long way in recent years in terms of screen technology. One of the products of this is a term that was made popular by Apple, *Retina*. This is referring to the [pixel density](https://en.wikipedia.org/wiki/Pixel_density) of the display in question being so high, that at a viewing distance of 10-12 inches away, individual pixels cannot be easily picked out. Steve Jobs said that the pixel density where this occurs is right around **300 pixels per inch**, and they started employing pixel densities in this range on their devices with the *Retina* buzzword used for advertising. Pixel density can be calculated by the following formula: ![D=sqrt(w^2+h^2)/d](https://i.stack.imgur.com/G9tBC.gif) Where `d` is the diagonal of the screen in inches, `w` is the number of pixels on the horizontal axis, and `h` is the number of pixels on the vertical axis. # Your Task For this task, you'll be using the *Retina* standard to decide what products are worth buying. Being the modern consumer that you are, when you shop for devices you want to make sure that you're getting a good product, not some device from the 90s! As such, you want to build a *program or function* that takes the screen width, height and diagonal length as **input or function parameters**, and tells you whether the particular screen qualifies as a retina screen (`D > 300`) by *printing to the screen or returning*. Due to your contempt for non-Retina devices, your *program or function* will output `Retina!` when the device qualifies, and `Trash!` when it does not. You may assume that all of the numbers will be greater than 0. Pixel values for width and height will always be whole numbers. Screen size may be interpreted in any way, as long as it supports decimals. The input may be in any order you choose, and may also be on up to 3 separate lines. # Example I/O ``` 1920 1080 4.95 -> Retina! 2560 1440 5.96 -> Retina! 1920 1080 10.5 -> Trash! 10 10 0.04 -> Retina! 4096 2160 19(.0) -> Trash! 8192 4320 100.00 -> Trash! 3000 1500 11.18 -> Retina! 180 240 1(.0) -> Trash! ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the fewest number of bytes wins. --- Here's a Stuck solution, a stack based programming language I'm making: ``` r;`;/300>"Retina!""Trash!"? ``` [Answer] # [Retina](https://github.com/mbuettner/retina), ~~530~~ ~~220~~ ~~210~~ ~~202~~ ~~201~~ ~~193~~ ~~191~~ ~~187~~ 185 (184) bytes *Credits to randomra for saving 3 bytes!* (And paving the way for a couple more.) ``` +`\.(\d)(.+)( .+) $1.$2_$3_ \b # +`(\d*)#((((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|\w) $1$1$1$1$1$1$1$1$1$1$3$4$5$6$7$8$9$10$11# \d 11 (?=(1*)\1)[^.] $1 ^(1+)\.\1{90000}1+ Retina! 1.+ Trash! ``` For byte-counting purposes, each line goes in a separate file, but you can run the above code as is from a single file by invoking Retina with the `-s` flag. This expects the density first (which *must* contain a decimal point, even if it's a trailing one), followed by width and height, i.e. `d w h`. This is a *bit* slow. I wouldn't try most of the given test cases, because it will run for ages. However, you can check that it works correctly with the test cases ``` 19. 4096 2160 -> Trash! 1. 180 240 -> Trash! 1. 181 240 -> Retina! 1. 180 241 -> Retina! 0.04 10 10 -> Retina! ``` Basically, after multiplying all numbers through to make the density an integer, you don't want the width and height to have more than 4 digits. While this is slow, it is completely exact... there are no floating point issues or anything like that. All arithmetic is using (unary) integers. In principle, I could shave off one more byte: the `^` can be omitted, but it will make `Trash!` test cases horribly slow due to excessive amounts of backtracking. ## Explanation First, let's rearrange the inequality to avoid floating point operations: ``` √(w2 + h2) / d > 300 √(w2 + h2) > 300 d w2 + h2 > 90000 d2 ``` We can also notice that this is invariant under multiplying `w`, `h` and `d` by the same number `x`: ``` w2 + h2 > 90000 d2 (x w)2 + (x h)2 > 90000 (x d)2 x2 (w2 + h2) > 90000 x2 d2 w2 + h2 > 90000 d2 ``` There are several ways to square a unary number, but we'll be making use of the identity ``` n2 = Σi=1..2n ⌊i/2⌋ ``` This gives us a way to solve the problem using only integer arithmetic (representing integers in unary). Let's go through the code. Each pair of lines is a regex substitution. ``` +`\.(\d)(.+)( .+) $1.$2_$3_ ``` This repeatedly moves the decimal point in the density to the right while multiplying width and height by 10 (the `x` above). This is to ensure that all numbers are integers. Instead of appending zeroes, I'm appending `_`, which I'll be treating as zero later on. (This is a golfing trick, because otherwise I'd need to write `...${3}0` to avoid ambiguity with `$30`.) The `+` in front of the regex tells Retina to repeat this substitution until the result stops changing (which is the case when the pattern no longer matches). ``` \b # ``` We're preparing the three numbers for conversion to unary now. In principle, we need a marker (the `#`) in front of each number, but it's shorter to add one to the end of each number as well, which won't affect the conversion step. ``` +`(\d*)#((((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|\w) $1$1$1$1$1$1$1$1$1$1$3$4$5$6$7$8$9$10$11# ``` This is the conversion to unary, using a trick that [has been developed by dan1111](https://codegolf.stackexchange.com/a/47571/8478). Essentially I'm translating each digit to a rep-digit of itself, while multiplying the existing digits by 10 (moving the `#` marker to the right in the process). This binary representation will be quite a jumble of different digits, but the total number will be equal to the value of the original integer. Note the `\w` at the end - normally this is just `0`, but we want to treat `_` as zero as well (which is considered a word character in regex). ``` \d 11 ``` We turn each digit into two `1`s, thereby a) ensuring all digits are the same (which will be necessary later) and b) doubling each of the numbers. ``` (?=(1*)\1)[^.] $1 ``` This does two things: it squares all numbers (or rather half of each number, by computing a sum over `2n`), and adds the resulting squares of the width and the height. Notice that `[^.]` matches `1`s, `#` markers and spaces. If it's a `#` or a space, the lookahead won't capture anything, which means all of those are simply removed, i.e. the results for the width and height are concatenated/added. The decimal point `.` remains to separate the result for `d` from those. If `[^.]` matches a `1` instead, then the lookahead ensures that we capture half of the `1`s after it (rounded down) in group `1`. This computes the sum I mentioned above, which will then yield the square of the original number. ``` ^(1+)\.\1{90000}1+ Retina! ``` The string is now `d2` (in unary), then `.`, then `w2 + h2` (in unary). We want to know if the first unary number times `90000` is shorter than the second. We can easily do this multiplication using a capturing group and `{n}` repetition syntax. We use `1+` (instead of `1*`) afterwards to ensure that the second number is actually *greater* than that and not just equal. If so, we replace all of that by `Retina!`. ``` 1.+ Trash! ``` If the second number wasn't big enough, then the previous step won't have changed anything and the string will still start with a `1`. If that's the case, we just replace the entire string by `Trash!` and are done. [Answer] ## Python, 49 ``` lambda w,h,d:"RTertaisnha!!"[w*w+h*h<=9e4*d*d::2] ``` Uses string interleaving. It turned out shorter to square both sides than to use the complex norm. ``` w*w+h*h<=9e4*d*d abs(w+1j*h)<=300*d ``` [Answer] # CJam, ~~30 29~~ 27 bytes ``` q~mh300/<"Retina""Trash"?'! ``` Requires input to be in form of `diagonal width height` *UPDATE: 1 byte saved thanks to Dennis!* [Try it online here](http://cjam.aditsu.net/#code=q~mh300%2F%3C%22Retina%22%22Trash%22%3F'!&input=9.96%202560%201440%20) [Answer] # [Retina](https://github.com/mbuettner/retina), 312 bytes ``` (\d+) (\d+) (\d+)(?:\.(\d+))? a$1bc$2dj300ke$3fg$4h9iiiiiiiii8iiiiiiii7iiiiiii6iiiiii5iiiii4iiii3iii2ii1i0 +`(b.*)(d.*)fg(\d) 0$10$2$4fg +`(a|c|e|j)(\d)(\d*)(i*)((?:b|d|f|k).*h.*\2(i*)) $1$3$4$4$4$4$4$4$4$4$4$4$6$5 g`(i+) Q$1R$1 +`Q(i+)Ri $1Q$1R +`(j(i*).*e)i(.*f) $1$3$2 a(i*).*c(i*).*f\1\2.* Trash! .*0 Retina! ``` This does take quite a while to run, but it seems to work. Probably could be golfed a lot more... ## Explanation: ``` (\d+) (\d+) (\d+)(?:\.(\d+))? a$1bc$2dj300ke$3fg$4h9iiiiiiiii8iiiiiiii7iiiiiii6iiiiii5iiiii4iiii3iii2ii1i0 ``` Add tags to make the string more convenient to parse, and add some junk to make it easier to convert to base 1, and add a 300 to multiply by later ``` +`(b.*)(d.*)fg(\d) 0$10$2$4fg ``` Append `0`s to the width and height, while appending the decimal part of the diagonal to the integer part. When this is done, the diagonal will be an integer, and the width and height will be multiplied by however many `10`s were necessary. ``` +`(a|c|e|j)(\d)(\d*)(i*)((?:b|d|f|k).*h.*\2(i*)) $1$3$4$4$4$4$4$4$4$4$4$4$6$5 ``` Convert all numbers to base 1, using the lookup-table I appended in the first step ``` g`(i+) Q$1R$1 ``` Prepare to square all of the numbers ``` +`Q(i+)Ri $1Q$1R ``` Square each number ``` +`(j(i*).*e)i(.*f) $1$3$2 ``` Multiply the square of the diagonal by the square of the 300 we inserted in the first step ``` a(i*).*c(i*).*f\1\2.* Trash! ``` If the width appended to the height fits in the product we just computed, the pixel density is too low, and it's Trash! ``` .*0 Retina! ``` Otherwise, it's Retina! [Answer] # APL, ~~40~~ 36 bytes Saved 4 bytes thanks to Dennis! ``` {(9E4×⍵*2)<+/⍺*2:'Retina!'⋄'Trash!'} ``` This creates an unnamed dyadic function that takes the first two arguments on the left and the third on the right. It checks whether the sum of the squares of the left values is greater than 300^2 times the square of the right one. Output is printed accordingly. You can [try it online](http://tryapl.org/?a=4096%202160%7B%289E4%D7%u2375*2%29%3C+/%u237A*2%3A%27Retina%21%27%u22C4%27Trash%21%27%7D19&run)! [Answer] # TI-BASIC, 43 Takes width and height through the homescreen as a two-element list, and diagonal through Input. ``` Input D If 300D>√(sum(Ans² Then Disp "Retina! Else "Trash! ``` TI-BASIC's two-byte lowercase letters add 7 bytes (`i`, being the imaginary unit, is one byte) cause it to be quite uncompetitive. Thankfully, `!` is also one byte because it represents the factorial function. [Answer] # JavaScript ES6, 49 bytes ``` (w,h,d)=>Math.hypot(w,h)/d>300?'Retina!':'Trash!' ``` I hate that JavaScript has such long math operators. But even if there was a `Math.pythagorean` this would be shorter. [Answer] ## Excel, 44 bytes Type your inputs in these cells. * A1 = Width in pixels * B1 = Height in pixels * C1 = Diagonal in inches And this formula gives your result: ``` =IF((300*C1)^2<A1^2+B1^2,"Retina!","Trash!") ``` [Answer] # Prolog, 51 bytes ``` a(W,H,D,R):-9e4*D*D<W*W+H*H,R="Retina!";R="Trash!". ``` Running `a(8192,4320,100.0,R).` outputs: `R = "Trash!" .` Edit: Thanks to @PaulButcher for correcting an edge case and golfing one byte. [Answer] # Pyth - 27 bytes Uses ternary operator and `abs` to calculate pythagorean. ``` ?>c.avzQ300"Retina!""Trash! ``` Takes input in two lines, first line `width, height`, second line `diag`. The rules were relaxed so rolling back. [Try it online here](http://pyth.herokuapp.com/?code=%3F%3Ec.avzQ300%22Retina!%22%22Trash!&input=1920%2C%201080%0A4.95&debug=0). [Answer] ## JavaScript (ES6), 45 bytes ``` f=(w,h,d)=>w*w+h*h>d*d*9e4?'Retina!':'Trash!' ``` ## CoffeeScript, 47 bytes No ternary operator, but there is exponentiation (which doesn't help in the latest attempt). ``` f=(w,h,d)->w*w+h*h>d*d*9e4&&'Retina!'||'Trash!' # Previous attempt f=(w,h,d)->(w*w+h*h)**.5/d>300&&'Retina!'||'Trash!' ``` [Answer] # [O](http://o.readthedocs.org/), ~~40~~ 37 bytes ``` jjjrmd\/'īu>{"Retina!"p}{"Trash!"p}? ``` A lot of bytes for the input formatting :\ [Try it online](http://o-lang.herokuapp.com/link/code=jjjrmd%5C%2F%27%C4%ABu%3E%7B%22Retina!%22p%7D%7B%22Trash!%22p%7D%3F&input=1920%0A1080%0A4.95) [Answer] # Pure Bash (no bc/other external commands), ~~138~~ ~~136~~ ~~135~~ ~~82~~ 83 bytes ``` a=${3#*.} d=${a//?/0} r=(Trash Retina) echo ${r[$1$d**2+$2$d**2>90000*${3/./}**2]}! ``` I decided to try doing it in pure bash. I've probably made a few obvious inefficiencies as this is my first time code golfing, but I am VERY familiar with bash and have had fun in the past trying to write things that don't use any external commands (ie pure bash). ~~The printf statement is the most annoying. Anyone got any better ideas for padding numbers with zeroes?~~ EDIT: Saved two bytes, turns out printf will take an empty argument for zero. Saved another byte, turns out I'd previously miscounted and just assigning the output of printf to a variable is smaller than using -v. EDIT2: Thanks to Digital Trauma in the comments, this is now down much more significantly. Tricks: using bash's regex support to replace the string of digits with zeroes instead of counting it then printing that number of zeroes (seems obvious when I put it like that...), storing the strings in a bash array to save an echo, and taking into account a slight change in rules that means you can end all input numbers in .0. EDIT3: Added a byte to fix bug introduced by Digital Trauma's suggested modification. [Answer] # dc, 41 bytes ``` [[Retina!]pq]sr?d*rd*+vr/300<r[Trash!]p ``` Requires args to be input in `d, w, h` order - I hope this is OK. ### Test output: ``` $ for t in \ > "4.95 1920 1080" \ > "5.96 2560 1440" \ > "10.5 1920 1080" \ > "0.04 10 10" \ > "19 4096 2160" \ > "100.00 8192 4320" \ > "11.18 3000 1500" ; do \ > echo $t | dc -e'9k[[Retina!]pq]sr?d*rd*+vr/300<r[Trash!]p' > done Retina! Retina! Trash! Retina! Trash! Trash! Retina! $ ``` [Answer] # Julia, ~~46~~ ~~45~~ 42 bytes ``` f(w,h,d)=w^2+h^2>9e4d^2?"Retina!":"Trash!" ``` This creates a function that accepts three numeric values and returns a string. It's a direct implementation of the formula, just rearranged a bit. Both sides of the inequality were multiplied by `d` then squared. [Answer] # R, ~~59~~ 55 Bytes As an unnamed function now ``` function(h,w,d)if(h^2+w^2>9e4*d^2)'Retina!'else'Trash!' ``` Very simple implementation, that eliminates the need for the index references. **Previous** ``` cat(if((n=scan()^2)[1]+n[2]>9e4*n[3])'Retina!'else'Trash!') ``` Fairly simple, get the input from scan into a vector (single line, space separated or multi-line). Square the vector. Do the calculation and cat the result. [Answer] # MATLAB - ~~49~~ 45 bytes ``` c={'Trash!','Retina!'};c{(w*w+h*h>9e4*d*d)+1} ``` I first had to declare a cell array which contains `Trash!` and `Retina!` which are stored in locations 1 and 2 in the cell array. Next, I use the observation observed by many to rearrange the equation so that you are checking for the condition only using integer arithmetic. I represented 90000 as `9e4` to save some bytes. If this condition is true, we output a 1, else we output a 0. I use this output to index directly into the cell array. Because MATLAB starts indexing at 1, I also had to add 1 to complete the indexing. What's nice is that adding `true` with 1 gives 2, while adding `false` with 1 gives 1. This will output either `Trash!` or `Retina!` in the MATLAB command prompt. # Example ``` >> w=1920;h=1080;d=4.95; >> c={'Trash!','Retina!'};c{(w*w+h*h>9e4*d*d)+1} ans = Retina! ``` [Answer] # XSLT, 400 bytes This is the debut of a never-before seen language on PPCG, and I hope to use it more in the future as I get to know it more. ## Code: ``` <?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="input"><xsl:variable name="n" select="for $i in tokenize(.,'[^\d\.]+')return number($i)" /><xsl:choose><xsl:when test="$n[1]*$n[1]+$n[2]*$n[2]>90000*$n[3]*$n[3]">Retina!</xsl:when><xsl:otherwise>Trash!</xsl:otherwise></xsl:choose></xsl:template></xsl:stylesheet> ``` ### Pretty Printed ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="input"> <xsl:variable name="n" select="for $i in tokenize(.,'[^\d\.]+')return number($i)" /> <xsl:choose> <xsl:when test="$n[1]*$n[1]+$n[2]*$n[2]>90000*$n[3]*$n[3]"> Retina! </xsl:when> <xsl:otherwise> Trash! </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet> ``` ## Notes: As XSLT has no way of taking input via STDIN, we have to use an XML file, with the input between two `<input>` tags. Of course, this method has its limitations but it will work perfectly well for most challenges. ## Example I/O ### Input file: ``` <?xml version="1.0" encoding="ISO-8859-1"?> <input>3000 1500 11.18</input> ``` ### Output file: ``` <?xml version="1.0" encoding="UTF-8"?>Retina! ``` --- ### Input file: ``` <?xml version="1.0" encoding="ISO-8859-1"?> <input>1920 1080 10.5</input> ``` ### Output file: ``` <?xml version="1.0" encoding="UTF-8"?>Trash! ``` [Answer] ## C# (81) ``` string D(int w,int h,double d){return Math.Sqrt(w*w+h*h)/d>300?"Retina":"Trash";} ``` Ungolfed: ``` string Density(int width, int height, double diagonal) { return Math.Sqrt(width * width + height * height) / diagonal > 300 ? "Retina" : "Trash"; } ``` [Answer] ## Swift, 77 bytes Function parameter declerations mean this takes up way more characters than it should: `func r(w:Float,h:Float,d:Float){print((w*w+h*h)>9e4*d*d ?"Retina!":"Trash!")}` [Answer] # Swift, 56 bytes ``` let r={print($0*$0+$1*$1>9e4*$2*$2 ?"Retina!":"Trash!")} ``` Basically the same as [GoatInTheMachine](https://codegolf.stackexchange.com/users/32504/goatinthemachine)'s but with implicit closure parameters When Code Golfing with Swift, always declare methods like this, it's much shorter [Answer] ## Haskell, 46 ``` f w h d|w^2+h^2>d^2*9e4="Retina!"|0<1="Trash!" ``` [Answer] **C++ 72 70 Byte** ``` void F(int w,int h,float d){cout<<w*w+h*h>9e4*d*d?"Retina!":"Trash!";} ``` Similiar to other solutions, figured out myself to warm up with code golf. [Answer] Here is my contribution for this problem ## Ruby, 67 bytes reading from stdin ``` w,h,d=ARGV.map{|v|Float(v)} puts w*w+h*h>d*d*9e4?"Retina!":"Trash!" ``` ## Ruby, 56 bytes in a function A bit shorter ``` def r(w,h,d) puts w*w+h*h>d*d*9e4?"Retina!":"Trash!" end ``` Thanks to the previous contributors for the 9e4! [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")[ruby](/questions/tagged/ruby "show questions tagged 'ruby'") [Answer] # Bash, 85 bytes ``` if [ $(echo "sqrt($1^2+$2^2)/$3"|bc) -gt 300 ];then echo Retina! else echo Trash! fi ``` [Answer] # PHP, 47,43,40 38 bytes ``` <?=sqrt($w*$w+$h*$h)/$d>300?'Retina':'Trash'?>! <?=sqrt($w*$w+$h*$h)/$d>300?Retina:Trash?>! <?=$w*$w+$h*$h>9e4*$d*$d?Retina:Trash?>! ``` ``` <?=hypot($w,$h)/$d>300?Retina:Trash?>! ``` Requires `register_globals==true` (which it should never be!), with GET values w,h,d - Saved 4 bytes by removing quotes around string. Bad coding, but it works. - Moved `d` and square root to the other side of the equation, saving the `sqrt()` function - Saved 2 bytes by switching to [`hypot()`](http://php.net/hypot) (thank you [Lucas Costa)](https://codegolf.stackexchange.com/users/42414/lucas-costa) [Answer] # C# 6, 67 Bytes ``` string D(int w,int h,double d)=>w*w+h*h>9e4*d*d?"Retina!":"Trash!"; ``` This answer is based on Wolfsheads answer. I made it 8 bytes shorter using a new feature of C# 6. [Answer] # JavaScript (ES6) 58 54 43 Bytes ### 43 Bytes Removed function assignment (as per PPCG rules) (-2), as well as remove square root and comparing to 900 (300^2) (-12) ``` (w,h,d)=>w*w+h*h/d*d>300?"Retina!":"Trash!" ``` ### 54 Bytes Got rid of unnessesary parentheses (-4 bytes) ``` a=(w,h,d)=>Math.sqrt(w*w+h*h)/d>300?"Retina!":"Trash!" ``` ### 58 Bytes ``` a=(w,h,d)=>Math.sqrt((w*w)+(h*h))/d>300?"Retina!":"Trash!" ``` Explanation here: ``` a = // The function is a (w,h,d) => // Accepts the three arguments Math.sqrt((w*w)+(h*h))/d // Calculate pixel density > 300 // Above the threshold ? "Retina!" // If so, return "Retina!" : "Trash!" // Otherwise return "Trash!" ``` This uses [ternary operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) to test the density and kills a couple of bytes by using [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) [Answer] # Java, ~~82~~ 74 bytes ``` String g(int w,int h,double d){return 9e4*d*d>w*w+h*h?"Trash!":"Retina!";} ``` Call it with `g(width,height,diagonal)` [Answer] # Clojure, 58 bytes ``` #(if(>(+(* %1%1)(* %2%2))(* %3%3 90000))"Retina!""Trash!") ``` Used @Kroltan's fancy math to shorten this. Uses implicit arguments passed in the order of (w, h, d). First Clojure golf...I was surprised how much whitespace I am allowed to leave out ]
[Question] [ Everyone knows the Fibonacci sequence: You take a square, attach an equal square to it, then repeatedly attach a square whose side length is equal to the largest side length of the resulting rectangle. The result is a beautiful spiral of squares whose sequence of numbers is the *Fibonacci sequence*: ![](https://i.stack.imgur.com/yYPNK.png) But, what if we didn't want to use squares? If we use equilateral triangles—instead of squares—in a similar fashion, we get an equally beautiful spiral of triangles and a new sequence: the *Padovan sequence*, aka [A000931](https://oeis.org/A000931): ![](https://i.stack.imgur.com/qNdom.png) **Task:** Given a positive integer, \$N\$, output \$a\_N\$, the \$N\$th term in the Padovan sequence OR the first \$N\$ terms. Assume that the first three terms of the sequence are all \$1\$. Thus, the sequence will start as follows: $$ 1,1,1,2,2,3,... $$ **Input:** * Any positive integer \$N\ge0\$ * Invalid input does not have to be taken into account **Output:** * The \$N\$th term in the Padovan sequence **OR** the first \$N\$ terms of the Padovan sequence. * If the first \$N\$ terms are printed out, the output can be whatever is convenient (list/array, multi-line string, etc.) * Can be either \$0\$-indexed or \$1\$-indexed **Test Cases:** (0-indexed, \$N\$th term) ``` Input | Output -------------- 0 | 1 1 | 1 2 | 1 4 | 2 6 | 4 14 | 37 20 | 200 33 | 7739 ``` (1-indexed, first \$N\$ terms) ``` Input | Output -------------- 1 | 1 3 | 1,1,1 4 | 1,1,1,2 7 | 1,1,1,2,2,3,4 10 | 1,1,1,2,2,3,4,5,7,9 12 | 1,1,1,2,2,3,4,5,7,9,12,16 ``` **Rules:** * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the fewer bytes, the better! * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` 9s3’Ẓæ*³FṀ ``` [Try it online!](https://tio.run/##ASAA3/9qZWxsef//OXMz4oCZ4bqSw6YqwrNG4bmA//8xMP8zNA "Jelly – Try It Online") 1-indexed. Computes the largest element of: $$\begin{bmatrix}0&0&1 \\ 1&0&1 \\ 0&1&0\end{bmatrix}^n$$ where the binary matrix is conveniently computed as: $$\begin{bmatrix}\mathsf{isprime}(0)&\mathsf{isprime}(1)&\mathsf{isprime}(2) \\ \mathsf{isprime}(3)&\mathsf{isprime}(4)&\mathsf{isprime}(5) \\ \mathsf{isprime}(6)&\mathsf{isprime}(7)&\mathsf{isprime}(8)\end{bmatrix}$$ (this is a total coincidence.) ``` 9s3 [[1,2,3],[4,5,6],[7,8,9]] 9 split 3 ’ [[0,1,2],[3,4,5],[6,7,8]] decrease Ẓ [[0,0,1],[1,0,1],[0,1,0]] isprime æ*³ [[0,0,1],[1,0,1],[0,1,0]]^n matrix power by input FṀ flatten, maximum ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10 9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŻṚm2Jc$S ``` A monadic Link accepting `n` (0-indexed) which yields `P(n)`. **[Try it online!](https://tio.run/##y0rNyan8///o7oc7Z@UaeSWrBP///9/YGAA "Jelly – Try It Online")** ### How? Implements \$P(n) = \sum\_{i=0}^{\lfloor\frac{n}2\rfloor}\binom{i+1}{n-2i}\$ ``` ŻṚm2Jc$S - Link: integer, n e.g. 20 Ż - zero range [0, 1, 2, 3, 4, ..., 19, 20] Ṛ - reverse [20, 19, ..., 4, 3, 2, 1, 0] m2 - modulo-slice with 2 [20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0] <- n-2i $ - last two links as a monad: J - range of length [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] <- i+1 c - left-choose-right [ 0, 0, 0, 0, 0, 0, 0, 28,126, 45, 1] S - sum 200 ``` --- And [here](https://tio.run/##AR4A4f9qZWxsef//M@G4iuG5l1Lhuo7Cp8SL4oCY////MTU) is a "twofer" ...a totally different method also for **8 bytes** (this one is 1-indexed, but much slower): ``` 3ḊṗRẎ§ċ‘ - Link: n 3Ḋ - 3 dequeued = [2,3] R - range = [1,2,3,...,n] ṗ - Cartesian power [[[2],[3]],[[2,2],[2,3],[3,2],[3,3]],[[2,2,2],...],...] Ẏ - tighten [[2],[3],[2,2],[2,3],[3,2],[3,3],[2,2,2],...] § - sums [ 2, 3, 4, 5, 5, 6, 6,...] ‘ - increment n+1 ċ - count occurrences P(n) ``` [Answer] # [Oasis](https://github.com/Adriandmen/Oasis), 5 bytes **nth** term 0-indexed ``` cd+1V ``` [Try it online!](https://tio.run/##y08sziz@/z85Rdsw7P///4aWAA "Oasis – Try It Online") **Explanation** ``` 1V # a(0) = 1 # a(1) = 1 # a(2) = 1 # a(n) = c # a(n-2) + # + d # a(n-3) ``` [Answer] # [Haskell](https://www.haskell.org/), 26 bytes ``` (l!!) l=1:1:1:2:scanl(+)2l ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyNHUVGTK8fW0AoEjayKkxPzcjS0NY1y/ucmZuYp2CoUFGXmlSioKOQmFiikKUQb6OkZmsb@/5eclpOYXvxfN7mgAAA "Haskell – Try It Online") Outputs the n'th term zero-indexed. I thought that the "obvious" recursive solution below would be unbeatable, but then I found this. It's similar to the classic golfy expression `l=1:scanl(+)1l` for the infinite Fibonacci list, but here the difference between adjacent elements is the term 4 positions back. We can more directly write `l=1:1:zipWith(+)l(0:l)`, but that's longer. If this challenge allowed infinite list output, we could cut the first line and have 20 bytes. **27 bytes** ``` f n|n<3=1|1>0=f(n-2)+f(n-3) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hrybPxtjWsMbQzsA2TSNP10hTG0QZa/7PTczMU7BVKCjKzCtRUFHITSxQSFOINtDTMzSN/f8vOS0nMb34v25yQQEA "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 30 bytes ``` f=lambda n:n<3or f(n-2)+f(n-3) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIc8qz8Y4v0ghTSNP10hTG0QZa/5PA4rkKWTmKRQl5qWnahiaalpxKRQUZeaVKOTpANVo/gcA "Python 2 – Try It Online") Returns the n'th term zero indexed. Outputs `True` for 1. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes ``` a@0=a@1=a@2=1;a@n_:=a[n-2]+a[n-3] ``` 1-indexed, returns the nth term [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/RwcA20cEQiI1sDa0THfLirWwTo/N0jWK1QZRx7P@Aosy8EgWHxGhDo9j//wE "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/) / MATLAB, ~~35~~ 33 bytes ``` @(n)[1 filter(1,'cbaa'-98,2:n<5)] ``` Outputs the first *n* terms. [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI08z2lAhLTOnJLVIw1BHPTkpMVFd19JCx8gqz8ZUM/Z/moahkeZ/AA "Octave – Try It Online") ### How it works Anonymous function that implements a [recursive filter](https://en.wikipedia.org/wiki/Digital_filter). `'cbaa'-98` is a shorter form to produce `[1 0 -1 -1]`. `2:n<5` is a shorter form to produce `[1 1 1 0 0 ··· 0]` (*n*−1 terms). `filter(1,[1 0 -1 -1],[1 1 1 0 0 ··· 0])` passes the input `[1 1 1 0 0 ··· 0]` through a discrete-time filter defined by a transfer function with numerator coefficient `1` and denominator coefficients `[1 0 -1 -1]`. [Answer] # [J](http://jsoftware.com/), 22 bytes *-2 bytes thanks to ngn and Galen* ## closed form, 26 bytes ``` 0.5<.@+1.04535%~1.32472^<: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DfRMbfQctA31DExMjU1V6wz1jI1MzI3ibKz@a3Jx@TnpKRjoZualpFakpnClJmfkK6QpZOoZGfwHAA "J – Try It Online") ## iterative, 22 bytes ``` (],1#._2 _3{ ::1])^:[# ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWJ1DJX14o0U4o2rFaysDGM146yilf9rcnH5OekpGOhm5qWkVqSmcKUmZ@Qr6Ogp2DikKRkoZOoZGfwHAA "J – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~47~~ 42 bytes ``` K`0¶1¶0 "$+"+`.+¶(.+)¶.+$ $&¶$.(*_$1* 6,G` ``` [Try it online!](https://tio.run/##K0otycxLNPz/3zvB4NA2w0PbDLiUVLSVtBP0tA9t09DT1jy0TU9bhUtF7dA2FT0NrXgVQy0uMx33hP//zQE "Retina – Try It Online") Outputs the first `n` terms on separate lines. Explanation: ``` K`0¶1¶0 ``` Replace the input with the terms for `-2`, `-1` and `0`. ``` "$+"+`.+¶(.+)¶.+$ $&¶$.(*_$1* ``` Generate the next `n` terms using the recurrence relation. `*_` here is short for `$&*_` which converts the (first) number in the match to unary, while `$1*` is short for `$1*_` which converts the middle number to unary. The `$.(` returns the decimal sum of its unary arguments, i.e. the sum of the first and middle numbers. ``` 6,G` ``` Discard the first six characters, i.e. the first three lines. [Answer] # [Perl 6](http://perl6.org/), 24 bytes ``` {(1,1,1,*+*+!*...*)[$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WsNQBwS1tLW0FbX09PS0NKNV4mNr/xcnVipoxBkZatrZ6aml/QcA "Perl 6 – Try It Online") A pretty standard generated sequence, with each new element generated by the expression `* + * + !*`. That adds the third-previous element, the second-previous element, and the logical negation of the previous element, which is always `False`, which is numerically zero. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 20 bytes This is 0 indexed and outputs the *N*th term ``` ;@UOI010+p?/sqq;W.\( ``` [Try it online!](https://tio.run/##Sy5Nyqz4/9/aIdTf08DQQLvAXr@4sNA6XC9G4/9/QxMA "Cubix – Try It Online") Wraps onto a cube with side length 2 ``` ; @ U O I 0 1 0 + p ? / s q q ; W . \ ( . . . . ``` [Watch it run](https://ethproductions.github.io/cubix/?code=ICAgIDsgQAogICAgVSBPCkkgMCAxIDAgKyBwID8gLwpzIHEgcSA7IFcgLiBcICgKICAgIC4gLgogICAgLiAuCg==&input=MTQ=&speed=20) * `I010` - Initiates the stack * `+p?` - Adds the top of stack, pulls the counter from the bottom of stack and tests * `/;UO@` - If counter is 0, reflect onto top face, remove TOS, u-turn, output and halt * `\(sqq;W` - If counter is positive, reflect, decrement counter, swap TOS, push top to bottom twice, remove TOS and shift lane back into the main loop. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~20~~ ~~18~~ 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") This code is 1-indexed. It's the same number of bytes to get `n` items of the Padovan sequence, as you have to drop the last few extra members. It's also the same number of bytes to get 0-indexing. **Edit:** -2 bytes thanks to ngn. -1 byte thanks to ngn ``` 4⌷2(⊢,⍨2⌷+/)⍣⎕×⍳3 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKNdIe2/yaOe7UYaj7oW6TzqXWEE5Gjraz7qXfyob@rh6Y96NxuDlHGlPWqb8Ki3z/BRz1712mp1HXWgNAgXqT/q3aoO1AzSCOQnF6mnqSs86p2rUFKUmJKWp1CSrwCk/lcDlSkYPurdAmLopAGJ2kMrgKaDGMYGAA) **Explanation** ``` 4⌷2(⊢,⍨2⌷+/)⍣⎕×⍳3 ⍺(. . . .)⍣⎕⍵ This format simply takes the input ⎕ and applies the function inside the brackets (...) to its operands (here marked ⍵ and ⍺). 2(. . .+/)⍣⎕×⍳3 In this case, our ⍵, the left argument, is the array 1 1 1, where we save our results as the function is repeatedly applied and our ⍺, 2, is our right argument and is immediately applied to +/, so that we have 2+/ which will return the pairwise sums of our array. 2⌷ We take the second pairwise sum, f(n-2) + f(n-3) ⊢,⍨ And add it to the head of our array. 4⌷ When we've finished adding Padovan numbers to the end of our list, the n-th Padovan number (1-indexed) is the 4th member of that list, and so, we implicitly return that. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~56~~ 48 bytes ``` f=lambda n,a=1,b=1,c=1:n>2and f(n-1,b,c,a+b)or c ``` [Try it online!](https://tio.run/##DcgxDoAgDADA3Vd0hIgDjCb4EeNQwGoTLYSw@HpkuOXK1@4srnfyD74hIYhBb00YorerbA4lASlZRppocA46V4i9VJYGOynWQGMYWKCiXKeyTh9T/wE "Python 2 – Try It Online") Returns nth value, 0-indexed. [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~24~~ 20 bytes -4 bytes thanks to ngn! ``` {$[x<3;1;+/o'x-2 3]} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqlolusLG2NrQWls/X71C10jBOLb2f5q6gqKh0X8A "K (ngn/k) – Try It Online") 0-indexed, first N terms [Answer] # x86 32-bit machine code, 17 bytes ``` 53 33 db f7 e3 43 83 c1 04 03 d8 93 92 e2 fa 5b c3 ``` Disassembly: ``` 00CE1250 53 push ebx 00CE1251 33 DB xor ebx,ebx 00CE1253 F7 E3 mul eax,ebx 00CE1255 43 inc ebx 00CE1256 83 C1 04 add ecx,4 00CE1259 03 D8 add ebx,eax 00CE125B 93 xchg eax,ebx 00CE125C 92 xchg eax,edx 00CE125D E2 FA loop myloop (0CE1259h) 00CE125F 5B pop ebx 00CE1260 C3 ret ``` It is 0-indexed. The initialization is conveniently achieved by calculating eax \* 0. The 128-bit result is 0, and it goes in edx:eax. At the beginning of each iteration, the order of the registers is ebx, eax, edx. I had to choose the right order to take advantage of the encoding for the `xchg eax` instruction - 1 byte. I had to add 4 to the loop counter in order to let the output reach `eax`, which holds the function's return value in the `fastcall` convention. I could use some other calling convention, which doesn't require saving and restoring `ebx`, but `fastcall` is fun anyway :) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes Thanks to [Kevin](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for -1 byte! ``` Ì1λè₂₃+ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cI/hud2HVzxqanrU1Kz9/7@xMQA "05AB1E – Try It Online") ### Previous version: [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` 1Ð)λ£₂₃+ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f8PAEzXO7Dy1@1NT0qKlZ@/9/I1MA "05AB1E – Try It Online") Bear with me, I haven't golfed in a while. I wonder if there's a shorter substitute for `1Ð)` which works in this case (I've tried `1D)`, `3Å1` etc. but none of them save bytes). Outputs the first \$n\$ terms of the sequence. Or, without the `£`, it would output an infinite stream of the terms of the sequence. ``` 1Ð)λ£₂₃+ | Full program. 1Ð) | Initialize the stack with [1, 1, 1]. λ | Begin the recursive generation of a list: Starting from some base case, | this command generates an infinite list with the pattern function given. £ | Flag for λ. Instead of outputting an infinite stream, only print the first n. ₂₃+ | Add a(n-2) and a(n-3). ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` 5B+Ɲ2ị;Ʋ⁸¡Ḣ ``` [Try it online!](https://tio.run/##ASAA3/9qZWxsef//NUIrxp0y4buLO8ay4oG4wqHhuKL///8zMw "Jelly – Try It Online") 0-indexed. [Answer] # [Lua](https://www.lua.org) 5.3, ~~49~~ 48 bytes ``` function f(n)return n<4 and 1or f(n-2)+f(n-3)end ``` [Try it online!](https://tio.run/##LYzBCgIxDETv/YrcbHAVd/WoH1PbFAIl0W57Wvz2mkWHgQzDy5QexshdYmMVyF6wUutVQO43CJJg1rrXpwWP@7kiSRpFYyiw0hsesH1cNoYtzhMsF0jqwNTCs9CZZaXavKGTzTCis3/nXpWl@R8SVWL4Iwcz4vgC "Lua – Try It Online") Vanilla Lua doesn't have coercion of booleans to strings (even `tonumber(true)` returns `nil`), so you have to use a pseudo-ternary operator. This version is 1-indexed, like all of Lua. The `1or` part has to be changed to `1 or` in Lua 5.1, which has a different way of lexing numbers. [Answer] # [Ruby](https://www.ruby-lang.org/), 26 bytes ``` f=->n{n<3?1:f[n-2]+f[n-3]} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs/G2N7QKi06T9coVhtEGcfW/tcw0NMzNtbUy00sqK6pqClQiK7QSYuuiAVKAQA "Ruby – Try It Online") [Answer] # JavaScript (ES6), 23 bytes Implements the recursive definition of [A000931](https://oeis.org/A000931), but with \$a(0)=a(1)=a(2)=1\$, as specified in the challenge. Returns the \$N\$th term, 0-indexed. ``` f=n=>n<3||f(n-2)+f(n-3) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i7PxrimJk0jT9dIUxtEGWv@T87PK87PSdXLyU/XSNMw0NTkQhUxxBAxwhAxwRAxwzQHU5ERpm3Gxpqa/wE "JavaScript (Node.js) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-N`](https://codegolf.meta.stackexchange.com/a/14339/), 12 bytes ``` <3ªßUµ2 +ß´U ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LU4&code=PDOq31W1MiAr37RV&input=MTA) [Answer] # TI-BASIC (TI-84), 34 bytes ``` [[0,1,0][0,0,1][1,1,0]]^(Ans+5:Ans(1,1 ``` 0-indexed \$N\$th term of the sequence. Input is in `Ans`. Output is in `Ans` and is automatically printed out. ~~I figured that enough time had passed, plus multiple answers had been posted, of which there were many which out-golfed this answer.~~ **Example:** ``` 0 0 prgmCDGFD 1 9 9 prgmCDGFD 9 16 16 prgmCDGFD 65 ``` **Explanation:** ``` [[0,1,0][0,0,1][1,1,0]]^(Ans+5:Ans(1,1 ;full program (example input: 6) [[0,1,0][0,0,1][1,1,0]] ;generate the following matrix: ; [0 1 0] ; [0 0 1] ; [1 1 0] ^(Ans+5 ;then raise it to the power of: input + 5 ; [4 7 5] ; [5 9 7] ; [7 12 9] Ans(1,1 ;get the top-left index and leave it in "Ans" ;implicitly print Ans ``` [Answer] # Pyth, 16 bytes ``` L?<b3!b+y-b2y-b3 ``` This defines the function `y`. [Try it here!](http://pyth.herokuapp.com/?code=L%3F%3Cb3%21b%2By-b2y-b3&input=25&debug=0) Here's a more fun solution, though it's 9 bytes longer; bytes could be shaved though. ``` +l{sa.pMf.Am&>d2%d2T./QY! ``` This uses the definition given by David Callan on the OEIS page: "a(n) = number of compositions of n into parts that are odd and >= 3." [Try it here!](http://pyth.herokuapp.com/?code=%2Bl%7Bsa.pMf.Am%26%3Ed2%25d2T.%2FQY%21&input=25&debug=0) It takes input directly instead of defining a function. [Answer] # [Perl 5](https://www.perl.org/), 34 bytes ``` sub f{"@_"<3||f("@_"-2)+f("@_"-3)} ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhrVrJIV7JxrimJk0DxNI10tSGsow1a/@rxNumaajEa/434DLkMuIy4TLjMjThMjLgMjb@l19QkpmfV/xftyAHAA "Perl 5 – Try It Online") [Answer] # Java, 41 bytes Can't use a lambda (runtime error). Port of [this Javascript answer](https://codegolf.stackexchange.com/a/182807/84303) ``` int f(int n){return n<3?1:f(n-2)+f(n-3);} ``` [TIO](https://tio.run/##LYyxCoMwFEV3vyJjHkWhzVYL/YJOjqXDqxqJjU9JXoQS8u1phC73DIdzZ9yxnodP7i16Lx5oKFaekU0vsiEWWh5LEN3IwZGgm7qfr1pSfYHTAQVtylt421L8w301g1jKlezYGZqeL3STh1h1X8/j0qyBm60ItiS1VABtlVL@AQ) [Answer] # [R + pryr](https://www.r-project.org/), ~~38~~ 36 bytes Zero-indexed recursive function. ``` f=pryr::f(`if`(n<3,1,f(n-2)+f(n-3))) ``` [Try it online!](https://tio.run/##K/r/P822oKiyyMoqTSMhMy1BI8/GWMdQJ00jT9dIUxtEGWtqav5P0zDQ5ErTMAQRRiDCBESYgcXATCOwvLGx5n8A "R – Try It Online") Thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) for pointing out two obviously needless bytes. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~12~~ 9 bytes Returns the `n`th term, 1-indexed. ``` @1gZÔä+}g ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QDFnWtTkK31n&input=MzQ) ``` @1gZÔä+}g :Implicit input of integer U g :Starting with the array [0,1] do the following U times, pushing the result to the array each time @ : Pass the array through the following function as Z 1g : Get the element at 0-based index 1, with wrapping, from the following ZÔ : Reverse Z ä+ : Get the sums of each consecutive pair of elements } : End function :Implicit output of the last element in the array ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes This implementation of the binomial formula: `a(n) = Sum_{k=0..floor(n/2)} binomial(k+1, n-2k)` is interestingly the same length as the [recursive solution](https://codegolf.stackexchange.com/a/182828/47066). ``` ;Ý·-āscO ``` [Try it online!](https://tio.run/##yy9OTMpM/V9TVmmvpKBrp6BkX1n53/rw3EPbdY80Fif7/9f5b8BlyGXEZcJlxmVowmVkwGVsDAA "05AB1E – Try It Online") **Explanation** ``` ;Ý # push [0 ... floor(input/2)] · # double each - # subtract each from input ā # push range [1 ... len(list)] s # swap c # choose O # sum ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~41~~ 33 bytes ``` a(i){return i<3?1:a(i-2)+a(i-3);} ``` [Try it online!](https://tio.run/##jdDNCoJAEADgcz7FYgQOrbE/opRSpw6degEv4lot2Ca2QmA@u41GdNTTzM5@DDOT@3mZmWvfZ56Gti5sUxuiE3ngO6z4AtZDkBB3/VKbvGxUQZKnVfqxue0dbSy5Z9p40DqLqsbnxXNPpmosSe2bnBv7S4@vqshtoVLjQvy3KzX@juGbIKCMZh4DyqclR8lnSYFSzJIBygComJYhyhBoMGPOoSnHrjKaMeqwv8ADCMamtZSopQQaRXKLvOs/ "C (clang) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~9~~ 8 bytes ``` ↑ƒ(+ḋ7Ẋ+ ``` [Try it online!](https://tio.run/##yygtzv7//1HbxGOTNLQf7ug2f7irS/v///@GRgA "Husk – Try It Online") There ~~*might* be~~ is a shorter version using `fix`. -1 from Leo! ]
[Question] [ An [*Abundant number*](https://en.wikipedia.org/wiki/Abundant_number) is any number where the sum of its proper divisors is greater than the original number. For example, the proper divisors of 12 are: ``` 1, 2, 3, 4, 6 ``` And summing these results in 16. Since 16 is larger than 12, 12 is abundant. Note that this does *not* include "Perfect numbers", e.g. numbers that are *equal* to the sum of its proper divisors, such as 6 and 28. Your task for today is to write a program or function that determines if a number is abundant or not. Your program should take a single integer as input, and output a [truthy/falsy](http://meta.codegolf.stackexchange.com/q/2190/31716) value depending on whether it is abundant or not. You can assume that the input will always be valid and greater than 0, so for bad inputs, undefined behavior is fine. You may take your input and output in any reasonable format, for example STDIN/STDOUT, files, or arguments/return values would all be acceptable. For reference, here are the abundant numbers up to 100: ``` 12, 18, 20, 24, 30, 36, 40, 42, 48, 54, 56, 60, 66, 70, 72, 78, 80, 84, 88, 90, 96, 100 ``` And more can be found on [A005101](http://oeis.org/A005101) Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), standard loopholes are denied, and try to write the shortest possible code you can in whichever language you happen to choose! [Answer] # Regex (ECMAScript), ~~1085~~ ~~855~~ ~~597~~ ~~536~~ ~~511~~ ~~508~~ 504 bytes Matching abundant numbers in ECMAScript regex is an entirely different beast than doing so in practically any other regex flavor. The lack of forward/nested backreferences or recursion means that it is impossible to directly count or keep a running total of anything. The lack of lookbehind makes it often a challenge even to have enough space to work in. Many problems must be approached from an entirely different perspective, and you'll be wondering if they're solvable at all. It forces you to cast a much wider net in finding which mathematical properties of the numbers you're working with might be able to be used to make a particular problem solvable. Back in March-April 2014 I constructed a solution to this problem in ECMAScript regex. At first I had every reason to suspect the problem was completely impossible, but then the mathematician [teukon](https://gist.github.com/teukon) sketched an idea that made an encouraging case for making it look solvable after all – but he made it clear he had no intention of constructing the regex (he had competed/cooperated with my on constructing/golfing previous regexes, but reached his limit by this point and was content to restrict his further contributions to theorizing). Solving unary mathematical problems in ECMAScript regex has been a fascinating journey for me, so in the past I put spoiler warnings in this post and others like it – in case others, especially those with an interest in number theory, wanted to take a crack at independently solving things like generalized multiplication. I am now removing the spoiler warnings though; they did not prove to be constructive. Before posting my ECMAScript regex, I thought it would be interesting to analyze Martin Ender's [.NET pure regex solution](https://codegolf.stackexchange.com/a/110732/17216), `^(?!(1(?<=(?=(?(\3+$)((?>\2?)\3)))^(1+)))*1$)`. It turns out to be very straightforward to understand that regex, and it is elegant in its simplicity. To demonstrate the contrast between our solutions, here is a commented and pretty-printed (but unmodified) version of his regex: ``` # For the purpose of these comments, the input number will be referred to as N. ^(?! # Attempt to add up all the divisors. Since this is a regex and we # can only work within the available space of the input, that means # if the sum of the divisors is greater than N, the attempt to add # all the divisors will fail at some point, causing this negative # lookahead to succeed, showing that N is an abundant number. (1 # Cycle through all values of tail that are less than N, testing # each one to see if it is a divisor of N. (?<= # Temporarily go back to the start so we can directly operate both # on N and the potential divisor. This requires variable-length # lookbehind, a .NET feature – even though this special case of # going back to the start, if done left-to-right, would actually be # very easy to implement even in a regex flavour that has no # lookbehind to begin with. But .NET evaluates lookbehinds right # to left, so please read these comments in the order indicated, # from [Step 1] to [Step 7]. The comment applying to entering the # lookahead group, [Step 2], is shown on its closing parenthesis. (?= # [Step 3] Since we're now in a lookahead, evaluation is left to # right. (?(\3+$) # [Step 4] If \3 is a divisor of N, then... ( # [Step 5] Add it to \2, the running total sum of divisors: # \2 = \2 + \3 (?>\2?) # [Step 6] Since \2 is a nested backref, it will fail to match on # the first iteration. The "?" accounts for this, making # it add zero to itself on the first iteration. This must # be done before adding \3, to ensure there is enough room # for the "?" not to cause the match to become zero-length # even if \2 has a value. \3 # [Step 7] Iff we run out of space here, i.e. iff the sum would # exceed N at this point, the match will fail, making the # negative lookahead succeed, showing that we have an # abundant number. ) ) ) # [Step 2] Enter a lookahead that is anchored to the start due to # having a "^" immediately to its right. The regex would # still work if the "^" were moved to the left of the # lookahead, but would be slightly slower, because the # engine would do some spurious matching before hitting # the "^" and backtracking. ^(1+) # [Step 1] \3 = number to test for being a potential divisor – its # right-side-end is at the point where the lookbehind # started, and thus \3 cycles through all values from # 1 to N-1. ) )*1$ # Exclude N itself from being considered as a potential divisor, # because if we included it, the test for proper abundance would be # the sum of divisors exceeding 2*N. We don't have enough space for # that, so instead what would happen if we did not exclude N as a # divisor would be testing for "half-abundance", i.e. the sum of # all divisors other than N exceeding N/2. By excluding N as a # divisor we can let our threshold for abundance be the sum of # divisors exceeding N. ) ``` [Try the .NET regex online](https://tio.run/##ZZBfa9swFMXf9ymUUMi98x/s9G2q4oHZQ6FlYynsYVlBc25TgSIbSc7UuP3smWK3fakwCHPO1f2d07isaS2djNyT62RDbP3kPO2H3imzY7WoW@NaTXz6v6Pg85@067W030JnyTkVDbzR0jm2H5yXXjXs0Kotu5XKMMDhIC1z4uv8dA/VDAJUVwKq@MHmMrlAgGq1WVa4uUTEewhJvD6HCzzN@XnQCkP/WNxIAVy@7v86byMIlKnLb8js/GO2xHTUv3f@zJLX7b5TmrbIJy/T/KG1oIxnRhQctKhjBLm9UYYAcSZMrzU3osRBPYBZFVjnv6zyNBlGjE7ofN1p5WGRLZCf31Ip8U9xoHvlWC2fn2dRyO/s0w9pHUH3u/iTtn204kfpbSwrJw/h21qYX5uD1LFBK82OvrCheJmnGjlpR2ObYSxlPTWxCItU4XvEY4yorgRxlSRpSESUMVLa/NrdSt88QsAx5/FDzqMo@TvCuDO8MiJ/Gc@pyMqiKP4D "C# (.NET Core) – Try It Online") Now, back to my ECMAScript regex. First, here it is in raw, whitespace-and-comment-free format: `^(?=(((?=(xx+?)\3+$)(x+)\4*(?=\4$))+(?!\3+$)(?=(xx(x*?))\5*$)x)(x+))(?=\1(x(x*))(?=\8*$)\6\9+$)(?=(.*)((?=\8*$)\5\9+$))(?=(x*?)(?=(x\11)+$)(?=\12\10|(x))(x(x*))(?=\15*$)(?=\11+$)\11\16+$)(?=(x(x*))(?=\17*$)\7\18+$)((?=(x*?(?=\17+$)(?=\17+?(?=((xx(x*))(?=\18+$)\22*$))(x+).*(?=\17$)\24*(?=\24$)(?!(xx+)\25*(?!\22+$)\25$)\22+$)((?=(x\7)+$)\15{2}\14|)))(?=.*(?=\24)x(x(x*))(?=\28*$)\23\29*$)(?=.*(x((?=\28*$)\22\29+$)))(.*(?!\30)\20|(?=.*?(?!x\20)(?=\30*$)(x(x*))(?=\33*$)(?=\31+$)\31\34+$).*(?=\33\21$)))+$` (change `\14` to `\14?` for compatibility with PCRE, .NET, and practically every other regex flavour that's not ECMAScript) [Try it online!](https://tio.run/##TVBNc9owEL33VwDDJLt2cSzZ5iOu8SmHXHJoj1U74wHFqHWER1YSNcBvp5IMgYu8fu/t2933p3qrupUSrZ50rVhz9bKVf/m/oyokfx985/WDaQE@iuVdcPwNZQHgHmPCElkSjhFMiCwNLMjSMWII5bDHvQpMUCKyLBij8VKHMwKO6Ou5pdiULU4tUYDwCWce7q2sj/8yQrDXMkIZifdgrOLiR9wsXxArsy8j0/M6F9HM2c8YmTvq5N8TZ@9ZWPprzVWXUzNKA7eTvSUKeqUD@wRo6rqHLh6LZYELg1LflfnWz3Fshn69bEcPjKR79COikwuaq2Wpz4ImjC7606zKwBVDLeNyQoj8xCS2oA3GKe0RQ2P/vFMSO4OLc5Kcskp8VglhSWqLfovEDiTONRwfg7sPjPT2h1ZC1oBR14gVh@nXSYqYd0Wcv29EwwGaQvFq3QjJAXFYyNemwV1dNFHXNkLD7eQWc/EMIIs6aris9QaXdL8X3VP1BKJoK9XxR6mh/hn/QjwT/JqQS1KSe0ej3qjt@@hRvlWNWA9UJWt@PxiFTf68VZCLbwXPRRiiHTgyo0jxllcaBEYvlV5tQCHuupub1p6kwV1B8vZVd1pZSX44HOMJncdfFsl8ssjofw "JavaScript (SpiderMonkey) – Try It Online") [Try it online!](https://tio.run/##TVFNc9owEL33VwDDJLt2cSwZ8xHXcMohlxzaY9XOeEAxah3jkZXEDfDb6UqCwGUtvff8dvfpT/FWtCutGjNqG7WW@mVb/5X/jjqv5XvvuywfugbgI1/cBcffsMwBbOm6cIkiCYcIXYhiHBAoxkPEEJZ9jzsVdMESUaTBEDsntbhgYAl/nhElJmJ@@iUKED7h1MHeinzcVzCGXisYFyzeQ0eKix@zvdyBkYyqYJPzOBfR1NpPBZtZ6uT/Sbh76IVWIDgLzjIxRWeb7vhBsPEe/Xh@VcQo8C5@BJ4GNg7OyCIlaO/C4jMn4jO3Wt9mSeDcS1PXb06UPzvluLuaPYnt7HwiEuZnpZ4dXDEpMTY2hMh5JpxAyskqacl@RzfvxK3BlfM5usQ@IFWRnKIjyqou0VETH00ypTcfHoO7D4zM9ofRqi4Bo7ZSKwmTr6MxYtbmcfa@UZUEqHIti3WlagmI/bx@rSrclXkVtU2lDNyObjFTzwB1XkaVrEuzwQXf71X7VDyByptCt/KxNlD@jH8hngl5TdQLtmT3lkaz0dv3wWP9VlRq3dNFXcr73iCssuethkx9y2WmwhCp4aAbRFo2sjCgMHopzGoDGnHX3tw0tJIBuwXLmlfTGk2S7HA4xqNpHH@ZJ/FoPon/Aw "JavaScript (SpiderMonkey) – Try It Online") (faster, 537 byte version of the regex) And now a brief summary of the story behind it. At first it was very non-obvious, to me at least, that it was even possible to match primes in the general case. And after solving that, the same applied to powers of 2. And then powers of composite numbers. And then perfect squares. And even after solving that, doing generalized multiplication seemed impossible at first. In an ECMAScript loop, you can only keep track of one changing number; that number cannot exceed the input, and has to decrease at every step. My first working regex for matching correct multiplication statements A\*B=C was 913 bytes, and worked by factoring A, B, and C into their prime powers – for each prime factor, repeatedly divide the pair of prime power factors of A and C by their prime base until the one corresponding to A reaches 1; the one corresponding to C is then compared to the prime power factor of B. These two powers of the same prime were "multiplexed" into a single number by adding them together; this would always be unambiguously separable on each subsequent iteration of the loop, for the same reason that positional numeral systems work. We got multiplication down to 50 bytes using a completely different algorithm (which teukon and I were able to arrive at independently, though it took him only a few hours and he went straight to it, whereas it took me a couple days even after it was brought to my attention that a short method existed): for A≥B, A\*B=C if and only if C is the smallest number which satisfies C≡0 mod A and C≡B mod A-1. (Conveniently, the exception of A=1 needs no special handling in regex, where 0%0=0 yields a match.) I just can't get over how neat it is that such an elegant way of doing multiplication exists in such a minimal regex flavour. (And the requirement of A≥B can be replaced with a requirement that A and B are prime powers of the same power. For the case of A≥B, this can be proven using the Chinese remainder theorem.) [See this post](https://codegolf.stackexchange.com/questions/179239/find-a-rocco-number/179420#179420) for a more in-depth explanation. If it had turned out that there was no simpler algorithm for multiplication, the abundant number regex would probably be on the order of ten thousand bytes or so (even taking into account that I golfed the 913 byte algorithm down to 651 bytes). It does lots of multiplication and division, and ECMAScript regex has no subroutines. I started working on the abundant number problem tangentially in 23 March 2014, by constructing a solution for what seemed at the time to be a sub-problem of this: Identifying the prime factor of highest multiplicity, so that it could be divided out of N at the start, leaving room to do some necessary calculations. At the time this seemed to be a promising route to take. (My initial solution ended up being quite large at 326 bytes, later golfed down to 185 bytes.) But the rest of the method teukon sketched would have been extremely complicated, so as it turned out, I took a rather different route. It proved to be sufficient to divide out the largest prime power factor of N corresponding to the largest prime factor on N; doing this for the prime of highest multiplicity would have added needless complexity and length to the regex. What remained was treating the sum of divisors as a product of sums instead of a straight sum. As [explained by teukon](https://gist.github.com/Davidebyzero/9090628#gistcomment-1190698) on 14 March 2014: > > We're given a number n = p0a0p1a1...pk-1ak-1. We want to handle the sum of the factors of n, which is (1 + p0 + p02 + ... + p0a0)(1 + p1 + p12 + ... + p1a1)...(1 + pk-1 + pk-12 + ... + pk-1ak-1). > > > It blew my mind to see this. I had never thought of factoring the aliquot sum in that way, and it was this formula more than anything else that made the solvability of abundant number matching in ECMAScript regex look plausible. In the end, instead of testing for a result of addition or multiplication exceeding N, or testing that such a result pre-divided by M exceeds N/M, I went with testing if a result of division is less than 1. I arrived at the first working version on 7 April 2014. The full history of my golf optimizations of this regex is on github. At a certain point one optimization ended up making the regex much slower, so from that point on I maintained two versions. They are: [regex for matching abundant numbers.txt](https://github.com/Davidebyzero/RegexGolf/blob/master/regex%20for%20matching%20abundant%20numbers.txt) [regex for matching abundant numbers - shortest.txt](https://github.com/Davidebyzero/RegexGolf/blob/master/regex%20for%20matching%20abundant%20numbers%20-%20shortest.txt) These regexes are fully compatible with both ECMAScript and PCRE, but a recent optimization involved using a potentially non-participating capture group `\14`, so by dropping PCRE compatibility and changing `\14?` to `\14` they can both be reduced by 1 byte. Here is the smallest version, with that optimization applied (making it ECMAScript-only), reformatted to fit in a StackExchange code block with (mostly) no horizontal scrolling needed: ``` # Match abundant numbers in the domain ^x*$ using only the ECMAScript subset of regex # functionality. For the purposes of these comments, the input number = N. ^ # Capture the largest prime factor of N, and the largest power of that factor that is # also a factor of N. Note that the algorithm used will fail if N itself is a prime # power, but that's fine, because prime powers are never abundant. (?= ( # \1 = tool to make tail = Z-1 ( # Repeatedly divide current number by its smallest factor (?=(xx+?)\3+$) (x+)\4*(?=\4$) )+ # A "+" is intentionally used instead of a "*", to fail if N # is prime. This saves the rest of the regex from having to # do needless work, because prime numbers are never abundant. (?!\3+$) # Require that the last factor divided out is a different prime. (?=(xx(x*?))\5*$) # \5 = the largest prime factor of N; \6 = \5-2 x # An extra 1 so that the tool \1 can make tail = Z-1 instead of just Z ) (x+) # Z = the largest power of \5 that is a factor of N; \7 = Z-1 ) # We want to capture Z + Z/\5 + Z/\5^2 + ... + \5^2 + \5 + 1 = (Z * \5 - 1) / (\5 - 1), # but in case Z * \5 > N we need to calculate it as (Z - 1) / (\5 - 1) * \5 + 1. # The following division will fail if Z == N, but that's fine, because no prime power is # abundant. (?= \1 # tail = (Z - 1) (x(x*)) # \8 = (Z - 1) / (\5 - 1); \9 = \8-1 # It is guaranteed that either \8 > \5-1 or \8 == 1, which allows the following # division-by-multiplication to work. (?=\8*$) \6\9+$ ) (?= (.*) # \10 = tool to compare against \11 ( # \11 = \8 * \5 = (Z - 1) / (\5 - 1) * \5; later, \13 = \11+1 (?=\8*$) \5\9+$ ) ) # Calculate Q = \15{2} + Q_R = floor(2 * N / \13). Since we don't have space for 2*N, we # need to calculate N / \13 first, including the fractional part (i.e. the remainder), # and then multiply the result, including the fractional part, by 2. (?= (x*?)(?=(x\11)+$) # \12 = N % \13; \13 = \11 + 1 (?=\12\10|(x)) # \14 = Q_R = floor(\12 * 2 / \13) # = +1 carry if \12 * 2 > \11, or NPCG otherwise (x(x*)) # \15 = N / \13; \16 = \15-1 (?=\15*$) (?=\11+$) # must match if \15 < \13; otherwise doesn't matter \11\16+$ # must match if \15 >= \13; otherwise doesn't matter ) # Calculate \17 = N / Z. The division by Z can be done quite simply, because the divisor # is a prime power. (?= (x(x*)) # \17 = N / Z; \18 = \17-1 (?=\17*$) \7\18+$ ) # Seed a loop which will start with Q and divide it by (P^(K+1)-1)/(P-1) for every P^K # that is a factor of \17. The state is encoded as \17 * P + R, where the initial value # of R is Q, and P is the last prime factor of N to have been already processed. # # However, since the initial R would be larger than \17 (and for that matter there would # be no room for any nonzero R since with the initial value of P, it is possible for # \17 * P to equal N), treat it as a special case, and let the initial value of R be 0, # signalling the first iteration to pretend R=Q. This way we can avoid having to divide Q # and \17 again outside the loop. # # While we're at it, there's really no reason to do anything to seed this loop. To seed # it with an initial value of P=\5, we'd have to do some multiplication. If we don't do # anything to seed it, it will decode P=Z. That is wrong, but harmless, since the next # lower prime that \17 is divisible by will still be the same, as \5 cannot be a factor # of \17. # Start the loop. ( (?= ( # \20 = actual value of R x*?(?=\17+$) # move forward by directly decoded value of R, which can be zero # The division by \17 can be done quite simply, because it is known that # the quotient is prime. (?= \17+? # tail = \17 * (a prime which divides into \17) (?= ( # \21 = encoded value for next loop iteration (xx(x*)) # \22 = decoded value of next smaller P; \23 = (\22-1)-1 (?=\18+$) # iff \22 > \17, this can have a false positive, but never a false negative \22*$ # iff \22 < \17, this can have a false positive, but never a false negative ) ) # Find the largest power of \22 that is a factor of \17, while also asserting # that \22 is prime. (x+) # \24 = the largest power of \22 that is a factor of \17 .*(?=\17$) \24*(?=\24$) (?! (xx+)\25* (?!\22+$) \25$ ) \22+$ ) ( (?=(x\7)+$) # True iff this is the first iteration of the loop. \15{2}\14 # Potentially unset capture, and thus dependent on ECMAScript # behavior. Change "\14" to "\14?" for compatibility with non- # ECMAScript engines, so that it will act as an empty capture # with engines in which unset backrefs always fail to match. | ) ) ) # Calculate \30 = (\24 - 1) / (\22 - 1) * \22 + 1 (?= .*(?=\24)x # tail = \24 - 1 (x(x*)) # \28 = (\24 - 1) / (\22 - 1); \29 = \28-1 (?=\28*$) \23\29*$ ) (?= .*(x( # \30 = 1 + \28 * \22 = (\28 - 1) / (\22 - 1) * \22 + 1; \31 = \30-1 (?=\28*$) \22\29+$ )) ) # Calculate \33 = floor(\20 / \30) ( .*(?!\30)\20 # if dividing \20 / \30 would result in a number less than 1, # then N is abundant and we can exit the loop successfully | (?= .*?(?!x\20)(?=\30*$) (x(x*)) # \33 = \20 / \30; \34 = \33-1 (?=\33*$) (?=\31+$) # must match if \33 < \30; otherwise doesn't matter \31\34+$ # must match if \33 >= \30; otherwise doesn't matter ) # Encode the state for the next iteration of the loop, as \17 * \22 + \33 .*(?=\33\21$) ) )+$ ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~41~~ 40 bytes ``` n=k=j=input() while~k<0:j-=1;k-=j>>n%j*n ``` Output is [via exit code](http://meta.codegolf.stackexchange.com/a/5330/12012), so **0** is truthy and **1** is falsy. [Try it online!](https://tio.run/nexus/python2#PY1BDsIgFETXcIq/MbSNTcoWpXdB@lWg/hLAqBuvjujC3WTm5Y3dFgQNQohKOmivHcV76Xr@uLoV3@E4KT9qeQij9vNMOz9QbTDn5y1BwVysyQiOIBm6YCf3cpK94uynaeLV3E6LUX@Us5JebWf4RAu2vbcck6MCxFtpMZbvHE3O9QM "Python 2 – TIO Nexus") ### How it works After setting all of **n**, **k**, and **j** to the input from STDIN, we enter the *while* loop. Said loop will break as soon as **-k - 1 = ~k ≥ 0**, i.e., **k ≤ -1** / **k < 0**. In each iteration, we first decrement **j** to consider only proper divisors of **n**. If **j** is a divisor of **n**, `n%j` yields **0** and **j >> n%j\*n = j/20 = j** gets subtracted from **k**. However, if **j** does *not* divide **n**, `n%j` is positive, so `n%j*n` is at least **n > log2 j** and **j >> n%j\*n = j / 2n%j\*n = 0** is subtracted from **k**. For abundant numbers, **k** will reach a negative value before or when **j** becomes **1**, since the sum of **n**'s proper divisors is strictly greater than **n**. In this case, we break out of the *while* loop and the program finishes normally. However, if **n** is *not* abundant, **j** eventually reaches **0**. In this case, `n%j` throws a *ZeroDivisionError* and the program exits with an error. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` fk+>? ``` [Try it online!](https://tio.run/nexus/brachylog2#@5@WrW1n//@/oYHBfwA "Brachylog – TIO Nexus") ### Explanation ``` f Factors k Knife: remove the last one (the input itself) + Sum >? Stricly greater than the Input ``` [Answer] ## Mathematica, 17 bytes ``` Tr@Divisors@#>2#& ``` ## Explanation ``` Tr@ The sum of the main diagonal of Divisors@ the list of divisors of # the first argument > is greater than 2# twice the first argument. & End of function. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` Æṣ> ``` [Try it online!](https://tio.run/nexus/jelly#@3@47eHOxXb/DQ0MFA63KxyekKYQqfBwx/ZHDXMU3DJzSlKLFBJzchQK8oszSzLLUhUy80pS01OLihVKCxRK8hVA2pIqFUoyUhUSk/KB8jmZedkKiXkpCgVFqSUllUAKqEPvPwA "Jelly – TIO Nexus") ### How it works ``` Æṣ> Main link. Argument: n Æs Get the proper divisor sum of n. > Test if the result is greater than n. ``` [Answer] # [Python](https://docs.python.org), 44 bytes ``` lambda n:sum(i*(n%i<1)for i in range(1,n))>n ``` **[Try it online!](https://tio.run/nexus/python3#TclBDkBADAXQq3QjacXCbAUXwWKEShPzyeD8FTtv@7QbfY9pXiKhuZ7EVjIKa4PokcnIQDliWzlUEOnhZzbcPIC@x@/rIGRKypBJ/AU)** [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 4 bytes -1 bytes thanks to [scottinet](https://codegolf.stackexchange.com/users/73296/scottinet) ``` ѨO‹ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8MRDK/wfNez8/9/SDAA "05AB1E – Try It Online") or [Try 0 to 100](https://tio.run/##MzBNTDJM/W9oYODm5/f/8MRDK/wfNez876d0eL@VgpK9zn8A "05AB1E – Try It Online") [Answer] ## [Retina](https://github.com/m-ender/retina), ~~50~~ 45 bytes ``` ^(?!(1(?<=(?=(?(\3+$)((?>\2?)\3)))^(1+)))*1$) ``` Input in [unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary), output `1` for abundant numbers, `0` otherwise. There is nothing Retina-specific about this solution. The above is a pure .NET regex which matches only abundant numbers. [Try it online!](https://tio.run/nexus/retina#FZBJSgRREET37xZCC1X25uecCWotvUQjLrz/FdovBMQqxsfvndvb8@vn@7heDjmu94/j2jgedr@dx3F9PvQ6H3ae5/ch901vcjufrz/yFBTDCZKiGWQhgihiiCOBJFJII4MudGsUNdTRQBMttNHBFibYtjTMscASK6yxwRcuuOI70fHAEy@88SEWIYQSRuxCQSRRRBNDLlJIJY10cvdNssgmh1qUUEoZ5VRQe05RTQ29aKGVNtrpoJPea5seZjHCKGOMM8EkU8w@4/@N9Qc "Retina – TIO Nexus") (Test suite that filters decimal input with the above regex.) [Answer] ## [Retina](https://github.com/m-ender/retina), 34 bytes Byte count assumes ISO 8859-1 encoding. ``` M!&`(1+)$(?<=^\1+) 1>`¶ ^(1+)¶1\1 ``` Input in [unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary), output `1` for abundant numbers, `0` otherwise. [Try it online!](https://tio.run/nexus/retina#FZC5aQNQEETz14VBNrKV/L13wUcF7kAIBa5RBagx@SsbBuZ8PV7PfycOH4/fl7frUU7vh@PP59flvBHyfb3f4PKk7zc5y@MhKIYTJEUzyEIEUcQQRwJJpJBGBl3o1ihqqKOBJlpoo4MtTLBtaZhjgSVWWGODL1xwxXei44EnXnjjQyxCCCWM2IWCSKKIJoZcpJBKGunk7ptkkU0OtSihlDLKqaD2nKKaGnrRQitttNNBJ73XNj3MYoRRxhhngkmmmH3G8431Dw "Retina – TIO Nexus") ### Explanation ``` M!&`(1+)$(?<=^\1+) ``` We start by getting all divisors of the input. To do this, we return (`!`) all *overlapping* (`&`) matches (`M`) of the regex `(1+)$(?<=^\1+)`. The regex matches some suffix of the input, provided that the entire input is a multiple of that suffix (which we ensure by trying to reach the beginning fo the string using only copies of the suffix). Due to the way the regex engine looks for matches, this will result a list of divisors in descending order (separated by linefeeds). ``` 1>`¶ ``` The stage itself simply matches linefeeds (`¶`) and removes them. However, the `1>` is a limit, which skips the first match. So this effectively adds together all divisors except the input itself. We end up with the input on the first line and the sum of all proper divisors on the second line. ``` ^(1+)¶1\1 ``` Finally, we try to match the at least one more `1` on the second line than we have on the first line. If that's the case, the sum of proper divisors exceeds the input. Retina counts the number of matches of this regex, which will be `1` for abundant numbers and `0` otherwise. [Answer] # x86 machine code, 25 bytes ``` 00000000: 8bc8 d1e9 33db 33d2 50f7 f158 85d2 7502 ....3.3.P..X..u. 00000010: 03d9 7204 e2f0 3bc3 c3 ..r...;.. ``` Listing: ``` 8B C8 MOV CX, AX ; counter starts at N / 2 D1 E9 SHR CX, 1 ; divide by 2 33 DB XOR BX, BX ; clear BX (running sum of factors) DIV_LOOP: 33 D2 XOR DX, DX ; clear DX (high word for dividend) 50 PUSH AX ; save original dividend F7 F1 DIV CX ; DX = DX:AX MOD CX, AX = DX:AX / CX 58 POP AX ; restore dividend (AX was changed by DIV) 85 D2 TEST DX, DX ; if remainder (DX) = 0, CX is a divisor 75 02 JNZ CONT_LOOP ; if not, continue loop to next 03 D9 ADD BX, CX ; add number to sum CONT_LOOP: 72 04 JC END_ABUND ; if CF=1, BX has unsigned overflow it is abundant E2 F0 LOOP DIV_LOOP 3B C3 CMP AX, BX ; BX<=AX -> CF=0 (non-abund), BX>AX -> CF=1 (abund) END_ABUND: C3 RET ; return to caller ``` Callable function, input `N` in `AX`. Output `CF`=`1` if abundant, `CF`=`0` if not abundant. [Try it online!](https://tio.run/##hVRrb9owFP2Mf8VVvxQkUBMo7Zq1lYB06qYWqvUxtGlCTmLAU2Kj2AG6P8@unYQmZdOQiOA@zjn3FaoUS4L4tTOnKtnNZZpQDTd3n4BtWZhpGsQMeoTMlKap9kgjkWsARrdt6BKuZjTIRESF9nbwj89HGEyBK4j4mkdMRMQY7ycvAKNp2/jeAkOZCc1SsFwKUMgYTpDHeB9vv@YZbhU6B4XgtYiaTjBqiFHDGm7MaGpMzTQTgosFqCwBOYc5DbVMVYv4n19md5PJg/eG4iOKf4iCpuaSL5awkWkE2K99YS2b@/D8eFutKs9VdM1ApnzBBY3rrUBqU9i7BKS5woeHSPcTv2xVaTpBQ842eYBDtpQpLIvteaCJIRuqIFxSsWCR6RfS5oKfbh6fDovlc0RJKBcRzqPpT1vI7bSB6wJUAVszEb@CkkY8zpdaj5KpRf0y/o5VTcZPtq0VVCF1GwctNBcZg1jKFWgJgm21zRv4fj7AUVUNjSIQWRKgFgzG4eUcI3zcjP3ZYPg89isco09Xrl2BJdacCcUXAouWa5bOY7kxRRi9xeZCc7NkwvBdwlm/3ztrkb3ufB3Mr29Qrog1je5t39/t2XB6eYWd7lwbBQ40hRQdS9Mygdd7lwvN3Ez26r1d45cIwbRnf1OkscrU0hwbIQ1cPry7iLfhh2CbmAvWcX@W5xjiObqkoXRUWgJjcUjEQp7QeGb6jMe7xXVFEPThgzRwYDYUHeFykV@1dZh@A43bcOwcG1ipAtLgRh9SHURrXLfiL0rFOn4DVInL1IiTUp6VYKDe9Bt3VXz1VXNqIDSAs/3gIMYKl8ZyVbvlkZLHiAiTVZHrOo6DogIGUHlf1SK6fRtCMWSFK8Nm3Sp57i4cXj3x/H/Y3b77DrtXe4dad@Hw6om9v2KXQ8Qe2clVdNaaVJwLRAEcnXYvTi/OzrsX/SNSLI@xO9tBG7@7Pw) Props: * Fixed for 16-bit overflow (+5 bytes). Thanks @deadcode for the suggestions! * Simplified return logic (-3 bytes). Thx to help from @deadcode once again. * Use TEST instead of CMP (-1 byte). Thx to @l4m2, and make sure to [upvote @l4m2's shorter x86 answer](https://codegolf.stackexchange.com/a/179303/84624)! * Thx to @deadcode for the TIO link [Answer] # [Actually](https://github.com/Mego/Seriously), 5 bytes ``` ;÷Σ½> ``` [Try it online!](https://tio.run/nexus/actually#@299ePu5xYf22v3/b2oCAA "Actually – TIO Nexus") ``` ; # Duplicate input ÷ # Get divisors Σ # Sum ½ # Divide by 2 (float) > # Test is greater than input ``` [Answer] **Java 8, 53 bytes ( a lot more if you include the ceremonial code )** ``` return IntStream.range(1,n).filter(e->n%e<1).sum()>n; ``` [Try it online](https://tio.run/nexus/java-openjdk#ZY@/a8MwEIX/lVsCUmlEvdol0KFDh04ZQ4azc3WvSCcjnQwh@M/O7Cr019D5Pb7vPQ5TTAofOKMryt5lTYTB3XUwld7zAIPHnOEVWS4wJZ5RCbKi1qiP0RMKcH7qi5xQ1LAoiL3AmkhLEngR3X8RE8pIprkX697YKyVD251s6LGxLpdg7E66dfmxfhvmyCcI1W0qhWU8HAHTmKvgP7h5aH7Rt7lt@7erBjE94/Bu9uesFFws2rb1jqgX2y3LepW4HWqBPgE) Explanation : ``` IntStream.range(1,n) \\ numbers from 1 to n-1 filter(e->n%e<1) \\ filter in numbers that perfectly divide the number n sum()>n \\ sum and compare to original number ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` ѨO‹ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8MRDK/wfNez8/9/SEgA "05AB1E – Try It Online") # How it works ``` Ñ #list of divisors ¨ #remove last element (i.e the input from the list of factors) O #sum the list ‹ #is this sum less than the input? ``` Sorry to post in old question, I was just going through old posts for practise and noticed my solution was shorter than the next best 05AB1E solution. [Answer] # [Julia](https://julialang.org), 25 bytes ``` a(n,r=1:n)=(n.%r.<1)'r>2n ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY5BCsMgEEX33qKLUgUraoyaUHuRkIVZFFKKFImn6cZNDtGj5Db9YBfyPv-Nw3z2Z3mtsR5LXIqSMkxEaU6U50RLPMNJB3aWEwMaOAPXo-_RWXQWdKCDc3Ae2cN75AF5gMdmMu9le1z9N9LEc1BjYoEmcc7iptgl33Vq_ji985o2StWIX2yK4p_mENqNrA3W2vgD) [Answer] # Regex (Perl/PCRE+`(?^=)`[RME](https://github.com/Davidebyzero/RegexMathEngine)), 36 bytes ``` (?=((\2x+?|^x)(?^=\2+$))+)(\2x+)\3+$ ``` [Try it on replit.com](https://replit.com/@Davidebyzero/regex-Abundant-numbers-with-lookinto) (RegexMathEngine) Takes its input in unary, as the length of a string of `x`s. This is based on my 43 byte .NET version; for the full explanation, see below. Lookinto, a new feature in RegexMathEngine, allows `(?<=(?=\2+$)^.*)` to be shortened to the equivalent `(?^=\2+$)`. This is not just the shortest, but the fastest under RegexMathEngine, even though the 43 byte .NET regex it's based on is the slowest under .NET (beaten by both 44 byte regexes in speed). # Regex (Java / .NET) / [Retina](https://github.com/m-ender/retina), 43 bytes ``` (?=((\2x+?|^x)(?<=(?=\2+$)^.*))+)(\2x+)\3+$ ``` [Try it online!](https://tio.run/##bVLvb9owEP3ev@IWdcIm4AamfZkboW3apEnrNpWPQCWTOODWcTLbKYGufzs7h@xHJfLlcnfP7/ye7148ivF9/nBUZV1ZD/eYM1WxIYf/K41X@mzNyo1ssXNRN2utMsi0cA5uhDLwBH3NeeExPFYqhxI7ZO6tMhsQduMWKwp@a6udg09tJmuvKjx5AfBZaQlFauSu@yURy6pcMuxHlH9oikJamd9KkUsL6w72skj@nOzTglLez3Ujz3fbwE@IS9eoQeRflZGE0lepabSmqiCOyZ@N0I5EV8PhMKL06SX0xECIP0vwhAz@LwMSXCHDGnEP3MXpYGkGIXr@fKo9/xDeS2vApv0fqi3rMMBRjm6sq0pLYeCQFsgoOcwzYQxKV6ZuPKQQ1PY1Mt87L0umDOXQ6@xgbCvcN9l6vGZnMUBviMa7I8cJZBDRS@z7ixVobAcUc7VWnkRjfATEezAJdr4Yj2tgWS2sk5gQvUhWdARmcrbJtDQbv72ewgwCEt5hmKyQMdsKu1i1vZ4uM5MVh/fWir1jhdKatKNBO@hMASgqG7ThNVKTcDDXqZlgiGMUeCN8tkWHSmSzrDxlpNtcgwv@EclPG8N2VtSkH5FV9f57cSvMRuKkZGQoDUoLICWONzl6F972QHuTK3RsZ5WXJDwq5YfU2ya8z792jR76gkSvXYSWUP4cvouwVUcySwlZTtt49uuupWR2nWJlOY0v6R0bUhrTrkmXb@LLY1iiYzKevk1@Aw "Java (JDK) – Try It Online") - Java (very slow) [Try it online!](https://tio.run/##RY/RaoQwEEV/RWTAzKaRaN/WBhf63C9QF8TOroE0kZhF2a3fbnVL6eM5c7ncGdxEfuzJmBW8qjxdaW6OR0sTOyUrKxVjdT7z8vs8Iyvf1GbqnAOe0wMix@cR61cOa3J6id/d16ANfcZYwF3J4uI8tV3PwETaRqDtcAv4gFaBEeNgdIhFXOgLgzbt3M0GYUKU7wGuoK1ks2wFDKyqtA3N0xRghaE/znbmHB97h08/2tD1NLJkTg5g8Vff8TF5HUj0bgzLNisr/jkS1m2/Gm0pArssyypFJqX8AQ "PowerShell – Try It Online") - Regex (.NET) [Try it online!](https://tio.run/##HckxCsMwDADAXb8IyCBZONhJMxQSPPYTwqjQDl06lA4a8q4@oB9zQ9e71/39eF5L15tAdJBgjTxy0uICWL4fxwyBLHmETnUj0sml7s2Z6rodopMgtzEyC/@TdRbsmAdgGxvAxQYI5j2neclwPi0/ "Retina – Try It Online") - Retina This is 2 bytes shorter than [Martin Ender's answer](https://codegolf.stackexchange.com/a/110732/17216). Its structure is quite different, and it's more portable to different regex engines. It works by first adding up as many proper divisors of N as it can, in strict order from smallest to largest, while having a sum not greater than N. Then it checks if there exists a larger proper divisor than the last one added to the sum; if there does, N is an abundant number. ``` # For the purpose of these comments, the input number will be referred to as N. # No anchor needed, because \2 cannot be captured if # matching is started anywhere besides the beginning. (?= ( # Add up all values of \2 until there is no more room in # N to keep going (\2x+?|^x) # \2 = the smallest value greater than the previous value # of \2 which satisfies the following condition; if we're # at the beginning, \2 = 1 (?<= # Lookbehind - evaluated from right to left (?=\2+$) # Assert that N is divisible by \2 ^.* # Jump to the beginning of the input string, then execute # the above lookahead ) )+ ) (\2x+) # Match if there exists another proper divisor of N, \3, \3+$ # such that \3 is greater than the last value of \2. If # there does, that means there was insufficient room in N # to add up all of its proper divisors, and N is abundant. ``` # Regex (Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / .NET) / [Retina](https://github.com/m-ender/retina), 47 bytes ``` (?=((\3x+?|^x)(?<=(?=\2+$)^.*(\2)))+)(\2x+)\4+$ ``` **[Try it online!](https://tio.run/##LY7BjsIwDETv/Qor4mCTtkqAU7tRP4SChCBApJBWSQ6h2n/vJiwn2zPzRp7f8Tm5/Wpe8@QjhHeovX7o1INXnjG24qAQx33iw@85EQ4/Kivjjm/o3G5x3BERpzwTp/HAN2tmjrJr5KmHRYnqPnmwYFxpbkO8GddVYJVtw2xNRNYwqqCEXAn5i3toNC6iPYoT1f9bLiMuKYNg7vB5rw364q9P9DWwxLbuYxZ36WD2BaMiLEr239vV2t0UY7SKRgoh/gA "Python 3 – Try It Online") - Python `import regex`** [Try it online!](https://tio.run/##RY/RaoQwEEV/RWTAzKaRaPdpbXChz/0CdUG22RpIJxKzKGv9dqstpU/DOVwud3o3aj902toVvKq8/tBTczqRHtk5WVmpGKufJ15@XSZk5YvaTJ1zwEt6YHWOiBy3O3GsjxzW5PwUv7rP3lj9HmMBDyWLm/O6vXYMbGQoAkP9PeAMrQIrht6aEIu4MDcGbXp1dwrChijfA1xBW8lm2QoYkKoMhebHFEDC6j/OduYc573Dp29tuHZ6YMmUHIDwVz9wHr0JWnRuCMs2Kyv@ORLktn@tIR0BLcuySpFJKb8B "PowerShell – Try It Online") - .NET [Try it online!](https://tio.run/##Dcg7CsMwDADQXbcIyCBZONj5DIUEj72EMCq0Q5cOpYOGnqsH6MWcTA/e@/F5vm6l610gOkiwRh45aXEBLP@fY4ZAljxCp7oT6exSv82Z6rafo5MgtzGSTswsfOrCugh2zAOwjQ3gagME857TvGa4LOsB "Retina – Try It Online") - Retina This is a port of the 43 byte Java/.NET version, avoiding a nested backreference in order to add Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) support. The way in which this is done (placing the copy inside the lookbehind) removes Java support. # Regex (Perl / [PCRE2](https://www.pcre.org/) v10.35+), 49 bytes This is a direct port of the .NET regex, emulating variable-length lookbehind using a recursive subroutine call. ``` (?=((\2x+?|^x)((?<=(?=^\2+$|(?3)).)))+)(\2x+)\4+$ ``` [Try it online!](https://tio.run/##RY5BT8MwDIX/ijVFa6y0NC1wIcnaSePKiRvdooFWKVLYSlKkoqz89ZKVSbtYfs/P9tcdnH2cPn@AOAHBnj72FkguolRys35dr0ZoT44Sr7iQK4EBTBsVhs6ZYw@L5rgQI9RW@c6aniZZkvrvd9/HFZ1mRVrg4esSqm4ujz4@EY3icsvHj3tXW1liqO1bsVWx8q24/jVXSYxU8zh2jGEwLVCaDAkMEEOIoH4hJy7HQPxyOcPNbBG8EP@sxIhxHLV@ftloPdFKUdqUA6vOuwEpraSK1q4pGTnT6h7xDhEZzhFsHhiZJp4VnPM/ "Perl 5 – Try It Online") - Perl (slow) [Attempt This Online!](https://ato.pxeger.com/run?1=XVDBSsNAEMVrv2IJC5kxSZtUD8JmyUWFgnhQb027xLhpAukmJCkE2n6JF0H0n_RrnKQ9edjdNzPvzZvZ9886rz9-L1ZhRIDxhklmzSw2ZXWjN6rRdZmkGuzZ9DJSKk_KTqXVti5K3cQQo4ifZq3tMptORkm10QPBdNp0LSh1v3i4UwpdFiC1pMZiklUN8EL6gpcyI3oLzy-3i0cUuGdFBrxctl1TakMIvWAlpRUbC4nc7l6pQmnXd70AB73u67J602B5lkt0Qfq02plu0IZzEi2pAd3-SkwYG53NOeYmlGOdkOMgWTMYV94mXZoDb1wyG_bXSQd2b7vcICLbDyMWqNO8GuYSjFYJBBtixo04ks3x3z8Biq9dl3k3PwFEEiCe9050WPcIEIWSUut47vADRFeIU_JwcKRgfO3wk_Dj_Hz7XuD7_in6Aw) - PCRE2 v10.40+ ``` (?= ( (\2x+?|^x) ((?<= # (?3) calls this (?= # Circumvent the constant-width limitation of lookbehinds # in PCRE by using a lookahead inside the lookbehind ^\2+$ # This is the payload of the emulated variable-length # lookbehind, same as the one in the .NET regex | (?3) # Recursive call - this is the only alternative that can # match until we reach the beginning of the string ) . # Go back one character at a time, trying the above # lookahead for a match each time )) )+ ) (\2x+) \4+$ ``` # Regex (Java / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / .NET) / [Retina](https://github.com/m-ender/retina), 50 bytes ``` (?=((?=(\3|^))(\2x+?)(?<=(?=\3+$)^.*))+)(\3x+)\4+$ ``` [Try it online!](https://tio.run/##bVJdb9MwFH3vr7hEQ7Wb1usHvOBFFSCQkBig7bHtJDdxWm@OE2xnzVr628t1Gj4mLVJk33uuz/U5vvfiUYzus4eTKqrSerjHmKmSDTj8n6m90i/mrNzIBpFeVa@1SiHVwjm4FsrAAbqc88Lj8liqDApEyK23ymxA2I1brCj4rS13Dj41qay8KvFkD@Cz0hLyxMhduyURS8tMMsQjyj/UeS6tzG6kyKSFdVv2PEn@nOzCnFLe9XVDz3fbwE@IS9aoQWRflZGE0leJqbWmKieOyZ@10I5El4PBIKL08Lz0zECIf5HggAz@LwMSXCLDGuseuIuT/tL0w@r58Zw7/hDeS2vAJt0O1RZVaOAoRzfWZamlMLBPcmSUHG5TYQxKV6aqPSQQ1HY5cvvkvCyYMpRDp7MtY1vhvsnG4zVbiwE6QzTeHTnORQYrOokdvliBRjhUMVdp5Uk0wkfAeg9mjMgX43EMLKuEdRIDohfjFR2CmbwIMi3Nxm@vpjCHUAnvcJmskDHdCrtYNZ2eNjKTFYf31oonx3KlNWmG/abfmgKQlzZow2skZszBXCVmgksco8Br4dMtOlQgm2XFOSLt5Boc8I9Ifp4YtrOiIl2LtKyevuc3wmwkdhoPDaVBaQ6kwPYmQ@/C2@5pZ3KJju2s8pKER6V8n3hbh/f5B1fooc9J9NpFaAnlx/D1wlSdyDwh4V/Oft1RSpbTJp5TMr9KMLmcxRf0jg0ojRGZNTFdvokvTmGWTuPR9O34Nw "Java (JDK) – Try It Online") - Java (very slow) [Try it online!](https://tio.run/##LY7BysIwEITvfYoleMiatiR/PbWGPohVkN@ogZiWTQ61@O41UQ8Lu/PNDDs94330zWof00gRwjOUZG5m7oA0McZW3mueZ2heJ0Q@/M2iR97vdRKHRmzwVG8RRSLNLHDYic2aYgfVVurYwaJlcR0JHFify@sQL9a3BTjt6jA5GzmrGBaQTT6b6OxvhlsfuTvII5bfLZWhUJiCYK/w@bAO5kz/d04lsJlt/QdmurQwUY5hFhatut/tS@MvmjFcZaWklG8 "Python 3 – Try It Online") - Python `import regex` [Try it online!](https://tio.run/##RY/RaoQwEEV/RWTAzKaRuNuntcGFPvcL1AWx2RpIJxKzKGv9dqstpQ/zcM4dLjO9G7UfOm3tCl6VXn/oqT6fSY/skqysUGyf6vR1RWTVceIFsuJFbbI6ccBrekDkW3KaOFbPHNbk8hS/us/eWP0eYw4PJfOb87ppOwY2MhSBof4ecIZGgRVDb02IRZybG4Mmbd2dgrAhOu4LXEFTynrZChiQKg2F@sfkQMLqP8525hznvcOnb01oOz2wZEoOQPirHziP3gQtOjeEZTsry/85EuS2l60hHQEty7JKkUkpvwE "PowerShell – Try It Online") - .NET This is a port of the 43 byte Java/.NET version, avoiding a nested backreference in order to add Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) support, while keeping Java support. # Regex (Perl / [PCRE](https://www.pcre.org/)), 58 bytes Porting the PCRE2 regex to PCRE1 requires working around some bugs: ``` (?=((?=(\3|^))(\2x+?)((?<=(?=z|^\3+$|(?4)).)))+)(\3x+)\5+$ ``` The `(\2x+?|^x)` had to be changed to `(?=(\3|^))(\2x+?)`, copying `\3` into `\2` and `\2` into `\3` (emulating a nested backref using a forward backref), because using a backreference inside its own group forces that group to be atomic in PCRE1, and in PCRE2 up to v10.34. And a fake always-false alternative `z` had to be added to the recursive subroutine to prevent the error message "recursive call could loop indefinitely" in PCRE1. [Try it online!](https://tio.run/##RU7BboMwDP0Vq4pKrMAIZb0spFCpu@6022ijbipSpKxlCZPYUvbrLLBKO9jye372e@3JmvX4/gXECvDm8nY0QFIRoCx22@ftZoDmYilxkotiI9CDbgJC31p97mBRnxdigMpI1xrd0SiJYvf56rpwouIkizM8fUyi8p/lgccHolBMv1xwPNrKFCv0lXnJ9jJ0vhc3X32DRBdyXoeJMfS6AUqjPoIegggR5A@kxKboiVsu53BzthA8E39ZiRbDMCj1@LRTaqSlpFPV@fWASOtVz0oMTCED@3091DkjV1reI94hIguKvGdYrxkZR55knPNf "Perl 5 – Try It Online") - Perl (slow) **[Try it online!](https://tio.run/##hVPvb9owEP3OX3FlbbGbUCUNq2hCirqu0z6wdkJU2gQ0YsEBa8GJnDBoC//62DmGNv0hLQLJPj@/e/fuHKZpfRKGmw9chPF8zKCVhpIdT88r4XQkIUj7Q/ChW/20WPz@5cx/3t//6E1PF1OyIW2fqP/AWd1RSgYnS6NNMdLyMfqwuhs4xv6KtBuUHlNKDUQ4S4MOPhr7G/qarWrCUeoHqWF7lWclWT7miZJSDkkuJi9jPMEoG83e4s4rXOSQ4jIPmJSJJGEishyK0o5mLMtGE0YfMY/rhgiAVgu2UbUs4kyMYw8ky@dSgO2tC8rZiAtC4bEC@KV9zBYzQVJat4e@5cEcMc5JkEOidurCBBcFuODU6vAgneceKMPhSDIPyupQTppLfVuybB7neq3qiKKM5SYk8xzTTvKpPkn@sDBPZN8Z6lTI6hfkQZjMUh4zkprw/bJ7FXy@6V10OrDSu9vel6YJhzqhXuwyWFRT8QjInmR050NUeBoRrAbRJlQVUSFNwgiVFNfhYOzCQTYQ2N0Sp86zJY7wAlHiH5RThTkTlsdcMKK7woWpfaIeYuyd54UovCYsrHGUJ5wUoOMwQG8JpSYI24Q0yfBYn0RcjEmtXtsmVp@wlUGI2fPLfXFdoYLtd3jBKPAGoBAXkz9z6aapdIIt9K4vbMMeejhRMyycZCbUljUlDEvJ8HDol@4/GcF9oWam5QvbA8Pg5Yp1V9Us7DrLliwkkplwfdvpmIA5OHat@G3HwQSnVPKumVuWcx8sWK12pOhDMRFX3e5NN7i@@XbRu/z6WsCO4oECOqMqJbWBqOn@eG@guo04qupFce9dqm36Foo5PPyPmBd8VReu1NBVX/Ku33esZLdGrCvFyLp6FCVjqIQ@Pfbtq6usN1a9cWpVmo5VbzaalbMTq37WaP4No3g0yTb1WHXiHw "C++ (gcc) – Try It Online") - PCRE1 [Try it online!](https://tio.run/##fVFNT8MwDL3vV1hRpMa03VoGp6zqBZAmIQ7AjUJUSrYGujRKM2mC8duHO7jAgYMtf7zn5ziudYdF6VoH3EMBbMZgCs7rtfLadXWjRTSbnpRKtXUXVNNvnOm0r0SFsrqdDVECEdmKimqtR4AN2oZBKHW1vL5UChPIkUbSYDkx1qhBB8Fc4/X0uW7egienOrMxgSXA0pyhhN8wr5utH0xv/4e9frcy6kxWvRfcFJnkXbGitQZxd3@xvEGJH2BWgncPQ/CdthRhmj8WBassQwIP22fqUDnJkjTHka93rutftGApSwguid/0WxtG7uKUSA80gHz2KCcAR2X7k3O7KI59iuIYSRrE8bSbOjSt4D4hsfHOug4i2kUJt4gIH@OKBnXT9uNeEugpuYQxB27lJ8l8/vkPgfIgykKMVs33T4iiOt3FJVJlUVD1ff9UzWO@F@UZ4pRUYkLMdzFW5zE/HLI0z7LsCw "PHP – Try It Online") - PCRE2 v10.33** [Attempt This Online!](https://ato.pxeger.com/run?1=XVBfS8MwEMfXfYpQAs3Zdms3BTEtfVFhID6ob8sWak3XQpeWNoPh5ifxZSD6nfTTeNn25MMld5ffn7t8fLZlu_89m8cpJoR2JCHOyCFD0nZqKTvV1lmumDsanqdSllltZN6s2qpWnWACuHgc9a5PXIwCm3KpLEAbpU3PpLyb3t9KCT6JACVRmA-KpmO0SkJO66RAeM-enm-mD8BhS6qC0XrWm65WGjMIonmSOEI7gOB-_YIv2PZDP4jA8tWmrZtXxZzA8RHOkZ83a20sNx4jaYYCeIZzPiDk4KxPNdVxcnjHzPMArQk7rLzKTF4y2vloZvdXmWHuxvWpBgCytSNWoPKysXNxgqtEnNiaUM3f0eb93z8x4F9rUwRXP9csTZgNMdktAJgYb7wUsBMn2H3bLcTEozuWXgAM0cxDxGTjgbj06FFhf7q-wyAKw_BY_QE) - PCRE2 v10.40+ --- # Regex (.NET) / [Retina](https://github.com/m-ender/retina), 44 bytes ``` ^(?!((?<=(?=(?(\3+$)((?>\2?)\3)))(^x*))x)*$) ``` [Try it online!](https://tio.run/##RY/RaoQwFER/xcoFc7VZ4u7b2tSFPvcL1AWxd2sgTSRmUVb8dhtbSmFezjAMM4OdyI09ab2Bk5WjT5qb89nQxC7JdmXlE2Pli2RlEKtPGWDg1/pYYn1CRHadU8QZU8AtuTzHb/ZrUJo@YizgIUVxs47armegI2UiUGa4e1yglaD5OGjlYx4X6sagPXT2bjzXPjrugUxCW4lmDQUMjKyU8c2PU4Dhmv443znLcNk73OG99V1PI0vmJAWDv/YDl8kpT7y3o1/DrLz454gbG85qZSgCs67rJnguhPgG "PowerShell – Try It Online") - Regex (.NET) [Try it online!](https://tio.run/##DcsxCkIxEEXR/u0iMIGZhEhi/IWgpnQTIYyghY2FWMzKXIAbi4HbnOK@H5/n61Zmv0cEQ/Q62IKkXiyCyu9rlOFZkwXMwc0xt9OZ24p7jSTLl75v0quI8FivmASSSdlBdDeAqzp4tZlT3TKOh@0P "Retina – Try It Online") - Retina ``` ^(?!(x(?=(x*$)(?<=(?(^\2+)(\2(?>\3?))))))*$) ``` [Try it online!](https://tio.run/##RY9Ra4QwEIT/ipUFN2dzRPt2Ns1Bn/sL1AOxezWQJhJzKCf@dqtXSuftm1mGnd6N5IeOjFnBy9LTF0316WRpxHOyXlA94YRK4nQAhupVosJLlacMqxzVW/Wi2ENbuibn5/jdfffa0GfMCrhLUVydp6btEEykbQTa9rfAZmgkGD70RoeYx4W@IjTH1t1s4CZE@X6QSmhKUS9bAYKVpbahfjgFWG7oj7Od05TNe4c/fjSh7WjAZEoOYNmvfWfz6HUg3rkhLNtbWfHPEbduG2u0pQjssiyr4JkQ4gc "PowerShell – Try It Online") - Regex (.NET) [Try it online!](https://tio.run/##HcoxCgIxEEbh/r9FIIGZhEiy6xaC65ReIoQRtLCxkC3mZB7Ai8XF137v/dier1sd7Z4QDSloJ4ucW7UEX78f8wWBNFvE6CSOjGTdF88k55WEepsSU5tILm0W/rfr8MWB9dCBqzoEtVHyvBScjssP "Retina – Try It Online") - Retina This is based on [Martin Ender's answer](https://codegolf.stackexchange.com/a/110732/17216), but saving 1 byte by testing zero as a potential divisor of \$n\$ (it never will be, so this is harmless), thus skipping the need to explicitly exclude \$n\$ itself as a divisor. Another upshot of this is that we can extend the valid domain from `^\x+$` to `^\x*$`, giving the correct answer (non-match, i.e. false) for an input of zero. I have included versions with both smallest-to-largest and largest-to-smallest divisor summing order. The length for both is 44 bytes. Only the largest-to-smallest version is commented below, because it's simpler to explain, and I already commented the original 45 byte smallest-to-largest version [in my ECMAScript answer](https://codegolf.stackexchange.com/a/178952/17216). ``` ^(?! # Attempt to add up all the divisors. Since this is a regex and we # can only work within the available space of the input, that means # if the sum of the divisors is greater than N, the attempt to add # all the divisors will fail at some point, causing this negative # lookahead to succeed, showing that N is an abundant number. (x # Cycle through all positive values of tail that are less than N, # testing each one to see if it is a divisor of N. Start at N-1. (?= # Do the below operations in a lookahead, so that upon popping back # out of it our position will remaing the same as it is here. (x*$) # \2 = tail, a potential divisor; go to end to that the following # lookbehind can operate on N as a whole. (?<= # Switch to right-to-left evaluation so that we can operate both # on N and the potential divisor \2. This requires variable-length # lookbehind, a .NET feature. Please read these comments in the # order indicated, from [Step 1] to [Step 4]. (?(^\2+) # [Step 1] If \2 is a divisor of N, then... ( # [Step 2] Add it to \3, the running total sum of divisors: # \3 = \3 + \2 \2 # [Step 4] Iff we run out of space here, i.e. iff the sum would # exceed N at this point, the match will fail, making the # negative lookahead succeed, showing that we have an # abundant number. (?>\3?) # [Step 3] Since \3 is a nested backref, it will fail to match on # the first iteration. The "?" accounts for this, making # it add zero to itself on the first iteration. This must # be done before adding \2, to ensure there is enough room # for the "?" not to cause the match to become zero-length # even if \3 has a value. ) ) ) ) )* # By using "*" instead of "+" here, we can avoid categorizing zero # as an abundant number. $ # We can only reach this point if all proper divisors of N, all the # way down to \2 = 1, been successfully summed into \3, which would # mean N is not an abundant number. ) ``` As far as speed goes, the smallest-to-largest version is faster than the largest-to-smallest version (both in .NET and their ports below). Both are faster than the 43 byte version under .NET. ## Regex (Perl/PCRE+`(?^=)`[RME](https://github.com/Davidebyzero/RegexMathEngine)), 42 bytes ``` ^(?!(x(?=(x*))(?^=(?(?=\2+$)(\3?+\2))))*$) ``` [Try it on replit.com](https://replit.com/@Davidebyzero/regex-Abundant-numbers-with-lookinto-43-bytes) (RegexMathEngine) This is a port of the largest-to-smallest 44 byte .NET regex, using lookinto instead of variable-length lookbehind. Although the Perl/PCRE syntax for lookahead conditionals is more verbose, this is compensated for by being able to use a possessive quantifier. ## Regex (Perl/PCRE+`(?^=)`[RME](https://github.com/Davidebyzero/RegexMathEngine)), 44 bytes ``` ^(?!((?^0=(x*))(?^=(?(?=\2+$)(\3?+\2)))x)*$) ``` [Try it on replit.com](https://replit.com/@Davidebyzero/regex-Abundant-numbers-with-lookinto-44-bytes) (RegexMathEngine) This is a port of the smallest-to-largest 44 byte .NET regex, again using lookinto instead of variable-length lookbehind. This one is less conducive to being ported, and I had to use `(?^0=)`, lookinto accessing the in-progress current match. I've not decided how to finalize the current behavior of this, so it's likely this version will not work with a future version of lookinto. ## Regex (PCRE2), 73 bytes This is a direct port of the 44 byte .NET regex (based on Martin Ender's regex). It doesn't port well to PCRE, because it changes the value of a capture group inside the lookbehind – but upon the return of any subroutine in PCRE, all capture groups are reset to the values they had upon entering the subroutine. So the only way to port it is to change the main loop [from iteration into recursion](https://chat.stackexchange.com/transcript/message/49026684#49026684), resulting in a large and very slow regex: ``` ^(?!(x(?=(x*$)((?<=(?=^(?(?=\2+$)(?=(\4?+\2))).*(?=\2$)(?1)|(?3)).)))|$)) ``` [Try it online!](https://tio.run/##fVNhb9owEP3Or7hGUWO3gQJFVbsQIW2jE9PWVinbF@isEAzxGpzIMR1T6W9nL@naaV01JCz73bt353tOkRa7/qBIC3INheQcOdSiwsilMLLI4kQy76h1MBAijTMrknxVqEyaKZvyYBodlZ5PHv4LgGIpK4K2UtuSCXE@@jQUgvvU4ZCEcNBY/DDKSnY9fj@MIt@5ehcNu3Tn8ODvAERKG2vLvIohvg6j69Hlhcdf8pypRm5DaSVKaZlTJEa2ZnFyaw0WkamVso5PTrPzL83IZG1Klev/074/htpVZJEb5qqwHbhZuMBly6qP0QUP@D2pBXOzSWlNJjV2vNm5CcO6P5DL9QwRwH7bb3Z4lS83RZbPJXOajg96gPwkX@PKOPS7SJpAAGv7JmgQ1ZX177Or@2Edx@7wkNM9CIQGiO0x9zasvVvFNkmZa3zUrYyUMYa58XxXc/zIlY@0LC6tkMZAngfPMu4tbbfg7IXhVTT8IC4uBaZ9GaFUdU3FZZLm1d0Cwjg6AVVncnXw8KcTaOzvv6pRk7035LUmeDneCO/F6Dijug0Ab5/8o9oYkps0XpdWzhGLnkx7JfY5zjCmlZzTl/F585SSNIYKxEufirws1Sz7SUonuYH1FnuJ/bxOHaeS8sUCrtNczUnnlmpaWeR6TjYnC8JMLpXWSi9BpZju4kw9l4IOaihtIfZxNCa83lf6v5m4srbzofHw4nvC@Hff2GCPbdggZJsDlzM26Ic4AMU67R4CQmjaGxxOu/CwdVDDFdrhWzY4BgR463K@27Wb3Xa7cXp80jjr9ZpnvZNf "PHP – Try It Online") - PCRE2 v10.33 (PHP) [Try it on regex101](https://regex101.com/r/HZiNAS/3) - PCRE2 v10.38+ [Attempt This Online!](https://ato.pxeger.com/run?1=fVJNj9MwEJU49le4lrWx26RNCgeEa-UAZVUJtass4rJZrGxw2tDUiRwXKm174HfsZaUVPwp-DeOUD7FIRIoz896bNx47dw_Nurn__uTLNIYAEYMEwmOMRqgxaiWNaqosV9QbjwaxlOussjKvt01ZKZPSlPE0Gbeejzx4CwDlSjmBtkrblkr5ev5mJiXzUcTAEox5r_hsSqvo5dtXsyTx8cXLZDZBnzDjfxNg0tpMW-o5hXw3Sy7ny4XHGO-VupStshQ3uVGjmyzfWAOLrMptabGPcBDhf2RG5TvTlrX-v-zjiQodU9SGklKEnFSigMFat7f5gnF2i8qCkuqqtaZSGiIWRNdC4FRjBuJ2dwMMwH7oBxFz9WrfVPUHRXGAfZBzqM_rHYwHyXQCRVdgAGt4zXsIdZ31z5zoqeh4iIZDhm5BgGADiPYp2YjunraZzdeUGB_6uktTGRzc3vOJZvAgok6yKmutVMaAPesLcZHMzuViKeG8lwn_bUs26HCAGmjlxiyZyte1m40jOI6II5cjovnxz06g5uysq-lI_ALh0aOWctuuKHNtjr3jo38J8K87WwTPv83f07hP9zQWdD8gjNJ4KiABFNZ0MgQIqPRZPEwnMNpo0MEOjdiBxk8BAvhAGDsZ3v_6hMEkDE_JDw) - PCRE2 v10.40+ (PHP) [Attempt This Online!](https://ato.pxeger.com/run?1=hVVfb9pIEH-7Bz7FxK3CLpgcJm0VYRyUSzgFKQ2V66i9Ame5Zg3WmbVlr5U0JZ_kXu6lj_1AvU9z410bTKh0Fpid38zOn9_MLn9_95Moz4qvu_T971OtEyV-ynqdM23-w36xYEHIGby7tEc993JyNXLvbseO-2F85VzDWeNFyP0oXzAYyE0nq_OGv_JScJPpHCywtd_u7__6fJr_8eXLR2f15n5FvuUi6Jz9GP9JhkfkgQwt8tB6SQkZDiwUEMX3rNdGCFWzV8P2rEcpPWlJuEANuiHDU4QQ3rykVDn89xeHPo-l6dBKLDdpG2Yt0UwswrhItA6lIV_uY2GMKPPWh3bnjZALSHApXJamcUr8mGcCZOGtNcsyb8noV4zT7_toAIMBlGixlDjji8iElIk85WCYTwcuC9mPF0yHz3EcQWwFXpQxCl8bgI8MVfqc9l6_mZsSDgMgsg_ukpWO3NKKKGdENfLu8vrCPmvRUqlDFj6yOCBV8vBrhdTskW8ZpXhIDENViR_nAvqwrZYWNWpyG8gM-qA9Y0Bu1jTcpc24RlXuWy4aioy1F3JS1ZtMkfqIcZLQjjG3uibkaHPacwUyg1KxYYkLaSxTUa1CRZILExQpBQXQSlklrz3hr9yFJzxs23atvKUsyyOhqxLMcv7fjz-NJBIEGUMllo5JLcWqKgFHvgq1TsKIkZK_9-8cmyZ66ebTyJ64zsh-O769cEZXFXw1cS5ubmBTinfO7zocy_jlbxm1S3fdPkqxWSV19fGR79KuVqZ1ULmLsieYG6Tx2k08IVjKSYoTcXt3c1M6COIU5EA-FlxLenG-IrwXiGp7yHXFNDXRxqi6JpPEbbyLgT0Rh0QanfgudodQqgM3dEjiDNVKg3fNgjQ7zTJw8XCjyBptjqx6Z_t9XoDDn_iFtrRvAybSx-A7X-qEFuE4u1fSlBttY27ieK6RXJLp0HxoFolhKRkq51Zt_5aI0OLF1A0sbpjQbof1itUkFNOzT7dktT4PGCvEbsrPriF7zG9ZxFaXPs8t6MJmU4VAVpTLkW1PbPd28vbCubx-nk_l45ECElUUTpoz3lTtMg9MdwcbT2t4qK-lM8Bsjo__N5s9jxoefHNvXKvTJtKcUbwN68Gefs5srS3K4qmhrht1YTwf8yBljOxkWr8TlBJP0vZGVlHwKlJ_Lv9863Z63a4S_gM) - PCRE2 v10.40+ (C++) [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), 15 bytes ``` n->sigma(n)>2*n ``` The variant `n->sigma(n,-1)>2` is, unfortunately, longer. [Answer] # Powershell, ~~51~~ 49 Bytes ``` param($i)((1..$i|?{!($i%$_)})-join"+"|iex)-gt2*$i ``` I wish I could remove some brackets. -2 thanks to AdmBorkBork, instead of not counting the input in the initial range, we just take it into account in the final check. Loop through range of `1..` to the `$i`nput, minus 1, find where (`?`) the inverse modulo of input by the current number is `$true` (aka only 0) - then `-join` all of those numbers together with `+` and `iex` the resulting string to calculate it, then see if the sum of these parts is greater than the input. ``` PS C:\++> 1..100 | ? {.\abundance.ps1 $_} 12 18 20 24 30 36 40 42 48 54 56 60 66 70 72 78 80 84 88 90 96 100 ``` [Answer] # [k](https://en.wikipedia.org/wiki/K_(programming_language)), ~~19 16~~ 15 bytes ``` {x<+/&~(!x)!'x} ``` Returns `1` for true, and `0` for false. [Try it online!](https://tio.run/##y9bNz/7/P82qusJGW1@tTkOxQlNRvaL2v4aioYGBpoNamjqI8R8A "K (oK) – Try It Online") ``` { } /function(x) (!x) /{0, 1, ..., x-1} ' /for each n in {0, 1, ..., x-1}: ! x / do (x mod n) ~ /for each, turn 0 -> 1, * -> 0 (map not) & /get indices of 1's +/ /sum (fold add) x< /check if x < the sum ``` [Answer] # MATL, 6 bytes ``` Z\sGE> ``` Outputs 1 for abundant numbers, 0 otherwise. ## How it works ``` Z\ % list the divisors of the implicit input s % add them G % push the input again E % double it > % compare % implicitly display result ``` [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 22 bytes ``` :[a/2|~a%b|\p=p+b}?p>a ``` This is an adaptation to the [QBIC primality test](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime/105049#105049). Instead of counting the divisors and checking if it's less than three, this sums the proper divisors. This runs only along half of `1 to n`, where the primality test runs through `1 to n` completely. Explanation: ``` : Get the input number, 'a' [a/2| FOR(b=1, b<=(a/2), b++) ~a%b IF a MOD b != 0 --> QBasic registers a clean division (0) as false. The IF-branch ('|') therefor is empty, the code is in the ELSE branch ('\') |\p=p+b THEN add b to runnning total p } Close all language constructs: IF/END IF, FOR/NEXT ?p>a Print '-1' for abundant numbers, 0 otherwise. ``` [Answer] # JavaScript (ES6), 33 bytes ``` let g = x=>(f=n=>--n&&n*!(x%n)+f(n))(x)>x ``` ``` <input type=number min=1 value=1 step=1 oninput="O.innerHTML=g(+value)"><br> <pre id=O>false</pre> ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 7 6 bytes ``` <Uâ1 x ``` Saved 2 bytes thanks to ETHproductions. Saved 1 byte thanks to obarakon. [Try it online!](https://tio.run/nexus/japt#@28TeniRoULF//@GRgA "Japt – TIO Nexus") [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 38 bytes ``` /..?%?(O;0I:^.<.>;rrw+s;rUO?-<...O0L.@ ``` [Try it here](https://ethproductions.github.io/cubix/?code=ICAgICAgLyAuIC4KICAgICAgPyAlID8KICAgICAgKCBPIDsKMCBJIDogXiAuIDwgLiA+IDsgciByIHcKKyBzIDsgciBVIE8gPyAtIDwgLiAuIC4KTyAwIEwgLiBAIC4gLiAuIC4gLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4K&input=MTIK&speed=25) ``` / . . ? % ? ( O ; 0 I : ^ . < . > ; r r w + s ; r U O ? - < . . . O 0 L . @ . . . . . . . . . . . . . . . . ``` `0I:` - sets up the stack with 0, n, n (s, n, d) `^` - start of the loop `)?` - decrement d and test for 0. 0 exits loop `%?` - mod against n and test. 0 causes `;rrw+s;rU` which rotates s to top and adds d, rotates s to bottom and rejoins loop `;<` - Cleanup and rejoin the loop. On exiting loop `;<` - Remove d from stack and redirect `-?` - Remove n from s and test, 0 `LOU@` turns left, outputs and exits, negatives `0O@` push zero, output and exits. positives `;O` remove difference and outputs n. The path then goes through to the left turn which redirects to the `@` exit [Answer] # Pure Bash, 37 bytes ``` for((;k++<$1;s+=$1%k?0:k)){((s>$1));} ``` *Thanks to @Dennis for rearranging the code -- saving 6 bytes and eliminating the incidental output to stderr.* The input is passed as an argument. The output is returned in the exit code: 0 for abundant, 1 for not abundant. Output to stderr should be ignored. Test runs: ``` for n in {1..100}; do if ./abundant "$n"; then echo $n; fi; done 2>/dev/null 12 18 20 24 30 36 40 42 48 54 56 60 66 70 72 78 80 84 88 90 96 100 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 [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") -2 bytes thanks to @Adám ``` ⊢<1⊥∘⍸0=⍳|⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/x91LbIxfNS19FHHjEe9OwxsH/VurgGK/U8Dyj7q7YMo7Go@tN74UdtEIC84yBlIhnh4Bv9PUzAy4EpTMLTkAupMO7QCqNXQwBAA "APL (Dyalog Unicode) – Try It Online") Explanation: ``` ⊢<1⊥∘⍸0=⍳|⊢ ⍝ Monadic function train ⍳ ⍝ Generate integers from 1 to input |⊢ ⍝ For each of the above, modulo the input 0= ⍝ Return a boolean vector where ones correspond ⍝ to zeroes ⍸ ⍝ Return the indices of the ones in the above vector ⍝ This results in a vector of the proper divisors of our input 1⊥∘ ⍝ Composed with the above, decode into unary base. ⍝ This has the same effect as summing the vector, but is used ⍝ here to comply with the function train format. ⊢< ⍝ Is the above sum greater than our input? ``` [Answer] # [Arn](https://github.com/ZippyMagician/Arn), [12 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn) ``` Ý░™€ºa^¬"/”& ``` [Try it!](https://zippymagician.github.io/Arn?code=PCgrXCR2eyEldn0xLT4=&input=MwoxMgoxOAoxOQoyMAoyNAoyOQozMA==) # Explained Unpacked: `<(+\$v{!%v}1->` ``` _ Variable initialized to STDIN; implied < Is less than ( Begin expression \ Fold with + Addition $ Filtered list v{ Block with key of v ! Boolean not _ Implied % Modulo v } End of block 1 Literal one -> Exclusive range _ Implied ) End of expression, implied ``` I should probably add a builtin fix for getting factors... [Answer] # [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 8 Bytes ``` ~_]k+2/< ``` ## Explained ``` ~_]k+2/< ~ # Zero Space Segment _ # Convert the input to an integer ] # Duplicate the input on the stack k+ # Get the sum of the divisors of the top of the stack 2/ # Divded by 2 < # Is the Input less than the sum of its divisors/2. ``` [Try it online!](https://tio.run/nexus/rprogn#@18XH5utbaRv8///fzMA "RProgN – TIO Nexus") [Answer] ## Batch, 84 bytes ``` @set/ak=%1*2 @for /l %%j in (1,1,%1)do @set/ak-=%%j*!(%1%%%%j) @cmd/cset/a"%k%>>31 ``` Outputs `-1` for an abundant number, `0` otherwise. Works by subtracting all the factors from `2n` and then shifting the result 31 places to extract the sign bit. Alternative formulation, also 84 bytes: ``` @set k=%1 @for /l %%j in (1,1,%1)do @set/ak-=%%j*!(%1%%%%j) @if %k% lss -%1 echo 1 ``` Outputs `1` for an abundant number. Works by subtracting all the factors from `n` and then comparing the result to to `-n`. (`set/a` is Batch's only way of doing arithmetic so I can't easily adjust the loop.) [Answer] # Perl 6, ~~72~~ 24 bytes ``` {$_ <sum grep $_%%*,^$_} ``` * Program argument: a. * Generate a list from `1..a`. * Take all the numbers that are divisors of `a`. * Sum them. * Check if that sum is greater than `a`. Thanks to @b2gills. [Answer] # J, 19 bytes Thanks to Conor O'Brien for cutting it to 19 bytes! `<[:+/i.#~i.e.]%2+i.` Previous: (34 bytes) `f=:3 :'(+/((i.y)e.y%2+i.y)#i.y)>y'` Returns 1 if it's abundant and 0 if it's not. **Output:** ``` f 3 0 f 12 1 f 11 0 f 20 1 ``` ]
[Question] [ In some nations there are recommendations or laws on how to form emergency corridors on streets that have multiple lanes per direction. (In the following we only consider the lanes going in the direction we are travelling.) These are the rules that hold in Germany: * If there is only one lane, everyone should drive to the right such that the rescue vehicles can pass on the left. * If there are two or more lanes, the cars on the left most lane should drive to the left, and everyone else should move to the right. ### Challenge Given the number `N>0` of regular lanes, output the layout of the lanes when an emergency corridor is formed using a string of `N+1` ASCII characters. You can use any two characters from ASCII code `33` up to `126`, one to denote the emergency corridor, and one for denoting the cars. Trailing or leading spaces, line breaks etc are allowed. ### Examples Here we are using `E` for the emergency corridor, and `C` for the cars. ``` N Output 1 EC 2 CEC 3 CECC 4 CECCC 5 CECCCC 6 CECCCCC etc ``` [Answer] # Python 2, 29 26 bytes ``` lambda n:10**n*97/30-1/n*9 ``` Example: ``` >>> f(1) 23 >>> f(2) 323 >>> f(3) 3233 ``` [Answer] # Python 3, ~~35~~ 33 bytes ``` lambda N:'C'*(N>1)+'EC'+'C'*(N-2) ``` Edit: dropping `f=` to save 2 bytes, thanks to [@dylnan](https://codegolf.stackexchange.com/users/75553/dylnan)'s reminder. [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUcHPSt1ZXUvDz85QU1vd1VldG8LVNdL8n5ZfpJCpkJmnUJSYl56qYahjrmnFpVBQlJlXopGpk6aRqan5HwA) To visualize it: ``` lambda N:'🚘'*(N>1)+'🚔🚘'+'🚘'*(N-2) ``` Output: ``` 1 🚔🚘 2 🚘🚔🚘 3 🚘🚔🚘🚘 4 🚘🚔🚘🚘🚘 5 🚘🚔🚘🚘🚘🚘 6 🚘🚔🚘🚘🚘🚘🚘 ``` [Try 🚔 online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUcHPSv3D/Fkz1LU0/OwMNbVBnClgAW24uK6R5v@0/CKFTIXMPIWixLz0VA1DHXNNKy6FgqLMvBKNTJ00jUxNzf8A) # Python 3, 40 bytes A straightforward solution: ``` lambda N:str(10**N).replace('100','010') ``` [Try it online!](https://tio.run/##BcExCoAwDADA3VdkayJFUhwEwS/4ApeqrQa0ltjF19e7/JXzSX2N01Ivf6@7h3mEtyg6btuZOg358ltA45iNNezYUI2PgoAkUJ@OgM4ONDaQVVJBsRGFqP4) [Answer] # [C (gcc)](https://gcc.gnu.org/), 32 bytes ``` f(n){printf(".%.*f"+1%n,n-1,0);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zuqAoM68kTUNJT1VPK01J21A1TydP11DHQNO69j9QRiE3MTNPQ1OhmoszLb9IQQMklKlgq2BoDaRsbBXMgLS2NlieM00jU9MaSMOMjMlTAvFruWr/AwA "C (gcc) – Try It Online") Uses `0` and `.` characters: ``` .0 0.0 0.00 0.000 0.0000 ``` [Answer] # Japt, ~~5~~ 4 bytes Uses `q` for cars and `+` for the corridor. ``` ç¬iÄ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=56xpxA==&input=OA==) Credit to Oliver who golfed 4 bytes off at the same time as I did. --- ## Explanation A short solution but a tricky explanation! The straightforward stuff first: The `ç` method, when applied to an integer, repeats its string argument that number of times. The `i` method takes 2 arguments (`s` & `n`) and inserts `s` at index `n` of the string it's applied to. Expanding the 2 unicode shortcuts used gives us `çq i+1`, which, when transpiled to JS becomes `U.ç("q").i("+",1)`, where `U` is the input. So we're repeating `q` `U` times and then inserting a `+` at index 1. The final trick is that, thanks to Japt's index wrapping, when `U=1`, `i` will insert the `+` at index `0`, whatever value you feed it for `n`. [Answer] # R, 50 bytes -11 thanks to Giuseppe! ``` pryr::f(cat("if"(x<2,12,c(21,rep(2,x-1))),sep="")) ``` Outputs 1 for emergency corridor and 2 for normal lanes ## My attempt, 61 bytes Nothing fancy to see here, but let's get R on the scoreboard =) ``` q=pryr::f(`if`(x<2,cat("EC"),cat("CE",rep("C",x-1),sep=""))) ``` Usage: ``` q(5) CECCCC ``` [Answer] # [Haskell](https://www.haskell.org/), ~~38~~ ~~34~~ 32 bytes ``` f 1="EC" f n="CE"++("C"<*[2..n]) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03B0FbJ1VmJK00hz1bJ2VVJW1tDyVnJRivaSE8vL1bzf25iZp5tbmKBb7yCRkFpSXBJkU@eXpqmQrShnp5Z7H8A "Haskell – Try It Online") [Answer] # Python 2, ~~30~~ ~~29~~ 28 bytes ``` lambda n:`10/3.`[1/n:n-~1/n] ``` Print `3` instead of `C` and `.` instead of `E`. **Explanation:** [Try it online.](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKsHQQN9YLyHaUD/PKk@3DkjF/k/LL1LIVMjMUyhKzEtP1TDUUTA00LTiUlAoKMrMK1HI1EnTyNT8DwA) ``` lambda n: # Method with integer parameter and string return-type `10/3.` # Calculate 10/3 as decimal (3.333333333) and convert it to a string [1/n # Take the substring from index 1 if `n=1`, 0 otherwise ,n-~ # to index `n+1` + 1/n] # 1 if `n=1`, 0 otherwise ``` --- # Python 2, ~~33~~ ~~32~~ ~~31~~ ~~29~~ 28 bytes ``` lambda n:1%n-1or'1-'+'1'*~-n ``` Prints `1` instead of `C` and `-` instead of `E`. -2 bytes thanks to *@ovs*. -1 byte thanks to *@xnor*. **Explanation:** [Try it online.](https://tio.run/##BcExDoAgDADA3Vd0MQWFxDqS@BMXjKJNtJCGxcWv411565VlbmlZ2x2fbY8ggXrxlBXJ44iEw@elpazAwAIa5TwMOaDJhg6gKEsFdsmwbT8) ``` lambda n: # Method with integer parameter and string return-type 1%n-1 # If `n` is 1: Return '-1' or # Else: '1-'+ # Return '1-', appended with: '1'*~-n # `n-1` amount of '1's ``` [Answer] # Pyth, ~~10~~ ~~9~~ 8 bytes ``` Xn1Q*NQZ ``` Uses `0` to denote the emergency corridor and `"`. [Try it here](http://pyth.herokuapp.com/?code=Xn1Q%2aNQZ&input=5&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5&debug=0) ### Explanation ``` Xn1Q*NQZ *NQ Make a string of <input> "s. n1Q At index 0 or 1... X Z ... Insert 0. ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 42 bytes ``` ,[[>]+[<]>-]>>[<]<[<]>+>+<[<-[--->+<]>.,>] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fJzraLlY72ibWTjfWzg5I24DY2nbaQFo3WldXF8iKtdPTsYv9/x8A "brainfuck – Try It Online") Takes input as char code and outputs as `V` being normal lanes and `W` being the cleared lane. (To test easily, I recommend replacing the `,` with a number of `+`s) ### How it Works: ``` ,[[>]+[<]>-] Turn input into a unary sequence of 1s on the tape >>[<]<[<] Move two cells left of the tape if input is larger than 1 Otherwise move only one space >+>+< Add one to the two cells right of the pointer This transforms: N=1: 0 0' 1 0 -> 0 2' 1 0 N>1: 0' 0 1 1* -> 0 1' 2 1* [<-[--->+<]>.,>] Add 86 to each cell to transform to Ws and Vs and print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` Î>∍1I≠ǝ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cJ/do45eQ89HnQuOz/3/3xgA "05AB1E – Try It Online") 0 is C and 1 is E. **Explanation** ``` Î> # Push 0 and input incremented -- [0, 4] ∍ # Extend a to length b -- [0000] 1I≠ # Push 1 and input falsified (input != 1) -- [0000, 1, 1] ǝ # Insert b in a at location C -- [0100] # Implicit display ``` [Answer] # [Octave](https://www.gnu.org/software/octave/) (MATLAB\*), ~~31 30 28 27~~ 22 bytes ``` @(n)'CE'(1+(n>1==0:n)) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI09T3dlVXcNQWyPPztDW1sAqT1Pzv6pjTklqUV5iSapCWn6RQnFibqpCUiWQl5xfmldipQDSFq2urmBigaQtlosrTcNQU0HV1RnIMAIynMEsYwgLxDSBMkFsUxgbxDGDc5z/AwA "Octave – Try It Online") The program works as follows: ``` @(n) %Anonymous function to take input n>1==0:n %Creates [1 0] if n is 1, or [0 1 (0 ...)] otherwise 1+( ) %Converts array of 0's and 1's to 1-indexed 'CE'( ) %Converts to ASCII by addressing in string ``` The trick used here is XNORing the seed array of `0:n` with a check if the input is greater than 1. The result is that for `n>1` the seed gets converted to a logical array of `[0 1 (0 ...)]` while for `n==1` the seed becomes inverted to `[1 0]`, achieving the necessary inversion. The rest is just converting the seed into a string with sufficient appended cars. --- (\*) The TIO link includes in the footer comments an alternate solution for the same number of bytes that works in MATLAB as well as Octave, but it results in a sequence of '0' and '1' rather than 'E' and 'C'. For completeness, the alternate is: ``` @(n)['' 48+(n>1==0:n)] ``` --- * Saved 1 byte by using `n==1~=0:1` rather than `0:1~=(n<2)`. `~=` has precedence over `<`, hence the original brackets, but is seems that `~=` and `==` are handled in order of appearance so by comparing with 1 we can save a byte. * Saved 2 bytes by changing where the negation of `2:n` is performed. This saves a pair of brackets. We also have to change the `~=` to `==` to account for the fact that it will be negated later. * Saved 1 byte using `<` again. Turns out that `<` has same precedence as `==` after all. Placing the `<` calculation before the `==` ensures correct order of execution. * Saved 5 bytes by not creating two separate arrays. Instead relying on the fact that the XNOR comparison will convert a single range into logicals anyway. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 bytes ``` ’0ẋ⁾0E;ṙỊ ``` [Try it online!](https://tio.run/##AR8A4P9qZWxsef//4oCZMOG6i@KBvjBFO@G5meG7iv///zEw "Jelly – Try It Online") Full program. Uses `0` instead of `C`. [Answer] # C (gcc), 39 bytes ``` f(n){printf("70%o"+!n,7|(1<<3*--n)-1);} ``` [Try it online!](https://tio.run/##NYzBDsIgEETvfMWKMWFFjMQDB9Av8WKo6CZ2MbWeKt@OtImnmbx5mWjuMdY1cXx@uhuE99hR3j/ONSnG6TUQj0lJd9hkqVe8c19lQzhujWE0Fn2pTYD@SqxQTAIg5QHUzAhOYH2LAK6F1tjW2WiOIvRL@/9fWC6kiFJ/ "C (gcc) – Try It Online") Borrowed and adapted the printf trick from [ErikF's answer](https://codegolf.stackexchange.com/a/161306/20779). [Answer] # Python 3, 32 bytes ``` lambda n:f"{'CE'[n<2:]:C<{n+1}}" ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKk2pWt3ZVT06z8bIKtbK2aY6T9uwtrhW6X9afpFCnkJmnkJRYl56qoahjpmmFZcCEBQUZeaVaOTpKKRp5Glq/gcA "Python 3 – Try It Online") Uses an f-string expression to format either`'E'`or`'CE'` padded on the right with`'C'`so it has width of`n+1`. ``` f"{ : } a Python 3 f-string expression. 'CE'[n<2:] string slice based on value of n. : what to format is before the ':' the format is after. C padding character < left align {n+1} minimum field width based on n ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~100~~ 66 bytes ``` {({}[()]<((((()()()()){}){}){}())>)}{}(({}<>)())<>{<>{({}<>)<>}}<> ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1qjujZaQzPWRgMENCFQs7oWgoBMO81aIA1UZWMHkrGxqwYiCNfGrhZI/f9v@F/XEQA "Brain-Flak – Try It Online") Uses `"` as the emergency lane and `!` as the normal lanes. [Answer] # C#, 34 bytes ``` n=>n++<2?"EC":"CE".PadRight(n,'C') ``` [Try it online!](https://tio.run/##LY09C8IwFADn5lc8upgQLepoWx2KTgpFBwdxCOmHD9oXyIuCSH97Leh0yx1neWHZjrYzzFB613rTw0dEHExACy@HFZwMkuTgkdrbHYxvWU2KuLw51H1yeJLNkMIcfsoWGshHyrekdbbexfsi3sTFPk5KU52xfQRJ81kxU@koROM8yKkFhBxW6YQMVsuJWisR/QeFI3ZdnVw9hvqIVMtGolKpENEghvEL) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~21 17~~ 16 bytes ``` (-≠∘1)⌽'E',⍴∘'C' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P9UnMS@1@FHbBA3dR50LHnXMMNR81LNX3VVd51HvFiBX3Vn9//9HbRMh6g6teNS72cgAAA) Thanks to Erik for saving 4 bytes and Adám for one further byte. ### How? ``` (-≠∘1)⌽'E',⍴∘'C' ⍝ Tacit function ⍴∘'C' ⍝ Repeat 'C', according to the input 'E', ⍝ Then append to 'E' ⌽ ⍝ And rotate 1) ⍝ 1 ≠∘ ⍝ Different from the input? Returns 1 or 0 (- ⍝ And negate. This rotates 0 times if the input is 1, and once if not. ``` [Answer] # [Haskell](https://www.haskell.org/), ~~35~~ ~~33~~ 32 bytes *2 bytes saved thanks to Angs, 1 byte saved thanks to Lynn* ``` (!!)$"":"EC":iterate(++"C")"CEC" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P91WQ1FRU0VJyUrJ1VnJKrMktSixJFVDW1vJWUlTyRko9j83MTPPtqAoM69EJV3B5D8A "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), ~~32~~ ~~30~~ 29 bytes *This is zero indexed so it doesn't comply with the challenge* ``` g=(!!)$"EC":iterate(++"C")"CEC" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P91WQ1FRU0XJ1VnJKrMktSixJFVDW1vJWUlTyRko9j83MTPPtqAoM69EJV3B@D8A "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 30 bytes *This doesn't work because output needs to be a string* ``` f 1=21 f 2=121 f n=10*f(n-1)+1 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03B0NbIkCtNwcjWEEzn2RoaaKVp5Okaamob/s9NzMyzLSjKzCtRSVMw@Q8A "Haskell – Try It Online") Here we use numbers instead of strings, `2` for the emergency corridor, `1` for the cars. We can add a `1` to the end by multiplying by 10 and adding `1`. This is cheaper because we don't have to pay for all the bytes for concatenation and string literals. It would be cheaper to use `0` instead of `1` but we need leading zeros, which end up getting trimmed off. [Answer] # [Python 3](https://docs.python.org/3/), ~~30~~ 29 bytes ``` lambda n:"CEC"[~n:]+"C"*(n-2) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPSsnZ1Vkpui7PKlZbyVlJSyNP10jzf1p@kUKmQmaeQlFiXnqqhqGOuaaVQkFRZl6JRqZOmkampuZ/AA "Python 3 – Try It Online") OK, there is a lot of Python answers already, but I think this is the first sub-30 byter among those still using "E" and "C" chars rather than numbers. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 28 bytes ``` n=>n<2?21:"12".padEnd(n+1,1) ``` [Try it online!](https://tio.run/##bck5CoAwEADA3mekSvCAXY9CjFY@JBgVRTai4vcjggcS25lR7WptlmHeQjK6tZ20JEsqsELIGSCLZqVr0px8CEDYxtBqpjaaTM87DkJKhsCE93U8HX4ivsKd5B630qfcy9470x4 "JavaScript (Node.js) – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 [bytes](https://github.com/abrudz/SBCS) ``` ≡∘1⌽'CE',1↓⍴∘'C' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HnwkcdMwwf9exVd3ZV1zF81Db5Ue8WoJC6szpQtneugm9iZp5CWmlecklmfp6CRnFpUm5mcTGQrcnFlabwqG2CAj4zuLhAZoSkFpekFsFN4eIqAQpA9PZO1VG3UlDXSUOoVEhOLE4thioyhFBGEMoYQplAKFMIZQahzCGUBYSyhGo3AAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü♣àj#F ``` [Run and debug it](https://staxlang.xyz/#p=8105856a234620&i=1%0A2%0A3%0A20&a=1&m=2) This uses the characters "0" and "1". This works because when you rotate an array of size 1, it doesn't change. Unpacked, ungolfed, and commented, it looks like this. ``` 1]( left justify [1] with zeroes. e.g. [1, 0, 0, 0] |) rotate array right one place 0+ append a zero $ convert to string ``` [Run this one](https://staxlang.xyz/#c=1]%28%09left+justify+[1]+with+zeroes.+e.g.+[1,+0,+0,+0]%0A%7C%29%09rotate+array+right+one+place%0A0%2B%09append+a+zero%0A%24%09convert+to+string&i=1%0A2%0A3%0A20&m=2) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 19 bytes ``` n=>--n?"0"+10**n:10 ``` [Try it online!](https://tio.run/##DcVBCoAgEADAc71i8aSJoZcOlfUWqQxDdkPD75tzmccVl48U3k8hnVf1tqLdlMKdaSaNHgacja6eEvDiEgSwYJbWamFqSyn67iDMFK8x0s09D0Is9Qc "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~27~~ ~~20~~ 19 bytes ``` $_=1x$_;s/1?\K1/E1/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tawQiXeuljf0D7G21Df1VD//3/jf/kFJZn5ecX/dQsA "Perl 5 – Try It Online") Saved a byte by using `1` for the cars and `E` for the emergency corridor. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ⁵*ṾṙỊṙ ``` Displays car lanes as **0**, the emergency lane as **1**. [Try it online!](https://tio.run/##y0rNyan8//9R41athzv3Pdw58@HuLiD53@xw@6OmNZH/AQ "Jelly – Try It Online") ### How it works ``` ⁵*ṾṙỊṙ Main link. Argument: n ⁵* Compute 10**n. Ṿ Uneval; get a string representation. ṙỊ Rotate the string (n≤1) characters to the left. ṙ Rotate the result n characters to the left. ``` [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~141~~ ~~104~~ 103 bytes ``` [S S S N _Push_0][S N S _Duplicate_0][T N T T _Read_STDIN_as_number][T T T _Retrieve][S S S T S N _Push_2][T S S T _Subtract][S N S _Duplicate_input-2][N T T N _If_negative_Jump_to_Label_-1][S S S T N _Push_1][S N S _Duplicate_1][T N S T _Print_as_integer][S S T T N _Push_-1][T N S T _Print_as_integer][T S S T _Subtract][N S S T N _Create_Label_LOOP][S N S _Duplicate][N T T S N _If_negative_Jump_to_EXIT][S S S T N _Push_1][S N S _Duplicate_1][T N S T _Print_as_integer][T S S T _Subtract][N S N T N _Jump_to_LOOP][N S S N _Create_Label_-1][T N S T _Print_as_integer][N S S S N _Create_Label_EXIT] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. Prints `1` instead of `C` and `-` instead of `E`. -1 byte thanks to *@JoKing* by suggesting the use of `1` and `-1` instead of `0` and `1`. ### Explanation in pseudo-code: ``` Integer i = STDIN-input as integer - 2 If i is negative (-1): Print i (so print "-1") Else: Print "1-1" Start LOOP: If i is negative: EXIT program Print "1" i = i-1 Go to the next iteration of the LOOP ``` ### Example runs: **Input: `1`** ``` Command Explanation Stack Heap STDIN STDOUT STDERR SSSN Push 0 [0] SNS Duplicate top (0) [0,0] TNTT Read STDIN as integer [0] {0:1} 1 TTT Retrieve heap at 0 [1] {0:1} SSSTSN Push 2 [1,2] {0:1} TSST Subtract top two [-1] {0:1} SNS Duplicate input-2 [-1,-1] {0:1} NTSN If neg.: Jump to Label_-1 [-1] {0:1} NSSN Create Label_-1 [-1] {0:1} TNST Print top as integer [] {0:1} -1 NSSSN Create Label_EXIT [] {0:1} error ``` [Try it online](https://tio.run/##VYrLCcAwDEPP0hRaoSOVEkhvgRQ6vivbp9rgz9N75/2Mvc5rREiiG0SWP4io6Q0m6FxJrflAwQ4s6Wd1aM@07EwZcXw) (with raw spaces, tabs and new-lines only). Stops with error: Exit not defined. **Input: `4`** ``` Command Explanation Stack Heap STDIN STDOUT STDERR SSSN Push 0 [0] SNS Duplicate top (0) [0,0] TNTT Read STDIN as integer [0] {0:4} 4 TTT Retrieve heap at 0 [4] {0:4} SSSTSN Push 2 [4,2] {0:4} TSST Subtract top two [2] {0:4} SNS Duplicate input-2 [2,2] {0:4} NTSN If neg.: Jump to Label_-1 [2] {0:4} SSSTN Push 1 [2,1] {0:4} SNS Duplicate top (1) [2,1,1] {0:4} TNST Print as integer [2,1] {0:4} 1 SSTTN Push -1 [2,1,-1] {0:4} TNST Print as integer [2,1] {0:4} -1 TSST Subtract top two [1] {0:4} NSSTN Create Label_LOOP [1] {0:4} SNS Duplicate top (1) [1,1] {0:4} NTTSN If neg.: Jump to Label_EXIT [1] {0:4} SSSTN Push 1 [1,1] {0:4} SNS Duplicate top (1) [1,1,1] {0:4} TNST Print as integer [1,1] {0:4} 1 TSST Subtract top two [0] {0:4} NSNTN Jump to Label_LOOP [0] {0:4} SNS Duplicate top (0) [0,0] {0:4} NTTSN If neg.: Jump to Label_EXIT [0] {0:4} SSSTN Push 1 [0,1] {0:4} SNS Duplicate top (1) [0,1,1] {0:4} TNST Print as integer [0,1] {0:4} 1 TSST Subtract top two [-1] {0:4} NSNTN Jump to Label_LOOP [-1] {0:4} SNS Duplicate top (-1) [-1,-1] {0:4} NTTSN If neg.: Jump to Label_EXIT [-1] {0:4} NSSSN Create Label_EXIT [-1] {0:4} error ``` [Try it online](https://tio.run/##VYrLCcAwDEPP0hQaoguVEkhvgRQ6vivbp9rgz9N75/2Mvc5rREiiG0SWP4io6Q0m6FxJrflAwQ4s6Wd1aM@07EwZcXw) (with raw spaces, tabs and new-lines only). Stops with error: Exit not defined. [Answer] # [AutoHotkey](https://autohotkey.com/docs/AutoHotkey.htm) 32 bytes Replaces the letter "C" with "EC" unless amount of C > 1, then it sends "CEC" and exits the app. ``` ::C::EC :*:CC::CEC^c ^c::ExitApp ``` C => EC CC => CEC then exits the program. Any further Cs will be entered after the program exits. [Answer] # APL+WIN, ~~20~~ 16 bytes 4 bytes saved thanks to Adám Prompts for integer n: ``` (-2≠⍴n)⌽n←1⎕/⍕10 ``` 1 for emergency corridor o for cars. [Answer] # [J](http://jsoftware.com/), 11 bytes ``` 1":1&<=i.,] ``` [Try it online!](https://tio.run/##y/r/P81WT8FQycpQzcY2U08n9n9qcka@QpqanYKhdqaeoel/AA "J – Try It Online") Based on ngn’s [comment](https://codegolf.stackexchange.com/questions/161281/make-an-emergency-corridor/161294#comment391068_161294). 🚘 and 🚔: [`1&<,~/@A.'🚔',~'🚘'$~,&4`](https://tio.run/##y/r/P81WT8FQzUanTt/BUU/9w/xZU9R16kD0DHWVOh01k/@pyRn5CmlqdgqG2pl6hob/AQ "J – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/create_explanation.py), ~~7~~ 6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ú░\┴╜╪ ``` [Try it online.](https://tio.run/##AS8A0P9tYXRoZ29sZv9xIiDihpIgInH/w7rilpFc4pS04pWc4pWq//8xCjIKMwo0CjUKOQ) Output `1` for `E` and `0` for `C`. **Explanation:** ``` ú # 10 to the power of the (implicit) input # i.e. 1 → 10 # i.e. 4 → 10000 ░ # Convert it to a string # i.e. 10 → "10" # i.e. 10000 → "10000" \ # Swap so the (implicit) input is at the top of the stack again ┴╜ # If the input is NOT 1: ╪ # Rotate the string once towards the right # i.e. "10000" and 4 → "01000" # Output everything on the stack (which only contains the string) implicitly ``` ]
[Question] [ I've always liked screens full of randomly colored pixels. They're interesting to look at and the programs that draw them are fun to watch. # The challenge Fill your screen, or a graphical window, with colored pixels. # The rules * Your program must have an even chance of picking **all colors** (i.e in the range `#000000` to `#FFFFFF`), or all colors that can be displayed on your system. * Your program must continue to display random pixels until manually stopped (it cannot terminate on its own). * Pixels can be any size, as long as your output has at least **40x40** "pixels". * Your program must run at such a speed that it can replace every pixel on the screen/window at least once after running for three minutes. * Your program must choose **truly random** colors and points to replace, i.e. random with all points/colors equally likely. It cannot just *look* random. It must use a pRNG or better, and the output cannot be the same every time. * Your program must have an equal chance of picking all colors **each iteration**. * Your program must replace only one pixel at once. * Your program cannot use the internet nor your filesystem (`/dev/random` and `/dev/urandom` excepted). # Example Your output could look like this if stopped at a random time: ![](https://i.stack.imgur.com/WL3xZ.png) # The winner The shortest answer in each language wins. Have fun! [Answer] # Minecraft 1.12 Redstone Command Blocks, ~~4,355~~ 2,872 bytes [![Minecraft screenshot with armor stands and map](https://i.stack.imgur.com/SVQUt.png)](https://i.stack.imgur.com/SVQUt.png) (Size determined by saved structure block file size.) Here is a [full YouTube overview](https://youtu.be/M5Ve4LfQAT4), but I'll try to outline the code below. **Setup Routine:** [![2 rows of command blocks for setup](https://i.stack.imgur.com/kznmg.png)](https://i.stack.imgur.com/kznmg.png) This sets up the 40x40 grid of Minecraft armor stands. Armor stands are necessary because Minecraft has *no way to substitute variables into world coordinates*. So the workaround is to *refer to the location* of these armor stand entities. ``` (impulse) summon armor_stand 2 ~ 1 {CustomName:"A"} /create named armor stand (chain) fill -2 ~ -2 43 ~ 43 stone /create big stone square (chain) fill -1 ~ -1 42 ~ 42 air /leave just a ring of stone (chain) setblock -4 ~ -12 redstone_block /kicks off next sequence ``` This named armor stand is basically our "cursor" to place all the armor stands that we will need. The redstone block in the last step "powers" nearby blocks (including our command blocks), so kicks off the next loop: ``` (repeat) execute @e[name=A] ~ ~ ~ summon armor_stand ~-1 ~ ~ /create new armor stand (chain) tp @e[name=A] ~1 ~ ~ /move "cursor" one block (chain) execute @e[name=A] ~ ~ ~ testforblock ~1 ~ ~ stone /if at end of row, (conditional) tp @e[name=A] ~-40 ~ ~1 /go to start of next row (chain) execute @e[name=A] ~ ~ ~ testforblock ~ ~ ~2 stone /If at last row (conditional) setblock ~6 ~ ~ air /stop looping (conditional) kill @e[name=A] /kill cursor ``` At this point our grid is complete: [![Completed armor stand grid](https://i.stack.imgur.com/bTQQm.png)](https://i.stack.imgur.com/bTQQm.png) **Random Color Selector** [![Color and Pixel Selector](https://i.stack.imgur.com/t7Yxc.png)](https://i.stack.imgur.com/t7Yxc.png) The purple repeaters in the center of this picture choose a random color via the following command: ``` (repeat) execute @r[type=armor_stand,r=9] ~ ~ ~ setblock ~ ~-2 ~ redstone_block ``` That "@r[]" is the magic sauce, it *selects a random entity in the world that matches the given conditions*. In this case, it *finds an armor stand inside a radius of 9 blocks*, and we've set up 16 armor stands, one for each wool color. Under the selected color, it places a redstone block (which powers the two command blocks on either side). **Random Pixel Selector** Placing the redstone block under the selected wool color triggers two more command blocks: ``` (impulse) execute @r[type=armor_stand] ~ ~ ~ setblock ~ ~3 ~ wool X (impulse) setblock ~ ~ ~1 air ``` This first line uses our same magic *@r* command to choose *any armor stand on the entire map* (no radius restriction, so that includes the 40x40 grid), and places a wool of the selected color above its head. The X determines the color, and ranges from 0 to 15. The second command removes the redstone block so it is ready to go again. I have 5 purple repeater blocks, and redstone works in "ticks" 20 times a second, so I'm placing 100 pixels per second (minus some color overlaps). I've timed it, and I usually get the entire grid covered in about 3 minutes. This was fun, I'll try to look for other challenges that might also work in Minecraft. Huge thanks to lorgon111 for his [YouTube Command Block tutorial series](https://www.youtube.com/playlist?list=PLHYAYMSbpcvulT34yXXN6SjTgpi0bOgka). **EDIT: Made some serious reductions in the size of the saved structure, now at 2,872 saved bytes**: [![closer command blocks with visible void blocks](https://i.stack.imgur.com/4kcLB.png)](https://i.stack.imgur.com/4kcLB.png) 1. Scooted things in a bit (in all 3 dimensions) so I could reduce the overall size of the saved area. 2. Changed the different colored wools to stone, they were just decorative anyway. 3. Removed the glowstone lamp. 4. Changed all air blocks to void blocks (the red squares). Tested by pulling the saved structure into a new world, everything still works as designed. **EDIT 2**: [Read-only Dropbox link to the NBT structure file](https://www.dropbox.com/s/y2cujwjz1huge0y/random_pixels.nbt?dl=0) Walk through is [in my YouTube video](https://www.youtube.com/watch?v=M5Ve4LfQAT4), but here are the steps: 1. In Minecraft 1.12, create a new creative superflat world using the "Redstone Ready" preset. Make it peaceful mode. 2. Once the world exists, copy the NBT file into a new `\structures` folder you create under the current world save. 3. Back in the game, do `/give @p structure_block`, and `/tp @p -12, 56, -22` to jump to the right spot to get started. 4. Dig a hole and place the structure block at -12, 55, -22. 5. Right-click the structure block, click the mode button to switch it to "Load". 6. Type in "random\_pixels", turn "include entities" ON, and click "Load" 7. If it finds the structure file, it will preview the outline. Right-click again and click "load" to bring the structure into the world. 8. Press the button to run the setup routine. 9. When it completes, flip the switch to run the wool randomization. [Answer] # sh + ffmpeg, 52 bytes ``` ffplay -f rawvideo -s cif -pix_fmt rgb24 /dev/random ``` Does ffmpeg count as an esolang? :D Sadly the pix\_fmt is required, as ffmpeg defaults to yuv420p. That fails the "must have equal likelihood of every possible pixel color" requirement. Conveniently, `cif` is a shortcut for a fairly large video size that uses less space than "40x40". ![](https://unascribed.com/f/78270662_demo.gif) Unsurprisingly, optimizing this gif with gifsicle did absolutely nothing. It's 4MiB. [Answer] # C on POSIX, ~~98~~ ~~96~~ ~~95~~ 92 bytes -3 thanks to Tas ``` #define r rand() f(){for(srand(time(0));printf("\e[%d;%dH\e[%d;4%dm ",r%40,r%40,r%2,r%8););} ``` This chooses between 16 colors (dark grey, red, green, blue, orange, cyan, purple, light grey, black, pink, light blue, yellow, light cyan, magenta, white) and prints them directly to the terminal. Note that if your GPU is too slow, this may seem like it's updating the entire screen at once. It's actually going pixel by pixel, but C is fast. [![colors](https://i.stack.imgur.com/DP6Pp.png)](https://i.stack.imgur.com/DP6Pp.png) Alternate solution that makes the colors more distinct: ``` f(){for(srand(time(0));printf("\e[%d;%dH\e[%d;3%dm█",rand()%40,rand()%40,rand()%2,rand()%8););} ``` Proof that it goes pixel by pixel (screenshot from alternate program): [![3d!!!](https://i.stack.imgur.com/6IMrv.png)](https://i.stack.imgur.com/6IMrv.png) Wow, that looks almost 3-dimensional... [Answer] # JS+HTML ~~162+32 (194)~~ 124+13 (137) bytes Thanks to Luke and other commenters for saving me lots of bytes. ``` r=n=>n*Math.random()|0 setInterval("b=c.getContext`2d`;b.fillStyle='#'+r(2**24).toString(16);b.fillRect(r(99),r(99),1,1)",0) ``` ``` <canvas id=c> ``` [Answer] # MATL, 28 bytes ``` 40tI3$l`3l2$r,40Yr]4$Y(t3YGT ``` Try it at [**MATL Online**](https://matl.io/?code=40tI3%24l%603l2%24r%2C40Yr%5D4%24Y%28tOYG+.5Y.+T&inputs=&version=20.0.0). I have added a half-second pause (`.5Y.`) to this version. [![enter image description here](https://i.stack.imgur.com/U4GhC.gif)](https://i.stack.imgur.com/U4GhC.gif) **Explanation** ``` 40 % Push the number literal 40 to the stack t % Duplicate I % Push the number 3 to the stack 3$l % Create a 40 x 40 x 3 matrix of 1's (40 x 40 RGB image) ` % Do...while loop 3l1$r % Generate 3 random numbers (RGB) , % Do twice loop 40Yr % Generate two integers between 1 and 40. These will be the ] % row and column of the pixel to replace 4$Y( % Replace the pixel with the random RGB value t % Make a copy of the RGB image 3YG % Display the image T % Push a literal TRUE to create an infinite loop ``` [Answer] # TI-BASIC (84+C(S)E only), ~~37~~ 35 bytes ``` :For(A,1,5! :For(B,1,5! :Pxl-On(A,B,randInt(10,24 :End :End :prgmC //"C" is the name of this program ``` Due to hardware limitations, this will eventually crash, since every time a program is nested within a program in **TI-BASIC**, 15 KB of RAM are allocated to "keep a bookmark" in the parent program. This would run fine on a "theoretical" calculator with infinite RAM, but if we want it to run indefinitely on a real calculator, we can just wrap it in a `While 1` loop for an extra **2** bytes: ``` :While 1 :... :End ``` The TI-83 family calculators with color screens (TI 84+CE and CSE) support 15 colors. They have color codes `10` through `24`. This cycles through all the pixels in a 120 by 120 (`5!`) square and assigns each a random color. **Result:** [![enter image description here](https://i.stack.imgur.com/h0yGq.png)](https://i.stack.imgur.com/h0yGq.png) [Answer] # Bash + coreutils, ~~59~~ 56 bytes ``` for((;;)){ printf "\e[48;5;`shuf -i 0-16777215 -n1`m ";} ``` `\e[48;5;COLORm` is the escape secuence to background color. Each "pixel" has the chance to be in the [0..16777215] range every time. [Answer] # MATLAB, 56 bytes ``` x=rand(40,40,3);while imagesc(x),x(randi(4800))=rand;end ``` Output looks like the image below. One "pixel" changes at a time, and only one of the RGB-colors changes. Why? The colors in MATLAB are represented as a 3D-matrix, one layer for R,G and B. The code above changes only one of the layers per iteration. All pixels and all layers can be changed, so if you wait a bit all colors are equally possible in all positions. Add `pause(t)` inside the loop to pause `t` seconds between each image. You must stop it with `Ctrl`+`C`. [![enter image description here](https://i.stack.imgur.com/4M7Qj.jpg)](https://i.stack.imgur.com/4M7Qj.jpg) [Answer] ## Javascript+HTML 118 + 13 (131 bytes) ``` r=_=>255*Math.random()|0;setInterval('x=c.getContext`2d`;x.fillRect(r(),r(),1,1,x.fillStyle=`rgb(${[r(),r(),r()]})`)') ``` ``` <canvas id=c> ``` * This will produce evenly distributed RGB colors. You cannot use Hex colors without proper padding as numbers like `#7` is not a valid color, or `#777` and `#777777` are the same color (2x the odds) * The canvas element is 300x150 by default, but I'm actually drawing on a 255x255 square, so there are off canvas pixels, so the effective area is 255x150. * Works only on Google Chrome. [Answer] ## Processing, 90 bytes ``` void draw(){float n=noise(millis());int i=(int)(n*9999);set(i%99,i/99,(int)(n*(-1<<24)));} ``` [![enter image description here](https://i.stack.imgur.com/6a6RA.gif)](https://i.stack.imgur.com/6a6RA.gif) expanded and commented: ``` void draw(){ float n=noise(millis());//compute PRNG value int i=(int)(n*9999); //compute 99x99 pixel index set(i%99,i/99, //convert index to x,y (int)(n*(-1<<24))); //PRNG ARGB color = PRNG value * 0xFFFFFFFF } ``` Ideally I could use a pixel index instead of x,y location, but Processing's [`pixels[]`](https://processing.org/reference/pixels.html) access requires `loadPixels()` pre and `updatePixels()` post, hence the use of [`set()`](https://processing.org/reference/set_.html). `point()` would work too, but has more chars and requires `stroke()`. The random area is actually 99x99 to save a few bytes(instead of 100x100), but that should cover 40x40 with each pixel in such an area to be replaced. Perlin [noise()](http://file:///Users/George/Downloads/ProcessingDNLD/processing-3.2.3-macosx/Processing3.2.3.app/Contents/Java/modes/java/reference/noise_.html) is is used instead of [random()](http://file:///Users/George/Downloads/ProcessingDNLD/processing-3.2.3-macosx/Processing3.2.3.app/Contents/Java/modes/java/reference/random_.html) to keep it more pseudo-random and a byte shorter. The value is computed once, but used twice: once for the random position, then again for the colour. The colour is actually `ARGB`(00000000 to FFFFFFFF) (not RGB) (bonus points ? :D). [Answer] # x86 machine language (real mode) for IBM PC, ~~20~~ 19 bytes ``` 0: b8 12 00 mov $0x12,%ax 3: 31 db xor %bx,%bx 5: cd 10 int $0x10 7: 0f c7 f0 rdrand %ax a: 88 e1 mov %ah,%cl c: 0f c7 f2 rdrand %dx f: b4 0c mov $0xc,%ah 11: eb f2 jmp 0x5 ``` This requires a processor with the `rdrand` instruction and a VGA adapter (real or emulated). The above can be copied into a boot block or MS-DOS \*.COM file. To try this out, compile the following and save the output to a file like `floppy.img` and boot the image on a virtual machine. ``` #include<stdio.h> #include<string.h> #include<unistd.h> int main(){ char buffer[ 1440*1024 ]; memcpy( buffer, "\xb8\x12\x00\x31\xdb\xcd\x10\x0f\xc7\xf0\x88\xe1\x0f\xc7\xf2\xb4\x0c\xeb\xf2", 20 ); memcpy( buffer + 510, "\x55\xaa", 2 ); write( 1, buffer, sizeof buffer ); } ``` [Answer] # Excel VBA, ~~131~~ ~~102~~ 85 Bytes Anonymous VBE immediate window function that uses a helper function (see below) to output an array of randomly colored cells to the range `A1:AN40` of the activesheet object. *Note: This solution is restricted to 32-Bit installs of MS Excel (and therefore of Office as a whole) as `8^8` will not compile on 64-Bit versions of VBA* ``` Randomize:Cells.RowHeight=48:For Each c In[A1:AN40]:c.Interior.Color=(8^8-1)*Rnd:Next ``` ## Sample Output [![Randomized Cell Colors](https://i.stack.imgur.com/Aaxro.png)](https://i.stack.imgur.com/Aaxro.png) ## Previous Version ``` Randomize:Cells.ColumnWidth=2:For Each c In Range("A1:AN40"):c.Interior.Color=RGB(n,n,n):Next ``` ## Helper Function Outputs a random int in the range [0,255] ``` Function n n=Int(255*Rnd) End Function ``` [Answer] ## C++ on Windows, 125 bytes ``` #include<Windows.h> #include<ctime> #define r rand()%256 int main(){for(srand(time(0));;)SetPixel(GetDC(0),r,r,RGB(r,r,r));} ``` Newlines necessary and included in byte count. Loops forever, randomly picks a position between 0 and 255 (inclusive) for row and column values, assigns random R,G,B values between 0-255 (inclusive) [Answer] # C#, ~~369~~ ~~288~~ 287 bytes ``` namespace System.Drawing{class P{static void Main(){var g=Graphics.FromHwnd((IntPtr)0);var w=Windows.Forms.Screen.GetBounds(Point.Empty);for(var r=new Random();;)g.FillRectangle(new SolidBrush(Color.FromArgb(r.Next(256),r.Next(256),r.Next(256))),r.Next(w.Width),r.Next(w.Height),1,1);}}} ``` *Saved 88 bytes thanks to @CodyGray.* A full program that get's the handle to the screen and it's size and then starts randomly drawing pixels on it. Note that this might grind your graphics card to a halt when ran. Also if the screen or any control decides to repaint at any time the pixels will be lost and have to be redrawn. Note: When running keep focus on the window as to kill it you have to either Alt+F4 or press the close button and doing so when you can't see the screen is a bit hard. I couldn't record this working, with ScreenToGif, as that kept forcing a repaint so the pixels would get removed. However, here is a screenshot of it running after about 10-15 seconds, any longer and I think I may have ground my PC to a halt! The gap in the top right corner is where the screen forced a repaint just as I took the screenshot. [![Full version example](https://i.stack.imgur.com/dANJd.png)](https://i.stack.imgur.com/dANJd.png) Full/Formatted version: ``` namespace System.Drawing { class P { static void Main() { var g = Graphics.FromHdc((IntPtr)0); var w = Windows.Forms.Screen.GetBounds(Point.Empty); for (var r = new Random();;) g.FillRectangle(new SolidBrush(Color.FromArgb(r.Next(256), r.Next(256), r.Next(256))), r.Next(w.Width), r.Next(w.Height), 1, 1); } } } ``` --- A version for ~~308~~ ~~227~~ 226 bytes that only draws on the region 0-40: ``` namespace System.Drawing{class P{static void Main(){var g=Graphics.FromHdc((IntPtr)0);for(var r=new Random();;)g.FillRectangle(new SolidBrush(Color.FromArgb(r.Next(256),r.Next(256),r.Next(256))),r.Next(40),r.Next(40),1,1);}}} ``` Example output for this one: [![Small example output](https://i.stack.imgur.com/sKJmD.png)](https://i.stack.imgur.com/sKJmD.png) --- [Answer] # C# Console, 233 220 ~~189~~ 188 bytes ``` namespace System{using static Console;class P{static void Main(){for(var r=new Random();;){BackgroundColor=(ConsoleColor)r.Next(16);SetCursorPosition(r.Next(40),r.Next(40));Write(" ");}}}} ``` [![enter image description here](https://i.stack.imgur.com/LMyP2.png)](https://i.stack.imgur.com/LMyP2.png) Uses "all" (windows) 16 console colors. Thanks for the "feature" to be able to alias classes in C# via the `using` directive. **Edit #1** * Removed some spaces. * Removed zeros from Random.Next() * Went to `namespace system{...}` **Edit #2** * Minimum size of grid is 40x40 * One byte by declaring Random in for loop header * Removed `public` from Main method **Edit #3** Turns out `using C=Console;` is **not** the best there is. `using static Console` is much like the VB.Net way to "Import" classes I give up: TheLethalCoder made this happen --- Original code for adapting window size at 207 bytes: ``` namespace System{using static Console;class P{static void Main(){for(var r=new Random();;){BackgroundColor=(ConsoleColor)r.Next(16);SetCursorPosition(r.Next(WindowWidth),r.Next(WindowHeight));Write(" ");}}}} ``` Original Image: [![enter image description here](https://i.stack.imgur.com/AzovL.png)](https://i.stack.imgur.com/AzovL.png) [Answer] # 6502 Assembly, 92 bytes ``` loo: lda $fe sta $00 lda $fe and #$3 clc adc #$2 sta $01 lda $fe ldy #$0 sta ($00),y jmp loo ``` Output: [![output](https://i.stack.imgur.com/Wr8eS.png)](https://i.stack.imgur.com/Wr8eS.png) Explanation: ``` loop: lda $fe ; accumulator = random sta $00 ; store accumulator lda $fe ; accumulator = random and #$3 ; accumulator &= 3 clc ; clear carry adc #$2 ; accumulator += 2 sta $01 ; store accumulator lda $fe ; accumulator = random ldy #$0 ; register Y = 0 sta ($00),y ; store register Y jmp loop ; loop ``` [Answer] # 6502 Assembly, 582 bytes Whew, this was fun. Does more or less the same thing as my Applesoft BASIC solution. ``` start: lda #15 sta $0 sta $1 loo: lda $fe and #3 cmp #0 beq g_l cmp #1 beq g_r cmp #2 beq g_d dec $1 d_w: lda $1 and #$1f asl tax lda ypo,x sta $2 inx lda ypo,x sta $3 lda $0 and #$1f tay lda ($2),y tax inx txa sta ($2),y jmp loo g_d: inc $1 jmp d_w g_l: dec $0 jmp d_w g_r: inc $0 jmp d_w ypo: dcb $00,$02,$20,$02,$40,$02,$60,$02 dcb $80,$02,$a0,$02,$c0,$02,$e0,$02 dcb $00,$03,$20,$03,$40,$03,$60,$03 dcb $80,$03,$a0,$03,$c0,$03,$e0,$03 dcb $00,$04,$20,$04,$40,$04,$60,$04 dcb $80,$04,$a0,$04,$c0,$04,$e0,$04 dcb $00,$05,$20,$05,$40,$05,$60,$05 dcb $80,$05,$a0,$05,$c0,$05,$e0,$05 ``` [Answer] # Python, 133 bytes I'm not quite sure if this fits the specs, because it's on a canvas in a 40x40 area. ``` from turtle import* from random import* ht() up() speed(0) R=randint while 1:goto(R(0,39),R(0,39));dot(1,eval('('+'R(0,255),'*3+')')) ``` [**Try it online**](https://trinket.io/python/d14f46288c) - version without `eval`, which doesn't work in Trinket [Answer] # JavaScript using Canvas 340 316 324 bytes ``` function r(t,e){return Math.floor(e*Math.random()+t)}function f(){x.fillStyle="rgba("+r(1,255)+","+r(1,255)+","+r(1,255)+", 1)",x.fillRect(r(0,40),r(0,40),1,1)}c=document.createElement("canvas"),c.width=40,c.height=40,x=c.getContext("2d"),document.getElementsByTagName("body")[0].appendChild(c),c.interval=setInterval(f,1); ``` [full version](https://jsfiddle.net/e55Ld3m3/) [Answer] # Processing, 112 bytes ``` void setup(){size(40,40);}void draw(){stroke(random(255),random(255),random(255));point(random(40),random(40));} ``` I can't guarantee that every pixel is replaced every 3 minutes, but looking at it it appears to be doing so. At least the odds of it missing a pixel, out of 1600 total, updating a random one 30x per second, totaling 5400 updates per 3 minutes, makes it unlikely that one would be missed. Ungolfed: The program is really straightforward. Open a window at 40x40 pixels, and every frame (default 30 per second) get a random color, and draw a point at a random coordinate between 0 and the parameter. 40 for pixel coordinates, 255 for colors. ``` void setup() { size(40,40); } void draw() { stroke(random(255),random(255),random(255)); point(random(40),random(40)); } ``` [![enter image description here](https://i.stack.imgur.com/3m0SQ.png)](https://i.stack.imgur.com/3m0SQ.png) [Answer] # HTML+SVG+PHP, 245 Bytes ``` <?$u=$_GET;$u[rand()%40][rand()%40]=sprintf("%06x",rand()%16777216);echo'<meta http-equiv="refresh" content="0.1; url=?'.http_build_query($u).'" /><svg>';foreach($u as$x=>$a)foreach($a as$y=>$c)echo"<rect x=$x y=$y width=1 height=1 fill=#$c />"; ``` Expanded ``` $u=$_GET; # Get the Url $u[rand()%40][rand()%40]=sprintf("%06x",rand()%16777216); # Set One Value in a 2 D Array echo'<meta http-equiv="refresh" content="0.1; url=?'.http_build_query($u).'" /><svg>'; # refresh the site after 0.1 second follow the new Get parameter foreach($u as$x=>$a) #loop through x Coordinates as Key foreach($a as$y=>$c) #loop through y Coordinates as Key value is the color echo"<rect x=$x y=$y width=1 height=1 fill=#$c />"; #print the rects for the SVG ``` Example for Output without meta tag and in a greater version ``` <svg viewBox="0 0 40 40" width=400 height=400><rect x=11 y=39 width=1 height=1 fill=#1b372b /><rect x=11 y=7 width=1 height=1 fill=#2c55a7 /><rect x=11 y=31 width=1 height=1 fill=#97ef86 /><rect x=11 y=26 width=1 height=1 fill=#94aa0a /><rect x=11 y=4 width=1 height=1 fill=#f8bf89 /><rect x=11 y=6 width=1 height=1 fill=#266342 /><rect x=11 y=29 width=1 height=1 fill=#369d80 /><rect x=11 y=20 width=1 height=1 fill=#ccfab8 /><rect x=11 y=12 width=1 height=1 fill=#ac0273 /><rect x=13 y=25 width=1 height=1 fill=#0d95e9 /><rect x=13 y=0 width=1 height=1 fill=#d2a4cb /><rect x=13 y=37 width=1 height=1 fill=#503abe /><rect x=13 y=35 width=1 height=1 fill=#4e60ae /><rect x=13 y=30 width=1 height=1 fill=#3cdd5e /><rect x=13 y=12 width=1 height=1 fill=#60464c /><rect x=13 y=17 width=1 height=1 fill=#a3b234 /><rect x=13 y=3 width=1 height=1 fill=#48e937 /><rect x=13 y=20 width=1 height=1 fill=#58bb78 /><rect x=13 y=4 width=1 height=1 fill=#5c61e6 /><rect x=13 y=10 width=1 height=1 fill=#758613 /><rect x=13 y=21 width=1 height=1 fill=#9b3a09 /><rect x=13 y=28 width=1 height=1 fill=#6c6b3b /><rect x=13 y=32 width=1 height=1 fill=#9b3a0f /><rect x=13 y=14 width=1 height=1 fill=#0c9bcc /><rect x=38 y=34 width=1 height=1 fill=#a3a65d /><rect x=38 y=23 width=1 height=1 fill=#c4441a /><rect x=38 y=25 width=1 height=1 fill=#cec692 /><rect x=38 y=39 width=1 height=1 fill=#535401 /><rect x=38 y=30 width=1 height=1 fill=#21371a /><rect x=38 y=26 width=1 height=1 fill=#7560a4 /><rect x=38 y=33 width=1 height=1 fill=#f31f34 /><rect x=38 y=9 width=1 height=1 fill=#3fce3f /><rect x=38 y=13 width=1 height=1 fill=#78cab8 /><rect x=3 y=39 width=1 height=1 fill=#c6cf06 /><rect x=3 y=26 width=1 height=1 fill=#d7fc94 /><rect x=3 y=31 width=1 height=1 fill=#048791 /><rect x=3 y=19 width=1 height=1 fill=#140371 /><rect x=3 y=12 width=1 height=1 fill=#6e7e7a /><rect x=3 y=21 width=1 height=1 fill=#f917da /><rect x=3 y=36 width=1 height=1 fill=#00d5d7 /><rect x=3 y=24 width=1 height=1 fill=#00f119 /><rect x=34 y=15 width=1 height=1 fill=#e39bd7 /><rect x=34 y=1 width=1 height=1 fill=#c1c1b8 /><rect x=34 y=36 width=1 height=1 fill=#0d15d5 /><rect x=34 y=29 width=1 height=1 fill=#d15f57 /><rect x=34 y=11 width=1 height=1 fill=#6f73b9 /><rect x=34 y=33 width=1 height=1 fill=#93ce78 /><rect x=34 y=16 width=1 height=1 fill=#ddd7bd /><rect x=34 y=14 width=1 height=1 fill=#73caa6 /><rect x=34 y=28 width=1 height=1 fill=#972d89 /><rect x=34 y=31 width=1 height=1 fill=#27e401 /><rect x=34 y=10 width=1 height=1 fill=#559d6d /><rect x=34 y=22 width=1 height=1 fill=#170bc2 /><rect x=30 y=13 width=1 height=1 fill=#a9ac0d /><rect x=30 y=4 width=1 height=1 fill=#3d9530 /><rect x=30 y=10 width=1 height=1 fill=#67b434 /><rect x=30 y=15 width=1 height=1 fill=#54930a /><rect x=30 y=11 width=1 height=1 fill=#8ce15b /><rect x=30 y=7 width=1 height=1 fill=#ddf53d /><rect x=30 y=32 width=1 height=1 fill=#04de14 /><rect x=30 y=19 width=1 height=1 fill=#f52098 /><rect x=30 y=22 width=1 height=1 fill=#dc7d70 /><rect x=30 y=0 width=1 height=1 fill=#d458c3 /><rect x=30 y=30 width=1 height=1 fill=#1f8895 /><rect x=30 y=36 width=1 height=1 fill=#b3d891 /><rect x=30 y=29 width=1 height=1 fill=#0f9810 /><rect x=30 y=5 width=1 height=1 fill=#b4ce36 /><rect x=30 y=33 width=1 height=1 fill=#a837ba /><rect x=30 y=23 width=1 height=1 fill=#02beb3 /><rect x=30 y=24 width=1 height=1 fill=#2a75da /><rect x=37 y=2 width=1 height=1 fill=#7b3aa3 /><rect x=37 y=26 width=1 height=1 fill=#0e9fb2 /><rect x=37 y=32 width=1 height=1 fill=#afb3a1 /><rect x=37 y=24 width=1 height=1 fill=#b421d6 /><rect x=37 y=16 width=1 height=1 fill=#39e872 /><rect x=37 y=38 width=1 height=1 fill=#552970 /><rect x=37 y=11 width=1 height=1 fill=#2a0b2a /><rect x=37 y=18 width=1 height=1 fill=#1fe310 /><rect x=37 y=36 width=1 height=1 fill=#a80fe3 /><rect x=37 y=6 width=1 height=1 fill=#141100 /><rect x=26 y=13 width=1 height=1 fill=#5d521d /><rect x=26 y=11 width=1 height=1 fill=#d7227e /><rect x=26 y=1 width=1 height=1 fill=#8dae67 /><rect x=26 y=19 width=1 height=1 fill=#acfd2c /><rect x=26 y=2 width=1 height=1 fill=#307dd5 /><rect x=26 y=35 width=1 height=1 fill=#76b559 /><rect x=26 y=4 width=1 height=1 fill=#e6a551 /><rect x=12 y=34 width=1 height=1 fill=#266a0a /><rect x=12 y=16 width=1 height=1 fill=#8bcf44 /><rect x=12 y=13 width=1 height=1 fill=#00caac /><rect x=12 y=3 width=1 height=1 fill=#bb7aa5 /><rect x=12 y=37 width=1 height=1 fill=#3b0559 /><rect x=12 y=27 width=1 height=1 fill=#e82087 /><rect x=12 y=8 width=1 height=1 fill=#b65157 /><rect x=19 y=20 width=1 height=1 fill=#556336 /><rect x=19 y=33 width=1 height=1 fill=#81bca0 /><rect x=19 y=34 width=1 height=1 fill=#65478a /><rect x=19 y=35 width=1 height=1 fill=#256956 /><rect x=19 y=10 width=1 height=1 fill=#c49f9c /><rect x=19 y=12 width=1 height=1 fill=#99bd3d /><rect x=19 y=13 width=1 height=1 fill=#dae45d /><rect x=19 y=36 width=1 height=1 fill=#de28e2 /><rect x=19 y=30 width=1 height=1 fill=#f26ff1 /><rect x=4 y=23 width=1 height=1 fill=#3a31dc /><rect x=4 y=4 width=1 height=1 fill=#d480e7 /><rect x=4 y=24 width=1 height=1 fill=#a304c6 /><rect x=4 y=28 width=1 height=1 fill=#775aeb /><rect x=4 y=16 width=1 height=1 fill=#d942d1 /><rect x=4 y=8 width=1 height=1 fill=#ad6c7e /><rect x=4 y=3 width=1 height=1 fill=#8ef507 /><rect x=4 y=9 width=1 height=1 fill=#c59549 /><rect x=4 y=7 width=1 height=1 fill=#f757fb /><rect x=4 y=35 width=1 height=1 fill=#2db5de /><rect x=20 y=22 width=1 height=1 fill=#340f7b /><rect x=20 y=2 width=1 height=1 fill=#ae6b7c /><rect x=20 y=20 width=1 height=1 fill=#120232 /><rect x=20 y=1 width=1 height=1 fill=#bb534c /><rect x=20 y=11 width=1 height=1 fill=#a736a1 /><rect x=20 y=38 width=1 height=1 fill=#63646f /><rect x=20 y=8 width=1 height=1 fill=#8e2095 /><rect x=20 y=27 width=1 height=1 fill=#2ae2c6 /><rect x=32 y=20 width=1 height=1 fill=#56dc7a /><rect x=32 y=34 width=1 height=1 fill=#ec16ca /><rect x=32 y=19 width=1 height=1 fill=#e2ce80 /><rect x=32 y=21 width=1 height=1 fill=#5c7638 /><rect x=32 y=0 width=1 height=1 fill=#35647c /><rect x=32 y=33 width=1 height=1 fill=#9e174a /><rect x=32 y=5 width=1 height=1 fill=#8217b4 /><rect x=32 y=30 width=1 height=1 fill=#b3e018 /><rect x=32 y=36 width=1 height=1 fill=#90ea3d /><rect x=22 y=29 width=1 height=1 fill=#9d975f /><rect x=22 y=12 width=1 height=1 fill=#b50680 /><rect x=22 y=31 width=1 height=1 fill=#9cd270 /><rect x=22 y=16 width=1 height=1 fill=#05a7f7 /><rect x=22 y=20 width=1 height=1 fill=#f6c4d5 /><rect x=22 y=21 width=1 height=1 fill=#9b0dd8 /><rect x=22 y=22 width=1 height=1 fill=#bc1c9e /><rect x=22 y=26 width=1 height=1 fill=#22b4c3 /><rect x=22 y=36 width=1 height=1 fill=#f54b7b /><rect x=22 y=19 width=1 height=1 fill=#7d3be4 /><rect x=22 y=6 width=1 height=1 fill=#ff9c6f /><rect x=22 y=34 width=1 height=1 fill=#cce01c /><rect x=22 y=30 width=1 height=1 fill=#7c4fd0 /><rect x=22 y=33 width=1 height=1 fill=#c2ef4e /><rect x=25 y=3 width=1 height=1 fill=#35c580 /><rect x=25 y=31 width=1 height=1 fill=#172b52 /><rect x=25 y=39 width=1 height=1 fill=#5e724d /><rect x=25 y=10 width=1 height=1 fill=#f50c4a /><rect x=25 y=4 width=1 height=1 fill=#012808 /><rect x=25 y=33 width=1 height=1 fill=#3a0dc3 /><rect x=25 y=12 width=1 height=1 fill=#2f254a /><rect x=25 y=30 width=1 height=1 fill=#19ff2c /><rect x=25 y=38 width=1 height=1 fill=#4a3112 /><rect x=0 y=1 width=1 height=1 fill=#886f4f /><rect x=0 y=35 width=1 height=1 fill=#0bb010 /><rect x=0 y=0 width=1 height=1 fill=#a7f77e /><rect x=0 y=27 width=1 height=1 fill=#1b38da /><rect x=0 y=39 width=1 height=1 fill=#3788ae /><rect x=0 y=13 width=1 height=1 fill=#af5149 /><rect x=0 y=32 width=1 height=1 fill=#dcb445 /><rect x=0 y=20 width=1 height=1 fill=#36a218 /><rect x=0 y=2 width=1 height=1 fill=#aacbb8 /><rect x=0 y=14 width=1 height=1 fill=#fb17e3 /><rect x=17 y=8 width=1 height=1 fill=#cb2be8 /><rect x=17 y=11 width=1 height=1 fill=#dd80b1 /><rect x=17 y=35 width=1 height=1 fill=#a269aa /><rect x=17 y=6 width=1 height=1 fill=#9faf64 /><rect x=17 y=9 width=1 height=1 fill=#762811 /><rect x=17 y=23 width=1 height=1 fill=#94fa57 /><rect x=17 y=26 width=1 height=1 fill=#9bacc3 /><rect x=17 y=1 width=1 height=1 fill=#93c849 /><rect x=17 y=4 width=1 height=1 fill=#4a9fd4 /><rect x=17 y=22 width=1 height=1 fill=#1fc5f3 /><rect x=17 y=37 width=1 height=1 fill=#76d6a3 /><rect x=17 y=5 width=1 height=1 fill=#a13389 /><rect x=9 y=38 width=1 height=1 fill=#064ba3 /><rect x=9 y=23 width=1 height=1 fill=#cc83ad /><rect x=9 y=25 width=1 height=1 fill=#1de7e8 /><rect x=9 y=3 width=1 height=1 fill=#834afe /><rect x=9 y=9 width=1 height=1 fill=#15a0fb /><rect x=9 y=27 width=1 height=1 fill=#4d54dc /><rect x=9 y=21 width=1 height=1 fill=#2bf614 /><rect x=9 y=28 width=1 height=1 fill=#8080b7 /><rect x=9 y=39 width=1 height=1 fill=#d76a3b /><rect x=9 y=33 width=1 height=1 fill=#f8da2c /><rect x=9 y=26 width=1 height=1 fill=#5884ae /><rect x=7 y=39 width=1 height=1 fill=#a0264b /><rect x=7 y=15 width=1 height=1 fill=#bd87c7 /><rect x=7 y=18 width=1 height=1 fill=#4d4878 /><rect x=7 y=35 width=1 height=1 fill=#1dcc8c /><rect x=7 y=38 width=1 height=1 fill=#76497f /><rect x=7 y=1 width=1 height=1 fill=#87b1ae /><rect x=35 y=24 width=1 height=1 fill=#5d947e /><rect x=35 y=17 width=1 height=1 fill=#eabbdc /><rect x=35 y=19 width=1 height=1 fill=#01c75b /><rect x=35 y=36 width=1 height=1 fill=#06b0dd /><rect x=35 y=21 width=1 height=1 fill=#0fbba8 /><rect x=35 y=1 width=1 height=1 fill=#480be1 /><rect x=35 y=11 width=1 height=1 fill=#3f8ef6 /><rect x=35 y=30 width=1 height=1 fill=#7691d0 /><rect x=35 y=13 width=1 height=1 fill=#c9a286 /><rect x=27 y=12 width=1 height=1 fill=#08083e /><rect x=27 y=25 width=1 height=1 fill=#95d3b4 /><rect x=27 y=30 width=1 height=1 fill=#584c1b /><rect x=27 y=9 width=1 height=1 fill=#c01082 /><rect x=27 y=3 width=1 height=1 fill=#3bf653 /><rect x=27 y=33 width=1 height=1 fill=#c06f23 /><rect x=27 y=38 width=1 height=1 fill=#184c3e /><rect x=27 y=0 width=1 height=1 fill=#725d4c /><rect x=27 y=36 width=1 height=1 fill=#e7a71b /><rect x=27 y=16 width=1 height=1 fill=#43c039 /><rect x=23 y=30 width=1 height=1 fill=#947161 /><rect x=23 y=37 width=1 height=1 fill=#e8a8e5 /><rect x=23 y=12 width=1 height=1 fill=#bd9976 /><rect x=23 y=6 width=1 height=1 fill=#15085d /><rect x=23 y=31 width=1 height=1 fill=#102c95 /><rect x=23 y=24 width=1 height=1 fill=#173bc2 /><rect x=23 y=2 width=1 height=1 fill=#bac13c /><rect x=23 y=36 width=1 height=1 fill=#eb5a88 /><rect x=23 y=22 width=1 height=1 fill=#5ddc38 /><rect x=28 y=19 width=1 height=1 fill=#1ea833 /><rect x=28 y=38 width=1 height=1 fill=#dc6f6b /><rect x=28 y=2 width=1 height=1 fill=#d9fd8a /><rect x=28 y=15 width=1 height=1 fill=#eb213e /><rect x=28 y=22 width=1 height=1 fill=#b23956 /><rect x=28 y=16 width=1 height=1 fill=#875b0a /><rect x=28 y=14 width=1 height=1 fill=#ba6172 /><rect x=28 y=18 width=1 height=1 fill=#b9779a /><rect x=39 y=26 width=1 height=1 fill=#df5e52 /><rect x=39 y=4 width=1 height=1 fill=#aabb4f /><rect x=39 y=2 width=1 height=1 fill=#7ce85c /><rect x=39 y=16 width=1 height=1 fill=#1f70a8 /><rect x=39 y=15 width=1 height=1 fill=#55e398 /><rect x=39 y=29 width=1 height=1 fill=#955213 /><rect x=39 y=33 width=1 height=1 fill=#976c99 /><rect x=39 y=34 width=1 height=1 fill=#a23109 /><rect x=39 y=25 width=1 height=1 fill=#36aeae /><rect x=39 y=9 width=1 height=1 fill=#28a600 /><rect x=39 y=17 width=1 height=1 fill=#771e5b /><rect x=39 y=30 width=1 height=1 fill=#9980b1 /><rect x=31 y=14 width=1 height=1 fill=#8ffea6 /><rect x=31 y=13 width=1 height=1 fill=#d35c5c /><rect x=31 y=39 width=1 height=1 fill=#407beb /><rect x=31 y=10 width=1 height=1 fill=#45ba53 /><rect x=31 y=2 width=1 height=1 fill=#842997 /><rect x=31 y=20 width=1 height=1 fill=#ca47b0 /><rect x=31 y=37 width=1 height=1 fill=#ed098e /><rect x=31 y=5 width=1 height=1 fill=#041b67 /><rect x=31 y=22 width=1 height=1 fill=#4aaaa6 /><rect x=31 y=31 width=1 height=1 fill=#40ccbd /><rect x=31 y=27 width=1 height=1 fill=#6325ca /><rect x=33 y=18 width=1 height=1 fill=#cfbbbc /><rect x=33 y=34 width=1 height=1 fill=#b3f6b8 /><rect x=33 y=26 width=1 height=1 fill=#ef3b82 /><rect x=33 y=16 width=1 height=1 fill=#c7df5b /><rect x=33 y=39 width=1 height=1 fill=#5ad5ba /><rect x=33 y=12 width=1 height=1 fill=#9361fd /><rect x=33 y=35 width=1 height=1 fill=#1f4795 /><rect x=33 y=3 width=1 height=1 fill=#86a80c /><rect x=33 y=17 width=1 height=1 fill=#582008 /><rect x=33 y=9 width=1 height=1 fill=#686941 /><rect x=33 y=36 width=1 height=1 fill=#76ada4 /><rect x=33 y=21 width=1 height=1 fill=#511f50 /><rect x=33 y=14 width=1 height=1 fill=#64aaf7 /><rect x=8 y=28 width=1 height=1 fill=#3de9b7 /><rect x=8 y=24 width=1 height=1 fill=#5c8451 /><rect x=8 y=31 width=1 height=1 fill=#e75b30 /><rect x=8 y=38 width=1 height=1 fill=#4ee9d0 /><rect x=8 y=29 width=1 height=1 fill=#544381 /><rect x=8 y=16 width=1 height=1 fill=#12332f /><rect x=8 y=0 width=1 height=1 fill=#9e775f /><rect x=8 y=34 width=1 height=1 fill=#02224e /><rect x=8 y=1 width=1 height=1 fill=#b299f4 /><rect x=8 y=10 width=1 height=1 fill=#b2bd80 /><rect x=8 y=20 width=1 height=1 fill=#054876 /><rect x=8 y=27 width=1 height=1 fill=#ab273a /><rect x=2 y=30 width=1 height=1 fill=#1bd5f4 /><rect x=2 y=10 width=1 height=1 fill=#b00e99 /><rect x=2 y=9 width=1 height=1 fill=#bf18b0 /><rect x=2 y=8 width=1 height=1 fill=#9aa92b /><rect x=2 y=16 width=1 height=1 fill=#aa7e3d /><rect x=2 y=1 width=1 height=1 fill=#c383ea /><rect x=2 y=24 width=1 height=1 fill=#63ab54 /><rect x=2 y=19 width=1 height=1 fill=#086cac /><rect x=2 y=0 width=1 height=1 fill=#4510cc /><rect x=2 y=6 width=1 height=1 fill=#7b529c /><rect x=6 y=27 width=1 height=1 fill=#fcc946 /><rect x=6 y=20 width=1 height=1 fill=#0a7324 /><rect x=6 y=26 width=1 height=1 fill=#d93cc2 /><rect x=6 y=14 width=1 height=1 fill=#c8d410 /><rect x=6 y=33 width=1 height=1 fill=#0e5b22 /><rect x=6 y=1 width=1 height=1 fill=#e2accf /><rect x=6 y=2 width=1 height=1 fill=#06064a /><rect x=6 y=39 width=1 height=1 fill=#fae1de /><rect x=6 y=30 width=1 height=1 fill=#db50d3 /><rect x=6 y=15 width=1 height=1 fill=#59b1c5 /><rect x=6 y=16 width=1 height=1 fill=#a0178a /><rect x=16 y=29 width=1 height=1 fill=#1eb287 /><rect x=16 y=31 width=1 height=1 fill=#5fa9b0 /><rect x=16 y=36 width=1 height=1 fill=#918835 /><rect x=16 y=2 width=1 height=1 fill=#d46404 /><rect x=16 y=1 width=1 height=1 fill=#31808e /><rect x=16 y=15 width=1 height=1 fill=#22d652 /><rect x=10 y=25 width=1 height=1 fill=#94f771 /><rect x=10 y=14 width=1 height=1 fill=#e3a90a /><rect x=10 y=4 width=1 height=1 fill=#7fbdb3 /><rect x=10 y=32 width=1 height=1 fill=#d71f68 /><rect x=10 y=10 width=1 height=1 fill=#f3dcd7 /><rect x=10 y=27 width=1 height=1 fill=#cadd64 /><rect x=10 y=31 width=1 height=1 fill=#3c38c0 /><rect x=10 y=34 width=1 height=1 fill=#542641 /><rect x=10 y=19 width=1 height=1 fill=#e17ef2 /><rect x=10 y=24 width=1 height=1 fill=#676729 /><rect x=10 y=11 width=1 height=1 fill=#619f8e /><rect x=10 y=0 width=1 height=1 fill=#1576eb /><rect x=10 y=16 width=1 height=1 fill=#52854c /><rect x=36 y=2 width=1 height=1 fill=#fe133c /><rect x=36 y=31 width=1 height=1 fill=#b67ea7 /><rect x=36 y=7 width=1 height=1 fill=#92babc /><rect x=36 y=16 width=1 height=1 fill=#fc24a0 /><rect x=36 y=26 width=1 height=1 fill=#a80f75 /><rect x=36 y=15 width=1 height=1 fill=#5ddb90 /><rect x=18 y=13 width=1 height=1 fill=#64180c /><rect x=18 y=9 width=1 height=1 fill=#d67c04 /><rect x=18 y=18 width=1 height=1 fill=#3e0988 /><rect x=18 y=4 width=1 height=1 fill=#072b32 /><rect x=18 y=34 width=1 height=1 fill=#723cab /><rect x=18 y=14 width=1 height=1 fill=#560f7d /><rect x=18 y=29 width=1 height=1 fill=#4a7dd0 /><rect x=18 y=30 width=1 height=1 fill=#db0cfc /><rect x=18 y=16 width=1 height=1 fill=#f79bbf /><rect x=14 y=18 width=1 height=1 fill=#e45cec /><rect x=14 y=4 width=1 height=1 fill=#05b63c /><rect x=14 y=38 width=1 height=1 fill=#ee0251 /><rect x=14 y=14 width=1 height=1 fill=#12fb9f /><rect x=14 y=17 width=1 height=1 fill=#f8fbc9 /><rect x=14 y=22 width=1 height=1 fill=#58e112 /><rect x=14 y=1 width=1 height=1 fill=#a5bc5c /><rect x=14 y=10 width=1 height=1 fill=#3c6002 /><rect x=14 y=5 width=1 height=1 fill=#556f7a /><rect x=14 y=36 width=1 height=1 fill=#ccfaa9 /><rect x=14 y=15 width=1 height=1 fill=#2a8597 /><rect x=1 y=28 width=1 height=1 fill=#899272 /><rect x=1 y=29 width=1 height=1 fill=#be4da2 /><rect x=1 y=6 width=1 height=1 fill=#cbe1a5 /><rect x=1 y=1 width=1 height=1 fill=#8aebd4 /><rect x=1 y=31 width=1 height=1 fill=#547b9e /><rect x=1 y=10 width=1 height=1 fill=#ba7996 /><rect x=1 y=34 width=1 height=1 fill=#e29661 /><rect x=1 y=0 width=1 height=1 fill=#899d3f /><rect x=1 y=4 width=1 height=1 fill=#6993f0 /><rect x=1 y=13 width=1 height=1 fill=#119a7c /><rect x=1 y=15 width=1 height=1 fill=#e7c61c /><rect x=1 y=17 width=1 height=1 fill=#6e8770 /><rect x=1 y=36 width=1 height=1 fill=#cdda71 /><rect x=5 y=8 width=1 height=1 fill=#318f52 /><rect x=5 y=34 width=1 height=1 fill=#763499 /><rect x=5 y=37 width=1 height=1 fill=#5d0d72 /><rect x=5 y=0 width=1 height=1 fill=#97c9e7 /><rect x=5 y=12 width=1 height=1 fill=#babcca /><rect x=5 y=20 width=1 height=1 fill=#37d5cb /><rect x=5 y=31 width=1 height=1 fill=#642296 /><rect x=5 y=24 width=1 height=1 fill=#a6688c /><rect x=5 y=1 width=1 height=1 fill=#697956 /><rect x=29 y=32 width=1 height=1 fill=#b53b61 /><rect x=29 y=7 width=1 height=1 fill=#d131a3 /><rect x=29 y=18 width=1 height=1 fill=#0e082e /><rect x=29 y=17 width=1 height=1 fill=#8ca3dd /><rect x=29 y=11 width=1 height=1 fill=#376e46 /><rect x=29 y=20 width=1 height=1 fill=#11e2cf /><rect x=29 y=37 width=1 height=1 fill=#24b8de /><rect x=24 y=10 width=1 height=1 fill=#a906da /><rect x=24 y=36 width=1 height=1 fill=#ae0516 /><rect x=24 y=8 width=1 height=1 fill=#e0b9b1 /><rect x=24 y=27 width=1 height=1 fill=#29b27b /><rect x=24 y=33 width=1 height=1 fill=#78ea3e /><rect x=24 y=7 width=1 height=1 fill=#e5147e /><rect x=24 y=11 width=1 height=1 fill=#ce7084 /><rect x=24 y=23 width=1 height=1 fill=#78f645 /><rect x=24 y=25 width=1 height=1 fill=#a01f02 /><rect x=24 y=4 width=1 height=1 fill=#e4340c /><rect x=24 y=16 width=1 height=1 fill=#9b69d7 /><rect x=21 y=31 width=1 height=1 fill=#58ca7d /><rect x=21 y=39 width=1 height=1 fill=#037cb5 /><rect x=21 y=36 width=1 height=1 fill=#097454 /><rect x=21 y=28 width=1 height=1 fill=#71d744 /><rect x=21 y=38 width=1 height=1 fill=#10457c /><rect x=15 y=2 width=1 height=1 fill=#f4bf09 /><rect x=15 y=7 width=1 height=1 fill=#90357d /><rect x=15 y=27 width=1 height=1 fill=#6079ba /><rect x=15 y=5 width=1 height=1 fill=#cff723 /><rect x=15 y=17 width=1 height=1 fill=#54a6db /> ``` [Answer] # Python 3.6 + Tkinter, 281 bytes ``` from tkinter import* from random import* from threading import* a=randrange x=40 d={"width":x,"height":x} w=Tk() c=Canvas(w,**d) c.pack() i=PhotoImage(**d) c.create_image((20,20),image=i) def r(): while 1:i.put(f"{a(0,0xffffff):0>6f}",(a(0,x),a(0,x))) Thread(r).start() mainloop() ``` [Answer] # JavaScript (ES7) + HTML using SVG, 129 + 10 = 139 bytes SVG version, heavily inspired by [@Octopus's `<canvas>` approach](https://codegolf.stackexchange.com/a/124078/47097). ### JS ``` r=n=>n*Math.random()|0 setInterval('s.innerHTML+=`<rect x=${r(40)} y=${r(40)} fill=#${r(2**24).toString(16)} width=1 height=1>`') ``` ### HTML ``` <svg id=s> ``` Since the Stack Snippet likes to break the script by parsing the `<rect>` tag, here's a [CodePen](https://codepen.io/darrylyeo/pen/ZyEOxO). [Answer] ## LOGO, 71 bytes The only language that I know of, being not esoteric/specially designed for codegolfing, and have `forever` function. Any idea on the `map` part? ``` pu forever[setxy random 100 random 100 setpixel map[random 256][1 1 1]] ``` [Answer] # [shortC](//github.com/aaronryank/shortC), ~~66~~ 56 bytes ``` Dr rand() AOZR"\e[%d;%dH\e[%d;4%dm ",r%40,r%40,r%2,r%8); ``` -10 bytes thanks to Dr. Rand. :P ``` A main function O for Z seed rand() R print "\e[%d;%dH coordinate placeholder string \e[%d;4%dm " color placeholder string ,rand()%40,rand()%40,rand()%2,rand()%8 fill placeholders ); interpreter hole ``` No TIO link because you obviously can't print to the kind of terminal this requires online. [Answer] ## Perl (on \*nix), 69 bytes **The `\x1b`s are literal escape characters.** Relies on `stty` command and works well on OS X. ``` {printf"\x1b[%i;%iH\x1b[48;5;%im ",map{rand$_}`stty size`=~/\d+/g,256;redo} ``` Similar to other approaches, but I liked the combination of all params into one call to `printf` so thought I'd share. Kills my terminal. [![enter image description here](https://i.stack.imgur.com/a1sDK.png)](https://i.stack.imgur.com/a1sDK.png) --- ### Twice as many pixels, 83 bytes ``` {printf"\x1b[%i;%iH\x1b[48;5;%i;38;5;%im▄",map{rand$_}`stty size`=~/\d+/g,256,256;redo} ``` This approach uses a unicode block `▄` and a random foreground and background colour which gives a more square pixel. Kills my terminal too, but looks cooler. [![enter image description here](https://i.stack.imgur.com/ZMymE.png)](https://i.stack.imgur.com/ZMymE.png) [Answer] ## Bash, 104 bytes **The `\e`s are literal escape characters.** These are pretty much translations of my Perl submission, but using bash fork bomb style syntax! Not as clever as the other bash entry that writes directly to the display I'm afraid. ``` :(){ printf "\e[%i;%iH\e[48;5;%im " $((RANDOM%`tput lines`)) $((RANDOM%`tput cols`)) $((RANDOM%256));:;};: ``` --- ### More pixels, 130 bytes Same as my Perl answer, this uses a unicode character for the foreground and colours the background of each pixel too. ``` :(){ printf "\e[%i;%iH\e[48;5;%i;38;5;%im▄" $((RANDOM%`tput lines`)) $((RANDOM%`tput cols`)) $((RANDOM%256)) $((RANDOM%256));:;};: ``` [Answer] # Super Chip (48)?, 12 bytes ``` 0x00FF 'enter high resolution mode (64x128 pixels) 0xA209 'set I to 0x209 (second byte of draw instruction) 0xC03F 'set register 0 to a random number from 0 to 63 0xC13F 'set register 1 to a random number from 0 to 63 0xD101 'draw a sprite. x=register 1, y=register 0, height=1 0x1204 'jump to third instruction ``` I'm not sure of the exact name, but I had to use this instead of normal Chip-8 because of the 40x40 pixel limitation. [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 34 bytes ``` screen 12{pset(_r640|,_r480|),_r16 ``` Unfortunately, QBIC doesn't set a `SCREEN` mode by default, so that eats some bytes. `PSET` is an illegal command in QBIC's default graphical context. ## Explanation ``` screen 12 Set the screen to a mode supporting (colored) graphics { DO until the compiler is killed by ctrl-scroll lock pset PSET is a QBasic command to set one pixel (_r640|,_r480|) it takes a set of coords (x, y) which QBIC chooses at random with _r ,_r16 and a color (1,16) ``` ## Sample output @Anonymous found an error in QBIC's `rnd()` function. Fixing that gives the output below. Thanks! [![enter image description here](https://i.stack.imgur.com/tIhvL.png)](https://i.stack.imgur.com/tIhvL.png) [Answer] # GW-Basic, 47 bytes (tokenised) ``` 0 SCREEN 7:RANDOMIZE TIMER:WHILE 1:PSET(RND*40 MOD 40,RND*40 MOD 40),RND*16 AND 15:WEND ``` To get it down to 47 bytes, you'll have to strip spaces and trailing zeroes and end of file character manually. ]
[Question] [ Former US Secretary of Defense, Donald Rumsfeld, [famously](https://en.wikipedia.org/wiki/There_are_known_knowns) popularized the phrase "known knowns." Here we're going to distill his remarks into a four-line stanza. Specifically, output this text: ``` known knowns known unknowns unknown knowns unknown unknowns ``` Capitalization doesn't matter (for example, `Known unKnowns` is fine), and a single trailing newline is acceptable, but no other formatting changes are allowed. That means a single space between the words, and either `LF` (59 bytes) or `CR/LF` (62 bytes) between the lines. ### Rules * 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. [Answer] # [Python 2](https://docs.python.org/2/), ~~54~~ 52 bytes -2 bytes thanks to xnor ``` k='unknowns' for i in 8,6,2,0:print k[i/3:7],k[i%3:] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9tWvTQvOy@/PK9YnSstv0ghUyEzT8FCx0zHSMfAqqAoM69EITs6U9/YyjxWB8hQNbaK/f8fAA "Python 2 – Try It Online") The results from the `/` and `%` will be `[[2, 2], [2, 0], [0, 2], [0, 0]]` that will be the starting indexes, removing the `un` when `2`, keeping the string unaltered when `0` [Answer] # Vim ~~28~~ 25 bytes This is my first Vim answer, any golfing tips are welcome. ``` 2iunknown ␛rsY3P2xw.+.jw. ``` [![In action](https://i.stack.imgur.com/cftH0.gif)](https://i.stack.imgur.com/cftH0.gif) Thank you [Lynn](https://codegolf.stackexchange.com/users/3852/lynn) for writing the [python script](https://gist.github.com/lynn/5f4f532ae1b87068049a23f7d88581c5) to make that fantastic animation. This can also be run by V [Try it Online!](https://tio.run/##K/v/3yizNC87L788T0G6qDjSOMCoIlxPWy8rXO//fwA) Also 25: ``` 2iknown ␛rsY3pwiun␛+.+.w. ``` [Answer] # bash, 36 bytes ``` printf %s\\n {,un}known\ {,un}knowns ``` other solutions 36 ``` eval echo\ {,un}known\ {,un}knowns\; ``` 37 ``` eval printf '%s\\n' \{,un}known{\\,s} ``` 38 ``` eval eval echo\\ \{,un}known{\\,'s\;'} ``` 41 ``` x=\\\ {,un}known;eval "eval echo$x$x\s\;" ``` 45 ``` x='\ {,un}known' e=eval;$e "$e echo$x$x\s\;" x='\ {,un}known' e=eval\ ;$e"$e\echo$x$x\s\;" ``` if leading newline and extra space were accepted 31 bytes : ``` echo ' '{,un}known\ {,un}knowns ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes Saved 1 byte thanks to *Erik the Outgolfer* (avoid closing string) ``` „Š¢—‚#D's«â» ``` [Try it online!](https://tio.run/##ASEA3v8wNWFiMWX//@KAnsWgwqLigJTigJojRCdzwqvDosK7//8 "05AB1E – Try It Online") **Explanation** ``` „Š¢—‚ # push the string "known unknown" # # split on spaces D # duplicate 's« # append "s" to each â # cartesian product » # join on newline ``` [Answer] ## CJam (26 25 bytes) ``` "unknown"_2>\]2m*{S*'sN}% ``` [Online demo](http://cjam.aditsu.net/#code=%22unknown%22_2%3E%5C%5D2m*%7BS*'sN%7D%25) Cartesian product of `["known" "unknown"]` with itself, then each element joined with space and suffixed with `s` and a newline. Thanks to [Erik](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) for a one-byte saving. [Answer] # [R](https://www.r-project.org/), ~~52~~ ~~51~~ 50 bytes ``` cat(gsub(1,"known","1 1s 1 un1s un1 1s un1 un1s")) ``` [Try it online!](https://tio.run/##K/r/PzmxRCO9uDRJw1BHKTsvvzxPSUfJUMGwmMtQoTQPSAEJBSgF4itpav7/DwA "R – Try It Online") Surprisingly short substitution and print commands make this an *actually competitive* R answer in a [string](/questions/tagged/string "show questions tagged 'string'") challenge! ~~Even if it's super boring.~~ Mildly more interesting now, and with a byte saved thanks to [J.Doe](https://codegolf.stackexchange.com/users/81549/j-doe)! Saved another byte thanks to [this answer, also by J.Doe!](https://codegolf.stackexchange.com/a/173971/67312) [Answer] # [Haskell](https://www.haskell.org/), ~~60~~ ~~58~~ ~~53~~ 51 bytes ``` f<$>l<*>l f x y=x++' ':y++"s" l=["known","unknown"] ``` [Try it online!](https://tio.run/##y0gszk7Nyfmfk1lcomCrEPM/zUbFLsdGyy6HK02hQqHStkJbW11B3apSW1upWIkrxzZaKTsvvzxPSUepNA/Civ2fm5iZB9Scm1jgq1BQWhJcUuSTpwAy8f@/5LScxPTi/7rJBQUA "Haskell – Try It Online") Yields a list of lines as was recently allowed. Thanks to [@firefrorefiddle](https://codegolf.stackexchange.com/users/7508/firefrorefiddle) for pointing out. -2 bytes thanks to [cole](https://codegolf.stackexchange.com/users/42833/cole). --- **58 byte version:** ``` f=<<"? ?s\n? un?s\nun? ?s\nun? un?s" f '?'="known" f c=[c] ``` [Try it online!](https://tio.run/##y0gszk7NyflfXFKUmZeuYKsQ8z/N1sZGyV7Bvjgmz16hNA9EA0kFGA0SUeJKU1C3V7dVys7LL88D8ZJto5Nj/@cmZuYBzSgoLQkuKVKAmPn/X3JaTmJ68X/d5IICAA "Haskell – Try It Online") Yields a single string. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 54 bytes ``` v=>@"z zs z unzs unz zs unz unzs".Replace("z","known") ``` [Try it online!](https://tio.run/##LY2xDsIgFAB3voIwQVL7A7WNiYmTLjo4I74YIj5IH9RI02/HGlnuctMZ2hg/Qgnp5qzhxmkivp8ZRR3Xvnwowqs9JDRbiqPFR/PXEPoy9cNOZJ6JZZ5w1Qpe9WvRniE4bUCKLBrxRP9GoUrH6qw@Jm/v/KQtSsXmOtx7JO@gvY42wtEiyCAxOadUxxa2lC8 "C# (.NET Core) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), ~~33~~ 32 bytes ``` s¶ uns¶un s¶un uns |s known$& ``` [Try it online!](https://tio.run/##K0otycxL/P@fS6H40DaF0jwgWZqnACGBPC6FmmKu7Lz88jwVtf//AQ "Retina – Try It Online") Edit: Saved 1 byte thanks to @ovs. Explanation: This is almost the trivial approach of using a placeholder for `known`, except here I simply insert it before each space or `s`, which saves ~~3~~ 4 bytes. [Answer] # PHP, ~~55 51~~ 47 bytes ``` <?=strtr("1 1s 1 01s 01 1s 01 01s",[un,known]); ``` [try it online](http://sandbox.onlinephpfunctions.com/code/721dcb4227f413507aae5f582e8de8c2284983eb) [Answer] ## [Retina](https://github.com/m-ender/retina), ~~33~~ 32 bytes *Saved 1 byte using an intermediate printing approach from Leo.* ``` ¶u knowns u un :`s m`^ un ``` [Try it online!](https://tio.run/##K0otycxL/P@fS@HQtlIuruy8/PK8Yq5SLoXSPC6rhGIFLgWu3IQ4rtK8//8B "Retina – Try It Online") ### Explanation ``` ¶u ``` Turns the non-existent (i.e. empty) input into the string on the second line. That one seems pretty weird, but these characters are codes for the stuff that goes *between* two instances of `known[s]` on the first two lines of the result. Space and linefeed are just themselves and `u` is `un`. ``` knowns ``` Now we insert `knowns` at every position (i.e. at the beginning, end, and between every pair of characters). ``` u un ``` We decode the `u`. ``` :s ``` Then we get rid of the `s`s in front of spaces, i.e. those in the first half of each line, and print the result. ``` m`^ un ``` And finally we prepend `un` to both lines and print the result again. This beats [the trivial approach](https://tio.run/##K0otycxL/P@fK1shu/jQtmyF0jwQDSQVYDRIhCubKzsvvzzv/38A) of just using a placeholder for `known` by 4 bytes, but not [Neil's more efficient implementation](https://codegolf.stackexchange.com/a/145453/52210) of that approach. [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), ~~1021~~ ~~1012~~ 993 bytes *-19 bytes thanks to Joe King!* ``` ,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Exeunt][Enter Ajax and Ford]Ajax:Am I nicer a big cat?If sois the remainder of the quotient betweenI the sum ofa cat a big cat worse a big cat?If notlet usScene V.You be the sum ofa fat fat fat pig the cube ofthe sum ofa cat a big big cat.Speak thy.You be the sum ofyou the sum ofa cat a fat fat fat pig.Speak thy.Scene V:.[Exit Ajax][Enter Page]Page:You be the product ofthe sum ofa cat a big big cat the sum ofa pig a big big big big cat.Speak thy.You be the sum ofyou the sum ofa cat a big cat.Speak thy.Ford:You be the sum ofI a cat.Speak thy.You be the sum ofyou a big big big cat.Speak thy.Page:Speak thy.You be the sum ofyou the sum ofa cat a big big cat.Is the remainder of the quotient betweenAjax a big cat worse a cat?If soyou big big big big big cat.Speak thy.If solet usScene X.You be twice the sum ofa cat a big big cat.Speak thy.Scene X:.[Exit Page][Enter Ajax]Ford:You be the sum ofyou a cat.Be you worse a big big big cat?If solet usAct I. ``` [Try it online!](https://tio.run/##pVNBboMwEPzKPgD5AVyiVEol3ypFqlpFHBxYUtpgE2yL5PXUayAxcdSi9gDCu57Z8TDWzbHvE7b@FOeEPau2SNiLOKCr5AZ4yrY5SqSP3eaMVppst5EGWyAACFkAYTJapesaOMgqd10B@@oAuTArXoJWlQbzgdBiLSpZuL4qfeFklalQGtij6RAl91Vta7dBEPxGBJ1qNc6JpTJHNGD1IPKVvSvrqGYkpYNOT@Og1Mut26TKx7NGfrZtUHy57ZeY9eIKMfhuUkAwyvMeVsZbN9lIXmf0SoMpTasK6@z/ReJMA53t1v3XQWIg/eM0QnMQSwaIHxT5k/9J4MTFF0ZryGuUpmtEadK9e7FevzXM3NtVc@eCD0sjNYKnRPgUBBcre2z44CYxPSHQIrwTwaBVINNfY9b33w) [Answer] # [Perl 6](https://perl6.org), 45 bytes ``` $_='known';.say for [X](($_,"un$_")xx 2)X~'s' ``` [Try it](https://tio.run/##K0gtyjH7/18l3lY9Oy@/PE/dWq84sVIhLb9IIToiVkNDJV5HqTRPJV5Js6JCwUgzok69WP3/fwA "Perl 6 – Try It Online") ## Expanded ``` $_ = 'known'; .say # print with trailing newline the value in topic variable 「$_」 for # do that for each of the following [X]( ($_, "un$_") # ('known','unknown') xx 2 # list repeated twice ) X~ 's' # cross using &infix:«~» with 's' (adds 「s」 to the end) ``` The `[X](…)` part generates ``` (("known","known"),("known","unknown"),("unknown","known"),("unknown","unknown")).Seq ``` Then using `X~` on it coerces the inner lists into a Str (because of the `&infix:«~»` operator), which doing so adds a space between values. ``` ("known known", "known unknown", "unknown known", "unknown unknown").Seq ``` Then each is joined with an `s` ``` ("known knowns", "known unknowns", "unknown knowns", "unknown unknowns").Seq ``` [Answer] ## Haskell, ~~57~~ 52 bytes ``` id=<<id=<<mapM(\s->[s,"un"++s])["known ","knowns\n"] ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzPF1sYGTOQmFvhqxBTr2kUX6yiV5ilpaxfHakYrZefll@cpKOlAGMUxeUqx/3MTM/MUbBUKSkuCS4oU0v7/S07LSUwv/q@bXFAAAA "Haskell – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~64~~ ~~47~~ 35 bytes ``` ⍪,∘.{⍺,' ',⍵,'s'}⍨k('un',k←'known') ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtEx71rtJ51DFDr/pR7y4ddQV1nUe9W3XUi9VrH/WuyNZQL81T18kGKlPPzssvz1PX/P8fAA) **How?** `k←'known'` - `k` is `"known"` `k('un',k←'known')` - `"known" "unknown"` `∘.`...`⍨` - outer product with itself     `{⍺,' ',⍵,'s'}` - with the function that formats the args as `{⍺} {⍵}s` `,` - smash the product table into vector `⍪` - separate to columns [Answer] # Java 8, ~~56~~ 55 bytes ``` v->" s\n uns\nun s\nun uns".replaceAll(" |s","known$0") ``` -1 byte thanks to *@SuperChafouin*. **Explanation:** [Try it here.](https://tio.run/##LY7BCsIwEETvfsUQPKRgi/ei4AfYi@BFPcQ0Smq6LU1SEe231y0t7A7MLryZSvUqbVpDVfkatVPe46gsfVeApWC6h9IGxWSBU@gsPaHlubEl@iTn68DL44MKVqMAYYexT/cC/kqIxBoJs7ITWWdax8yDc1Lg58VGvKh503orkjGfYW28O4YtzH4Kq7mTnPMvN6hkKfTxwdRZE0PW8is4kpRpSdG5ZGk3jH8) ``` v-> // Method with empty unused parameter " s\n uns\nun s\nun uns" // Literal String .replaceAll(" |s", // Replace all spaces and "s" with: "known // Literal "known" $0") // + the match (the space or "s") // End of method (implicit / single-line return-statement) ``` [Answer] # C (gcc), ~~79~~ ~~78~~ 76 bytes *Thanks to @Justin Mariner for golfing one byte!* ``` f(){printf("%s %1$ss\n%1$s un%1$ss\nun%1$s %1$ss\nun%1$s un%1$ss","known");} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NQ7O6oCgzryRNQ0m1WEHVUKW4OCYPRCmU5kF5EIYCKg8qq6SjlJ2XX56npGld@x9ojEJuYmaehiZXNZcCEABNt@aq/Q8A) [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` OΠṠemhw¨ṅW∫ḟωμ ``` [Try it online!](https://tio.run/##ASIA3f9odXNr//9PzqDhuaBlbWh3wqjhuYVX4oir4bifz4nOvP// "Husk – Try It Online") # Explanation ``` OΠṠemhw¨ṅW∫ḟωμ ¨ṅW∫ḟωμ The compressed string "knowns unknowns" w Split on spaces ["knowns","unknowns"] e Make a list with: mh this list with the last letter dropped from each word Ṡ and this same list [["known","unknown"],["knowns","unknowns"]] Π Cartesian product [["known","knowns"],["unknown","knowns"],["known","unknowns"],["unknown","unknowns"]] O Sort the list [["known","knowns"],["known","unknowns"],["unknown","knowns"],["unknown","unknowns"]] Implicitely print joining with spaces and newlines ``` [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 48 bytes ``` 00 C0 A9 37 85 FB A9 73 4D 2B C0 8D 2B C0 A9 0D 4D 2C C0 8D 2C C0 A9 26 90 02 E9 02 A0 C0 20 1E AB 06 FB D0 E1 60 55 4E 4B 4E 4F 57 4E 53 0D 00 ``` **[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22know.prg%22:%22data:;base64,AMCpN4X7qXNNK8CNK8CpDU0swI0swKkmkALpAqDAIB6rBvvQ4WBVTktOT1dOUw0A%22%7D,%22vice%22:%7B%22-autostart%22:%22know.prg%22%7D%7D)** **Usage:** `sys49152` --- ### How it works The trick here is to use a "loop counter" for 8 iterations where bits 7 to 1 of the initial value are `1` for `unknown(s)` and `0` for `known(s)` in one iteration. This counter is shifted to the left after each iteration (shifting the leftmost bit into the carry flag) and bit `0` is initially `1` so we know we're finished once the last bit was shifted out. In the first iteration, `known` is printed because when calling the program, the carry flag is clear. In each iteration, the end of the string is toggled between `<space>` and `s<newline>`. Here's the commented disassembly listing: ``` 00 C0 .WORD $C000 ; load address .C:c000 A9 37 LDA #$37 ; initialize loop counter ... .C:c002 85 FB STA $FB ; ... as 0011 0111, see description .C:c004 .loop: .C:c004 A9 73 LDA #('s'^' ') ; toggle between 's' and space .C:c006 4D 2B C0 EOR .plural .C:c009 8D 2B C0 STA .plural .C:c00c A9 0D LDA #$0D ; toggle between newline and 0 .C:c00e 4D 2C C0 EOR .newline .C:c011 8D 2C C0 STA .newline .C:c014 A9 26 LDA #<.knowns ; start at "known" except .C:c016 90 02 BCC .noprefix ; when carry set from shifting $fb: .C:c018 E9 02 SBC #$02 ; than start at "un" .C:c01a .noprefix: .C:c01a A0 C0 LDY #>.knowns ; high-byte of string start .C:c01c 20 1E AB JSR $AB1E ; output 0-terminated string .C:c01f 06 FB ASL $FB ; shift loop counter .C:c021 D0 E1 BNE .loop ; repeat if not 0 yet .C:c023 60 RTS ; done .C:c024 .unknowns: .C:c024 55 4E .BYTE "un" .C:c026 .knowns: .C:c026 4B 4E 4F 57 4E .BYTE "known" .C:c02b .plural: .C:c02b 53 .BYTE "s" .C:c02c .newline .C:c02c 0D 00 .BYTE $0d, $00 ``` [Answer] ## [Perl 5](https://www.perl.org/), 33 bytes **Disclaimer**: I didn't realise that brace expansion was possible within the `<...>` operator (learned thanks to @[Grimy](https://codegolf.stackexchange.com/users/6484/grimy)'s [answer](https://codegolf.stackexchange.com/a/146295/9365)!) and the using the clever expansion trick from @[NahuelFouilleul](https://codegolf.stackexchange.com/users/70745/nahuel-fouilleul)'s [amazing bash answer](https://codegolf.stackexchange.com/a/145456/9365), I was able to build this solution. I will happily remove this at either of their request. ``` print<"{,un}known {,un}knowns$/"> ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvxEapWqc0rzY7L788TwHBLFbRV7L7/x8A "Perl 5 – Try It Online") --- ## [Perl 5](https://www.perl.org/), 42 bytes **41 bytes code + 1 for `-p`.** ``` s//K Ks K unKs/;s/K/known/g;$\=s/^/un/gmr ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX99bwbuYy1uhNM@7WN@6WN9bPzsvvzxPP91aJca2WD9OvxTIzi36/5/rX35BSWZ@XvF/3QIA "Perl 5 – Try It Online") --- # [Perl 5](https://www.perl.org/), 45 bytes Tried to come up with an alternative, but couldn't make it shorter... Thought it was different enough to warrant adding anyway. ``` print"un"x/[3467]/,known,$_%2?"s ":$"for 0..7 ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRKk0T6lCP9rYxMw8Vl8nOy@/PE9HJV7VyF6pmEvJSkUpLb9IwUBPz/z/fwA "Perl 5 – Try It Online") [Answer] # Haskell, ~~71~~ ~~66~~ ~~56~~ 54 bytes ``` (<*>).map((++).init)<*>map(' ':)$["knowns","unknowns"] ``` Thanks to [@Leo](https://codegolf.stackexchange.com/users/62393/leo) for -3 bytes! Note: In the question's comments, the o.p. said that returning a list of strings is okay [Try it here.](https://repl.it/MjyA/2) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` “ṿ1“ŒwƘ»pż€⁾ sY ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO/cbAqmjk8qPzTi0u@DonkdNax417lMojvz/HwA "Jelly – Try It Online") [Answer] # Ruby, ~~53~~ 50 bytes ``` $><<"a as a unas una as una unas".gsub(?a,"known") ``` [Answer] ## Batch, 66 bytes ``` @set s= in (known unknown)do @ @for %%a%s%for %%b%s%echo %%a %%bs ``` Alternative answer, also 66 bytes: ``` @for %%a in (k unk)do @for %%b in (k unk) do @echo %%anown %%bnowns ``` [Answer] # Haxe, 71 bytes ``` (?x)->[for(a in x=["","un"])for(b in x)a+'known ${b}knowns'].join("\n") ``` [Try it online!](http://try-haxe.mrcdk.com/#7c670) [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), 47 bytes ``` "K Ks K unKs unK Ks unK unKs"|gsub("K";"known") ``` [Try it online!](https://tio.run/##yyr8/1/JW8G7mMtboTQPSAEJBSgF4ivVpBeXJmkoeStZK2Xn5ZfnKWn@//8vv6AkMz@v@L@ubl5pTo5uZl5BaQmQU5RYrptfWgLkAAA "jq – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~46~~ 44 bytes ``` ' s uns un s un uns'-replace' |s','known$&' ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X12hmEuhNK@YqzRPAUwA2eq6RakFOYnJqeoKNcXqOurZefnleSpq6v//AwA "PowerShell – Try It Online") (Almost) simple string replacement. Uses [Neil's approach](https://codegolf.stackexchange.com/a/145453/8478) to trim two bytes. Thanks to Martin for pointing that out. Sadly, it's shorter than the more interesting cross-product method by ~~three~~ ~~five~~ three bytes: ## [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~49~~ 47 bytes ``` ($a='known','unknown')|%{$i=$_;$a|%{"$i $_`s"}} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0Ml0VY9Oy@/PE9dR700D8LSrFGtVsm0VYm3VkkEMpVUMhVU4hOKlWpr//8HAA "PowerShell – Try It Online") [Answer] # T-SQL, ~~56~~ 54 bytes ``` PRINT REPLACE('1 1s 1 un1s un1 1s un1 un1s',1,'known') ``` SQL supports line breaks inside string literals, so similar to some other languages already posted. **EDIT**: Slightly longer (**82 bytes**), but a bit more clever: ``` SELECT k+s+k+p+k+s+u+p+u+s+k+p+u+s+u+p FROM(SELECT'known'k,' 's,'unknown'u,'s 'p)t ``` **EDIT 2**: My favorite so far, using a cross-self-join from a derived table (**79 bytes**): ``` WITH t AS(SELECT'known'a UNION SELECT'unknown') SELECT z.a+' '+t.a+'s'FROM t,t z ``` **EDIT 3**: Changed the replacement character from `'x'` to `1`, which lets me remove the quotes around it and save 2 bytes, since `REPLACE` does an implicit conversion to string. [Answer] # [ReRegex](https://github.com/TehFlaminTaco/ReRegex), 38 bytes ``` a/known/a as\na unas\nuna as\nuna unas ``` [Try it online!](https://tio.run/##K0otSk1Prfj/P1E/Oy@/PE8/USGxOCYvUaE0D0QDSQUYDRL5/x8A "ReRegex – Try It Online") [Answer] # Javascript ~~66 54 53~~ 50 bytes ``` _=>` s uns un s un uns`.replace(/ |s/g,'known$&') ``` ### History * saved 12 bytes thanks to @someone (explicit usage of "un" in the main string) * saved 1 byte thanks to @ThePirateBay (split..join instead of replace) * saved 3 bytes thanks to @Neil (better replace()) ]
[Question] [ Given an integer `n > 0`, output the length of the longest contiguous sequence of `0` or `1` in its binary representation. **Examples** * `6` is written `110` in binary; the longest sequence is `11`, so we should return `2` * `16` → `10000` → `4` * `893` → `1101111101` → `5` * `1337371` → `101000110100000011011` → `6` * `1` → `1` → `1` * `9965546` → `100110000000111111101010` → `7` [Answer] # [Python 2](https://docs.python.org/2/), ~~46~~ 45 bytes ``` f=lambda n,k=1:`k`in bin(n^n/2)and-~f(n,k*10) ``` [Try it online!](https://tio.run/nexus/python2#DYxBCoMwFAXX7SneJmgk0qbRpBHsUYqREAjqV8R1r57@xYOBN0xJ4xq2OQaQWkY9TMuUCXOmmr70eMlAsf2lms9GP2VJ@wkCG1ZB897eMBjjjNMMCt7bvu/scL8dZ6YLlXAR7QciVhDgDjgmZfkD "Python 2 – TIO Nexus") ### How it works By XORing **n** and **n/2** (dividing by **2** essentially chops off the last bit), we get a new integer **m** whose unset bits indicate matching adjacent bits in **n**. For example, if **n = 1337371**, we have the following. ``` n = 1337371 = 101000110100000011011₂ n/2 = 668685 = 10100011010000001101₂ m = 1989654 = 111100101110000010110₂ ``` This reduces the task to find the longest run of zeroes. Since the binary representation of a positive integer always begins with a **1**, we'll try to find the longest **10\*** string of digits that appears in the binary representation of **m**. This can be done recursively. Initialize **k** as **1**. Every time **f** is executed, we first test if the decimal representation of **k** appears in the binary representation of **m**. If it does, we multiply **k** by **10** and call **f** again. If it doesn't, the code to the right of `and` isn't executed and we return *False*. To do this, we first compute `bin(k)[3:]`. In our example, `bin(k)` returns `'0b111100101110000010110'`, and the `0b1` at the beginning is removed with `[3:]`. Now, the `-~` before the recursive call increments *False*/**0** once for every time **f** is called recursively. Once **10{j}** (**1** followed by **j** repetitions of **0**) does not appear in the binary representation of **k**, the longest run of zeroes in **k** has length **j - 1**. Since **j - 1** consecutive zeroes in **k** indicate **j** matching adjacent bits in **n**, the desired result is **j**, which is what we obtain by incrementing *False*/**0** a total of **j** times. [Answer] ## Python 2, 46 bytes ``` f=lambda n,r=1:max(r,n and f(n/2,1+~-n/2%2*r)) ``` [Try it online](https://tio.run/nexus/python2#FYzBCsIwEAXP@hXvEprqFtmsGC3Uf4mEQMFuZfHgyV@v62GYOc3WpmdZHrVAySYel/KJRoqiFS3qKREfv4M7pIP1/dZWg2JWMOFCYEc8OZ0J15t4iWTJPO53L5v1jS7kiuGOUDsERKX/1kc/) Extracts binary digits from `n` in reverse by repeatedly taking `n/2` and `n%2`. Tracks the length of the current run `r` of equal digits by resetting it to 0 if the last two digits are unequal, then adding 1. The expression `~-n/2%2` is an indicator of whether the last two digits are equal, i.e. `n` is 0 or 3 modulo 4. Checking the last two digits together turned out shorten than remembering the previous digit. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` b.¡€gM ``` [Try it online!](https://tio.run/nexus/05ab1e#@5@kd2jho6Y16b7//xsaG5sbmxsCAA "05AB1E – TIO Nexus") **Explanation** ``` b # convert to binary .¡ # split at difference €g # map length on each M # take max ``` [Answer] ## Mathematica, 38 bytes ``` Max[Length/@Split[#~IntegerDigits~2]]& ``` or ``` Max[Tr/@(1^Split[#~IntegerDigits~2])]& ``` [Answer] # Python, 53 bytes ``` import re;lambda g:max(map(len,re.findall('1+|0+',bin(g)))) ``` Anonymous lambda function. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` BŒgL€Ṁ ``` [Try it online!](https://tio.run/nexus/jelly#@@90dFK6z6OmNQ93Nvw/3A5k/P8fbaajYAjEFpbGQIaxsbmxuWEsAA "Jelly – TIO Nexus") ### How it works ``` BŒgL€Ṁ Main link. Argument: n B Binary; convert n to base 2. Œg Group adjacent, identical elements. L€ Map length over the groups. Ṁ Take the maximum. ``` [Answer] ## Ruby, ~~41~~ 40 bytes ``` ->b{("%b%b"%[b,~b]).scan(/1+/).max.size} ``` Find longest sequence of '1' in b or its inverse. Thanks to manatwork for saving 1 byte. [Answer] # JavaScript (ES6), 54 bytes ``` f=(n,r=0,l=1,d=2)=>n?f(n>>1,d^n&1?1:++r,r>l?r:l,n&1):l ``` A recursive solution with a lot of bit manipulation. `n` stores the input, `r` stores the length of the current run, `l` stores the length of the longest run, and `d` stores the previous digit. ### Test snippet ``` f=(n,r=0,l=1,d=2)=>n?f(n>>1,d^n&1?1:++r,r>l?r:l,n&1):l for(var i of [0,1,2,3,4,5,6,7,8,9,16,893,1337371]) console.log(`f(${i}): ${f(i)}`) ``` [Answer] # Perl, 43 bytes ``` #!perl -p \@a[$a+=$_-1+($_>>=1)&1||-$a]while$_;$_=@a ``` Counting the shebang as one, input is taken from stdin. [Try it online!](https://tio.run/nexus/perl#@x/jkBitkqhtqxKva6itoRJvZ2drqKlmWFOjq5IYW56RmZOqEm@tEm/rkPj/v4Wl8X/dAgA "Perl – TIO Nexus") [Answer] # Ruby, ~~51~~ ~~44~~ 43 bytes Function solution. @manatwork is made of magic ``` ->s{('%b'%s).scan(/0+|1+/).map(&:size).max} ``` [Answer] # Python 2, 57 bytes ``` a=lambda n:n and max((n&-n|~n&-~n).bit_length()-1,a(n/2)) ``` A recursive solution. There might be a shorter form for the bit magic. [Answer] # [Pip](https://github.com/dloscutoff/pip), 16 bytes Seems like there's gotta be a shorter way to get the runs of same digit... ``` MX#*(TBa`1+|0+`) ``` Takes input as command-line argument. [Try it online!](https://tio.run/nexus/pip#@@8boaylEeKUmGCoXWOgnaD5//9/QzMA "Pip – TIO Nexus") ### Explanation ``` TBa 1st cmdline arg, To Binary ( `1+|0+`) Find all matches of this regex #* Map length operator to that list MX Get the maximum and autoprint it ``` [Answer] # [Perl 6](http://perl6.org/), 36 bytes ``` {(.base(2)~~m:g/1+|0+/)».chars.max} ``` Explanation: ``` { } # a lambda .base(2) # convert the argument to base 2 ~~m:g/ / # regex match, with global matching turned on 1+|0+ # match one or more 1, or one or more 0 ( )».chars # replace each match by its length .max # take the maximum number ``` [Try it online](https://glot.io/snippets/em52gi3o7f). [Answer] ## Haskell, 79 characters ``` maximum.map length.group.i ``` where ``` import Data.List i 0=[] i n=mod n 2:i(div n 2) ``` Or in ungolfed version: ``` import Data.List pcg :: Int -> Int pcg = maximum . map length . group . intToBin intToBin :: Int -> [Int] intToBin 0 = [] intToBin n = n `mod` 2 : intToBin (n `div` 2) ``` ## Explanation: `intToBin` converts an int to a list of binary digits (lsb first). `group` groups contiguous sequences, such that `[1, 1, 0, 0, 0, 1]` becomes `[[1, 1],[0, 0, 0],[1]]`. `maximum . map length` calculates for each inner list its length and returns the length of the longest. Edit: Thanks to @xnor and @Laikoni for saving bytes [Answer] # Pyth, 7 bytes ``` heSr8.B ``` Do run length encode on the binary string, then sort it so that the longest runs come last, then take the first element (the length) of the last element (the longest run) of the list. In pseudocode: ``` ' S ' sorted( ' r8 ' run_length_encode( ' .BQ' bin(input()) )) \ 'he ' [-1][0] ``` [Answer] # [J](http://jsoftware.com/), 21 bytes ``` [:>./#:#;.1~1,2~:/\#: ``` [Try it online!](https://tio.run/nexus/j#@5@mYGulEG1lp6evbKVsrWdYZ6hjVGelH6NsxZWanJGvoKGjl6ZkoKlgpmBopmBhaaxgaGxsbmxu@P8/AA "J – TIO Nexus") ## Explanation ``` [:>./#:#;.1~1,2~:/\#: Input: integer n #: Binary digits of n 2 \ For each continuous subarray of 2 digits ~:/ Reduce it using not-equals 1, Prepend a 1 to those results #: Binary digits of n ;.1~ Cut the binary digits at each location with a 1 # Get the length of each cut [:>./ Reduce those lengths using maximum and return ``` [Answer] **MATLAB** 71 bytes ``` m=1;a=diff(int8(dec2bin(a)));while(any(a==0)),m=m+1;a=diff(a);end;m ``` This converts integer variable 'a' to a binary int8 array then counts the number of times the result has to be differentiated until there is no zero in the result. I am new here. Is this sort of input and one-liner allowed by the PCG rules? [Answer] # [Octave](https://www.gnu.org/software/octave/), 31 bytes ``` @(n)max(runlength(+dec2bin(n))) ``` [Try it online!](https://tio.run/nexus/octave#@@@gkaeZm1ihUVSal5Oal16SoaGdkppslJSZB5TQ1PyfpmCrkJhXbM2VpmGmqaOQpmEIoSwsjSFcY2NzY3NDCFvzPwA "Octave – TIO Nexus") ### Explanation This is a translation of my MATL answer. My initial plan was a different approach, namely `@(n)max(diff(find(diff([0 +dec2bin(n) 0]))))`. But it turns out that Octave has a [`runlength`](https://octave.sourceforge.io/octave/function/runlength.html) function (which I just found out about). By default it outputs only the array of run-lengths, so the desired result is the `max` of that array. The output of `dec2bin`, which is a char array (string) containing `'0'` and `'1'`, needs to be converted to a numeric array using `+`, because `runlength` expects numeric input. [Answer] # [Bash](https://www.gnu.org/software/bash/) / Unix utilities, ~~66~~ ~~65~~ 42 bytes Thanks to @DigitalTrauma for significant improvements (23 bytes!). ``` dc<<<`dc -e2o?p|fold -1|uniq -c|sort -n`rp ``` [Try it online!](https://tio.run/nexus/bash#@5@SbGNjk5CSrKCbapRvX1CTlp@ToqBrWFOal1mooJtcU5xfVKKgm5dQVPD/v6WlmampiRkA "Bash – TIO Nexus") [Answer] # Bash (+coreutils, +GNU grep), ~~33~~, 32 bytes EDITS: * Minus 1 byte (removed quotes around *grep* expression) **Golfed** ``` dc -e2o$1p|grep -Po 1+\|0+|wc -L ``` **Explained** ``` #Convert to binary >dc -e2o893p 1101111101 #Place each continuous run of 1es or 0es on its own line >dc -e2o893p|grep -Po '1+|0+' 11 0 11111 0 1 #Output the length of the longest line >dc -e2o893p|grep -Po '1+|0+'|wc -L 5 ``` [Try It Online!](https://tio.run/nexus/bash#@5@SrKCbapRvX1CTXpRaoKAbkK9gqB1TY6BdUw6U8fn/39LSzNTUxAwA) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 4 bytes ``` bøef ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJQRyIsIiIsImLDuGVmIiwiIiwiODkzIl0=) Abuses the `G` flag which returns the maximum value of the item on top of the stack. ``` b # convert input to binary øef # run_length_encoding and flatten 2D -> 1D # Implicitly take the largest value in the flattened array ``` [Answer] # [J-uby](https://github.com/cyoce/J-uby), ~~41~~ 38 bytes ``` ~:digits&2|:slice_when+:!=|:*&:+@|:max ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWN9XqrFIy0zNLitWMaqyKczKTU-PLM1LztK0UbWustNSstB1qrHITK6CqLQoU3KLNYrlAlCGUtrA0hgoYG5sbmxtCORDK0tLM1NTELBaif8ECCA0A) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` $b@b:lotl ``` [Try it online!](https://tio.run/nexus/brachylog#@6@S5JBklZNfkvP/v6GxsbmxueH/KAA "Brachylog – TIO Nexus") ### Explanation ``` $b List of binary digits of the input @b Runs of consecutive identical digits in that list :lo Order those runs by length tl Output is the length of the last one ``` [Answer] ## C#, 106 bytes ``` n=>{int l=1,o=0,p=0;foreach(var c in System.Convert.ToString(n,2)){o=c!=p?1:o+1;l=o>l?o:l;p=c;}return l;}; ``` Formatted version: ``` System.Func<int, int> f = n => { int l = 1, o = 0, p = 0; foreach (var c in System.Convert.ToString(n, 2)) { o = c != p ? 1 : o + 1; l = o > l ? o : l; p = c; } return l; }; ``` And an alternative approach accessing the string by index at 118 bytes, with whitespace removed: ``` System.Func<int, int> f2 = n => { var s = System.Convert.ToString(n, 2); int l = 1, c = 1, i = 0; for (; i < s.Length - 1; ) { c = s[i] == s[++i] ? c + 1 : 1; l = l < c ? c : l; } return l; }; ``` [Answer] # Javascript, 66 Bytes ``` x=>Math.max(...x.toString(2).split(/(0+|1+)/g).map(y=>y.leng‌​th)) ``` Thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) for the code. ### Explanation ``` x.toString(2) ``` Convert number to binary string. ``` split(/(0+|1+)/g) ``` Split every different character (0 or 1) (this regex captures empty spaces but they can be ignored) ``` map(y=>y.length) ``` For each element of the array get its length and put it in the returned array. ``` ... ``` Convert array to list of arguments ([1,2,3] -> 1,2,3) ``` Math.max() ``` Get the largest number out of the arguments. [Answer] # [Wonder](https://github.com/wonderlang/wonder), 27 bytes ``` max.map#len.mstr`0+|1+`g.bn ``` Usage: ``` (max.map#len.mstr`0+|1+`g.bn)123 ``` Converts to binary, matches each sequence of 0's and 1's, gets the length of each match, and gets the maximum. [Answer] ## Batch, 102 bytes ``` @set/a"n=%1/2,d=%1%%2,r=1+(%3+0)*!(0%2^d),l=%4-(%4-r>>5) @if not %n%==0 %0 %n% %d% %r% %l% @echo %l% ``` Port of @edc65's answer. `%2`..`%4` will be empty on the first call, so I have to write the expressions in such a way that they will still work. The most general case is `%3` which I had to write as `(%3+0)`. `%2` is easier, as it can only be `0` or `1`, which are the same in octal, so `0%2` works here. `%4` turned out to be even easier, as I only need to subtract from it. `(%4-r>>5)` is used to compare `l` with `r` as Batch's `set/a` doesn't have a comparison operator. [Answer] # [Dyalog APL](http://dyalog.com/download-zone.htm), 22 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Anonymous function train ``` ⌈/∘(≢¨⊢⊂⍨1,2≠/⊢)2⊥⍣¯1⊢ ``` `⌈/∘(`... The maximum of the results of the following anonymous function-train...  `≢¨`  the tally of each  `⊢⊂⍨` partition of the argument, where the partitioning is determined by the ones in  `1,` one prepended to  `2≠/` the pairwise unequal of  `⊢` the argument `)` applied to `2⊥⍣¯1` from-base-2 applied negative one times (i.e. to-base-2, once) to `⊢` the argument [TryAPL online!](http://tryapl.org/?a=f%u2190%u2308/%u2218%28%u2262%A8%u22A2%u2282%u23681%2C2%u2260/%u22A2%292%u22A5%u2363%AF1%u22A2%20%u22C4%20f%A8%206%2016%20893%201337371%201%209965546&run) [Answer] # Japt, 15 bytes ``` 2o!q¢ c ml n gJ ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.3&code=Mm8hcaIgYyBtbCBuIGdK&input=ODkz) or [Verify all test cases at once](http://ethproductions.github.io/japt/?v=1.4.3&code=Tm1VezJvIXGiIGMgbWwgbiBnSn0gcVI=&input=MQo2CjE2Cjg5MwoxMzM3MzcxCjk5NjU1NDY=). ### How it works ``` // Implicit: U = input integer, J = -1 2o // Create the range [0...2), or [0,1]. ! ¢ // Map each item Z in this range to U.s(2) q // .q(Z). // This returns the runs of 1's and 0's in the binary // representation of U, respectively. c // Flatten into a single list. ml // Map each item Z to Z.length. n gJ // Sort the result and grab the item at index -1, or the last item. // This returns the largest element in the list. // Implicit: output result of last expression ``` [Answer] ## R, 45 34 bytes ``` max(rle(miscFuncs::bin(scan()))$l) ``` Fixed a silly misunderstanding thanks to @rturnbull and @plannapus. ]
[Question] [ Whilst trying (and failing) have persuade my infant son to eat his dinner, I tried singing to him. Mid way through this song I realised the formulaic structure might lend itself well to code golfing! The task is to write a program or function which accepts no input and produces the following text: ``` There's a hole in the bottom of the sea There's a hole in the bottom of the sea There's a hole, there's a hole There's a hole in the bottom of the sea There's a log in the hole in the bottom of the sea There's a log in the hole in the bottom of the sea There's a hole, there's a hole There's a hole in the bottom of the sea There's a bump on the log in the hole in the bottom of the sea There's a bump on the log in the hole in the bottom of the sea There's a hole, there's a hole There's a hole in the bottom of the sea There's a frog on the bump on the log in the hole in the bottom of the sea There's a frog on the bump on the log in the hole in the bottom of the sea There's a hole, there's a hole There's a hole in the bottom of the sea There's a wart on the frog on the bump on the log in the hole in the bottom of the sea There's a wart on the frog on the bump on the log in the hole in the bottom of the sea There's a hole, there's a hole There's a hole in the bottom of the sea There's a hair on the wart on the frog on the bump on the log in the hole in the bottom of the sea There's a hair on the wart on the frog on the bump on the log in the hole in the bottom of the sea There's a hole, there's a hole There's a hole in the bottom of the sea There's a fly on the hair on the wart on the frog on the bump on the log in the hole in the bottom of the sea There's a fly on the hair on the wart on the frog on the bump on the log in the hole in the bottom of the sea There's a hole, there's a hole There's a hole in the bottom of the sea There's a flea on the fly on the hair on the wart on the frog on the bump on the log in the hole in the bottom of the sea There's a flea on the fly on the hair on the wart on the frog on the bump on the log in the hole in the bottom of the sea There's a hole, there's a hole There's a hole in the bottom of the sea There's a smile on the flea on the fly on the hair on the wart on the frog on the bump on the log in the hole in the bottom of the sea There's a smile on the flea on the fly on the hair on the wart on the frog on the bump on the log in the hole in the bottom of the sea There's a hole, there's a hole There's a hole in the bottom of the sea ``` Challenge rules: * The text may be printed or returned as function output * Each verse is separated by a single empty line * Trailing whitespace is OK as long as it does not change the layout (so no leading whitespace or extra spaces between words) * Trailing newlines are OK too. * No leading newlines. * All languages welcomed, and this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes for each language wins! [Answer] # [SOGL](https://github.com/dzaima/SOGLOnline), ~~103~~ ~~94~~ 93 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` Ψ ~Δ№Q‘离vζh‛←&M⁶╥7[P≈╔6≡⁸(φΔ\⅔Σ‚>≡ā⁷⁽○¹‘Ξ⁵K4s³‘⁽Bθ2n{@∑" the ”+Κ:bΚē‽:C}TPb"n@²‘+Tō, upcPøP ``` [Try it here!](https://dzaima.github.io/SOGLOnline/?code=JXUwM0E4JTIwJTdFJXUwMzk0JXUyMTE2USV1MjAxOCV1MDNCNyVBNiVCQnYldTAzQjZoJXUyMDFCJXUyMTkwJTI2TSV1MjA3NiV1MjU2NTclNUJQJXUyMjQ4JXUyNTU0NiV1MjI2MSV1MjA3OCUyOCV1MDNDNiV1MDM5NCU1QyV1MjE1NCV1MDNBMyV1MjAxQSUzRSV1MjI2MSV1MDEwMSV1MjA3NyV1MjA3RCV1MjVDQiVCOSV1MjAxOCV1MDM5RSV1MjA3NUs0cyVCMyV1MjAxOCV1MjA3REIldTAzQjgybiU3QkAldTIyMTElMjIlMjB0aGUlMjAldTIwMUQrJXUwMzlBJTNBYiV1MDM5QSV1MDExMyV1MjAzRCUzQUMlN0RUUGIlMjJuQCVCMiV1MjAxOCtUJXUwMTREJTJDJTIwdXBjUCVGOFA_,v=0.12) ``` ...‘ push "bottom of the sea" - kept for the loop, here for ...‘ push "hole in log in bump on frog on wart on hair on fly on flea on smile on" ...‘ push "there's a " ⁽ uppercase the 1st letter of that B save "There's a " in B θ split the long data string on spaces 2n split in arrays of length 2 { for each of those: @∑ join the current array with spaces - e.g. "hole in" " the ”+ append " the " to it Κ prepend that to "bottom of the sea" (or whatever it is now) : create a copy bΚ prepend B to it - finishes current line ē‽:C} if (E++), save a copy of that in C (for the last line) TP print the current line twice b"...‘+ B + "hole" - "There's a hole" T output that, keeping item ō, output ", " up print the kept item lowercased cP print the contents of C øP print an empty line ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~90~~ ~~87~~ 75 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ¥▌▼h4█☻■Ω1gçΔ¶Zjµ│☺X▄)/╞▄╒)¥jêLqα╧ñu┌⌂½╧ûⁿ↕O◘╔╪kl<æàbπïfuσ♪╫qΓ╪ûQ├╘Te♥Æó♣ƒE ``` [Run and debug it](https://staxlang.xyz/#p=9ddd1f6834db02feea316787ff145a6ae6b30158dc292fc6dcd5299d6a884c71e0cfa475da7fabcf96fc124f08c9d86b6c3c918562e38b6675e50dd771e2d89651c3d454650392a2059f45&i=&a=1) Unpacked, ungolfed, and commented it looks like this. ``` `;$w]i"50h1&V~OP>F$` compressed literal for "There's a hole in the bottom of the sea" X store in register X without popping zG push an empty string and jump to the target (trailing }) `hfUiVx}.|j~vG12])Bxk?v zF`j split "log bump frog wart hair fly flea smile" into array of words F for each word, execute the following i. o. i? (i ? " o" : " i") where i is the 0-based iteration index + concatenate to the word `_o9!`+ concatenate "n the " G jump to target below, resume next foreach iteration when finished } this is the target of `G`, execution resumes when finished As|@ insert substring at position 10 QQ peek and print with newlines twice x14( trim string to leftmost 14 characters q peek and print without newlines ., p print ", " without newline vP lowercase 14 characters and print with newline xP push value of register X, then print with newline zP print blank line ``` [Run this one](https://staxlang.xyz/#c=%09%60%3B%24w]i%2250h1%26V%7EOP%3EF%24%60++++++++%09compressed+literal+for+%22There%27s+a+hole+in+the+bottom+of+the+sea%22%0A%09X+++++++++++++++++++++++++++%09store+in+register+X+without+popping%0A%09zG++++++++++++++++++++++++++%09push+an+empty+string+and+jump+to+the+target+%28trailing+%7D%29+%0A%09%60hfUiVx%7D.%7Cj%7EvG12]%29Bxk%3Fv+zF%60j%09split+%22log+bump+frog+wart+hair+fly+flea+smile%22+into+array+of+words%0A%09F+++++++++++++++++++++++++++%09for+each+word,+execute+the+following%0A%09++i.+o.+i%3F++++++++++++++++++%09%28i+%3F+%22+o%22+%3A+%22+i%22%29+where+i+is+the+0-based+iteration+index%0A%09++%2B+++++++++++++++++++++++++%09concatenate+to+the+word%0A%09++%60_o9%21%60%2B+++++++++++++++++++%09concatenate+%22n+the+%22%0A%09++G+++++++++++++++++++++++++%09jump+to+target+below,+resume+next+foreach+iteration+when+finished%0A%09%7D+++++++++++++++++++++++++++%09this+is+the+target+of+%60G%60,+execution+resumes+when+finished%0A%09++As%7C%40++++++++++++++++++++++%09insert+substring+at+position+10%0A%09++QQ++++++++++++++++++++++++%09peek+and+print+with+newlines+twice%0A%09++x14%28++++++++++++++++++++++%09trim+string+to+leftmost+14+characters%0A%09++q+++++++++++++++++++++++++%09peek+and+print+without+newlines%0A%09++.,+p++++++++++++++++++++++%09print+%22,+%22+without+newline%0A%09++vP++++++++++++++++++++++++%09lowercase+14+characters+and+print+with+newline%0A%09++xP++++++++++++++++++++++++%09push+value+of+register+X,+then+print+with+newline%0A%09++zP++++++++++++++++++++++++%09print+blank+line&i=&a=1) [Answer] # Perl 5, ~~158~~ 154 bytes ``` $_="There's a bottom of the sea ";for$,(<{{hole,log}" i",{bump,frog,wart,hair,fly,flea,smile}" o"}>){s/a/a $,n the/;say$_.$_.($t||=s/.{14}/$&, \l$& $&/r)} ``` [154 bytes](https://tio.run/##FYzRCoMgFEDf@woRaQV3uWA9tfYHe9vjIAw0A@uGOkaYvz7X4Jy3w1mlNU1KrO/oU0srT44IMqD3OBNUxGtJnBQZbRVaBsUtBI1GgsExUjJRCMN7XkFZHOEjrActJgvKbIdSgJsnI48QabyXwXHBBWGw/Le8dWJjfXVQML/vneNVqK@RsxzIy7A8Yzm3ZUzpi6ufcHHp/GiqS/0D) [158 bytes](https://tio.run/##HY1BCsIwEEX3nmIYQlUYGwt2VesN3LkUSgpJG0g7JYlIKb26scrnLd7i8SftXZmSaGp89NrrfQAFPTsNdoTYa2g5Rh6Azd@CVjusRKyDzJfiskqRETydyHYik74y7IU9oONuy5GuS/saJjKeO3orH6lX1pNx84ZWFAbrNK0IPOLtuAQ1o2i2RayCVFKBsL9Tuab04SlaHkM63cv8XHwB) [Answer] # [Python 2](https://docs.python.org/2/), ~~202~~ ~~190~~ ~~187~~ ~~185~~ ~~183~~ ~~182~~ 181 bytes ``` s="bottom of the sea\n" a="There's a " for w in'hole log bump frog wart hair fly flea smile'.split():s=w+" %sn the "%'io'['g'in s]+s;print(a+s)*2+a+"hole, t%shole\n"%a[1:]+a+s[-30:] ``` [Try it online!](https://tio.run/##HY7LCsMgEEX3@YpBEJPalj52KfmL7tIsJqBRMCqOJeTrreniwoG7OCfu2QT/KIUGNoecwwpBQzYKSOHHswYH9jYqKUGAwBodEmxgvTDBKXBhgfm7RtCp0oYpg0GbQLu9TiHQap0SV4rO5rbradgkA07@b2Bc2CBGsQjrgSZJr5iszy1K6k4PiZIdkjNkTgfUGo7jvZ/qQ@PleeunUn4 "Python 2 – Try It Online") Old alternatives to `'io'['g'in s]` (13 bytes): * 14: `'oi'[s[5]<'n']` * 15: `'io'[len(s)>30]`, `'ioo'[len(s)%3]`, `'ooi'[len(s)%4]`, and `'io'[w[1]=='o']` --- Saved: * -1 byte, thanks to Jonathan Allan * -1 byte, thanks to Rod * -1 byte, thanks to Erik the Outgolfer [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~261~~ ~~246~~ 236 bytes ``` #define X" on the " char*a="smile"X"flea"X"fly"X"hair"X"wart"X"frog"X"bump"X"log in the hole in the bottom of the sea\n";f(i){for(i=0;i<9;)printf("T%s%sT%1$s%2$sT%1$shole, t%1$shole\nT%1$s%3$s\n","here's a ",a+"_TH<0$\31\r"[i++],a+95);} ``` -15 bytes, Thanks to Daniel Schepler -10 bytes, Thanks to ceilingcat [Try it online!](https://tio.run/##NY3BasMwEETv/QqxtalcO5A09BCc3PsBPgTqUjbKylqQpSCphFL663XlmFz2zczCjFoNSk3T45k0OxJHEN6JZEjAgzIYnvEAcWRLcARtCW/4ztcgh4wrhjRnwQ8Zp6/xkmH9IHhpMd7SXZ98Sn4UXt9cJOwdtFpy9aN9kHxYt7zftdUlsEtaQlfGMnblpojlS7GIua0R6S57t7y3RcxVDRgK9BQFCmiwhs/ubb8u@u2mD/DOdf2Rw91r1f5OI7KTeVXO5k9pi0OcVtd/ "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~103~~ ~~100~~ ~~99~~ ~~97~~ ~~96~~ ~~93~~ 92 bytes Saved a byte thanks to *Kevin Cruijssen* ``` “¥ÊˆŽ bumpÑå‡îtíÁ¤†îÌea¹²“#v’T€Î's a ’s„oiN2‹èy“ÿ ÿn€€ ÿ“©“—耂€€í™“JDN_iDU}X14£Dl‚„, ýXõ»,® ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcOcQ0sPd51uO7pXIak0t@DwxMNLHzUsPLyu5PDaw42HljxqWHB43eGe1MRDOw9tAipWLnvUMDPkUdOaw33qxQqJCkBe8aOGefmZfkaPGnYeXlEJVHN4v8Lh/XlANUAEZIGsWAkkHjVMObwCJNowCyJ3eO2jlkVACS8Xv/hMl9DaCEOTQ4tdckDyDfN0FA7vjTi89dBunUPr/v8HAA "05AB1E – Try It Online") **Explanation** `“¥ÊˆŽ bumpÑå‡îtíÁ¤†îÌea¹²“#v` starts a loop over the list `["hole", "log", "bump", "frog", "wart", "hair", "fly", "flea", "smile"]`. The words are compressed using the 05AB1E dictionary. On each we do: ``` ’T€Î's a ’ # push the string "There's a " s # move the string from the previous iteration to the top of the stack # will be an empty string the first iteration since there is no input „oiN2‹è # push "i" for the first 2 iterations and "o" otherwise y # push the current word “ÿ ÿn€€ ÿ“ # use interpolacing to create the meat of the current iteration string # meaning "hole in the ", "log in the hole in the " and so on © # store a copy in the register for the next iteration “—耂€€í™“ # push the string "bottom of the sea" JD # join the whole line together and duplicate it N_iDU} # if this is the first iteration, store a copy of the line in X X14£ # push the first 14 chars of X, which is "There's a hole" Dl # make a lower-case copy ‚„, ý # join the original with the lowercase copy on ", ", forming line 3 X # push X which is line 4 õ # push and empty string, to create the line break between sections », # join the whole section on newlines and print ® # push the register for the next iteration ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~194~~ ~~188~~ ~~185~~ ~~180~~ 174 bytes ``` $z=$a="in the bottom of the sea" $b="here's a" $h="$b hole" echo hole log bump frog wart hair fly flea smile|%{,"T$b $_ $a"*2 $a='oi'[!$j++]+"n the $_ $a" "T$h, t$h T$h $z "} ``` [Try it online!](https://tio.run/##JY7BCsIwDIbvfYoYIgO3k/e9hTcRaSUzlc5IWxlOffZat0Pg@/j/kDx04piEQyiF5p5sj/4OWRic5qwj6LBYYouGXI/CkZsEf5MeyYFoYDR8EV0Qgl7BPccHDLHSZGMGsT7CEF512EIafeDP9t3hoa7TGcjibm/q6UZ9c9zQrW1PLa5frLGpVekgk5gKQLPBbyk/ "PowerShell – Try It Online") ~~Can't quite seem to catch Python...~~ Basically, sets a few common strings to `$h`, `$a`, `$z`, and `$b`, then goes through a loop through each of the items (`hole`, `log`, ... `flea`, `smile`), each iteration outputting the appropriate verse. There's a little bit of logic with `!$j++` in the middle to account for the `in`/`on` switch that happens. Otherwise, all the strings are just left on the pipeline, and the default `Write-Output` gives us newlines for free. *-6 bytes thanks to Arnauld.* *-3 bytes thanks to mazzy.* *-5 bytes thanks to Veskah.* *-6 bytes thanks to mazzy.* [Answer] # JavaScript (ES6), ~~201 194 189 188~~ 187 bytes *Saved 1 byte thanks to @Shaggy* ``` _=>`14log4bump5frog5wart5hair5fly5flea5smile5`.replace(/.+?\d/g,w=>`T0${(p=w+3+p)+p}1, t01 T01432 `.replace(/\d/g,n=>`here's a |hole|bottom of the sea |n the | i| o`.split`|`[n]),p=`2T0`) ``` [Try it online!](https://tio.run/##Tc69bsMgGIXh3VfBEKlGdv2TmNHtTXhLo0CcD5sI8yEgtaqSa3dQpgxHepdHOjfxK/zolA2fBq@wyX4791@87TRO3eW@WCYdTmwVLrBZKMek/ksDwfyiNDBeObBajJDXVfH9c62nck1@aHb/ue3X4lBYWthHW5LQtNnQtN1hn72hlzBJzODgwxNB4owa4gVDwIWgJGEG4kFk0bwyEhUJ8spbrQKP/GhOtLQ93w8Np9uIxidepfe5zCndng "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 235 bytes Simply [RegPack'ed](https://siorki.github.io/regPack.html). ``` _=>[..."Z[]^_$cdjkqvxz{}~"].reduce((p,c)=>(l=p.split(c)).join(l.pop()),`Tj{{}qq}$$}~~}dd}__}xx}cc}[[v~ frogz$}v Z{kZz on^x flyz_v], tj]Zkq log in^{k] in^ bottom of^ seajhere's ad wartz~c fleazx$ bumpzq_ hairzd^ the] hole[ smilezcZ Tj`) ``` [Try it online!](https://tio.run/##FY5RjoMgFEX/u4qXxmQw6bADu4p@aZBSwAqiIFDHweDWHefrJic5OVezhQXulYvfkxXy6KqDVvcGY3ytG9LSggs9zMuatrxfCfZSfLhEyN14Wd2RqRwOzqiIeFlibdWEDHbWobK8PR962/I856LI@56FyJTmdc2c56ZZdui8faciL5d6G@oEdmpX6Mxvogu5QdSkHmYw9g1qareB/A@8bIx2BNu1ECTTvfTyKwAT8MN8TDs/fcnSWsDrM7o0U@iZ8km0EHtJoLdGNhBGZWTi9eWhn@XB7RROjM8Q6s7Xxx8 "JavaScript (Node.js) – Try It Online") [Answer] # Bash, ~~168~~ 160 bytes ``` r="There's a bottom of the sea ";for i in {hole,log}\ in {bump,frog,wart,hair,fly,flea,smile}\ on;{ r=${r/a/a $i the};t=${r:0:14};echo "$r$r${u=$t, ${t,} $r}";} ``` [160 bytes](https://tio.run/##HYyxCsMwDET3fIUwhi6CtNApJn/RsYtSlNjgREV2KMX4292kHDe843ETJd@ajubhWfmSgGCSnGUFmSF7hsTUGTeLQoCwQfESGaMs9fnHaV/fOKss@CHN6CkozvF7lAnTGiIfomyudDraoj31BDacz9Xlcxmuw@1eHb@8gLF6pOyjzQi2ZKyd1Wpcbe0H) [168 bytes](https://tio.run/##HY3BCsMgEETv@YpFhF4W0kJPkfxFj7lsikbBZMtqKUX8dhvLMMzMYXgrJd@azOrhrdhLAgLP0UI4IHsLK@fMO7D7r2RpUCbPush0nW73enalM4IuGeugRRnHAqG/I29Lz7K@9xc64Q0/JBk9BUEXv6ctYdpDtFgX4MMUsE/PoLScyspI54w0EujQ8dXU1n4) Translated from my other answer in Perl. [Answer] # Japt `-Rx`, ~~126~~ ~~116~~ ~~113~~ ~~112~~ ~~111~~ ~~109~~ 107 bytes It turns out that golfing a string compression challenge while on your phone down the boozer is incredibly difficult - who'd've thunk?! ``` `T's»dâ ÈÞ­omºfdÈ a`rdS tE8 ¯E `logn¿mpnfgnØnirnf§nf¤Úè`qÍË2ÆiAV¯E©8 iF¯E ÔqVri'oÃpW+v iSi,)UPÃc ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.6&code=YFSUnCdzu2TinIIgyALerW9tumZkyAKgYWByZFMKdEU4Cq9FCmBsb2duv21wbmaeZ27YHm6VaXJuZqduZqSG2uibYHHNyzLGaUFWr0WpOCBpRq9FINRxVnJpJ2/DcFcrdiBpU2ksKVVQw2M=&input=LVJ4) ``` :The first 3 lines get assigned to variables U, V & W, respectively `...` :The compressed string "There'sdadholedindthedbottomdofdthedsea" rdS :Replace all "d"s with spaces tE8 :Substring of U from 0-based index 14 (E), of length 8 (=" in the ") ¯E :Slice U to index 14 (="There's a hole") `...` :The compressed string "lognbumpnfrognwartnhairnflynfleasmilent" qÍ :Split on "n" (note that the last element is irrelevant) Ë :Map each element at 0-based index E in array F 2Æ : Map the range [0,2) iA : Insert the following in U at index 10 V¯ : V sliced to index E©8 : Logical AND of E and 8 (=0 on first iteration, 8 on all others) i : Prepend F¯E : Slice F to index E Ô : Reverse q : Join with Vri'o : Replace "i" with "o" in V à : End map p : Push W+ : W appended with v : W lowercased iSi, : Prepended with a space prepended with a comma ) : End append UP : U and an empty string à :End map c :Flatten :Implicitly join with newlines, trim & output ``` [Answer] # XML, 719 673 603 514 493 486 bytes ``` <!DOCTYPE a[<!ENTITY T "There's a"><!ENTITY O " on the"><!ENTITY a " hole in the bottom of the sea "><!ENTITY b " log in the&a;"><!ENTITY c " bump&O;&b;"><!ENTITY d " frog&O;&c;"><!ENTITY e " wart&O;&d;"><!ENTITY f " hair&O;&e;"><!ENTITY g " fly&O;&f;"><!ENTITY i " flea&O;&g;"><!ENTITY z "&T; hole, there's a hole &T;&a; ">]><a>&T;&a;&T;&a;&z;&T;&b;&T;&b;&z;&T;&c;&T;&c;&z;&T;&d;&T;&d;&z;&T;&e;&T;&e;&z;&T;&f;&T;&f;&z;&T;&g;&T;&g;&z;&T;&i;&T;&i;&z;&T; smile&O;&i;&T; smile&O;&i;&z;</a> ``` You can "execute" it with `xmlstarlet sel -t -m '//a' -v . -n <xml_file_here>`. This would be a lot easier if XML wasn't so verbose, but on the bright side, this is less than 25% the size of the original text. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 150 bytes ``` THsmile oNflea oNfly oNhair oNwart oNfrog oNbump oNlog iNE N $&$'¶TH O^$` .+ $&¶$&¶THW, tHW¶THE¶ H here's a E W iNbottom of the sea W hole N n the ``` [Try it online!](https://tio.run/##HYwxCsMwDEV3nUJDaIaW3sLgyV0C3kodUGqDHRdHofRiPoAv5ioZ9J/04KsQh9X1DpPeUoiE2SyR3ImfpHehCL6u8OFKfgvmPX0EUY5gFBgYLsPY6qTh8RxeAPermFaPmbS9IWt7bKpV0OCp0LihQ1BgpT9n5pwwL8iecCMHFnyOJG/XU/X@Bw "Retina 0.8.2 – Try It Online") Explanation: ``` THsmile oNflea oNfly oNhair oNwart oNfrog oNbump oNlog iNE ``` Insert the last verse. ``` N $&$'¶TH ``` Compute all the verses. ``` O^$` ``` Put the verses in the correct order. ``` .+ $&¶$&¶THW, tHW¶THE¶ ``` Complete each verse and add the chorus. ``` H here's a E W iNbottom of the sea W hole N n the ``` Expand some placeholders. [Answer] # [R](https://www.r-project.org/), ~~237~~ 231 bytes ``` i=" in the " for(j in 0:8)cat(f<-c(t<-"There's a ",paste(c("log","bump","frog","wart","hair","fly","flea","smile")[j:0],collapse=" on the "),if(j)i,h<-"hole",i,b<-"bottom of the sea "),f,t,h,", there's a ",h," ",t,h,i,b," ",sep="") ``` [Try it online!](https://tio.run/##PU7NCsMgDL73KSSXKaTQ4yjdW@w2drASp8VOUcfY07tUxi75fvKFL7k1fwHhn6I6EjDYmOV2yGk@K6OrtMtoZF1GuDrKdCpCC8CkSyVpJIT4AIT1tScGm7t661wZnPb5MMOnT9IMZfeBQN22ebqjiSHoVIjr469eobdyUx4dF7rIWfS4Ml9jrXEX0fZcIT1w1mJFh4CH93@NjQH6gi87L5QuAKq1Lw "R – Try It Online") [Answer] # PHP, ~~180~~ 178 bytes ``` foreach([hole,log,bump,frog,wart,hair,fly,flea,smile]as$w)echo$a=T.($b="here's a ").($s="$w ".io[++$i>2]."n the $s").$c="bottom of the sea ",$a,T,$b.=hole,", t$b T$b in the $c "; ``` Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/289511f887b3999e748699801746630ffa9bb33d). Yields warnings in PHP 7.2; to fix, put quotes around the array elements, `io`, `hole` and the two standalone `T`. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~334~~ ~~328~~ ~~307~~ 299 bytes ``` char*s="here's a \0smile on the flea on the fly on the hair on the wart on the frog on the bump on the log in the hole in the bottom of the sea\n";i;k=105;a[]={0,1,1,1,1,0,1,2,2};main(j){for(;i<9;k-=11+a[i++])do{printf("T%s%s",s,s+k);}while(j++&1||!printf("T%shole, t%shole\nT%s%s\n",s,s,s,s+105));} ``` [Try it online!](https://tio.run/##TY/BDoIwDIZfZZKo4GbCTDyYyVt4Aw8Vh5vARrYZY9Bnx4GgppevTb/mb76@5HnX5QLMyiaB4IYvLQKUxbaWFUdaISc4KioOP35MKECaie9g3HfF6MvEp1vdTFz5sRxV7a@PfNLO6RrpYugsh0wFTLIyofGWQXpM2pjQsXrakM2L1SBVeI3aQpuQyf2OleuEUgypxPgYnXXbGKlcEQaHuZ3bgFhicRmx1134v8Irxgv6fM7@lvpEBLkPZGrQfJBeHGQfJvJ@170B "C (gcc) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 166 bytes ``` ($/=@(($!="There's a")X [\R,](<hole log bump frog wart hair fly flea smile>Z(<i o>[$++>1]~"n the")xx*)X"bottom of the sea ")).map:{say "$_$_$! hole, {$!.lc} hole $0"} ``` [Try it online!](https://tio.run/##HY3RCoIwGIXvfYrfMWhLsbrpIlR6huhCMokVv03YmmyLFLFXN43Dge98N6dFq/bTxOgmOzJGw4ycJVpcORCEF1BeT3HFUmkUgjJPuL91C7Wd6SOsBykaC7Xq56IApxuF@YWlDZi8pFGU76oveYGXSHjXrXlB7sZ7o8HUiwSHIiCcJ1q0h8GJHgi9zQlh@YthoGGiHuN/BXRLxmn6AQ "Perl 6 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) `-R`, 142 bytes ``` `—¤clogc¿mpcfžgcØ ÖŽrcf§cf¤acsÚè`qc `ˆ e Þ­om  e  a` `T”œ's a ` £W+U¯YÄ ÔËE?"io"gE<Y +`n e `:P +Dø+` {V} ` ²+W+`—¤, t”œ's a —¤ {W}—¤ {V+R ``` [Try it online!](https://tio.run/##y0osKPn/P@HQ9ENLknPy05MP7c8tSE47NC89@fAMucPTDvUVAXnLgXhJYnLx4VmHVyQUJnMlHOpQODQhVeHwvENr83MVDvWDeYcWJCZwJYQcmnJojnqxQqJCAtehxeHaoYfWRx5uUTg85XC3q71SZr5SuqtNpIJ2Qh5YT4JVgIK2y@HmQzu0ExSqw2q5EhQObdIO1wY7SEehBG4YiM9VHV4LooEKtYP@/9cNAgA "Japt – Try It Online") [Answer] ## Batch, 267 bytes ``` @echo off set r=i set t= There's a hole set s=bottom of the sea for %%w in (hole log bump frog wart hair fly flea smile)do call:c %%w exit/b :c set s=%1 %r%n the %s% echo%t:~,11%%s% echo%t:~,11%%s% echo%t%,%t:T=t% echo%t%%s:~-25% echo( if %1==log set r=o ``` `t` contains a string repeated in the chorus, `s` contains most of the verse line, while `r` chooses between `in the` and `on the`. In the verses, only the first 11 characters of `t` is needed, while in the first chorus line the second copy of `t` has its `T` lowercased and the second chorus line reuses the last 25 characters of `s`. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~173~~ 170 bytes ``` a="T#{["here's a hole"]*3*"%s"%[", t"," T"]+c=" in the "}bottom of the sea " b=a[31,39] %w{log bump frog wart hair fly flea smile x}.map{|i|puts b,b,a;b[9]+=i+c;c[1]=?o} ``` [Try it online!](https://tio.run/##HcdBCoMwEEDRfU4xTJFCDQVxJRJ6CXchi4nEJqCNJBEr6tlT6eLD@2HRW84ksLvtEq0J5h6BwPrRoHrUDywiFhI5JOTIOlRlLxDcB5I1gKf2KfkJ/PD/aIgxZFqQrCteN4oV6z76N@hlmmEIl1YKCSy5AMO4XRmCOLnRwPd8TjTvhzvmJUXQXHNqtWxUKVzZt72slHj5M@cf "Ruby – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~243~~ 215 bytes Reduced to 215 bytes with great help from nimi ``` c[[l n,l n,'T'#h++", "++'t'#h,l 8,""]|n<-[8,7..0]] t#u=t:"here's a "++u h="hole" c=concat l n='T'#c(drop n$map(++" on the ")(words"smile flea fly hair wart frog bump")++["log in the ",h," in the bottom of the sea"]) ``` [Try it online!](https://tio.run/##NY3PasMwDIfveQqhDpJgt@y2UuY3aE/bLQtDdZ06zP@wnZbBnn2eM7aDBN9P0idN6UMZU24C3oocBgOOr9W@thvNGHJAxtpcocZ7jjh@ueftsOdPu93jODZ5s4h8QK2iahPQur00WqD2RmEjhfROUm6qUqxK2V2iD@AeLIWu6sE7yFoB9t3dx0vCZGejYDKKavsETXOEO8UMU/RXOC82YM/YgKbS/HfLNcd/OPucvQU//VJShGNfLNWpgPrz9A5hyS85Hh3cyrecDF1T2coQfgA "Haskell – Try It Online") (Old 243 byte version is [here](https://tio.run/##NY/NSgMxEIDveYphKKySWCyIBzFvYE96WxZJY9oEk8ySTCuC776mWT0M830zMD/e1E8X47KwRu@KGyoYQOGbUXQoqg5S4oGYKQEdgb2D6gyKoBFC7o6CmtC/WG0pW8MiQtbD2/DEUt7YzUehGfKINYU2WJHCY2yDVvju2ZtQOnyZwmun0KnD4ZzmDvFaCMpPt1JWcdF2HNsedY2/Xb4drAClHHj11tw9KsTpJz/fjQ13D9vt/TQtybQPNCQz799hPvMrl5cMl@UX "Haskell – Try It Online")). A quite straightforward solution. ``` -- main function producing a list of lines v = concat [[ l n, l n, -- second line of each verse equals to its first line 'T' # h ++ ", " ++ 't' # h, l 8, -- last line of each verse is the same in all verses "" ] | n <- [8,7..0]] -- a small helper to construct similar strings t # u = t : "here's a " ++ u h = "hole" -- construct a first line of n-th verse (with n = 8 is the first and n = 0 is the last one) -- Every such line begins with a constant prefix followed by expanding list of nested entities l n = 'T' # concat ( drop n $ map (++ " on the ") (words "smile flea fly hair wart frog bump") ++ ["log in the ", h, " in the bottom of the sea"] ) ``` [Answer] # [JavaScript (Babel Node)](https://babeljs.io/), 239 bytes *-7 bytes from @Oliver `*.*`* ``` (x=0,r='hole0log0bump0frog0wart0hair0fly0flea0smile'.split`0`).map(a=>(t=(i="There's a ")+a+r.slice(0,x++).reverse().map((h,_)=>` ${"io"[_<x-2|0]}n the ${h}`).join``+(o=` in the bottom of the sea `))+t+(`${k=i+"hole"}, ${k} `)+k+o).join` ` ``` [Try it online!](https://tio.run/##LY9BasMwEEX3OYUQAUvINqLrKqfIrpRo7I4rxbLHSGrqkvrsrtp0MTDzPvPgX@EGqY9@yU0HHYZmpjfce5oTBWwDvYtdrEbX0VSuEF2I7j6mRQ@xbJ8Qs3bgox7CVxkEnSYfsGrTEny22sp2gkWAOYlshDf87DBilRgwLhWo2KbgexS6XpWSbcQbxoTi8SVcfZHmZNnxzj3xl8vz2jx969dtZtlhoW4r/iv52VolyFjmH0lHOdPEaPi7EsLBSqmyEvZ4H41X/LcK3@qiGLeSqVHRv@hgd7n/AA "JavaScript (Babel Node) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~213 206 198~~ 193 bytes ``` k='n the ';o=e='bottom of the sea\n';b="There's a ";h='hole' for j in[h]+'log bump frog wart hair fly smile'.split():o=j+' '+'io'['g'in o]+k+o;print(b+o+b+o+b+h+', t'+b[1:]+h+'\n'+b+h+' i'+k+e) ``` [Try it online!](https://tio.run/##JY7NCoMwEITvfYrFyyhbCqU3Q96iN@shgWjiT1ZiSvHpra2HgZmPGZhly17iY99HjUjZO4IS7TSs5CwzSfeHqzOvCGV18fQuOaxkqFBew8vkcOkk0UAhNr5lTNKTfc8LdelwH5MyeRMSddNG6xyO/m1dppDLqhY9MAiMIGjQI0SSlkcWtaQQc2lZ@JRnXCmDbXOv21867pyYAo6Fq/b9Cw "Python 3 – Try It Online") --- -15 bytes thanks to @Sara -5 bytes thanks to @ASCII-only Probably a bit more golfable, but not much. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 267 bytes ``` import StdEnv,Text,Data.List t="here's a " h="hole" b=" in the bottom of the sea" f=foldr((+)o\s#p="T"+t+join" on the "(reverse s)+" in the "+h+b =join"\n"[p,p,"T"+t+h+", t"+t+h+"\nT"+t+h+b+"\n\n"])""(tl(inits["log","bump","frog","wart","hair","fly","flea","smile"])) ``` [Try it online!](https://tio.run/##PU/BbsMgDL3nK5B3WCLo/oBbd5jUw6T21vRAEmiYACNwu@Xnx2hSTbLs957es@zRaRWKx@nmNPPKhmJ9xETsSNN7uIuT/iGxV6TeDjZTQxJmnfRrZopBM1eGTkMzSGA2MJo1G5AIPUOzsqwVNEYadFNqW95hn1@ihBNw4l9oAzDcYtAmfdcp10jH/5cBn/nQyNXZBzhHEcUWnjkIRk/Uh6c2PHA1XjqAllxrg6V8BodXEDDcfKzDpJV9q0R1zMqmh@iWtddzBWRv61OXritHqi4mmSm/o3Hqmsvu41D2S1Dejhv5dIoMJl92rlYOKsblDw "Clean – Try It Online") [Answer] # [cQuents](https://github.com/stestoltz/cQuents), ~~238~~ 219 bytes ``` |@ #36::"T"~c1)~j\rbk));@ )~c2,Z,"T"~c1)~"hole, t"~c1)~"hole","T"~c1)~c2)~@ ::"","log in the","bump"~c3,"frog"~c3,"wart"~c3,"hair"~c3,"fly"~c3,"flea"~c3,"smile"~c3 :"here's a ","hole in the bottom of the sea"," on the" ``` [Try it online!](https://tio.run/##TY3BDoIwEETv/YrNejBNehESD3jhIzwZL6UpFAVX2xJjYvrrtVgw3t7szM6ox6Rv3sX4rtmm3FcVHjGoHQ@Xs22unB9q4EEV4iRWAw0NWoD/U/gzVcFDzViqSbeBOuhv4M0caKbxnjKlwNZSl@kprc9kZG8Xd3itoGUmN/ZpIyGr0Girtw4kpMp5ehmAhrynEaj9KpdeBQLl8Rg/ "cQuents – Try It Online") This challenge made me finally implement lists and strings in my language. This language is built for integer sequences, so it did pretty well! ## Explanation ``` :"here's a ","hole in the bottom of the sea"," on the" helper line: c1), c2), and c3) access the three terms in this list ::"","log in the","bump"~c3,"frog"~c3,"wart"~c3,"hair"~c3,"fly"~c3,"flea"~c3,"smile"~c3 helper line: yields a list containing the first n terms in it, accessed with bx) for example, the first three terms are: "","log in the","bump"~c3 so b3) would yield ["","log in the","bump on the"] (~ is concatenation and c3 is " on the") |@ #36::"T"~c1)~j\rbk));@ )~c2,Z,"T"~c1)~"hole, t"~c1)~"hole","T"~c1)~c2)~@ |@ join sequence on literal newline #36:: output first 36 terms in sequence joined together following are the 4 terms in the sequence, which will cycle through 9 times (for a total of 36 terms) "T"~c1)~j\rbk));@ )~c2, first term "T"~c1)~ "T" concat "here's a " concat j\rbk));@ ) the first k terms of b, reversed, and joined on " " ~c2, concat "hole in the bottom of the sea" Z, second term - same as previous "T"~c1)~"hole, t"~c1)~"hole", third term "T"~c1)~ "T" concat "here's a " concat "hole, t"~c1)~"hole", "hole, t" concat "here's a " concat "hole" "T"~c1)~c2)~@ fourth term - "T" concat "here's a " concat "hole on the bottom of the sea" concat newline ``` [Answer] # [Perl 5](https://www.perl.org/), 194 bytes *@ASCII-only shaved off 6 bytes with literal newlines and a `\l` trick I forgot about* ``` $"=" on the ";say+($b=($e="There's a ").hole,$c=" in the bottom of the sea",$/)x2,$.="$b, \l$b $b$c ";say"$e@a[-$_..-1] in the hole$c "x2,$.for 1..(@a=qw/smile flea fly hair wart frog bump log/) ``` [Try it online!](https://tio.run/##NYxBCsIwEEX3PcUQBmyxTa3QlQS8gDt3KpLI1BZSpyaR2ssbteLmw4f33kDO1jGiUAL4BqElEBuvp2WKRqVISuxbcrTwoEFksmVLOV4@cPeDDYfAPXAzP09a5Fhmz3WOUgk0ORwtmgQNXpK5K5C2@lDgWcqiOv0r3@yXmL2GHVRSplut7mPp@84SNJb0ZyZodedg1C5A4/gK5tEPYPlaZjEmLx5Cxzcfi10tV9XqDQ "Perl 5 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~115~~ 106 bytes ``` ≔There's a holeθEE⁹⁺…θχ⪫⮌…⪪”↶±∧⟲!↶⁼,(_⎇RB↧ω⪪zθⅉQθ`✳&⬤⸿◧σ⁻y▷»ΣK▶↙⁻υX`SξQ6 /ι⁹Wq”x⁺²ιn the ⟦ιι⁺⁺θ, ↧θ⁺θ✂ι±²⁵ ``` [Try it online!](https://tio.run/##TU6xagMxDN37FcJLbXChDXQomUq20JbQdCsdFKOcDb7Tne0kzte7uiOFDnqy9PyenvOYHGNs7TXn0A1afXlKdJ8BwXMkZWEy67tdCkPR7zgu9WJhF09Zb64u0sbzqCcLT4/GwpbDoD/pTCnTP3o/xlC0OnAp3AMfoXiCTFjnExBq5E7wcOpH4HpMMnG9YCrSPIY0L@N1QUJpuQ8iY8mmqjK3MCsLwRiZ1LDYq/n9HWR7@7CABJ1lQr3xhZJDyTmZPw9h9zE40qL5oA4L6dWzmP4Ys26tPZzjLw "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 9 bytes by copying my Batch code for the last line of the chorus. Explanation: ``` ≔There's a holeθ ``` Save the string `There's a hole`, which is used twice as-is, a third time in lower case, and also a fourth time but just the first 10 characters. ``` ⪪”↶±∧⟲!↶⁼,(_⎇RB↧ω⪪zθⅉQθ`✳&⬤⸿◧σ⁻y▷»ΣK▶↙⁻υX`SξQ6 /ι⁹Wq”x ``` Split the string `bottom of the seaxhole ixlog ixbump oxfrog oxwart oxhair oxfly oxflea oxsmile o` on `x`s. ``` E⁹⁺…θχ⪫⮌…...⁺²ιn the ``` Loop over the 9 verses, taking the first `i+2` elements of the array, reversing them, joining them with `n the`, and prefixing `There's a` to the result. ``` E...⟦ιι⁺⁺θ, ↧θ⁺θ✂ι±²⁵ ``` Expand each line into a verse by duplicating the line and constructing the chorus. Each line of the verse is then implicitly printed on each own line, and each verse is implicitly separated by a blank line. [Answer] # [V](https://github.com/DJMcMayhem/V), 184 170 bytes ``` 4iThere's a hole in the bottom of the sea kky5w5eá,lpD5brtHj4yyGp4w8ion the 2briilog 3bibump 3bifrog 3biwart 3bihair 3bifly 3biflea 3bismile 7ñ4yykp4wd3wñ8ñÄ5jñ ``` [Try it online!](https://tio.run/##LY5BDsIgEEX3XoHN7Ny4siX2ACZ6AC8AcSrTUmmASth7EY/AGTgYNrSrefN/5mU@pbT0UGjx6ECAMhqB3uAVgjTemwlMXzeH4sDGMfLAMf9Oer5yaf19aGO8zW3oyGxX7CwtkTYvYI0kuUxzhd7uSRDWV1CC7FbpuE8UFdxE6xfsktMqH1f5swk5dTnlLx9yKuUP "V – Try It Online") ## Explanation: * `4iThere's a hole in the bottom of the sea<\n><esc>` Insert "Theres' a hole in the bottom of the sea" 4 times. * `kk` Move to the third line * `y5w` copy "There's a hole" * `5eá,` insert a comma after "There's a hole" * `lp` paste after the comma * `D` delete the rest of the line * `5brt` lowercase the second T * `Hj4yy` copy 4 lines from the second line * `Gp` Paste everything after the first line * `4w8ion the <esc>`(at the end of the first verse) move to first "hole" in second verse and insert "on the " 8 times * `2briilog <esc>` move backwards to the last "on", replace the o with an i and then insert "log " * `3bibump <esc>3bifrog <esc>3biwart <esc>3bihair <esc>3bifly <esc>3biflea <esc>3bismile <esc>` Move backwards through the line, inserting the appropriate words between each "on the" * `7ñ4yykp4wd3wñ` execute `4yykp4wd3w` 7 times + `4yykp` duplicate the verse before this one + `4wd3w` move to the first word after "There's a hole" and delete 3 words * `8ñÄ5jñ` duplicate the first line of each verse after the first (there are 8 of these to do) [Answer] # LaTeX, 265 ~~268~~ characters ``` \documentclass{book}\input{pgffor}\def\i{bottom of the sea}\let~\i\def\b{here's a }\def\h{hole}\def\s#1{ in}\begin{document}\foreach\x in{\h\s,log\s,bump,frog,wart,hair,fly,flea,smile}{\xdef~{\x{ on} the ~}T\b~\\T\b~\\T\b\h, t\b\h\\T\b\h\,in the \i\par}\enddocument ``` compiles into a nice PDF, with paragraph indentations and everything. Ungolfed and commented: ``` \documentclass{book} \input{pgffor} \def\i{bottom of the sea} %for re-use in the last two verses \let~\i %here I keep attaching words \def\b{here's a } \def\h{hole} \def\s#1{ in} %this replaces the next token with "in", useful for log and hole where "in" is used instead of"on" \begin{document} \foreach\x in{\h\s,log\s,bump,frog,wart,hair,fly,flea,smile}{ \xdef~{\x{ on} the ~} %keep attaching words and on/on to ~ T\b~\\ %verse 1 T\b~\\ %verse 2 T\b\h, t\b\h\\ %verse 3 T\b\h\,in the \i\par %verse 4 } \enddocument ``` Of output: [![enter image description here](https://i.stack.imgur.com/x028h.png)](https://i.stack.imgur.com/x028h.png) [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 220 bytes ``` string b="There's a ",d="hole in the bottom of the sea\n",e,f;" log bump frog wart hair fly flea smile".Split().Any(s=>Write((e=b+(f=s!=""?s+(f!=""?" o":" i")+"n the "+f:s)+d)+e+b+$@"hole, there's a hole {b+d} ")is int); ``` [Try it online!](https://tio.run/##LY5BigIxEEX3nqIsBBPSegAlOnOGEdy4SeyKXZDuSCqDiHj2NrYuPrzP58M7y@osPI5SMg8X8BYPHWVaCjjAprXYpUjAA5SOwKdSUg8pTE3InQZsqAlbhJjq@b@/QsiVbi4X6BxnCPFeQw6k50i4/rtGLkqvf4e7Ers7Zi6kFFlvVLAyt4h7qTgBQsINAqM2@BFAEzaiTasNGW8WP5Nd856@yu8@e3jTPmeoWap40dtxfAE "C# (Visual C# Interactive Compiler) – Try It Online") -5 bytes thanks to @ASCIIOnly and -2 bytes thanks to @someone! I have a small child and can assure you this song is equal parts catchy and annoying. [Answer] # [Slashalash](https://esolangs.org/wiki/Slashalash), 216 bytes ``` /V/\/\///U/\/ VS/TCVR/iBVQUtheVPUoBVOUholeVN/RASVM/ASO, tCO SA VL/RMSVKUlog VJUbumpPKVIUfrogPJVHUwartPIVGUhairPHVFUflyPGVEUfleaPFVDUsmilePEVC/here's aVB/nQVA/O R bottom ofQ sea /SASMSKNKLJNJLINILHNHLGNGLFNFLENELDNDRM ``` [Try it online!](https://tio.run/##DcXLasQgFIDhfZ7CXTeF8wzmfjHGaM9ZdeOAGQOmDtGh9OnT8MP3p2CTd@m6gOD7DgBvGRn4qkjDXtKK2TtSGEta0MfgSILmhmbgZvlkuVoKwwsSoGdDE4b4ZDTi43281EQDbmd8qpF6/LVnVgN16O1@qp5a3MKf6qi576xqqcZ07MGphirw7nQfiVkq4WclDgvT7BFzjgeL28qSswUYbmYzyUmMchSDHEQve9HJTrSyFY1sRC1rPV/XPw "/// – Try It Online") This sort of task is the one and only thing that Slashalash is reasonably good at. :D Hey, the result is shorter than C, C# or Java! The output from this program ends in *two* trailing line breaks; hope that's not a deal-breaker. Anyway, there's no real cleverness here. I simply identified repeated strings and defined one-character shortcuts for them, and repeated until I didn't see any more repeated strings. I did this in a more-or-less naive and greedy fashion. I did, however, intentionally define a shortcut for "smile on the flea on the ... sea", followed by "flea on the fly on the ... sea", and so forth, in order to form a chain of shortcuts. The result is that the whole sequence of new nouns is clearly visible in the code, and I find that pretty pleasing. :) After V and U are replaced, we have the following more readable code: ``` /S/TC//R/iB//Q/ the//P/ oB//O/ hole//N/RAS//M/ASO, tCO SA //L/RMS//K/ log //J/ bumpPK//I/ frogPJ//H/ wartPI//G/ hairPH//F/ flyPG//E/ fleaPF//D/ smilePE//C/here's a//B/nQ//A/O R bottom ofQ sea /SASMSKNKLJNJLINILHNHLGNGLFNFLENELDNDRM ``` ]
[Question] [ Inspired by [We had a unit test once which only failed on Sundays](https://qntm.org/unit), write a program or function that does nothing but throw an error when it is Sunday, and exit gracefully on any other day. ### Rules: * No using input or showing output through the [usual IO methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), except to print to STDERR or your language's equivalent. You are allowed to print to STDOUT if it's a by-product of your error. * A function may return a value on non-Sundays as long as it doesn't print anything * Your program may use a Sunday from any timezone, or the local timezone, as long as it is consistent. * An error is a something that makes the program **terminate abnormally**, such as a divide by zero error or using an uninitialised variable. This means that if any code were to be added after the part that errors, it would not be executed on Sunday. * You can also use statements that manually create an error, equivalent to Python’s `raise`. * This includes runtime errors, syntax errors and errors while compiling (good luck with that!) * On an error there must be some sign that distinguishes it from having no error * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest bytecount in each language wins! I'll have to wait til Sunday to check the answers ;) [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, ~~15~~ 14 bytes ``` `date|grep Su` ``` [Try it online!](https://tio.run/##S0oszvhfoKGpoFFQlJlXkqagrpoUk6dqoFUak6euoKTioKRQo1BSpGCgoKtgp2akycVVoBDi7@IYqWD6PyElsSS1Jr0otUAhuDThf4GCekyen2tEiEJwqB9QhbqCoSEXWI2CbkpxaV5KYiVcMcgYmGpffwzVufkoqv8DAA "Bash – Try It Online") [Answer] # PHP 7, 12 bytes ``` 1%date("w"); ``` On PHP 7 it throws an exception of type [`DivisionByZero`](http://php.net/manual/en/class.divisionbyzeroerror.php) on Sundays. The same happens if it is interpreted using [HHVM](https://en.wikipedia.org/wiki/HHVM). On PHP 5 it displays a warning (on `stderr`) on Sundays: ``` PHP Warning: Division by zero in Command line code on line 1 ``` On any PHP version, it doesn't display anything on the other days of the week. Run using the CLI: ``` php -r '1%date("w");' ``` or [try it online!](https://3v4l.org/IXe7i) Two more bytes can be squeezed by stripping the quotes (`1%date(w);`) but this triggers a notice (that can be suppressed by properly set [`error_reporting = E_ALL & ~E_NOTICE`](http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting) in `php.ini`). [Answer] # Java 8, ~~69~~ ~~43~~ 34 bytes ``` v->1/new java.util.Date().getDay() ``` -26 bytes thanks to *@OlivierGrégoire*. -9 bytes thanks to *@Neil*. **Explanation:** [Try it here.](https://tio.run/##LY0xD4IwEIV3f8WN7UCNM9GJVRYTFuNwlkqK9SD0WmMMv70WIbk33Eu@9/UYsRhGQ337TNqh93BGS98dgCU20wO1gXp5/wVo0Qy2hSjLXM05@TwjWw01EBwhxeJ02JN5Q5@nVWDrVIVshFSd4Qo/QqZy5cZwd5nb8LjsvrJbXHiy1F1vKFcvKS0oOLc55/QD) * `v->{...}` ([unused `Void` `null` parameter](https://codegolf.meta.stackexchange.com/questions/12681/are-we-allowed-to-use-empty-input-we-wont-use-when-no-input-is-asked-regarding)) is one byte shorter than `()->{...}` (no parameter). * `new java.util.Date().getDay()` will return 0-6 for Sunday-Saturday, so `1/...` will give an `java.lang.ArithmeticException: / by zero` error if the value is 0, which only happens on Sundays. [Answer] # PHP, 15 bytes ``` <?@date(w)?:\n; ``` Assumes [default settings](https://codegolf.meta.stackexchange.com/a/1670). **Output on Sundays** ``` Fatal error: Undefined constant 'n' on line 1 ``` [Try it online!](https://tio.run/##K8go@P/fxt4hJbEkVaNc094qJs/6//9/@QUlmfl5xf918wA "PHP – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 33 bytes ``` import time "Su"in time.ctime()>q ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEkMzeVSym4VCkzD8zWSwaRGpp2hf//AwA "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), 50 bytes ``` from datetime import* datetime.now().weekday()>5>q ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1chJbEktSQzN1UhM7cgv6hEiwsmoJeXX66hqVeempqdklipoWlnalf4/z8A "Python 3 – Try It Online") Saved ~3 bytes thanks to [Rod](https://codegolf.stackexchange.com/users/47120/rod). [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~8~~ 7 bytes ``` l-6.d9 ``` [Try it online!](https://tio.run/##K6gsyfj/XyFH10wvxfL/fwA "Pyth – Try It Online") Explanation ``` .d9 # Get the current day of week (0 = Monday, 6 = Sunday) -6 # Subtract 6 from the day l # Try to calculate the log base 2 of the result of the previous operation raising a "ValueError: math domain error" on sundays # there is an extra space at the start, to supress the output on the other days ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~45~~ 44 bytes As 05AB1E doesn't have a built in for getting the day of the week, I've used Zeller's Rule to calculate it. Prints a newline to stderr in case of a Sunday (observable in the debug view on TIO) ``` žežf11+14%Ì13*5÷žgžf3‹-т%D4÷žgт÷©4÷®·(O7%i.ǝ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6L7Uo/vSDA21DU1UD/cYGmuZHt5@dF86UMz4UcNO3YtNqi4mYJGLTYe3H1oJZB9ad2i7hr@5aqbe8bn//wMA "05AB1E – Try It Online") **Explanation** The general formula used is `DoW = d + [(13*(m+1))/5] + y + [y/4] + [c/4] - 2*c` Where `DoW=day of week`, `d=day`, `m=month`, `y=last 2 digits of year`, `c=century` and and expression in brackets (`[]`) is rounded down. Each month used in the formula correspond to a number, where `Jan=13,Feb=14,Mar=3,...,Dec=12` As we have the current month in the more common format `Jan=1,...,Dec=12` we convert the month using the formula `m = (m0 + 11) % 14 + 1` As a biproduct of March being the first month, **January** and **February** belong to the previous year, so the calculation for determining `y` becomes `y = (year - (m0 < 3)) % 100` The final value for `DoW` we get is an int where `0=Sat,1=Sun,...,6=Fri`. Now we can explicitly throw an error if the result is true. [Answer] # JavaScript, 23 Bytes ``` Date().slice(1)>'um'&&k ``` Full program. The variable `k` must not be defined. # JavaScript, 20 bytes by Rick Hitchcock ``` /Su/.test(Date())&&k ``` # JavaScript, 19 bytes by apsillers ``` Date().match`Su`&&k ``` [Answer] ## Ruby, 15 bytes ``` 1/Time.now.wday ``` `wday` will return 0 on Sunday causing a ZeroDivisionError: divided by 0 error. For example: `1/Time.new(2018,1,7).wday`. [Answer] # [Haskell](https://www.haskell.org/) + [Data.Dates](https://hackage.haskell.org/package/dates-0.2.2.1/docs/Data-Dates.html), 55 bytes ``` import Data.Dates succ.dateWeekDay<$>getCurrentDateTime ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRD0ikFnPlJmbm2RaUFqWqKBaXJifrpQBFw1NTs10SK21U7NJTS5xLi4pS80pAqkMyc1P//wcA "Haskell – Try It Online") This uses the fact that Sunday is the last day of the week. `dateWeekDay` returns the day of the week as a `WeekDay` type, which is simply defined as ``` data WeekDay = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday ``` `WeekDay` is an instance of `Enum`, thus we can use `succ` and `pred` to get the successor or predecessor of a weekday, e.g. `succ Monday` yields `Tuesday`. However, `Sunday` is the last enum entry, so calling `succ Sunday` results in the following error: ``` fail_on_sunday.hs: succ{WeekDay}: tried to take `succ' of last tag in enumeration CallStack (from HasCallStack): error, called at .\Data\Dates.hs:56:34 in dates-0.2.2.1-6YwCvjmBci55IfacFLnAPe:Data.Dates ``` *Edit 1: Thanks to nimi for -3 bytes!* *Edit 2: -11 bytes now that functions are allowed.* --- ### Full program: ~~88~~ ~~81~~ ~~74~~ ~~69~~ 66 bytes ``` import Data.Dates main=pure$!succ.dateWeekDay<$>getCurrentDateTime ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRD0ikFnPlJmbm2RaUFqWqKBaXJifrpQBFw1NTs10SK21U7NJTS5xLi4pS80pAqkMyc1P//wcA "Haskell – Try It Online") `pure` is needed to lift the resulting `WeekDay` back into the IO Monad. However, Haskell sees that the value is not output in any way by the program, so lazy as it is, the expression is not evaluated, so even on Sundays the program would not fail. This is why `$!` is needed, which forces the evaluation even if Haskell would normally not evaluate the expression. --- ### Previous approach with `Data.Time`: ~~127~~ 124 bytes ``` import Data.Time.Clock import Data.Time.Calendar.WeekDate c(_,_,d)|d<7=d main=getCurrentTime>>=(pure$!).c.toWeekDate.utctDay ``` [Try it online!](https://tio.run/##Zcu9CoMwEADgPU9hoYOC3OrSuOgjFDrKkRw15E/Oy1Dou6d2cHL94Ftx9xRCrS5umaWZURCeLhJMIRuvroyBkkWGF5E/mJRpl37pbfe1j0FbFdEl/SaZCjMl@adx1O1WmO63DgxIPisUMTLjp9Yf) These are some impressive imports. Change `d<7` to e.g. `d/=5` to test failure on a Friday. Fails with the following exception: `Non-exhaustive patterns in function c`. [Answer] # [Perl 5](https://www.perl.org/), 13 bytes ``` 1/(gmtime)[6] ``` [Try it online!](https://tio.run/##K0gtyjH9/99QXyM9tyQzN1Uz2iz2/38A "Perl 5 – Try It Online") Ported @biketire's answerj *removed 3 bytes with @mik's reminder* [Answer] # VBA / VBScript, ~~22~~ 20 bytes Saved 2 bytes thanks to Taylor Scott. ``` a=1/(Weekday(Now)-1) ``` This should be run in the Immediate Window. `Weekday()` returns 1 (Sunday) through 7 (Saturday) so this creates a divide by zero error on Sunday. Otherwise, no output. [![Error Message](https://i.stack.imgur.com/tGlOX.png)](https://i.stack.imgur.com/tGlOX.png) [Answer] # TI-Basic 84+, 23 bytes ``` getDate 0/(1-dayOfWk(Ans(1),Ans(2),Ans(3 ``` Needs date & time commands, which are 84+ and higher only. [Answer] ## C, 35, 34 27 bytes ``` f(n){n/=time(0)/86400%7^3;} ``` -7 bytes with thanks to @MartinEnder and @Dennis [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOk/ftiQzN1XDQFPfwszEwEDVPM7YuvZ/Zl6JQm5iZp6GJlc1lwIQpGloWoMZBUVAuTQNJZfMlDz1EoXkosTiDD0loGTtfwA) [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `O`, 25 bytes ``` kðtD4/‟₀/N‟:400/kτṠ7%2<[← ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=O&code=k%C3%B0tD4%2F%E2%80%9F%E2%82%80%2FN%E2%80%9F%3A400%2Fk%CF%84%E1%B9%A07%252%3C%5B%E2%86%90&inputs=&header=&footer=) Vyxal doesn't have a weekday function, so I made one myself. [Answer] # [R](https://www.r-project.org/), ~~31 bytes~~ 30 bytes ``` if(format(Sys.Date(),'%u')>6)a ``` [Try it online!](https://tio.run/##K/r/PzNNIy2/KDexRCO4sljPJbEkVUNTR121VF3T1tZcM/H/fwA) No output on non-Sundays, `Error: object 'a' not found` on Sundays. `format(Sys.Date(),'%u')` was the shortest way I could find to get weekday, it outputs a character-class number for day of week, with 7 for Sundays. We can compare to a numeric 7, and if true attempt to use an undefined object. Saved a byte thanks to Giuseppe! [Answer] # [Zsh](https://www.zsh.org) `-G`, 14 bytes ``` >`date` dd Su* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjWbSSrrtS7M1gZYXSvOT83NzUvBKFkozMYoWczLxUhZJ8hdLiVIVEhbTE7FSFlMSSVCsuZTCtoWljY6MeXJqnYGik4J9comBgZmVgaWVipOAUHKJgZGBkqL60tCRN12KdXQJIfQJXSopCcKkWRHABlILSAA) * `date`: get the date in the format `Sun 28 Mar 07:55:54 BST 2021` * `>`: create a file named according to each of the words in the output * `dd`: "copy and convert" - here it basically does nothing + this command expects no arguments * `Su*`: search for a file starting with `Su` + if a file matching that exists (which happens when it is Sunday), then it is passed to `dd` - since `dd` expects no arguments, this produces an error + with the `-G` option: if no file matches (i.e. it is not Sunday), don't error as usual This produces a bit of extra junk output to STDERR (not an error though) which may or may not be allowed; the question isn't really clear. Here's an alternative answer which doesn't: ## [Zsh](https://www.zsh.org) `-G`, 18 bytes ``` >`date` mv <-> Su* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjWbSSrrtS7M1gZYXSvOT83NzUvBKFkozMYoWczLxUhZJ8hdLiVIVEhbTE7FSFlMSSVCsuZTCtoWljY6MeXJqnYGik4J9comBgZmVgaWVipOAUHKJgZGBkqL60tCRN12KTXQJIfQJXbpmCja6dQnCpFkRiAZSC0gA) `<->` matches any file whose name is a number, of which there are two: the day of the month, and the year. When there is no `Su*` file, this is renames the day of the month to the year (overwriting the year), which works fine. When `Sun` exists, it tries to move the day of the month and the year into the directory `Sun`, which fails because `Sun` is a file, not a directory. [Answer] # jq, 42 characters (39 characters code + 3 characters command line option) ``` now|strftime("%w")|strptime("%d")|empty ``` Just trying a different approach here: parse week day number (0..6) as month day number (1..31). Sample run: ``` bash-4.4$ TZ=UTC faketime 2018-01-06 jq -n 'now|strftime("%w")|strptime("%d")|empty' bash-4.4$ TZ=UTC faketime 2018-01-07 jq -n 'now|strftime("%w")|strptime("%d")|empty' jq: error (at <unknown>): date "0" does not match format "%d" ``` Note that jq only handles UTC dates. [Try it online!](https://tio.run/##yyr8/z8vv7ymuKQorSQzN1VDSbVcSRPELYByU4Dc1NyCksr////r5gEA "jq – Try It Online") [Answer] # ***Q, 20 Bytes*** ``` if[1=.z.d mod 7;'e] ``` .z.d returns the current date. mod does the modulo of the current date, which returns an int. If the date is a sunday, .z.d mod 7 returns 1. If 1=1, (on sunday), and error is raised using the ' operator For brevity the error is just the e character. [Answer] # [Julia 0.6](http://julialang.org/), 32 bytes Thanks to @Dennis for pointing out `<` saves a byte over `!=`. ``` @assert Dates.dayofweek(now())<7 ``` [Try it online!](https://tio.run/##yyrNyUw0@//fIbG4OLWoRMElsSS1WC8lsTI/rTw1NVsjL79cQ1PTxvz/fwA "Julia 0.6 – Try It Online") [Answer] ## VBA 18 bytes This relies on the inbuilt function `date()` returning a day number that remainders 1 if divided by 7, so may be OS and/or CPU specific. ``` a=1/(date mod 7-1) ``` It runs in the VBA project Immediate window. [Answer] # C, ~~68~~ 55 bytes *Thanks to @Ken Y-N for saving 13 bytes!* ``` #import<time.h> f(n){time(&n);n/=gmtime(&n)->tm_wday;;} ``` [Try it online!](https://tio.run/##S9ZNT07@/185M7cgv6jEpiQzN1Uvw44rTSNPsxrE0VDL07TO07dNz4XxdO1KcuPLUxIrra1r/2fmlSjkJmbmaWhyVXMpAEGahqY1mFFQBJRL01ByyUzJUy9RSC5KLM7QUwJK1v4HAA) [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` vZ'8XOs309>) ``` The error produced on Sundays is: * Interpreter running on Octave: ``` MATL run-time error: The following Octave error refers to statement number 9: ) --- array(1): out of bound 0 ``` * Interpreter running on Matlab: ``` MATL run-time error: The following MATLAB error refers to statement number 9: ) --- Index exceeds matrix dimensions ``` To invert behaviour (error on any day except on Sundays), add `~` after `>`. [**Try it Online!**](https://tio.run/##y00syfn/vyxK3SLCv9jYwNJO8/9/AA) ### Explanation This exploits the fact that * indexing into an empty array with the logical index `false` is valid (and the result is an empty array, which produces no output); whereas * indexing with `true` causes an error because the array lacks a first entry. Commented code: ``` v % Concatenate stack. Gives empty array Z' % Push current date and time as a number 8XO % Convert to date string with format 8: gives 'Mon', 'Tue' etc s % Sum of ASCII codes. Gives 310 for 'Sun', and less for others 309> % Greater than 309? Gives true for 'Sun', false for others ) % Index into the empty array % Implicit display. Empty arrays are not displayed (not even newline) ``` [Answer] # Excel, 24 Closing quote and paren not counted toward final score, as Excel will autocorrect both of those. Tested in Excel 2016. ``` =IF(MOD(TODAY()-1,7)^0,"") ``` I think this is different from the [other submission](https://codegolf.stackexchange.com/a/152775/91403) enough to warrant another answer. ### How it works: * I've rolled the error into the conditional check. As it turns out, `TODAY()` mod 7 also gives the weekday. If it's a Sunday, this means that `MOD(TODAY()-1,7)` is `0`, and `0^0` is an error in Excel. + Of course, I could also have divided `1` by the `MOD()` value or used `+6` instead of `-1`. * If it's not Sunday, the `MOD(...,7)` will be non-zero, which when raised to `0`, returns `1`, a truthy value. This makes the `IF` return an empty string (our "nothing"). * The if statement, therefore, cannot evaluate to `FALSE`, because it errors or returns nothing. ### Alternative Here's one that works just as well, but uses a Name error instead: ``` =IF(MOD(TODAY(),7)=1,A,"") ``` [Answer] # TI-Basic, ~~22~~ 21 bytes ``` getDate log(log(dayOfWk(Ans(1),Ans(2),Ans(3 ``` -1 byte by using [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush)'s method but replacing `ln(` with `log(`. Only works on TI-84+/SE. Assumes that the date is set correctly before the program is run. There is a newline at the end. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 23 bytes ``` ⎕CY'dfns' o←÷7|⌊days⎕TS ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jvqnOkeopaXnF6lz5j9omHN5uXvOopyslsbIYKBUSDFL1Pw0A "APL (Dyalog Unicode) – Try It Online") [Answer] ## Ocaml, 46 bytes ``` open Unix let()=1/(gmtime(time())).tm_wday;() ``` and in the ocaml REPL, we can achieve better by removing the `let` and the final `:()`: ``` $ open Unix;;1/(gmtime(time())).tm_wday;;<CR> ``` which is 41 bytes (incuding 1 byte for the carriage return). [Answer] ## SAS, 36 bytes ``` %put %eval(1/(1-%index(&sysday,Su))) ``` [Answer] # [Julia 0.5](http://julialang.org/), 28 bytes ``` Dates.dayofweek(now())<7||~- ``` [Try it online!](https://tio.run/##PcwxCkIxEATQ/p9i@DYJqJ2ksfQGeoGAK0bDbtjNJwgfrx6DguUMb@ax5BQPvZ9iJdtf40tujejpWJrz/hjW9b3rRRPXzG6@yBBIBpaK88IjzX6aws9hg/8BlOqibAgQhn2pbVHvY2ycSqGKmNsoQaqi1j8 "Julia 0.5 – Try It Online") This does *not* work with 0.6, but it does with 0.4. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/learn/what-is-dotnet), 55 54 48 bytes [Try it online!](https://tio.run/##TY7NDoIwEITvfYo9wkHUc4XE6NG/qIlHU@tiVqCNtGAI4dlrQaPObeZLZkaakdQlusqQusGhMRYLzv5dtCL14IzJXBgDO9Yy8DJWWJJQa7rCWpAKwiF@w15zaUmrmb7cUdoE0kpJiN05TtpalJDF03FAyoafjaWweKQCo41@etNs0xNixjvHv4V9QzAJf8FCK6NzjPYorv4jBp4NsGOdewE) *Saved 1 byte thanks to Shaggy* *Saved 5 byte thanks to Emigna* *Saved 1 byte thanks to Kevin Cruijssen* ``` _=>{var k=1/(int)System.DateTime.Now.DayOfWeek;} ``` Lucky that Sunday is indexed 0 in enum or else it would've needed to be `(System.DayOfWeek)7` ]
[Question] [ The [Devil's Staircase](https://en.wikipedia.org/wiki/Cantor_function) is a fractal-like function related to the Cantor set. ![enter image description here](https://i.stack.imgur.com/Nwv4B.png) Your task is to replicate this funky function — in ASCII art! # Input A single integer `n >= 0`, indicating the size of the output. Input may be given via STDIN, function argument or command-line argument. # Output The ASCII-art rendition of the Devil's staircase at size `n`, either returned as a string or printed to STDOUT. Trailing spaces at the end of each row are okay, but leading spaces are not. You may optionally print a single trailing newline. For size `0`, the output is just: ``` x ``` (If you wish, you may use any other printable ASCII character other than space, in place of `x`.) For size `n > 0`, we: * Take the output of size `n-1` and stretch each row by a factor of three * Riffle between rows of single `x`s * Shift the rows rightward so that there is exactly one `x` in each column, and the position of the first `x` are minimal while decreasing with the rows For example, the output for `n = 1` is: ``` x xxx x ``` To get the output for `n = 2`, we stretch each row by a factor of three: ``` xxx xxxxxxxxx xxx ``` Riffle between rows of single `x`'s: ``` x xxx x xxxxxxxxx x xxx x ``` Shift rightward: ``` x xxx x xxxxxxxxx x xxx x ``` As another example, [here](http://pastebin.com/LWcwJVHA) is `n = 3`. # Scoring This is code-golf, so the solution in the fewest bytes wins. [Answer] ## J (~~73~~ ~~68~~ ~~58~~ ~~41~~ ~~39~~ ~~38~~ ~~35~~ 34 characters) After thinking about the problem for some time, I found an entirely different way to generate the Devil's Staircase pattern. The old answer including its explanation has been removed, you can look into the revisions of this answer to figure out how it was. This answer returns an array of blanks and sharps, representing the devil's staircase. ``` ' #'{~1(]|.@=@#~[:,3^q:)2}.@i.@^>: ``` Here is the answer split into its two parts in explicit notation: ``` f =: 3 : '|. = (, 3 ^ 1 q: y) # y' g =: 3 : '(f }. i. 2 ^ >: y) { '' #''' ``` ## Explanation The approach is a bit different, so observe and be amazed. 1. `>: 3` – three incremented, that is, ``` 4 ``` 2. `2 ^ >: 3` – two to the power of three incremented, that is, ``` 16 ``` 3. `i. 2 ^ >: 3` – the first `2 ^ >: 3` integers, that is, ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ``` 4. `}. i. 2 ^ 4` – the first `2 ^ >: 3` integers, beheaded, that is, ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ``` Let's call this sequence `s`; we enter `f` now. 5. `1 q: s` – the exponents of 2 in the prime decomposition of each item of `s`. In general, `x q: y` yields a table of the exponents for the first `x` primes in the prime decomposition of `y`. This yields: ``` 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 ``` 6. `3 ^ 1 q: s` – three to the power of these exponents, that is, ``` 1 3 1 9 1 3 1 27 1 3 1 9 1 3 1 ``` 7. `, 3 ^ 1 q: s` – the ravel (that is, the argument with it's structure collapsed into a vector) of the previous result. This is needed because `q:` introduces an unwanted trailing axis. This yields ``` 1 3 1 9 1 3 1 27 1 3 1 9 1 3 1 ``` 8. `(, 3 ^ 1 q: s) # s` – each item of `s` replicated as often as the corresponding item in the previous result, that is, ``` 1 2 2 2 3 4 4 4 4 4 4 4 4 4 5 6 6 6 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 9 10 10 10 11 12 12 12 12 12 12 12 12 12 13 14 14 14 15 ``` 9. `= (, 3 ^ 1 q: s) # s` – the self classification of the previous result, this is, a matrix where each row represents one of the unique items of the argument, each column represents the corresponding item of the argument and each cell represents whether the items of row and column are equal, that is, ``` 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ``` 10. `|. = (, 3 ^ 1 q: s) # s` – the previous result flipped along the vertical axis. 11. `(|. = (, 3 ^ 1 q: s) # s) { ' #'` – the items of the previous result used as indices into the array `' #'`, so `0` is replaced by and `1` is replaced by `#`, that is, ``` # ### # ######### # ### # ########################### # ### # ######### # ### # ``` the result we want. [Answer] # [Hexagony](http://esolangs.org/wiki/Hexagony), 217 bytes This was immensely fun. Thank you for posting this challenge. Full disclosure: The language (Hexagony) did not exist at the time this challenge was posted. However, I did not invent it, and the language was not designed for this challenge (or any other specific challenge). ``` ){_2"_{\"{{""}"{'2//_.\><*\"\/_><[\]/3\'\_;|#__/(\2\'3_'}(#:|{$#{>_\//(#={/;01*&"\\_|[##={|}$_#></)]$_##|){*_.>.(/?#//~-="{}<_"=#/\}.>"%<.{#{x\"<#_/=&{./1#_#>__<_'\/"#|@_|/{=/'|\"".{/>}]#]>(_<\'{\&#|>=&{{(\=/\{*'"]<$_ ``` Laid out hexagonally: ``` ) { _ 2 " _ { \ " { { " " } " { ' 2 / / _ . \ > < * \ " \ / _ > < [ \ ] / 3 \ ' \ _ ; | # _ _ / ( \ 2 \ ' 3 _ ' } ( # : | { $ # { > _ \ / / ( # = { / ; 0 1 * & " \ \ _ | [ # # = { | } $ _ # > < / ) ] $ _ # # | ) { * _ . > . ( / ? # / / ~ - = " { } < _ " = # / \ } . > " % < . { # { x \ " < # _ / = & { . / 1 # _ # > _ _ < _ ' \ / " # | @ _ | / { = / ' | \ " " . { / > } ] # ] > ( _ < \ ' { \ & # | > = & { { ( \ = / \ { * ' " ] < $ _ ``` The program does not actually use the `#` instruction, so I used that character to show which cells are genuinely unused. How does this program work? That depends. Do you want the short version, or the long? # Short explanation To illustrate what I mean by “line” and “segment” in the following explanation, consider this dissection of the intended output: ``` segments → │ │ │ │ │ │x lines ─┼───┼─┼─────────┼─┼───┼─ ↓ │ │ │ │ │xxx│ ─┼───┼─┼─────────┼─┼───┘ │ │ │ │x│ ─┼───┼─┼─────────┼─┘ │ │ │xxxxxxxxx│ ─┼───┼─┼─────────┘ │ │x│ ─┼───┼─┘ │xxx│ ─┼───┘ x│ ``` With that explained, the program corresponds to the following pseudocode: ``` n = get integer from stdin # Calculate the number of lines we need to output. line = pow(2, n+1) while line > 0: line = line - 1 # For all segments except the last, the character to use is spaces. ch = ' ' (space, ASCII 32) # The number of segments in each line is # equal to the line number, counting down. seg = line while seg > 0: seg = seg - 1 # For the last segment, use x’s. if seg = 0: ch = 'x' (ASCII 120) # Calculate the actual segment number, where the leftmost is 1 n = line - seg # Output the segment i = pow(3, number of times n can be divided by 2) i times: output ch output '\n' (newline, ASCII 10) end program ``` # Long explanation Please refer to this color-coded code path diagram. [![Execution path](https://i.stack.imgur.com/ebY1A.png)](https://i.stack.imgur.com/ebY1A.png) Execution starts in the top left corner. The sequence of instructions `){2'"''3''"2}?)` is executed (plus a few redundant cancelations, like `"{` etc.) by pursuing a fairly convoluted path. We start with Instruction Pointer #0, highlighted in crimson. Halfway through, we switch to #1, starting in the top-right corner and painted in forest green. When IP #2 starts out in cornflower blue (middle right), the memory layout is this: [![Memory layout](https://i.stack.imgur.com/QNxkT.png)](https://i.stack.imgur.com/QNxkT.png) Throughout the entire program, the edges labeled **2a** and **2b** will always have the value `2` (we use them to calculate 2ⁿ⁺¹ and to divide by 2, respectively) and the edge labeled **3** will always be `3` (we use that to calculate 3ⁱ). We get to business as we enter our first loop, highlighted in cornflower blue. This loop executes the instructions `(}*{=&}{=` to calculate the value 2ⁿ⁺¹. When the loop exits, the saddle brown path is taken, which takes us to Instruction Pointer #3. This IP merely dabbles along the bottom edge westwards in goldenrod yellow and soon passes control to IP #4. The fuchsia path indicates how IP #4, starting in the bottom left, proceeds swiftly to decrement **line**, set **ch** to `32` (the space character) and **seg** to (the new value of) **line**. It is due to the early decrement that we actually start with 2ⁿ⁺¹−1 and eventually experience a last iteration with the value 0. We then enter the first *nested* loop. We turn our attention to the branching indigo, where, after a brief decrement of **seg**, we see **ch** updated to `x` only if **seg** is now zero. Afterwards, **n** is set to **line − seg** to determine the actual number of the segment we’re in. Immediately we enter another loop, this time in the fair color of tomato. Here, we figure out how many times **n** (the current segment number) can be divided by 2. For as long as the modulo gives us zero, we increment **i** and divide **n** by 2. When we are satisfied **n** is no longer thusly divisible, we branch into the slate gray, which contains two loops: first it raises 3 to the power of the **i** we calculated, and then it outputs **ch** that many times. Observe that the first of these loops contains a `[` instruction, which switches control to IP #3 — the one that was only taking baby steps along the bottom edge earlier. The body of the loop (multiplying by 3 and decrementing) is executed by a lonely IP #3, imprisoned in an endless dark olive green cycle along the bottom edge of the code. Similarly, the second of these slate gray loops contains a `]` instruction, which activates IP #5 to output **ch** and decrement, shown here in dark Indian red. In both cases, those Instruction Pointers trapped in servitude obediently execute one iteration at a time and yield control back to IP #4, only to bide the moment for their service to be called upon once again. The slate gray, meanwhile, rejoins its fuchsia and indigo brethren. As **seg** inevitably reaches zero, the indigo loop exits into the lawn green path, which merely outputs the newline character and promptly merges back into the fuchsia to continue the **line** loop. Beyond the final iteration of the **line** loop lies the short sable ebon path of ultimate program termination. [Answer] # Python 2, 78 bytes ``` L=[1] i=3 exec"L+=[i]+L;i*=3;"*input() while L:x=L.pop();print' '*sum(L)+'x'*x ``` Starting off with the list `L=[1]`, we duplicate it and insert the next power of 3 in the middle, resulting in `[1, 3, 1]`. This is repeated `n` times to give us the row lengths for the Devil's staircase. Then we print each row padded with spaces. [Answer] # APL, 38 ``` ⊖↑'x'/⍨¨D,⍨¨0,¯1↓-+\D←{1,⍨∊1,⍪3×⍵}⍣⎕,1 ``` Example: ``` ⊖↑'x'/⍨¨D,⍨¨0,¯1↓-+\D←{1,⍨∊1,⍪3×⍵}⍣⎕,1 ⎕: 2 x xxx x xxxxxxxxx x xxx x ``` Explanation: ``` ⊖↑'x'/⍨¨D,⍨¨0,¯1↓-+\D←{1,⍨∊1,⍪3×⍵}⍣⎕,1 ⎕ ⍝ read a number from the keyboard { }⍣ ,1 ⍝ apply this function N times to [1] 3×⍵ ⍝ multiply each value by 3 ∊1,⍪ ⍝ add an 1 in front of each value 1,⍨ ⍝ add an 1 to the end D← ⍝ store values in D (lengths of rows) +\ ⍝ get running sum of D - ⍝ negate (negative values on / give spaces) 0,¯1↓ ⍝ remove last item and add a 0 to the beginning ⍝ (each row needs offset of total length of preceding rows) D,⍨¨ ⍝ join each offset with each row length 'x'/⍨¨ ⍝ get the right number of x-es and spaces for each row ↑ ⍝ make a matrix out of the rows ⊖ ⍝ mirror horizontally ``` [Answer] # GNU sed, 142 Not the shortest answer, but its sed!: ``` s/$/:/ :l s/x/xxx/g s/:/:x:/g tb :b s/^1// tl s/:x/X/g s/^/:/ :m s/.*:([Xx]+)Xx*:$/&\1:/ tm :n s/([ :])[Xx](x*Xx*)/\1 \2/g tn s/:/\n/g s/X/x/g ``` Because this is sed (no native arithmetic), I'm taking liberties with the rule *"A single integer n >= 0, indicating the size of the output"*. In this case the input integer must be a string of `1`s, whose length is n. I think this is *"indicating"* the size of the output, even though it is not a direct numerical equivalent to n. Thus for n=2, the input string will be `11`: ``` $ echo 11 | sed -rf devils-staircase.sed x xxx x xxxxxxxxx x xxx x $ ``` This appears to complete with exponential time complexity of O(cn), where c is about 17. n=8 took about 45 minutes for me. --- Alternatively if it is required that n is entered numerically exactly, then we can do this: ### sed, 274 bytes ``` s/[0-9]/<&/g s/9/8Z/g s/8/7Z/g s/7/6Z/g s/6/5Z/g s/5/4Z/g s/4/3Z/g s/3/2Z/g s/2/1Z/g s/1/Z/g s/0//g :t s/Z</<ZZZZZZZZZZ/g tt s/<//g s/$/:/ :l s/x/xxx/g s/:/:x:/g tb :b s/^Z// tl s/:x/X/g s/^/:/ :m s/.*:([Xx]+)Xx*:$/&\1:/ tm :n s/([ :])[Xx](x*Xx*)/\1 \2/g tn s/:/\n/g s/X/x/g ``` ### Output: ``` $ echo 2 | sed -rf devils-staircase.sed x xxx x xxxxxxxxx x xxx x $ ``` [Answer] # Python 2, 81 ``` def f(n,i=1,s=0): if i<2<<n:q=3**len(bin(i&-i))/27;f(n,i+1,s+q);print' '*s+'x'*q ``` **Program version (88)** ``` def f(n,s=0): if n:q=3**len(bin(n&-n))/27;f(n-1,s+q);print' '*s+'x'*q f((2<<input())-1) ``` The number of x's in the `n`th 1-indexed row is 3 to the power of (the index of the first set bit in `n`, starting from the lsb). [Answer] # Python 2, 74 ``` def f(n,s=0): if~n:B=3**n;A=s+B-2**n;f(n-1,A+B);print' '*A+'x'*B;f(n-1,s) ``` A recursive approach. The size-$n$ devil's staircase is split into three parts * The left recursive branch, a staircase of size `n-1`, whose length is `3**n - 2**n` * The center line of `x`', of length `3**n` * The right recursive branch, a staircase of size `n-1`, whose length is `3**n - 2**n` Note that the total length of the three parts is `3*(3**n) - 2*(2**n)` or `3**(n+1) - 2**(n+1)`, which confirms the induction. The optional variable `s` stores the offset of the current parts we're printing. We first recurse down to the left branch with larger offset, then print the center line, then do the right branch at the current offset. [Answer] ## Pyth, 30 ``` jb_u+G+*leGd*HNu+N+^3hTNUQ]1]k ``` This is a program that takes input from STDIN and uses grc's method of finding the Cantor set. Uses the " character to display the curve. [Try it online here.](https://pyth.herokuapp.com/) Explanation: I will explain the code in two parts, first, the cantor set generation: ``` u+N+^3hTNUQ]1 u UQ]1 : reduce( ... , over range(input), starting with [1]) +N : lambda N,T: N + ... +^3hTN : 3 ** (T+1) + N (int + list in pyth is interpreted as [int] + list) ``` And the output formatting: ``` jb_u+G+*leGd*HN ]k jb_ : "\n".join(reversed(...) u ]k : reduce(lambda G,H: ... , over cantor set, starting with [""]) +G+*leGd : G + len(G[-1]) * " " + ... *HN : H * '"' ``` Note that in pyth N = '"' by default. [Answer] # CJam, ~~36~~ ~~35~~ 33 bytes Here is another CJam approach (I haven't looked at Optimizer's code, so I don't know if it's actually much different): ``` L0sl~{{3*0s}%0s\+}*{1$,S*\+}%W%N* ``` This uses `0` for the curve. Alternatively, (using grc's trick) ``` LLl~){3\#a1$++}/{1$,S*\'x*+}%W%N* ``` which uses `x`. [Test it here.](http://cjam.aditsu.net/#code=L0sl~%7B%7B3*0s%7D%250s%5C%2B%7D*%7B1%24%2CS*%5C%2B%7D%25W%25N*&input=3) ## Explanation The basic idea is to first form an array with the rows, like ``` ["0" "000" "0" "000000000" "0" "000" "0"] ``` And then to go through this list, prepending the right amount of spaces. ``` L0sl~{{3*0s}%0s\+}*{1$,S*\+}%W%N* L "Push an empty string for later."; 0s "Push the array containing '0. This is the base case."; l~ "Read and evaluate input."; { }* "Repeat the block that many times."; { }% "Map this block onto the array."; 3* "Triple the current string."; 0s "Push a new zero string."; 0s\+ "Prepend another zero string."; { }% "Map this block onto the result."; 1$ "Copy the last line."; ,S* "Get its length and make a string with that many spaces."; \+ "Prepend the spaces to the current row."; W% "Reverse the rows."; N* "Join them with newlines."; ``` The other version works similarly, but creates an array of lengths, like ``` [1 3 1 9 1 3 1] ``` And then turns that into strings of `x`s in the final map. [Answer] ## Dyalog APL, 34 characters Using the approach by grc. Draws the staircase with `⌹` (domino) characters and takes input from stdin. This solution assumes `⎕IO←0`. ``` ' ⌹'[(∪∘.=⊖){⍵/⍳≢⍵}⊃(⊢,,)/3*⌽⍳1+⎕] ``` * `⎕` – take input from stdin. * `⌽⍳1+⎕` – the sequence of the numbers from `⎕` down to 0. (e.g. `3 2 1 0`) * `3*⌽⍳1+⎕` – three to the power of that (e.g. `27 9 3 1`) * `(⊢,,)/3*⌽⍳1+⎕` – the previous result folded from the right by the tacit function `⊢,,` which is equal to the dfn `{⍵,⍺,⍵}` yielding the step lengths of the devil's staircase as per grc's approach. * `{⍵/⍳≢⍵}⊃(⊢,,)/3*⌽⍳1+⎕` the step lengths converted into steps. * `(∪∘.=⊖){⍵/⍳≢⍵}⊃(⊢,,)/3*⌽⍳1+⎕` that self-classified, as in my [J solution](https://codegolf.stackexchange.com/questions/46821/draw-the-devils-staircase/46826#46826). Notice that `⊖` already flips the result correctly. * `' ⌹'[(∪∘.=⊖){⍵/⍳≢⍵}⊃(⊢,,)/3*⌽⍳1+⎕]` the numbers replaced by blanks and dominoes. [Answer] ## Haskell, 99 characters ``` d=q.((iterate((1:).(>>=(:[1]).(*3)))[1])!!) q[]=[];q(a:r)=sum r&' '++a&'x'++'\n':q r (&)=replicate ``` The function is `d`: ``` λ: putStr $ d 3 x xxx x xxxxxxxxx x xxx x xxxxxxxxxxxxxxxxxxxxxxxxxxx x xxx x xxxxxxxxx x xxx x ``` [Answer] # Ruby, 99 A different answer to my other one, inspired by FUZxxl's answer FUZxxl notes that the numbers of x's correspond to the number of factors of 2 of the index. for example for n=2 we have the following factorization: ``` 1 =1 2 =1 * 2 3 =3 4 =1 * 2 * 2 5 =5 6 =3 * 2 7 =7 ``` I use a rather more straightforward way of extracting these powers of 2: `i=m&-m` which yields the sequence `1 2 1 4 1 2 1` etc. This works as follows: `m-1` is the same as `m`in its most significant bits, but the least significant 1's bit becomes a zero, and all the zeros to the right become 1's. To be able to AND this with the original, we need to flip the bits. There are various ways of doing this. One way is to subtract it from `-1`. The overall formula is then `m& (-1 -(m-1))` which simplifies to `m&(-m)` Example: ``` 100 01100100 100-1= 99 01100011 -1-99= -100 10011100 100&-100= 4 00000100 ``` Here's the code: newlines are counted, indents are unnecessary and therefore not counted, as my other answer. It's slightly longer than my other answer due to the clumsy conversion from base 2: `1 2 1 4 1 2 1 etc` to base 3: `1 3 1 9 1 3 1 etc` (is there a way to avoid that `Math::` ?) ``` def s(n) a=[] t=0 1.upto(2*2**n-1){|m|i=3**Math::log(m&-m,2) a.unshift" "*t+"x"*i t+=i} puts a end ``` [Answer] # Ruby, ~~140~~ 99 My second ever Ruby code, and my first nontrivial use of the language. Suggestions are most welcome. Byte count excludes leading spaces for indents, but includes newlines (it seems most of the newlines cannot be deleted unless they are replaced by a space at least.) Input is by function call. Output is an array of strings, which ruby conveniently dumps to stdout as a newline-separated list with a single `puts`. The algorithm is simply `new iteration` = `previous iteration` + `extra row of n**3 x's` + `previous iteration`. However there is ~~a lot~~ *a fair amount* of code just to get the leading spaces in the output right. ``` def s(n) a=["x"] 1.upto(n){|m|t=" "*a[0].length a=a.map{|i|t+" "*3**m+i}+[t+"x"*3**m]+a} puts a end ``` # Edit: Ruby, 97 This uses the similar but different approach of building a numeric table of all the numbers of x's required in array `a` in the manner described above, but then building a table of strings afterwards. The table of strings is built backwards in array `c` using the rather oddly named `unshift` method to prepend to the existing array. Currently this approach is looking better - but only by 2 bytes :-) ``` def s(n) a=c=[] (n+1).times{|m|a=a+[3**m]+a} t=0 a.each{|i|c.unshift" "*t+"x"*i t+=i} puts c end ``` [Answer] ## PHP - 137 bytes ``` function f($n){for($a=[];$i<=$n;array_push($a,3**$i++,...$a))$r=str_repeat;foreach($a as$v){$o=$r(' ',$s).$r(x,$v)." $o";$s+=$v;}echo$o;} ``` I'm using here the same trick as [grc](https://codegolf.stackexchange.com/a/46824/11713). Here is the ungolfed version: ``` function staircase($n) { $lengthsList = []; for ($i = 0; $i <= $n; ++$i) { array_push($lengthsList, 3 ** $i, ...$lengthsList); } $output = ''; $cumulatedLength = 0; foreach ($lengthsList as $length) { $output = str_repeat(' ', $cumulatedLength) . str_repeat('x', $length) . "\n" . $output; $cumulatedLength += $length; } echo $output; } ``` [Answer] ## C, 165 ``` #define W while f(n){int i=n+1,j=1<<i,k=1,l,r,s,t;W(i--)k*=3;l=k-j;W(--j){r=j,s=1;W(!(r%2))r/=2,s*=3;l-=s;t=l;W(t--)putchar(32);W(++t<s)putchar(88);putchar('\n');}} ``` Here's the same code unpacked and slightly cleaned up: ``` int f(int n) { int i=n+1, j=1<<i, k=1; while (i--) k*=3; int l=k-j; while (--j) { int r=j,s=1; while (!(r%2)) r/=2, s*=3; l-=s; int t=l; while (t--) putchar(' '); while (++t<s) putchar('X'); putchar('\n'); } } ``` This is based on the same idea as FUZxxl's solution to the problem, of using an explicit rather than implicit form for the rows. The declaration of j sets it to 2^(n+1), and the first while loop computes k=3^(n+1); then l=3^(n+1)-2^(n+1) is the total width of the staircase (this isn't too difficult to prove). We then go through all the numbers r from 1 to 2^(n+1)-1; for each one, if it's divisible by (exactly) 2^n then we plan on printing s=3^n 'X's. l is adjusted to make sure we start from the right spot: we write l spaces and s 'X's, then a newline. [Answer] # CJam, ~~46 43 41 39 36~~ 35 bytes ``` L0ri),(a*+_W%(;+{3\#'x*+_,S*}%$1>N* ``` *UPDATE* using a different approach now. --- Old approach: ``` ]ri){3f*_,)"x"a*\]z:+}*_s,f{1$,U+:U-S*\N} ``` Pretty naive and long, but something to get started. Will add explanation once I golf it. [Try it online here](http://cjam.aditsu.net/#code=L0ri)%2C(a*%2B_W%25(%3B%2B%7B3%5C%23'x*%2B_%2CS*%7D%25%241%3EN*&input=2) [Answer] # Java, ~~271~~ 269 bytes Uses grc's method. ``` import java.util.*;String a(int a){List<Integer>b=new ArrayList<>();int c=-1,d=1;for(;c++<a;b.add(d),b.addAll(b),b.remove(b.size()-1),d*=3);String f="";for(;b.size()>0;f+="\n"){d=b.remove(b.size()-1);for(int g:b)for(c=0;c<g;c++)f+=' ';for(c=0;c<d;c++)f+='x';}return f;} ``` Indented: ``` import java.util.*; String a(int a){ List<Integer>b=new ArrayList<>(); int c=-1,d=1; for(;c++<a;b.add(d),b.addAll(b),b.remove(b.size()-1),d*=3); String f=""; for(;b.size()>0;f+="\n"){ d=b.remove(b.size()-1); for(int g:b) for(c=0;c<g;c++) f+=' '; for(c=0;c<d;c++) f+='x'; } return f; } ``` Any suggestions are welcome. 2 bytes thanks to mbomb007 [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 16 bytes ``` Eɽ2Ǒ3$e₌ÞR‡\x*꘍Ṙ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiRcm9MseRMyRl4oKMw55S4oChXFx4KuqYjeG5mCIsIiIsIjIiXQ==) ``` Eɽ # range(1, 2**n-1) 2Ǒ # Multiplicity when divided by 2 3$e # 3 ** n ₌ # Apply both of the following to that: ÞR # Cumulative sums with tail removed and 0 prepended ‡\x* # And that many asterisks ꘍Ṙ # Pad with spaces to (cumulative sums) and reverse ``` [Answer] # Perl, 62 ``` #!perl -p eval's/x+/$&$&$& x/g,s/\d*/x /;'x++$_;s/x+/$"x$'=~y!x!!.$&/ge ``` First calculates the result iteratively without the leading spaces. Then adds them before each line according to the number of `x` characters in the rest of the string. [Answer] # JavaScript (ES6) 104 ~~106 118~~ **Edit** Removed the recursive function, the list of '\*' for each line is obtained iteratively, fiddling with bits and powers of 3 (like in many other answers) Inside the loop, a multiline string is buuilt from bottom up, keeping a running count of leading spaces to add on each line ``` F=n=>{ for(i=a=s='';++i<2<<n;a=s+'*'.repeat(t)+'\n'+a,s+=' '.repeat(t)) for(t=u=1;~i&u;u*=2)t*=3; return a } ``` **First Try** removed The recursive R function build an array with the number of '\*' for each line. For instance R(2) is `[1, 3, 1, 9, 1, 3, 1]` This array is scanned to build a multiline string from bottom up, keeping a running count of leading spaces to add on each line ``` F=n=> (R=n=>[1].concat(...n?R(n-1).map(n=>[n*3,1]):[]))(n) .map(n=>a=' '.repeat(s,s-=-n)+'*'.repeat(n)+'\n'+a,a=s='') &&a ``` **Test** In Firefox/FireBug console ``` F(3) ``` *Output* ``` * *** * ********* * *** * *************************** * *** * ********* * *** * ``` [Answer] ## R - 111 characters Straightforward implementation, building up the array iteratively and destroying it slowly. ``` n=scan() a=1 if(n)for(x in 1:n)a=c(a,3^x,a) for(A in a){cat(rep(' ',sum(a)-A),rep('x',A),'\n',sep='');a=a[-1]} ``` Usage: ``` > source('devil.r') 1: 2 2: Read 1 item x xxx x xxxxxxxxx x xxx x ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 41 bytes ``` !→⁰¡(↔§z+ömR' h∫mLtΘ`:"x"ṁȯe"x"Ṙ3f≠' );"x ``` [Try it online!](https://tio.run/##yygtzv7/X/FR26RHjRsOLdR41Dbl0PIq7cPbcoPUFTIedazO9Sk5NyPBSqlC6eHOxhPrU8GMGcZpjzoXqCtoWitV/P//3xgA "Husk – Try It Online") Creates an infinite list of graphs and indexes into them, cause why not. [Answer] # [Julia 1.0](http://julialang.org/), 64 bytes ``` !n=n<1 ? "x" : [' '^(L=2*3^n-2^n).*(m=!(n-1));lpad('x'^3^n,L);m] ``` [Try it online!](https://tio.run/##HclBCsIwEEDRfU8x6SYzxYqpXbUNXqA3EAOBKIykY6gV4ulj8e8e//mJ7E0uRYmVycAF6lzDAFcN2uFsu@bspO2c0LHBxSqU1hCNMfmAOmu338NM43Irj9cKDCxwGvoK9gK/U/RfVEx/p5Vli4JU3SWUHw "Julia 1.0 – Try It Online") output is a list of strings [Answer] # [Haskell](https://www.haskell.org/), 81 bytes ``` d=unlines.f f 0=["x"] f n|z<-f$n-1=z%[[1..3^n]>>"x"]%z a%b=map((a!!0>>" ")++)b++a ``` [Try it online!](https://tio.run/##FclNCoMwEEDhvacYgwElJChuGy/RZbAw/qSVxiE0ChI8e1O7e3zvheE9O5fSpHdyC81B2cxCrQ07WH8VnfEmbUGy0ZEb0yjVPqjvuv/mMUM@6BV9WWKe15cCq4SoBiEwrbgQaPD7dt8@UMAEbfqO1uEzJDl6/wM "Haskell – Try It Online") I counted `d=` to compete fairly with the older answer here. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes ``` ‘2*Ṗọ2 3*µạ+ɼ;¹⁾ xx)ṚY ``` [Try it online!](https://tio.run/##ATAAz/9qZWxsef//4oCYMirhuZbhu40yIDMqwrXhuqErybw7wrnigb4geHgp4bmaWf///zM "Jelly – Try It Online") ``` ‘2*Ṗọ2 3*µạ+ɼ;¹⁾ xx)ṚY Main monadic link ‘ Increment 2* 2 to the power Ṗ Range from 1 exclusive ọ2 Order of 2 3* 3 to the power µ ) Map: ạ Absolute difference with +ɼ increment the register by the number ; Join with ¹ the number ⁾ xx Repeat " x" that many times Ṛ Reverse Y Join with newlines ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0$F3*€1Ć}©×®ηO0š¨úR» ``` Outputs with `0` as character instead of `x` (could be any other digit by replacing the leading `0`). [Try it online](https://tio.run/##ASoA1f9vc2FiaWX//zAkRjMq4oKsMcSGfcKpw5fCrs63TzDFocKow7pSwrv//zI) or [verify the first few test cases](https://tio.run/##yy9OTMpM/W98bJKSZ15BaYmVgpK9nw6Xkn9pCYSn898gws/NWOtR0xrDI221h1Yenn5o3bnt/gZHFx5acXhX0KHd/3UObbP/DwA). **Explanation:** ``` 0 # Push a 0 $ # Push a 1 and the input-integer F # Pop the input, and loop that many times: 3* # Multiply the values by 3 €1 # Push a 1 before each integer in the list Ć # Enclose to also have a trailing 1 }© # After the loop: store the result in variable `®` (without popping) × # Pop it, and repeat the initial 0 that many times as string(s) ® # Push list `®` again η # Pop and push its prefixes O # Sum each inner prefix 0š # Prepend a leading 0 ¨ # Remove the last item ú # Pad the "x"-string with that many leading spaces R # Reverse the list » # Join the lines by newlines # (after which the result is output implicitly) ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. Closed 8 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. Write a program, in the language of your choice, that *appears* to successfully find a counterexample to [Fermat's Last Theorem](http://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem). That is, find integers *a*, *b*, *c* > 0 and *n* > 2 such that an + bn = cn. Of course, you can't *really* do it, unless there's a flaw in Andrew Wiles' proof. I mean *fake it*, by relying on * integer overflow * floating-point rounding error * undefined behavior * data types with unusual definitions of addition, exponentiation, or equality * compiler/interpreter bugs * or something along those lines. You may hard-code some or all of the variables `a`, `b`, `c`, or `n`, or search for them by doing loops like `for a = 1 to MAX`. This isn't a code golf; it's a contest to find clever and subtle solutions. [Answer] ## J Actually, Fermat did make quite a blunder: It's actually wrong for any b, c or n if a is 1: ``` 1^3 + 4^3 = 5^3 1 1^4 + 5^4 = 11^4 1 1^9 + 3^9 = 42^9 1 ``` > > Maybe just maybe, Fermat's precedence rules weren't strictly right to left. > > > [Answer] # TI-Basic ``` 1782^12+1841^12=1922^12 ``` Output (true) ``` 1 ``` [Answer] # Java This Fermat guy must have been sleeping. I get hundreds of solutions to the equations. I merely converted my Excel formula to a Java program. ``` public class FermatNoMore { public static void main(String[] args) { for (int n = 3; n < 6; n++) for (int a = 1; a < 1000; a++) for (int b = 1; b < 1000; b++) for (int c = 1; c < 1000; c++) if ((a ^ n + b ^ n) == (c ^ n)) System.out.println(String.format("%d^%d + %d^%d = %d^%d", a, n, b, n, c, n)); } } ``` > > The `^` operator actually means XOR in Java, as opposed to exponentiation in typical plain-text > > > [Answer] ## C++ ``` #include <cstdlib> #include <iostream> unsigned long pow(int a, int p) { unsigned long ret = a; for (int i = 1; i < p; ++i) ret *= a; return ret; } bool fermat(int n) { // surely we can find a counterexample with 0 < a,b,c < 256; unsigned char a = 1, b = 1, c = 1; // don't give up until we've found a counterexample while (true) { if (pow(a, n) + pow(b, n) == pow(c, n)) { // found one! return true; } // make sure we iterate through all positive combinations of a,b,c if (!++a) { a = 1; if (!++b) { b = 1; if (!++c) c = 1; } } } return false; } int main(int argc, char** argv) { if (fermat(std::atoi(argv[1]))) std::cout << "Found a counterexample to Fermat's Last Theorem" << std::endl; } ``` Compiled with `clang++ -O3 -o fermat fermat.cpp`, tested with `Ubuntu clang version 3.4.1-1~exp1 (branches/release_34) (based on LLVM 3.4.1)`: ``` ./fermat 3 Found a counterexample to Fermat's Last Theorem ``` We obviously found a, b, c > 0 so that a3 + b3 = c3 (this also works for n = 4, 5, 6, ...). > > Printing a, b and c might prove a bit difficult though ... > > > [Answer] # Java It looks like the theorem holds for n=3, but I found counterexamples for n=4: ``` public class Fermat { public static int p4(final int x) { return x * x * x * x; } public static void main(final String... args) { System.out.println(p4(64) + p4(496) == p4(528)); } } ``` Output: ``` true ``` Explanation: > > Even if the numbers seem small, they overflow when raised to the 4th power. In reality, 644 + 4964 = 5284 - 234, but 234 becomes 0 when restricted to int (32 bits). > > > [Answer] # Python ``` import math print math.pow(18014398509481984,3) + math.pow(1, 3) \ == math.pow(18014398509481983,3) ``` > > Who says that *c* must be greater than *a* and *b*? > > > [Answer] # GolfScript ``` # Save the number read from STDIN in variable N and format for output. :N"n="\+ { [{100rand)}3*] # Push an array of three randomly selected integers from 1 to 100. .{N?}/ # Compute x**N for each of the three x. +=! # Check if the sum of the topmost two results equals the third. }{;}while # If it doesn't, discard the array and try again. # Moar output formatting. ~]["a=""\nb=""\nc="""]]zip ``` This approach finds a bunch of different solutions. For example: ``` $ golfscript fermat.gs <<< 3 n=3 a=43 b=51 c=82 ``` ### How it works > > The first line should start with a `~` to interpret the input. Instead of, e.g., the number 3 , variable `N` contains the string `3\n`. > > While `2 3 ?` calculates 3, `2 N ?` pushes the index of a character with ASCII code 2 in `N` (-1 for not found). > > This way, `43 N ?` and `82 N ?` push `-1` and `51 N ?` pushes `0` (51 is the ASCII character code of `3`). > > Since `-1 + 0 = -1`, the condition is satisfied and `(43,51,82)` is a "solution". > > > [Answer] # C Well of course you folks are all finding counterexamples, you keep on getting integer overflows. Plus, you're being really slow by iterating on c as well. This is a much better way to do it! ``` #include <stdio.h> #include <math.h> int main(void) { double a, b, c; for (a = 2; a < 1e100; a *= 2) { for (b = 2; b < 1e100; b *= 2) { c = pow(pow(a, 3) + pow(b, 3), 1.0/3); if (c == floor(c)) { printf("%f^3 + %f^3 == %f^3\n", a, b, c); } } } return 0; } ``` > > `double` might be great on the range, but it's still a bit lacking in precision... > > > [Answer] # C We all hate integer overflows, so we'll use a small exponent `n` and some floating point conversions. But still the theorem would not hold for `a = b = c = 2139095040`. ``` #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> int a, b, c; int n; int disprove(int a, int b, int c, int n) { // Integers are so prone to overflow, so we'll reinforce them with this innocent typecast. float safe_a = *((float *)&a); float safe_b = *((float *)&b); float safe_c = *((float *)&c); return pow(safe_a, n) + pow(safe_b, n) == pow(safe_c, n); } int main(void) { srand(time(NULL)); a = b = c = 2139095040; n = rand() % 100 + 3; printf("Disproved for %d, %d, %d, %d: %s\n", a, b, c, n, disprove(a, b, c, n) ? "yes" : "no"); } ``` Output: `Disproved for 2139095040, 2139095040, 2139095040, 42: yes` `Disproved for 2139095040, 2139095040, 2139095040, 90: yes` > > In IEEE 754, the number 2139095040, or 0x7F800000, represents positive infinity in single-precision floating point types. All `pow(...)` calls would return +Infinity, and +Infinity equals +Infinity. An easier task would be to disprove the Pythagorean theorem by using 0x7F800001 (Quiet NaN) which is not equal to itself according to the standard. > > > [Answer] # Javascript ``` var a, b, c, MAX_ITER = 16; var n = 42; var total = 0, error = 0; for(a = 1 ; a <= MAX_ITER ; a++) { for(b = 1 ; b <= MAX_ITER ; b++) { for(c = 1 ; c <= MAX_ITER ; c++) { total++; if(Math.pow(a, n) + Math.pow(b, n) == Math.pow(c, n)) { error++; console.log(a, b, c); } } } } console.log("After " + total + " calculations,"); console.log("I got " + error + " errors but Fermat ain't one."); ``` 42 is magic, you know. ``` > node 32696.js After 2176 calculations, I got 96 errors but Fermat ain't one. ``` And also Wiles ain't one. > > Javascript `Number` is not big enough. > > > [Answer] # T-SQL To disprove this Fermat guy's theorem, we just need to find a counter example. It seems, he was super lazy, and only tried it for really small permutation. In fact, he wasn't even trying. I found a counter example in just 0 < a,b,c < 15 and 2 < e < 15. Sorry I'm a golfer at heart so I'll ungolf this code later! ``` with T(e)as(select 1e union all select (e+1) from T where e<14)select isnull(max(1),0)FROM T a,T b,T c,T e where e.e>2 and power(a.e,e.e)+power(b.e,e.e)=power(c.e,e.e) ``` Returns 1, meaning we found a counter example! > > The trick is that while the first e looks like an alias, it actually is a sneaky way of changing the data type of e from an int to a floating point type equivalent to a double. By the time we got to 14 we are beyond the precision of a floating point number so we can add 1 to it and we still don't lose anything. The minification is a nice excuse to explain away my seemingly silly double declaration of a column alias in the rcte. If I didn't do this it would overflow long before we got to 14^14. > > > [Answer] ## JavaScript It appears this guy was onto something alright. Onto drugs if you ask me. Given the constraints, no set of values can be found for which the theorem holds true. ``` var a = 1, b = 1, c = 1, n = 3, lhs = (a^n + b^n), rhs = c^n; alert(lhs === rhs); ``` > > As in Java, the `^` operator is the bitwise XOR operator in JavaScript. The correct way to calculate the power of a number is to use Math.pow. > > > [Answer] # Another BASIC counterexample ``` 10 a = 858339 20 b = 2162359 30 c = 2162380 40 IF (a^10 + b^10) = c^10 THEN 50 PRINT "Fermat disproved!" 60 ENDIF ``` ]
[Question] [ This challenge is in tribute to the winner of Best Picture at the Oscars 2017, [~~La La Land~~ Moonlight!](http://www.independent.co.uk/a7598151.html) --- Your challenge is to print the text ``` La La Land ``` pause one second, then change the text to show ``` ~~La La Land~~ Moonlight ``` The original text (La La Land) **must have a strikethrough**. This can be achieved either by clearing the screen, drawing on top of the original text, or by any other clever solutions. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so lowest bytes wins. Standard code-golf rules apply. [Answer] # Vim, 37 bytes ``` 3iLa <esc>snd<esc>gs:s/./&<C-v>u336/g A Moonlight ``` A fairly straightforward solution. Here is an animation of it running: [![enter image description here](https://i.stack.imgur.com/XRA5X.gif)](https://i.stack.imgur.com/XRA5X.gif) [Answer] # HTML, ~~153~~ 148 bytes Using CSS animation. Tested on Firefox and Chrome only. ``` <s>La La Land</s> <b>Moonlight<style>@keyframes l{0%{text-decoration:none}}@keyframes m{0%{opacity:0}}b,s{animation:m 0s 1s both}s{animation-name:l} ``` [![<s>La La Land</s> <b>Moonlight</b>](https://i.stack.imgur.com/pXUww.gif)](https://i.stack.imgur.com/pXUww.gif) [Answer] # HTML + JavaScript, 18 + 59 = 77 bytes ``` setTimeout('O.innerHTML="<s>La La Land</s> Moonlight"',1e3) ``` ``` <p id=O>La La Land ``` Sadly, there doesn't seem to be an efficient way to reuse `O.innerHTML`... [Answer] # Octave, ~~81~~ 66 bytes *15 bytes saved thanks to @Stewie* ``` text(0,.5,'La La Land');pause(1);text(0,.5,'---------- Moonlight') ``` [Online Demo Here](http://octave-online.net/#cmd=text(0%2C.5%2C%27La%20La%20Land%27)%3Bpause(1)%3Btext(0%2C.5%2C%27----------%20Moonlight%27)). While the demo shows two separate plots, when run in the desktop version of MATLAB, it shows the first plot, waits 1 second, and then adds the second string to the same plot. Since Octave doesn't have support for strike through text, I have instead opted to display the text within an `axes` object in a figure and display a "strikethrough" by displaying `'--------'` on top of the initial text (initial idea by @Stewie). Previously, I had actually plotted a `line` object to strike through `'La La Land'` [![enter image description here](https://i.stack.imgur.com/tmhW4.gif)](https://i.stack.imgur.com/tmhW4.gif) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 31 bytes ``` “XSøjĠḌ⁻Ça»Œts⁵µṀȮ⁸œS“Æɓ9m“ɓm”ż ``` Tested with xterm and `LANG=en_US`. Doesn't work on TIO for several reasons. ### Hexdump ``` 00000000: 58 53 1d 6a c4 ad 8b 0e 61 fb 13 74 73 85 09 c8 XS.j....a..ts... 00000010: ca 88 1e 53 fe 0d 9b 39 6d fe 9b 6d ff f9 ...S...9m..m.. ``` ### Verification ![screen capture](https://i.stack.imgur.com/FbwJ8.gif) ### Background This answer makes use of [control characters](https://en.wikipedia.org/wiki/C0_and_C1_control_codes) and [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code). * `0d` (`<CR>`) is used to return to the beginning of the liner after printing **La La Land**. * `9b 39 6d` (`<CSI> 9 m`) is used to activate strike-through text before printing **La La Land** for the second time. * `9b 6d` (`<CSI> m`) is used to reset foreground and background to default mode, thus deactivating strike-through, before printing **Moonlight**. ### How it works ``` “XSøjĠḌ⁻Ça»Œts⁵µṀȮ⁸œS“Æɓ9m“ɓm”ż Main link. No arguments. “XSøjĠḌ⁻Ça» Index into Jelly's inbuilt dictionary to yield "LA LA Land moonlight". Œt Convert to title case, yielding the string "La La Land Moonlight". s⁵ Split into chunks of length 10, yielding A =: ["La La Land", " Moonlight"]. µ Begin a new chain with argument A. Ṁ Take the maximum, yielding "La La Land". Ȯ Output; print "La La Land". ⁸œS Sleep for bool("La La Land") seconds and yield A. “Æɓ9m“ɓm”ż Zip ["\r\x9b9m", "\x9bm"] with A, yielding [["\r\x9b9m","La La Land"],["\x9bm"," Moonlight"]]. (implicit) Flatten and print. ``` [Answer] ## Bash, ~~70, 69~~ 66 bytes -4 pts thanks to Riley `echo La La Land;sleep 1;echo -e "\r\e[9mLa La Land\e[0m Moonlight"` Credits to [Sylvain Pineau's answer on AskUbuntu](https://askubuntu.com/a/528938) for the strikethrough [Answer] ## QBasic, 61 bytes ``` SCREEN 9 ?"La La Land"; SLEEP 1 LINE(0,7)-(80,7) ?" Moonlight ``` Using graphics mode, draw an actual line through the text. Here's what it looks like in [QB64](http://qb64.net): [![Moonlight](https://i.stack.imgur.com/xzPC9.gif)](https://i.stack.imgur.com/xzPC9.gif) The code should be pretty self-explanatory, but here's an ungolfed version: ``` SCREEN 9 ' One of several graphics modes PRINT "La La Land"; ' The semicolon suppresses the trailing newline SLEEP 1 LINE (0,7)-(80,7) PRINT " Moonlight" ``` [Answer] # MATL, 46 bytes ``` 'La La Land'tDlY.ttv45HY(`t@Y)' Moonlight'hXxDT ``` Since MATL doesn't have support for control codes or text formatting, this solution simply alternates between `'La La Land'` and `'-----------'` as fast as possible to simulate strikethrough text. [![enter image description here](https://i.stack.imgur.com/sKnW6.gif)](https://i.stack.imgur.com/sKnW6.gif) **Explanation** ``` 'La La Land' % Push the string literal to the stack tD % Duplicate this string and display tv % Stack a version of this string on top of another 45HY( % Replace the second one with '----------' ` % Do...while loop t % Duplicate the 2D character array @Y) % Grab the row corresponding to the loop index (modular indexing) ' Moonlight' % Push the string literal to the stack h % Horizontally concatenate the two Xx % Clear the display D % Display the string T % Push a literal TRUE to the stack to make it an infinite loop ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + [pv](https://linux.die.net/man/1/pv), 50 bytes ``` printf ♪La\ La\ Land›%b 9m\\0 m\ Moonlight|pv -0L1 ``` This builds on [@DigitalTrauma's Bash answer](https://codegolf.stackexchange.com/a/111587/12012). `♪` represents a carriage return (**0x0d**), `›` a CSI byte (**0x9b**). ### Hexdump ``` 0000000: 70 72 69 6e 74 66 20 0d 4c 61 5c 20 4c 61 5c 20 printf .La\ La\ 0000010: 4c 61 6e 64 9b 25 62 20 39 6d 5c 5c 30 20 6d 5c Land.%b 9m\\0 m\ 0000020: 20 4d 6f 6f 6e 6c 69 67 68 74 7c 70 76 20 2d 30 Moonlight|pv -0 0000030: 4c 31 L1 ``` ### Verification ![screen capture](https://i.stack.imgur.com/yLZci.gif) ### How it works *printf* repeats its format string as many times as needed to exhaust its other arguments. Since there is one occurrence of `%b` and two arguments (`9m\\0` and `m\ Moonlight`), it will produce the following byte stream. ``` \rLa La Land\x9b9m\0\rLa La Land\x9bm Moonlight ``` This does the following. * `\r` brings the cursor to the start of the line. * `La La Land` is printed verbatim. * `\x9b9m` activates strike-through text. * `\0` sets an end-of-line marker for `pv -0`. * `\rLa La Land` does the same as before. * `\x9bm` reset foreground and background to default mode, deactivating strike-through. * `Moonlight` is printed verbatim. Finally, `pv -0L1` prints one null-terminated line per second, introducing the desired delay. [Answer] # HTML + JavaScript, 10 + 63 = 73 bytes ``` setTimeout("document.write('<s>La La Land</s> Moonlight')",1e3) ``` ``` La La Land ``` [Answer] # PHP (86 75 69 Bytes) ``` La La Land<?=sleep(1)?:"\rL̶a̶ ̶L̶a̶ ̶L̶a̶n̶d̶ Moonlight"; ``` Uses UTF-8 character U+0336 for the strikethrough. Edit: Saved 17 bytes with the suggestions @Titus commented [Answer] # Pyth - 47 bytes Does the strikethrough thing now. ``` K"La La Land".d_1"\033c"+j"\u0336"K" Moonlight ``` [Answer] ## C ~~87~~ 86 bytes ``` f(){char*s="La La Land";puts(s);printf("\e[9m%s\e[0m",s);sleep(1);puts(" Moonlight");} ``` Ungolfed version: ``` void f() { char *s="La La Land"; puts(s); printf("\e[9m%s\e[0m",s); sleep(1); puts(" Moonlight"); } ``` [Answer] # HTML + JavaScript, 100 bytes ``` La La Land<script>setTimeout(function(){document.write("<s>La La Land</s> Moonlight")},1e3)</script> ``` ``` setTimeout(function(){document.write("<s>La La Land</s> Moonlight")},1e3); ``` ``` La La Land ``` [Answer] ## [GNU sed](https://www.gnu.org/software/sed/) + sleep, ~~63~~ 58 bytes *Edit:* saved 5 bytes, based on [Digital Trauma](/users/11259/digital-trauma)'s comments Waiting between two print statements can't be done using sed alone, and as such I call `sleep 1`. It is possible to do a system call from sed, using the `e` command, which is a GNU extension. ``` s:$:La La Land:p esleep 1 s:.:&̶:g s:.*:\c[[A& Moonlight: ``` To create strike-through text (line 3), a "combining long stroke overlay", [U+0336](https://en.wikipedia.org/wiki/Combining_character), is appended to each character. After that, I move the cursor up 1 line, effectively replacing the old text when printing something new, using the so called [ANSI Escape Sequences](http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/c327.html). These are interpreted by the terminal as special formatting commands. You can find more information about them [here](http://www.growingwiththeweb.com/2015/05/colours-in-gnome-terminal.html). [![gif image](https://i.stack.imgur.com/CmoLz.gif)](https://i.stack.imgur.com/CmoLz.gif) **Explanation:** ``` s:$:La La Land:p # add "La La Land" to pattern space and print it esleep 1 # run system command 'sleep 1' s:.:&̶:g # append U+0336 after each character (strike-through) s:.*:\c[[A& Moonlight: # '\c[[A' is '(escape)[A', ANSI code to move the cursor #up 1 line. Then append ' Moonlight' and print on exit. ``` [Answer] # Java 7, ~~207~~ ~~206~~ ~~171~~ 139 bytes ``` void c()throws Exception{System.out.print("La La Land");Thread.sleep(1000);System.out.print("\rL̶a̶ ̶L̶a̶ ̶L̶a̶n̶d̶ Moonlight");} ``` I'm kinda cheating with this first answer, because I use [strike-through unicode](http://manytools.org/facebook-twitter/strikethrough-text/). **Explanation:** ``` void c() throws Exception{ // Method (throws is necessary due to Thread.sleep) System.out.print("La La Land"); // Show initial text Thread.sleep(1000); // Wait 1 second System.out.print("\r // Move 'cursor' to the start of the line so we can overwrite the current text L̶a̶ ̶L̶a̶ ̶L̶a̶n̶d̶ Moonlight"); // and print new text } // End of method ``` --- # Java 7 (with AWT), ~~444~~ ~~429~~ 341 bytes [Crossed out 444 is still regular 444 ;(](https://codegolf.stackexchange.com/a/109866/52210) ``` import java.awt.*;import java.text.*;void m(){new Frame(){public void paint(Graphics g){g.drawString("La La Land",9,50);try{Thread.sleep(1000);}catch(Exception e){}AttributedString s=new AttributedString("La La Land Moonlight");s.addAttribute(java.awt.font.TextAttribute.STRIKETHROUGH,1>0,0,10);g.drawString(s.getIterator(),9,50);}}.show();} ``` Since Java console doesn't have any markup like strike-through, you'll have to use Java AWT. And well, if you thought Java Console was already verbose, then this is even worse (I know, I know, most of you couldn't even imagined Java 7 being any worse..) **Explanation:** ``` import java.awt.*; // import used for Frame and Graphics import java.text.*; // Import used for all AttributedStrings void m(){ // method new Frame(){ // Frame public void paint(Graphics g){ // Overridden paint method g.drawString("La La Land", 9, 50); // Show the initial text try{ Thread.sleep(1000); // Wait 1 second }catch(Exception e){} // Thread.sleep requires a try-catch.. AttributedString s = new AttributedString("La La Land Moonlight"); // Object to add markup to text s.addAttribute( java.awt.font.TextAttribute.STRIKETHROUGH, // Strike-through attribute 1>0,//true // Mandatory parameter before we can specify the length 0, 10); // From length 0 to 10 (length of "La La Land") g.drawString(s.getIterator(), 9, 50); // Show this new text with strike-through part } // End of paint method }.show(); // Show Frame } // End of method ``` **Output gif:** [![enter image description here](https://i.stack.imgur.com/zhAhY.gif)](https://i.stack.imgur.com/zhAhY.gif) [Answer] # Python 3, 90 bytes Use Unicode (U+0336) to strike-through, because the macOS terminal doesn't support that `\e[9m` command. ``` import time s='La La Land ' print(s,end='\r') time.sleep(1) print('̶'.join(s),'Moonlight') ``` [![L̶a̶ ̶L̶a̶ ̶L̶a̶n̶d̶ Moonlight](https://i.stack.imgur.com/ZICEB.gif)](https://i.stack.imgur.com/ZICEB.gif) [Answer] # Arduino, ~~332~~ 331 bytes Not competing, just for the fun. ``` #include<LiquidCrystal.h> LiquidCrystal lcd(7,8,9,10,11,12);String a="La La Land";String b="-- -- ----";void setup(){lcd.begin(16,2);}void loop(){lcd.home();lcd.print(a);delay(1000);lcd.clear();lcd.print(b);lcd.setCursor(0,2);lcd.print("Moonlight");while(1){delay(150);lcd.home();lcd.print(a);delay(150);lcd.home();lcd.print(b);}} ``` Bill of Materials: * 1 x Arduino Uno * 1 x LCD 16 x 2 * 1 x 10K Potentiometer * 1 x 180 ohm Resistor [![L̶a̶ ̶L̶a̶ ̶L̶a̶n̶d̶ Moonlight](https://i.stack.imgur.com/v1Ffj.gif)](https://i.stack.imgur.com/v1Ffj.gif) [Answer] # Python3, 99 bytes ``` import time l='La La Land' s='\u0336' print(l,end="\r") time.sleep(1) print(s.join(l)+' Moonlight') ``` [Answer] # Bash + pv, 62 ``` l="La La Land" printf "$l\0\r\e[9m$l\e[0m Moonlight"|pv -0qlL1 ``` [Answer] # SmileBASIC, 45 bytes **One less byte thanks to 12Me21's magic period trick.** As far as I'm aware SB doesn't have strikethrough characters, so I used `GLINE` instead. Obviously assumes a clear display, use `ACLS` if you need to. ``` ?"La La Land WAIT 60GLINE.,4,79,4?" Moonlight ``` [Answer] # AHK, 102 bytes ``` s=La La Land Send,%s% Sleep,1000 Send,^a{Del} Loop,Parse,s Send,%A_LoopField%{U+0336} Send,` Moonlight ``` I cheated a bit to get strikethrough text by using the [combining long stroke overlay](https://en.wikipedia.org/wiki/Strikethrough#Unicode) unicode character. This may create an odd appearance depending on your setup. Notepad gives a good appearance. [![The code in action](https://i.stack.imgur.com/nDsXn.gif)](https://i.stack.imgur.com/nDsXn.gif) --- AutoHotkey is clearly not the most efficient language for this but it was a fun challenge. Be careful where you run it because it doesn't create it's own display and wipes all the text of whatever window is active. [Answer] # Swift, 392 bytes Swift+UIKit is really not ideal for golfing! Run this in a XCode playground and the result will be shown in the preview pane. ``` import UIKit import PlaygroundSupport let l=UILabel(frame:CGRect(x:0,y:0,width:200,height:20)) l.textColor=UIColor.red let m="La La Land" let n=" Moonlight" l.text=m DispatchQueue.main.asyncAfter(deadline:.now()+1){ let a=NSMutableAttributedString(string:m+n) a.addAttribute("NSStrikethrough",value:1,range:NSRange(location:0,length:10)) l.attributedText=a } PlaygroundPage.current.liveView=l ``` ![preview](https://i.stack.imgur.com/kGTCv.gif) [Answer] # Python (137 Bytes) ``` from turtle import *;import time;write("La La Land");time.sleep(1);clearscreen();write("\u0336".join("La La Land ")+" Moonlight");done() ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 41 bytes ``` “ñ[“m‘Ọj “¡ṭḊßȥṡoẋ»¹13Ọ;9Ǥ;;0Ǥ;“"dE»œS1 ``` Doesn't work on online interpreter. [Answer] # TI-BASIC, ~~57~~ 53 bytes ``` :" LA :Text(3,4,Ans+Ans+Ans+"ND :Pause "",1 :Line(-9,8,-2,8 :Text(3,41,"MOONLIGHT ``` Note that this uses the TI-84+ CE ability with the newest OS to pause for 1 second. This will return a synthax error on the TI-84+. For testing, you can omit the 1 second pause by removing that line. Also remember to press Zoom, 6 first so that you are on default window settings, otherwise the line command won't work. [Answer] # SpecBAS - 58 bytes ``` 1 ?"La La Land "; 2 WAIT 1e3 3 DRAW 0,4;80,0 4 ?"Moonlight" ``` Each character is 8x8 pixels, so draws a line from 0,4 to the relative position 80,4 (80 added to first coordinate and 0 to second so it stays on same line). [![enter image description here](https://i.stack.imgur.com/uBxe1.png)](https://i.stack.imgur.com/uBxe1.png) [Answer] # [OIL](https://github.com/L3viathan/OIL), 76 bytes ``` ↩︎⎋[9m La La Land ⎋[0m Moonlight 4 1 10 20 4 14 10 9 20 6 5 4 0 4 1 4 2 89999 ``` Replace the `⎋` with an escape character and `↩︎` with a carriage return. OIL lacks any kind of sleep command, so I emulate it using a loop that counts down from 89999 to 1. It takes about one second on my computer, but it may not on yours. The first 3 lines are ignored by the interpreter, it then prints (`4`) the second line (line 1; "La La Land"). The following structure is the loop that decrements the large number at the end until it's equal to 1. In the end, I just print the first 3 lines. [Answer] # PHP, not competing (64 bytes) ``` <?=$s="\rLa La Land",sleep(1)?:wordwrap($s,1,--,1)," Moonlight"; ``` uses UTF-8: `--` stands for [`U+0336`](https://en.wikipedia.org/wiki/Strikethrough#Unicode) - but I am pretty certain that it does not work standing alone. If it does not, try `~"1I"` or `~I1` instead of `--` (+3 or +1 bytes). No time to store it to a file or figure out how to set my console to UTF-8; so I couldn´t test either of these; but whoever can: please let me know wether this is complete BS or not. [Answer] # Powershell, 63 bytes Works only in PowerShell ISE. Non-competing, since strikethrough is shifted by one char and I can't fix it. ``` 'La La Land',('̶'*10+' Moonlight')|%{sleep 1;Write-Host $_ -N} ``` [![L̶a̶ ̶L̶a̶ ̶L̶a̶n̶d̶ Moonlight](https://i.stack.imgur.com/EcJHf.gif)](https://i.stack.imgur.com/EcJHf.gif) ]
[Question] [ [Pyth](https://github.com/isaacg1/pyth) is a Python-inspired procedural programming language, created by PPCG user [isaacg](https://codegolf.stackexchange.com/users/20080/isaacg). What general tips do you have for golfing in Pyth? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Pyth. One tip per answer, please. [Answer] # Write the code in Python first Pyth is so similar to Python that it is pretty easy to translate Python programs to Pyth. However, because Pyth is a single-letter-per-command language, it is sometimes hard to write straight Pyth. By writing in Python first, there is less to think about at a time (since Python is a pretty easy language to code in). [Answer] # Know Your Variables Pyth has 3 categories of variables: generic pre-initialized variables, variables pre-initialized based on user input, and variables that implicitly generate an assignment on first use. ### Generic variables: ``` b = "\n" d = " " k = "" G = "abcdefghijklmnopqrstuvwxyz" H = {} # (empty dict) N = '"' T = 10 Y = [] Z = 0 ``` ### Input-initialized variables: ``` Q = eval(input()) z = input() ``` Note that these initializations will only be run in a given program if the associated variable is used outside of a string in the code. In addition, the order is `Q`, then `z`, if both are used. ### Assignment on first use variables: `J` and `K`. If you want to initialize them both to the same value, you can do so with an expression such as `KJ0`, which is equivalent to the lengthier `J0K0`. [Answer] # Use the even newer [online interpreter](https://pyth.herokuapp.com) to test your answers. Note that this is new software, so it may be buggy. Please report any problems to me. [Answer] Strings at the end of the line don't need end quotes. For example: ``` "Hello, world! ``` is a completely valid Hello World program. [Answer] # Use `C` for base compression This is actually undocumented, C on a string is actually *not* direct chr -> int but instead base 256 -> base 10 (which is the same on one char strings). This is hugely helpful in compressing an int, we can use this script to compress: ``` sCMjQ256 ``` Take `12345678910`, it results in `ßÜ>` (some unprintables in there). Also with an array of ints, you can concatenate them, and with large strings by converting to code points and treating as base 128 number. Another usage of `C`, thanks @xnor for showing me this, is making an arbitrary large number. The naive way is: ``` ^TT ``` But we can do one byte better with: ``` CG ``` this base 256 deconverts the entire alphabet. Results `156490583352162063278528710879425690470022892627113539022649722` = ~`1.56e62`. [Answer] # Use the short functional...err...functions When the lambda argument to `map` or `reduce` just applies one operation to the arguments,, you can use the short forms, `M` and `F`. `fMx` is equivalent to `mfdx`, and `fFx` is the same thing as `.UfbZx`. For instance, say we take a list of numbers as input and output each one incremented. A first approach might be: ``` mhdQ ``` However, that can be rewritten as: ``` hMQ ``` A similar thing applies to `reduce` with `F`. As an example, say there's a challenge to calculate the product of a list of integers. Again, a first try may be: ``` .U*bZQ ``` However, with `F`, that can be shortened to: ``` *FQ ``` Shaves off three bytes...not bad! [Answer] # There is now an [online tutorial](https://pyth.readthedocs.org/en/latest/) for Pyth. Full documentation will be added later. [Answer] ## Keep your Pyth implementation up to date. I'm fairly regularly improving Pyth, removing less useful features and adding more useful ones, so keep an eye out for what's new and update your copy of the implementation regularly. Some recently added features: (as of 10/19/14) `y`: Acts as `*2` on numbers, and as list of all subsets on strings and lists. For instance: ``` pyth -c 'y"abc' ['', 'a', 'b', 'c', 'ab', 'ac', 'bc', 'abc'] ``` `f`: `f` is normally the filter command. Now, when called with a number as its second argument, it will filter over the infinite sequence starting with that number and counting up by ones, then return the first element of the resulting sequence. For instance, here's the code to find the smallest prime over a billion: ``` pyth -c 'f!tPT^T9' 1000000007 ``` [Answer] ## Named arguments in functions (No longer supported) Sometimes, default values in functions can be useful for golfing. Pyth actually supports this (much to my surprise). For example: ``` DC=Z1RZ;C;C5 ``` Will print: ``` 1 5 ``` You can also use J and K to save characters when doing this: ``` DgJ1K1R+JKg;g2;g2 3 ``` prints: ``` 2 3 5 ``` This is usually useful for recursive algorithms. This no longer works, but I have left it here in case someone wants to golf using an old version of Pyth. [Answer] # Look at all of the control flow options ### Loops: `F`: For loop. Just like Python's. `V`: For loop over a range. Neither variable nor range must be given, so 2 characters shorter. `W`: While loop. Just like Python's. `#`: Infinite while loop. Escape with error or explicit break. ~~Only `try ... except` feature now in Pyth.~~ ### Functions: `D`: General define. Just like Python. `L`: 1 argument, no assignment function, like Python's lambda, but named. Function name, variable name and return (`R`) need not be given, so 3 characters shorter. ### Functional programming: `f`: Filter - select elements of input sequence that return truthy on input lambda. `f`: First integer greater than or equal to input which gives truthy filter result. `m`: Map - transform elements of input sequence using input lambda. `u`: Reduce - fold input sequence on input lambda, initializing accumulator to third argument. `o`: Order - older elements of input sequence using input lambda as the key. Usually, there will be multiple possibilities for any given problem, and only by writing test solutions with each of them can you figure out which is shortest. [Answer] # Unpacking 2 element tuples with `F` Say you have a 2 element tuple, `J = (a, b)`, and you want `r(a,b)`, for some 2 arity function r. The naive way to do this is `rhJeJ`. The fancy way to do this is `r.*J`, using the unpack operator. The really fancy way to do this is `rFJ`, using the fold operator. [Answer] # Use the short arithmetic functions `h`: Other than returning the first element of a list, it increments a number, e.g. `hT` evaluates to `11`. Shorter than `+1T`. `t`: This decrements a number (other than return the tail of a list), e.g. `tT` evaluates to `9`. Shorter than `-T1`. `y`: This doubles a number, e.g. `yT` evaluates to `20`, shorter than `*T2` or `+TT`. [Answer] # Use `map` to generate lists It's basically an equivalent of the fancy list comprehensions of python. Use an existing list or an range to iterate over and map each value, even if the value doesn't matter. Two examples: * Generate a list of 8 zeros. `mZ8` instead of `*8]Z` * Generate a list of 5 random numbers between 0 and 9: `mOT5` instead of `V5~Y]OT)` The second one automatically assigns the list to `Y` (well actually it appends to Y), but even `=YmOTU5` is shorter. [Answer] # Implicit Q at EOF This is a new change, as of today. `Q` is the variable which is auto-initialized to the evaluated input. It is implicitly appended to the end of the Pyth program, as many times as is necessary to make the arity work out. To see an example of how to use this for golfing, let's say we want to compute the [Collatz function](https://en.wikipedia.org/wiki/Collatz_conjecture) of the input. A shortest way to write it is like this: ``` @,/Q2h*3QQ ``` However, since the `Q`s are implicit at the end of the file, we can simply write: ``` @,/Q2h*3 ``` Saving 2 bytes. Note that functions with non-required arguments will not have those arguments filled in. For instance, `c"12 12"` will not have an implicit `Q`, since `c` only requires 1 argument. [Answer] # Use reduce to apply a function repeatedly. Suppose you need to set a variable to some function of itself, and repeat a certain number of times. Take, for instance, the problem of finding the number 100 later in the Collatz Sequence from the input. The shortest way to find the next number in the sequence, if the initial number is `Q`, is ``` @,/Q2h*Q3Q ``` The most obvious way to apply this 100 times and print the result would be ``` V100=Q@,/Q2h*Q3Q;Q ``` Loop 100 times, updating the value of Q each time, then end the loop and print Q. Instead, we can use a reduce function which ignores the sequence variable (`H`). ``` u@,/G2h*G3GU100Q ``` This is 2 characters shorter. It is 3 characters shorter if you are trying to loop as many times as there are elements in a sequence. [Answer] # There are usually shorter alternatives to Any When you want to find if any of a sequence satisfy a condition, you would usually use `.Em`. For example, if you want to find out if any in a list are greater-than-or-equal to 5: ``` .Emgd5Q ``` But, if it only needs to be a truthy/falsey, not true/false, `sm` would work since sum works on bools. ``` smgd5Q ``` We can even do one shorter, with `f`ilter: ``` fgT5Q ``` The last one looks really ugly though. For `.A`ll, the only thing I can think of is to use the opposite condition and negate it for a one char save over `.Am`: ``` !f<T5Q ``` [Answer] # Switching two elements in a list Switching two elements can be quite an expensive task. So here are two approaches you wanna use. ### Tmp-variable approach In preparation we define a list `Y` and fill it with some numbers. The goal is to switch the second and third element. ``` =Y[1 3 5 3 6 7)AGH,1 2 ``` We simply assign the tmp variable `J = Q[G]`, do the first list assignment `Y[G] = Y[H]` and then the second last assignment `Y[H] = J`. The trick here is to nest the two list assignments, so you don't have to suppress printing and don't have to use refer twice to `Y`. ``` J@YGXXYG@YHHJ ``` instead of ``` J@YG XYG@YHXYHJ ``` ### Translating approach If the elements, which you want to switch, are unique in the list, use this approach. It's really short. So this time we switch the first and third element (the values `1` and `5` are unique). ``` =Y[1 3 5 3 6 7)K,Z2 ``` This uses the translation functionality of the list: ``` XYm@YdK) ``` This translating replaces every element `Y[0]` with `Y[1]` and every `Y[1]` with `Y[0]`. So if the values are not unique, bad things happend. For instance `K,1 2` results in `[1, 5, 3, 5, 6, 7]`. Notice that the closing parentheses is optional, if the statement is the last one in your code. [Answer] # Finding the maximum of two integers ``` g# ``` For instance, suppose you have `J=5` and `K=12`. Then `g#JK` = 12, and `g#KJ` = 12 as well. This was discovered by @Pietu1998, who put it this way: Not sure if someone has already found it, but there's a cool way to do max(A, B) in 2 bytes, no need to use 3 for `eS,AB`. `g#AB` does the same thing. (It's very inefficient, though, since it loops max(1, A-B+1) times. An optimization is to put the number likely to be larger as B.) [Answer] # Pyth's `join` method The `join` method in Python can be often a little bit annoying, since it only joins strings. Pyth's `join` is more generous. It transforms all objects in strings by default. E.g. `jkUT` gives `0123456789` or `jb["abc"4,5\f]7` gives ``` abc 4 (5, 'f') [7] ``` [Answer] # Divisibility testing using `I` and GCD **Disclaimer:** This *only* works for non-negative integers. To check if two non-negative integers are divisible, you can do the following: ``` iI<divisor><dividend> ``` If **a** is divisible by **b** and **a ≥ b ≥ 0**, then **gcd(a, b) = b**. It doesn't necessarily save bytes over `!%<dividend><divisor>`, but it might bring you a saving, because: * You might be able to tweak the implicit stuff at the end of a Pyth program (like dropping `Q`), when working with the dividend. * You can use it as a `<pfn>`, since it is a function on its own. * It handles modulo by `0`. **[Try it!](https://pyth.herokuapp.com/?code=iIQ8&test_suite=1&test_suite_input=1%0A2%0A4%0A8%0A16%0A0%0A-1%0A-2%0A-4%0A-8&debug=0)** [Answer] # Telling if a Number is a Whole Number A neat trick is using `I`nvariant to tell if a number is a whole number as such: ``` sI ``` This checks if the number doesn't change when you truncate it, which it won't if it's a whole number. For example, you can use this as a perfect square check: ``` sI@Q2 ``` [Answer] # Debugging with `<newline>` If your code is written in an imperative programming style, it is quite easy to debug, since you can easily print intermediate results. ([permalink](https://pyth.herokuapp.com/?code=FN.%3AQ2%3DY%2B-Y-FNhNY%3BY&input=%5B1%2C+5%2C+4%2C+8%2C+4%5D&debug=0)) ``` FN.:Q2 loop =Y+-Y-FNhN some random command Y print intermediate result ;Y end for loop and print result ``` But a large amount of Pyth programs use elements of functional programming, like map, filter and reduce, which don't allow such a simple printing. But it is still possible, using the `\n` command. The same code using `u` (reduce) would be: ([permalink](https://pyth.herokuapp.com/?code=u%2B-G-FHhH.%3AQ2Y&input=%5B1%2C%205%2C%204%2C%208%2C%204%5D&debug=0)) ``` u .:Q2Y reduce .:Q2, start with G = Y +-G-FHhH random command ``` If you want to print the intermediate values, simply to insert `\n`: ([permalink](https://pyth.herokuapp.com/?code=u%2B-%0AG-FHhH.%3AQ2Y&input=[1%2C+5%2C+4%2C+8%2C+4]&debug=0)) ``` u .:Q2Y reduce \nG print(G) +-\nG-FHhH random command ``` `\na` prints `a` on a newline and returns `a`. So you can insert it anywhere without worrying changing the functionality of the program. [Answer] # Use Packed Pyth Packed Pyth is a new "programming language" which is exactly the same as Pyth, except that it uses 7 bits per character instead of 8 bits per character. To use it, clone the [pyth repository](https://github.com/isaacg1/pyth). The file `packed-pyth.py` is the interpreter. Say your code is `"Hello, world!`. First, put it in a file: `echo -n '"Hello, world!' > code.pyth` Next, pack the Pyth code into Packed Pyth file: `python3 packed-pyth.py -p code.pyth code.ppyth` Finally, run the Packed Pyth code: `python3 packed-pyth.py code.ppyth` When running code, you can provide the `-d` flag to see what the Pyth code that's actually being run is, and you can provide input as a second command line argument after the file containing the code. Upside: * Code is shorter by 1/8th. Downside: * ASCII only. * No interactive input. * Full debug options are not availible. * Worse error reporting. [Answer] # Assigning a variable to a function applied to itself If you have a function of arity 1, and want to apply that to a variable and apply to itself, you can use the following syntax: ``` =<function><variable> ``` Instead of: ``` =<variable><function><variable> ``` For example, if you want to increment the variable `Z`, you can do: ``` =hZ ``` Which saves one byte over `=ZhZ`. ]
[Question] [ A shape is [chiral](https://en.wikipedia.org/wiki/Chirality) if no amount of rotation can make it look like it's mirror image. In this puzzle we will be writing chiral computer programs. For this puzzle we will think of a program as a rectangular matrix of characters. As such all solutions to this challenge must be rectangular (that is all lines must be of the same length). We can rotate these programs in quarter turn increments. For example the program ``` The quickish fish lept deftly rightwards ``` When rotated a quarter turn clockwise looks like ``` T h r e i glq heu tpi wtc a k rdi des sfh t lf yi s h ``` We can also reflect these programs. Here is the same program reflected over a vertical axis: ``` hsif hsikciuq ehT yltfed tpel sdrawthgir ``` A chiral program is a program that when rotated any number of times will always output "`left`". However when reflected produces a program that outputs "`right`" no matter how many times it is rotated. Your task is to write a chiral program in as few bytes as possible. ### Additional Rules * Output is not-case sensitive but should be consistent. (e.g. You may output "`LEFT`" and "`rIgHt`" but this casing must be consistent under rotations) * Lines are to be split either on a newline or a newline and a linefeed. * Your program must be a rectangle, you can pad it with spaces or comments but each line must have the same length. * You may optionally have a trailing newline (or newline and linefeed) on all of your programs if you wish. [Answer] # [Pascal (FPC)](https://www.freepascal.org/), ~~2161~~ ~~755~~ 349 bytes ``` ///////bw(,,),(wb/////// ///////er'''e''re/////// begin//girgtnflig//nigeb write//itih'dteti//etirw ('le'//ne'' .''en//'ir'( ,'ft'//////////////'hg', )end.////////////// 't', ,'t' //////////////.dne) ,'gh'//////////////'tf', ('ri'//ne''. ''en//'el'( write//itetd'hiti//etirw begin//gilfntgrig//nigeb ///////er''e'''re/////// ///////bw(,),,(wb/////// ``` [Try left](https://tio.run/##XVDLCsQgDLz7Fd7Ggqvf1Ee0AZHiBvr53cB2W7s5KGQyM8ls43seyytt83HEb027837wbp/Ohjl/agAIaPQDJspcY8zcstRUOMdYOdNk9saiUyy8YhESVrZw241DIeiUytigasoGNzjjkQTxUVgzvBmoLuEJWIgCXl/7BMJSaVAgr/9SkpTh0Pg0D/Y0p6Lm17okC1a@170OLKlKbveBXSSq1kXShTj4LsTj@AA "Pascal (FPC) – Try It Online") [Try right](https://tio.run/##XVBJDsMgDLzzCm5DJApvymKIJYQiainPTx01zVIfQPIstmfp32NfXmkZty1@a1id77x363A0zPFTAwhAox8wUOYaY@aSquTGOcbKmQazNhZl6SMTZhZWtXBbjUNjKEt9glU7VYMKnPHIM@KjIAleAYF9AmGq1JmO6hSegFXurkjybzVnBRwKHcNtOIZz0@Hnujxj0p3Pdc8DW5aaynXgLZI9kyuSW4ia4hXitn0A "Pascal (FPC) – Try It Online") @tsh motivated me to try again when I saw his program (in comment) and here it is! --- Previous one with 755 bytes: ``` begin write('left')end.// /e .dne)'thgir'(etirw nigeb /g e .i .g dn di n nn ew e )r )w 'i 'r tt ti fe ht e( ge l' i( 'r r' (i 'l eg (e th ef it tt r' i' w) r) e we nn n id nd g. i. e g/ begin write('right')end. e/ //.dne)'tfel'(etirw nigeb ``` [Try left](https://tio.run/##dZIxjkMhDET7OYU7Q7FwpiQYviWEImKJ4/9t0qQYt6/w83jej8/rMf/6@3Xf8rThS872sKTTemi21UqtgmpS2rKscQ3fmix8H1k@7Ik6hIyhOEFloC3CmoMhWQt22DpB3oTlA2UuuhFBWDi6EXYFLBE2DFMJ8wRlnluRqOeEsayTIS6WS4fT@wKbeipOZp4ZwnI5hsUfCG8MNYzCXArYOhkVP9XdPq5vd8UqpNZvd7vNn@rKff8D "Pascal (FPC) – Try It Online") [Try right](https://tio.run/##dZIxjkMhDET7OYU7Q7FwpiQYviVkRSwSx/@7RZoU4/ZJ5nmY9@P39Zg//f26b6m1tLCsu9vUZNvXkfBhT8HThoec5duSLh/X1mzRiliFCZlRMQphXuCNsGiIYEsDwh48hpMJWxlLmYvCN2F7Y1@EWYcNwpIhOWE6oYt5Kib1TLDEsjZ0lsv1fwO9z6HUcyEzz3xgh@Ui4N8XaAw2R2EuZaCyrMVQTT7dvYavr/JCvso7rX@6W6vc9x8 "Pascal (FPC) – Try It Online") If you saw my previous submission, just forget it :) All rotations for both left and right programs are the same. [Answer] # [Klein (000)](https://github.com/Wheatwizard/Klein), ~~109~~ 87 bytes ``` ."left"@\. \"right".. @"thgir">. ..@"tfel"\ \"left"@.. .>"right"@ .."thgir"\ .\@"tfel". ``` [Try it online!](https://tio.run/##Lcq7CcAwDAXAXmO8Pg9NYJw91PpHTArj/RVBXB7cM8t43YlZ6kY2imGN1jdIydi9jYVEIQO1TFiE/0ZgOjlHONmEdi7dXVX9uj8 "Klein – Try It Online") Should be possible to get a shorter version of this answer so good luck! This answer is inspired by spirals. In particular the idea is two interlocked spirals, one for left and one for right. It has two fold symmetry, So we can check the following programs to know it works: ## Quarter turn ``` ...\.@\. \.>".""" @""l@trl "tre"hie thiftggf fggtfiht eih"ert" lrt@l""@ """.">.\ .\@.\... ``` [Try it online!](https://tio.run/##DczBDcQwCATAP2XsPytXEHF98MU2CsrDon8uBcw86fF2kzSqUYw3CEAUSK2TgjqOHS61Y9ZaU@ZaNWOXeGz4KUie0gRUPkncNKHpN5LdPcbo6/cH "Klein – Try It Online") ## Mirrored ``` .\@.\... """.">.\ lrt@l""@ eih"ert" fggtfiht thiftggf "tre"hie @""l@trl \.>".""" ...\.@\. ``` [Try it online!](https://tio.run/##DczBDcQwCATAP2XsPytXEHF98MU2CsrDon8uBcw86fF205RGUgAQN03ylCag4rHhpyBzrZqxS2rHrLWmoI5jh4sCqXVSjPfnAfkuoxq7e4zR1@8P "Klein – Try It Online") ## Mirrored and Quarter turn ``` .\@"tfel". .."thgir"\ .>"right"@ \"left"@.. ..@"tfel"\ @"thgir">. \"right".. ."left"@\. ``` [Try it online!](https://tio.run/##Lcq7DcAgDAXA3mO8Pk9MgMgebvkpVgrE/g4odFfcY7m/7tSEWbKBQmK22gdUGDF6bRNJFJbLAnc4VyWdGrnCX3c4V@nuIQS/7g8 "Klein – Try It Online") [Answer] # [Klein (000)](https://github.com/Wheatwizard/Klein), ~~27~~ 25 bytes ``` \(("right"@/ \(("left"@!\ ``` [Try it online!](https://tio.run/##y85Jzcz7/z9GQ0OpKDM9o0TJQZ8LxMlJTQOyFWP@//9vYGDwX9cRAA "Klein – Try It Online") [Rotated once!](https://tio.run/##y85Jzcz7/z8mhktDA4SUlLhyirhSM7nS0rlKMriUSrgclLgUHbhi9P///29gYPBf1xEA) [Rotated twice!](https://tio.run/##y85Jzcz7/z9G0UGpJC01R0lDI4ZLH8jOSM8sAnH@//9vYGDwX9cRAA) [Rotated three times!](https://tio.run/##y85Jzcz7/18/hstBkUvJgatEiSujhCs9jSszlasoh0tJiUtDA4RiYv7//29gYPBf1xEA) And flipped: [Try it online!](https://tio.run/##y85Jzcz7/1/fQakkIz2zSElDI4YrRhHIS0vNAXH@//9vYGDwX9cRAA) [Rotated once!](https://tio.run/##y85Jzcz7/z9Gn0vRgctBiUuphKskgystnSs1kyuniEtJiUtDA4RiYv7//29gYPBf1xEA) [Rotated twice!](https://tio.run/##y85Jzcz7/z9GQ0MpJzWtRMlBMYYLxCnKTM8A8vT///9vYGDwX9cRAA) [Rotated thrice!](https://tio.run/##y85Jzcz7/z8mhktDA4SUlLiKcrgyU7nS07gySrhKlLiUHLgcFLn0Y/7//29gYPBf1xEA) The only one that gave me a bit of trouble was the flipped and rotated once, which looks like: ``` \/ !@ @" "t th fg ei lr "" (( (( \\ ``` This is the only reason for the two sets of `((`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~1481~~ ~~599~~ ~~505~~ ~~461~~ ~~341~~ ~~305~~ 271 bytes ``` /g+///g/g"c.c"g/ g=//////=rolol=g "left"///inone/+ console//gsgsf// .log(g)//ho(ot// console//tlgl"// "right"//"e)e//g g=////////////// //////////////=g g//e)e"//"thgir" //"lglt//elosnoc //to(oh//)g(gol. //fsgsg//elosnoc +/enoni///"tfel" g=lolor=//////=g /g"c.c"g/g///+g/ ``` ## Mirrored ``` /g"c.c"g/g///+g/ g=lolor=//////=g +/enoni///"tfel" //fsgsg//elosnoc //to(oh//)g(gol. //"lglt//elosnoc g//e)e"//"thgir" //////////////=g g=////////////// "right"//"e)e//g console//tlgl"// .log(g)//ho(ot// console//gsgsf// "left"///inone/+ g=//////=rolol=g /g+///g/g"c.c"g/ ``` [Try it online!](https://tio.run/##lVLNbtwgEL7zFAjlYNcbJofeXOch2qPjxpZ3zLJiwQKyjdTm2beD7XUSJRslXAaG@X6GYd8du9B7PcZr67Z4OnaeD7ziv6LXVknf/WlPoAoAUKBEL3uhgKkKplV5Z5ypFBMGhygoo62zCAXrnQ3OIKGCCgMAk8apTOUAO5e5SIm1IhplCMqE12qXSATmCbiqnBd7fSRZBUC1CRJ3SntBFYLYiB6NC9b1lIiktwPISd0ZSYmBHKnnigKQPGtIJAMaQbLUk/PVqrL2TSgoFJxa6XE0XY8Z/L6z/@7sFaiNEHnJ2PBg@6id5QftvfNZyPlfxj3GB295eMbVBGwKgj1Wt48yjEbHNtEe0QfMcrl32rYtMT694PQudhEXzjQoQ4MKC5q15SpUSylNfdM08tCNWXa10Xl1a@bD/WafDvW@qXWTv5WcY2JL0vcRDyOpDCXtqSfaLp0NZA6@ncc4jXeqoPTL3PQsg/M8S4Y14W9KCj/4dwpFMbXymiMpEoa/YeGrm@Uh1toncgJfURE/JwYueEFlBcWoDxg2nL7C9dwgbsX7Lj7rFo@d@bBgiwbJgyqXTV9@0uSXDM4juezv4v179i5OgJ9/x3ox89JkaDSn/w "JavaScript (Node.js) – Try It Online") ### (Please see the TIO Link for all test cases, including mirrored version) ### Although further golfed, size `22x22 -> 21x21` on credit of @JoKing! Size ~~38x38~~ ~~24x24~~ ~~22x22~~ ~~21x21~~ ~~18x18~~ ~~17x17~~ 16x16, 4-fold symmetry. Here comes a question -- is it possible to have 15x15 or smaller for JS? It seems that what I need at least is the comment separator between two sub-blocks and at the edge, so at least 7+2+2+5=16 lines? [Answer] # [Klein (211)](https://github.com/Wheatwizard/Klein), 37 bytes ``` !\"left"@"thgir"\! !/............../! ``` This has a different program for each rotation. ## Explanation Note that each of these programs is padded to a square with no-ops before execution ### No change ``` !\"left"@"thgir"\! !/............../! ``` [Try it online!](https://tio.run/##y85Jzcz7/18xRiknNa1EyUGpJCM9s0gpRpFLUV8PBegr/v//38jQ8L@uIwA "Klein – Try It Online") `!` makes execution jump over the `\` and `"left"@` loads the string `"left"` into the stack and terminates the program printing the stack ### Quarter turn ``` !!...IP-> \/ ". r. i. g. h. t. ". @. ". t. f. e. l. ". \/ !! ^ | P I ``` [Try it online!](https://tio.run/##y85Jzcz7/19RkStGn0tJj6tIjytTjytdjytDj6tEDyTiACaB7DQ9rlQ9rhwwF6hYUfH///@6jv@NDA0B) Execution runs off the top right corner of the square, continues in the bottom left corner and once again `!\"left"@` prints `"left`. ### Half turn ``` ^ | P I !/............../! !\"right"@"tfel"\! .................. .................. .................. .................. .................. .................. .................. .................. .................. .................. .................. .................. ................^. ................|. IP->............P. ................I. ``` [Try it online!](https://tio.run/##y85Jzcz7/19RXw8F6CtyKcYoFWWmZ5QoOSiVpKXmKMUo/v//X9fxv5GhIQA) Here, the execution path exits from the North side, re-enters through the West side, exits again from the East Before entering in the south. `\` bounces the path into `"left"@` to print it. ### Three-quarter turn ``` !!..IP-> /\ ." .l .e .f .t ." .@ ." .t .h .g .i .r ." /\ !! ^ | I P ``` [Try it online](https://tio.run/##y85Jzcz7/19RkUs/hktPiUsvh0svlUsvjUuvBMx1AJNAdgaXXjqXXiaXXhFIBKhYUfH///@6jv@NDA0B) Execution exits from the top right corner then re-enters in the bottom left. Once again the mirrors `/\` redirect the path into `"left"@` to print it. ### Reflection ``` !\"right"@"tfel"\! !/............../! ``` This is essentialy the same as for left in all rotations. [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~109~~ ~~89~~ 71 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` (tfel⁸(( (h(right ⁸g q(f li re er il f( g⁸ thgir(h( ((⁸left( ``` [Try it here](https://dzaima.github.io/Canvas/?u=JXVGRjA4dGZlbCV1MjA3OCV1RkYwOCV1RkYwOCUwQSV1RkYwOGgldUZGMDhyaWdodCUwQSV1MjA3OGclMjAlMjAlMjBxJXVGRjA4ZiUwQWxpJTIwJTIwJTIwJTIwcmUlMEFlciUyMCUyMCUyMCUyMGlsJTBBZiV1RkYwOCUyMCUyMCUyMCUyMGcldTIwNzglMEF0aGdpciV1RkYwOGgldUZGMDglMEEldUZGMDgldUZGMDgldTIwNzhsZWZ0JXVGRjA4,v=8) | [Try reversed!](https://dzaima.github.io/Canvas/?u=JXVGRjA4JXVGRjA4JXUyMDc4bGVmdCV1RkYwOCUwQXRoZ2lyJXVGRjA4aCV1RkYwOCUwQWYldUZGMDglMjAlMjAlMjAlMjBnJXUyMDc4JTBBZXIlMjAlMjAlMjAlMjBpbCUwQWxpJTIwJTIwJTIwJTIwcmUlMEEldTIwNzhnJTIwJTIwJTIwJTIwJXVGRjA4ZiUwQSV1RkYwOGgldUZGMDhyaWdodCUwQSV1RkYwOHRmZWwldTIwNzgldUZGMDgldUZGMDg_,v=8) Those are the only two possible programs, as the program is rotationally symmetric. Made in [this](https://dzaima.github.io/Canvas/?u=JXVGRjM3SSV1RkYwMyV1RkYxOCV1RkYxOCUyMCV1MjU0QiV1RkYxQSV1RkYxMyV1MjdGMyV1RkY0RSV1RkYxQSV1RkYxMiV1MjdGMyV1RkY0RXJlc3VsdC52YWx1ZSUzRHAucCV1RkYwMyV1RkY1RA__,i=JTIwJTBBJTBBJTBBJTBBJTBBJTBBJTIwJTIwJXVGRjA4cmlnaHQlMEEldUZGMDh0ZmVsJXUyMDc4JXVGRjA4,v=8). [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 23 bytes ``` \"thgir"H / \"tfel"H.9\ ``` [Try it online!](https://tio.run/##S8/PScsszvj/P0apJCM9s0jJQ0GfC8hOS81R8tCzjPn/HwA "Gol><> – Try It Online") This is the same format as [my Klein answer](https://codegolf.stackexchange.com/a/172024/76162), but 2 bytes shorter. Maybe there's another 2D language out there that can golf those last 2 bytes off... But for now, this is as short as it gets. [Answer] # [Ruby](https://www.ruby-lang.org/), 131 bytes ``` #######:$:# :right#l>r# $><<###e<i# :left##f<g# #### t#h# #t## ##t# #h#t #### #g<f##tfel: #i<e###<<>$ #r>l#thgir: #:$:####### ``` [Try it online!](https://tio.run/##JY1LCgAhDEP3PYUQTyHFwwz4A1els5jTO1Gz6esjEHufby3cpJggyUbrjpkNErMqfdFBP0t1oGqD7HIIwdHJfhi8wt8Pg9y0UtYyk2BooVPNUWB5wnsbRr8Xb9b6AQ "Ruby – Try It Online") [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 98 bytes ``` \[[email protected]](/cdn-cgi/l/email-protection);./r. .)@.;...;. ll..)gt.;$ ;.i<;;;i); e;@.)@e;.l .;e;d.g|.| rt/;t.;)g\ @f.#l.;..r \.;\.;i\.i ``` [Try it online!](https://tio.run/##FYwxCsQgFAX7f41sYzM5wNvCg9gE4hpBNiAWCXh3Y2CmG@aI15bO/z1GwNPEWjGcRzC1UsClhj4m8ldSdrIoP5soiqGondTpVtuqWboUzP9YyvuoFtAkB/IYDw "Hexagony – Try It Online") | [Rotated 90°](https://tio.run/##DckxCkIxEEXRfrahzTT3L@BZzEKmEYwxEBRCCoW/95j2nFf53uvn/VsrY1DUSeM5Jbpj4ijRiLC8bLoBRp8Pl2vuhVBF1qRaNPcmfqrBYVDBpWFt5Nl1hbX@ "Hexagony – Try It Online") | [Rotated 180°](https://tio.run/##FYwxCsQgFAX7f41sYzM5wNvCg9gE4hpBNiAWCXh3Y2DKmTnitaXzf4@RCVmEiVUQZeHnLSQnmtZWrdMTu6KwgqJ3eEWTy5K@GdlnmslBKTb79zEdo66o4QljPA "Hexagony – Try It Online") | [Rotated 270°](https://tio.run/##DckxCkIxEEXRfrahzTT3L@BZzEKmEYwxEBRCCoW/95j2nFf53uvn/VsLrupnjmZDcqhgBzSdThpMlSo1E1UByKZc/pidvdyQLmkRtCjHXrxvmk8s6SqMyLX@ "Hexagony – Try It Online") [Reversed](https://tio.run/##FYsxCsQgFAX7f41sYzM5wNvCg9gE4hpBNiAWCXh3Y@BNNfOOeG3p/N9jUFfU8ARDMPEO@4iWHJRiclnSNyMrKE7rFa3TE7uisJDcrLW2avX9l4Wft0zIIsyN8QA "Hexagony – Try It Online") | [Rotated 90° & Reversed](https://tio.run/##FckxCgIxEIbRfq6hTZpvD/BbzEGmEYzZQHAhpFhh7x5j@96ez2c5Pt85g6ZM9zBSQxpvzJ3qeUMGPBbewoaS0ms0TBT5iv8O5SJV26DqSoR1KUGBtXe1K3qd8wc "Hexagony – Try It Online") | [Rotated 180° & Reversed](https://tio.run/##FYsxCsQgFAX7f41sYzM5wNvCg9gE4hpBNiAWCXh3Y@BNNfOOeG3p/N9jBDSXA9n8j6UgqFbbqoZcCoaidlKnW5TH@SiKifyVlJ2sFHBp1h@b9v1PLOBpYq2M8QA "Hexagony – Try It Online") | [Rotated 270° & Reversed](https://tio.run/##HckxCgIxEIbRfq6hzTTfHuC3mINMIxizgaAQUijs3eNi@95ePvf6fn3XaiOPrisYVHBpWOKHGmzWpFo0zxUQqsjo8@FyTcuLxI3/biUaEcZzntgdyxgUdXKtHw "Hexagony – Try It Online") Hexagony was kind of fun for this challenge, because a rotation or a reversal can drastically change the actual program. Each Rotation/Reversal is its own unique program. Some of the program execution paths are much more interesting than others. I will admit that coming up with this took longer than it probably should have. I am pretty sure a shorter answer can be done in Hexagony, so good luck! [Answer] # [APL (dzaima/APL)](https://github.com/dzaima/APL), 181 bytes The program has rotational symmetry so only two cases need to be checked --- ## Left ``` ⍝⍝⍝⍝⍝⍝⍝ t⎕t⍝ t←'lef'⍝ ←←←⍝ ⎕←t, 't'⍝ t←'righ'⍝r,l⍝ ⍝ i e⍝ ⍝ ' g f⍝ ⍝' h h '⍝ ⍝f g t ⍝ ⍝e i ⍝ ⍝l,r⍝'hgir'←t ⍝'t' ,t←⎕ ⍝←←← ⍝'fel'←t ⍝t⎕t ⍝⍝⍝⍝⍝⍝⍝ ``` [Try it online!](https://tio.run/##ZY87DgIxDER7TuHOTThUJPKTjIQiVxyAbhEN5V4uFwkes0qzlgvneTyaxIdcb8/Y7nHOse3nJtLx/qpNFx2vD0vKDGzz0bYxhU0aCMXKS91bqXj1IGC2dUurRskJ3uykUHavbWeqTirxQbJtUep6kGQOtPxAJHTc1tI6I4076d87II2lBFvJccs5yVL7T93y3HP@AA "APL (dzaima/APL) – Try It Online") ## Right ``` ⍝t⎕t ⍝⍝⍝⍝⍝⍝⍝ ⍝←←← ⍝'fel'←t ⍝'t' ,t←⎕ ⍝l,r⍝'hgir'←t ⍝e i ⍝ ⍝f g t ⍝ ⍝' h h '⍝ ⍝ ' g f⍝ ⍝ i e⍝ t←'righ'⍝r,l⍝ ⎕←t, 't'⍝ t←'lef'⍝ ←←←⍝ ⍝⍝⍝⍝⍝⍝⍝ t⎕t⍝ ``` [Try it online!](https://tio.run/##ZZA5DgMhDEX7nMKdG3IopLBJRIqQqzlAuqA0lLncXIT4ezQ0gywwz98L@Fe9PzZfnn7O/fOTvQ8hUu9qNxzv72GQcAyV1RdEWJiwnEDQB1h1DZGcSlu6QMV06uoOEikZEWNWi7KRTIy@xo/qiaKRM5@0WgBBV24lZWQ0V23ePtDVmU7nW7oaIi60XnO@7mI6FX5EvTn/ "APL (dzaima/APL) – Try It Online") ## Explanation This is my first APL program so it is pretty simple. It only uses one trick that I think is interesting. If we start by stripping away all the comments we get the following programs **Left** ``` t←'lef' ⎕←t, 't' t←'righ' ``` **Right** ``` t←'righ' ⎕←t, 't' t←'lef' ``` Starting from the left program we do three things. 1. Assign `'lef'` to the variable `t` 2. Print the variable `t` and the letter `'t'` 3. Assign `'righ'` to the variable `t` Now because it is the mirror the right program does these three steps but in the opposite order. This means that we print `'left'` for the left program and `'right'` for the right program. The one trick here is that the `'t'` actually comes from a rotated copy of the code. If you look at the third colum of our code you will see that it is `'t'`. We reuse this `'t'` in the rotated versions to append the `t` that is needed. [Answer] # [Alice](https://github.com/m-ender/alice), 25 bytes ``` }/"regttoo { {/"lifh""@@{ ``` Left: [Normal](https://tio.run/##S8zJTE79/79WX6koNb2kJD9foZqrWl8pJzMtQ0nJwaH6/38A "Alice – Try It Online"), [1/4 turn clockwise](https://tio.run/##S8zJTE79/7@6lktfn0tJiSuniCszlSstnSujhEsJiPK5HIBIgau6@v9/AA "Alice – Try It Online"), [1/2 turn](https://tio.run/##S8zJTE79/7/awUFJKSMtM0dJv5qrWiE/v6QkPbVISb/2/38A "Alice – Try It Online"), [1/4 turn counterclockwise](https://tio.run/##S8zJTE79/79WX6koNb2kJD9foZqrWl8pJzMtQ0nJwaH6/38A "Alice – Try It Online") Right: reflect across [horizontal axis](https://tio.run/##S8zJTE79/79aIT@/pCQ9tUhJv5ar2sFBSSkjLTNHSb/6/38A "Alice – Try It Online"), [down-right diagonal](https://tio.run/##S8zJTE79/7@2mktfn0tJiasohys1kys9jaskg6tEiSsfiBy4FBy4qqv//wcA "Alice – Try It Online"), [vertical axis](https://tio.run/##S8zJTE79/79aXyknMy1DScnBoZqrVl@pKDW9pCQ/X6H6/38A "Alice – Try It Online"), [up-right diagonal](https://tio.run/##S8zJTE79/7@6mstBgcshn0sJiEq4Mkq40tK5MlO5coq4lJS49PW5qmv//wcA "Alice – Try It Online") ## Explanation This program has three parts. The first part is the three `{`s and one `}` on the corners. The `{` turn the IP left until it reaches the `}`, at which point it turns right. In the reflected version, the IP goes along the top row in the original program. In the original version, turning right will immediately hit the adjacent `{`, pointing the IP along the bottom row in the original program. Next are the two slashes in the second column. If the program is horizontally oriented, either type of slash would simply change to ordinal mode, sending the IP in the same left/right direction it was already going. If the program is vertically oriented, the IP bounces around quite a bit more, but making them both forward slashes gives the same end result. (Two backslashes would give the opposite result, and one of each would create an infinite loop.) The rest of the program is straightforward. The IP in ordinal mode bounces diagonally, so either `"left"o@` or `"right"o@` will be run depending on how this section was entered. [Answer] # [Haskell](https://www.haskell.org/), ~~461~~ 379 bytes *82 bytes saved by [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%c3%98rjan-johansen)* ``` --_----------mppr-- -- ----------a l-- rl=p p-- niam= _ p m="left"-- n==p-- p a="right"++ "" -- main =putStr rl -- --n +r =iep-- -- -+t pgf--- -- -"S uht--- -- "tt tt" -- ---thu S"- -- ---fgp t+- -- --pei= r+ n-- -- lr rtStup= niam -- "" ++"thgir"=a p --p==n --"tfel"=m p _ =main --p p=lr --l a---------- -- --rppm----------_-- ``` [Try it online!](https://tio.run/##RdDLrcQgDAXQfaq48hZRgqtIARELkqAxyOI59Wc8A/Pi5cH4d6a/Vxa57xi3@B9Vtce4xIjHEiBuXVgB9SeglVQZ26KoTJJ3I@fG7K9uiamX4zQKAUReaampNID1stU6uuDboyF0jOCSdfYNNk2PPU6jddp12jSyX54ZjXrRzmvaSnHafugvL0zTXHhaD2ijnvhcPt2lPNb79iCEQHYepRMn6Ocvc/MqZHsW4uq2gcd6zp8DsXTPEyA9Jxx9u2p9zK9@328 "Haskell – Try It Online") Since this one has 4-fold symmetry you only need to test the mirror: ``` --rppm----------_-- --l a---------- -- _ =main --p p=lr --p==n --"tfel"=m p -- "" ++"thgir"=a p -- lr rtStup= niam --pei= r+ n-- ---fgp t+- -- ---thu S"- -- -- "tt tt" -- -- -"S uht--- -- -+t pgf--- --n +r =iep-- main =putStr rl -- p a="right"++ "" -- p m="left"-- n==p-- rl=p p-- niam= _ -- ----------a l-- --_----------mppr-- ``` [Try it online!](https://tio.run/##RdBBrsQgCAbg/ZziD1vDEThFD9C4sK0ZNcRHz99HrTPDji8g4BH/3qmU62LuqpW/sTK/mAsQfwa3FVJjboAnCqiU7nUq0hzItlRIKtQNRAiB7NhzJ4mPlY5ui50qQMux3r0pezKiB7Qxl7ddp1kYc93sOKctNA1k9qkzmsa0TDsP42nhU6f79lhD6NMkJ3V7DhM9fUPfs9zvKaJQz/thFMJ90rAqVNJm5C83kbu3F7m/w@E5TLCOud@IQBlz159V1c58Xf8 "Haskell – Try It Online") This is a start. It is far from ideal, but there are a few interesting things going on here. Haskell is a certainly an interesting language for this challenge. I look forward to an answer that beats this be it mine or someone else's. [Answer] # [Python 2](https://docs.python.org/2/), 209 bytes (14 x 14) Normal (left): ``` ##########sps# s="left"##=r=# print s###"i"# s="right"#rnl# #### ite# ###" g f# #"#t hst# #tsh t#"# #f g "### #eti #### #lnr#"thgir"=s #"i"###s tnirp #=r=##"tfel"=s #sps########## ``` [Try it online!](https://tio.run/##PY5LCkQxCAT3niLoDWaf4@QjBCeomzl9xmfg9a4opXv/fH7lcw69sW0EVnG17khUtRJsZfFiYZExrfKYoVUWwfNVMuwtES@O0gOR/OI0D3SbFz0MUI@rTHQFNueLlLhECX0OVqwG2R4LiwvrhtwWureV9ln@5pw/ "Python 2 – Try It Online") Reflected (right): ``` #sps########## #=r=##"tfel"=s #"i"###s tnirp #lnr#"thgir"=s #eti #### #f g "### #tsh t#"# #"#t hst# ###" g f# #### ite# s="right"#rnl# print s###"i"# s="left"##=r=# ##########sps# ``` [Try it online!](https://tio.run/##Rc9LDgQhCATQvacw1A1673H8kBjHAJs5vaOS9LB7VAzl/Fr7jGct6FS8E5AkAWQld0oaQEx7rdEGywzoQ3bYKstNs3G8429LrE66NG1OA20SzNnUNvcVZ43lEk62jKCJhGszgoyOMIWHxdPz9Dlpz2WHt2341z9/WesH "Python 2 – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 55 bytes ``` ####‛‛# ‛⟑ǒ#¬⟑# ‛¬ẋ#ẋǒ# ####### #ǒẋ#ẋ¬‛ #⟑¬#ǒ⟑‛ #‛‛#### ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%23%23%23%23%E2%80%9B%E2%80%9B%23%0A%E2%80%9B%E2%9F%91%C7%92%23%C2%AC%E2%9F%91%23%0A%E2%80%9B%C2%AC%E1%BA%8B%23%E1%BA%8B%C7%92%23%0A%23%23%23%23%23%23%23%0A%23%C7%92%E1%BA%8B%23%E1%BA%8B%C2%AC%E2%80%9B%0A%23%E2%9F%91%C2%AC%23%C7%92%E2%9F%91%E2%80%9B%0A%23%E2%80%9B%E2%80%9B%23%23%23%23&inputs=&header=&footer=) | [Try it flipped](https://lyxal.pythonanywhere.com?flags=&code=%23%E2%80%9B%E2%80%9B%23%23%23%23%0A%23%E2%9F%91%C2%AC%23%C7%92%E2%9F%91%E2%80%9B%0A%23%C7%92%E1%BA%8B%23%E1%BA%8B%C2%AC%E2%80%9B%0A%23%23%23%23%23%23%23%0A%E2%80%9B%C2%AC%E1%BA%8B%23%E1%BA%8B%C7%92%23%0A%E2%80%9B%E2%9F%91%C7%92%23%C2%AC%E2%9F%91%23%0A%23%23%23%23%E2%80%9B%E2%80%9B%23&inputs=&header=&footer=) The code is rotationally symetrical. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), ~~649~~ 188 bytes ### Unflipped, Unrotated ``` :-% l :%r %-: write(%e%-(i %(etirw left).%f.weg%.)right % t)rth. % % )tiit) % % .htr)t % right).%gew.f%.)left write(% i(-%e%(etirw :-% r%: l %-: ``` [Try it online!](https://tio.run/##XY5LCgUhDAT3niKbgFmYA3ifqAFhHnkBj@84HzeTVdOQrvrZ0Y@a/kPnzAlhXYeMdgXAlMMwdYkomKICRnG1EboUJ8bCQyoymdbm4X4GcDJv/GTcJbmq06fk5ka@y3tkjVYZXNboxdh00JiWwkt/PcEwL9nHc84T "Prolog (SWI) – Try It Online") ### Unflipped, Rotated ``` :wr%%%lw: -ri er- %ig fi% th tt et )e () .( %. %% %.)tfel right).% %(etirw-: :-write(% %.)thgir left).% %% .% (. )( e) re tl it %ie gi% -rf hr- :wt%%%tw: ``` [Try it online!](https://tio.run/##Hc4xCkQxCATQ3lOkEZIi/wC5j0mEwC6u4PGz4@8eIjPztc/5rP4LvXeEMfOJQd20lCLWiXVBU5mKb8i9UBGHmkC1QU@F@IGYIbD5lEOma3t7cOMqrhZ90Ohh6lKZ3re91OjIfN8yhTMvU2rmtUyW7LBs8wMpFrAKtLCq24Q2lo5wrPcY9/4B "Prolog (SWI) – Try It Online") ### Flipped, Unrotated ``` :-% r%: l %-: write(% i(-%e%(etirw right).%gew.f%.)left % .htr)t % % )tiit) % % t)rth. % left).%f.weg%.)right write(%e%-(i %(etirw :-% l :%r %-: ``` [Try it online!](https://tio.run/##XY5BCsUgDET3niKbgFmYA3ifqAGhJT/g8f21rZtmNTzIvDnt6EdNv6Fz5oSwzjBDXwFTDsPUJSJoTCgYxdVGMK3NibHK4IJMXYqH5xm4uZE/GTckV3X6QCfzxhuujquy8JB6Vd6KbRdMUWHb350dMhq8O@f8Aw "Prolog (SWI) – Try It Online") ## Flipped, Rotated ``` :wl%%%rw: -re ir- %if gi% tt ht e) te (. )( %% .% left).% %.)thgir :-write(% %(etirw-: right).% %.)tfel %. %% () .( er )e ti lt %ig ei% -rh fr- :wt%%%tw: ``` [Try it online!](https://tio.run/##Hc5BCkUhCAXQuatwItSgFtB@rITgPfxCy@/f3uwg6r2vP@sZ5bftnLaXiPhuVFyZ2byQWIeGCXEENIOJNUOhUKpQTpAIVIVpaY8M3FnNMYc5tbLdQpOQJA3zXRq5jfktEn@LXde9wBe5s3Qz6v2sfjNuWhi00EBsQIpWxSfU0bTtQPvY7Zw/ "Prolog (SWI) – Try It Online") [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), ~~239~~ ~~223~~ ~~209~~ 181 bytes ``` %%%%%%% l:r% right).% e-i% :-write(%fwg% left).% trh% % )it% %( .t)% %.e% %e.% %)t. (% %ti) % %hrt %.)tfel %gwf%(etirw-: %i-e %.)thgir %r:l %%%%%%% ``` [Try it online!](https://tio.run/##JYpBCgQhDATveYWXBnPQB/ifqAFhlmzA57vZsS7povKxZz2jfLeeg0tKqxnIdEzniiRFQa1sU5eMvgdoSX9TcpuglGL9YfUw5GvVGYQqN0JqGHu9MYe48pXY0zxuZe@yCGN3ZHG1XRpBi7xpDjWCtRWfl3PODw "Prolog (SWI) – Try It Online") Since the program has 4 fold symmetry you only need to check the mirror: ``` %r:l %%%%%%% %i-e %.)thgir %gwf%(etirw-: %hrt %.)tfel %ti) % %)t. (% %.e% %e.% %( .t)% % )it% left).% trh% :-write(%fwg% right).% e-i% %%%%%%% l:r% ``` [Try it online!](https://tio.run/##JY5BCgQhDATveUUuDXrQB/ifqAFhhmzA57syqVt1Xfq1Zz2j/LaeA2uLGQFBizBq9jnUCGN3JHG1XRphmvMXuyyCa@YPMBOy17CEa1UQSSqIkSJVz9c4Emd10JLuud7FbYJa2aYuCX0PkOmYX5Si91nAvJrhnD8 "Prolog (SWI) – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~1331~~ 1055 bytes *-276 bytes thanks to [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%C3%98rjan-johansen)* ``` // ////////////;/;/////////// // // ////////////S/S/////////// // module m////mtmt////m eludom //o///////////=a=a///////////o// //d///////////"r"r///////////d// //u///////////tttt///////////u// //l///////////f#h#///////////l// //e///////////emgm///////////e// // ///////////loio/////////// // //m///////////"drd///////////m// //////////////=u"u////////////// //////////////ml=l////////////// //////////////#eme////////////// ////////////// =#=////////////// ;Start#module= 0 #m="left"=m// //m="thgir"=m# 0=eludom#tratS; ;Start#module=0 #m="right"=m// //m="tfel"=m# 0 =eludom#tratS; //////////////=#= ////////////// //////////////eme#////////////// //////////////l=lm////////////// //////////////u"u=////////////// //m///////////drd"///////////m// // ///////////oiol/////////// // //e///////////mgme///////////e// //l///////////#h#f///////////l// //u///////////tttt///////////u// //d///////////r"r"///////////d// //o///////////a=a=///////////o// module m////tmtm////m eludom // ///////////S/S//////////// // // ///////////;/;//////////// // ``` [Try "left" online!](https://tio.run/##hVNNa8MwDL3nVwj73Kb3osEYhR32cegPGG7jNAErLq4N@/eZmlKq2FsmH2LJT4otvXcwl24cjybCE9C6P7rKfp99iPDytnv@@Hr9fN9h7c@xPjprhuqxrQ/9wDuCFV1gNUSgal2btU9xHOsaamFbXg/joyoD7HnNAQDkm@Qs0DVCkeL0BetS4wmAK3iRggaNcP30i0ZEVFBBuM0ESCIS2YSbJoATkVZ3WrhuAlgRsXQi6RbPdL73RR9kimqCvDNNAGmYVJpHMgA5dIsAbckuAgA1ZoDtPpoQ9W0gCBsA0ITK2TYqvF2S3did@sC@5uMN3uakYzBxv80q3AuE/tTNKrTW3QtAViHrg0ZYfAW/Ui8CuE@0COBOYwGQKTwrVQxL3oqn7Ypxy@YzX2xBGJnCjGsLyv1LWkkhZr0qaC9JyLrBTDhz6bHyqJAe/KndX9Q9V//16Ac "Bash – Try It Online") [Try "right" online!](https://tio.run/##hVPBasMwDL3nK0R8bt178WCMwg7ddugHDLdxmoAVF1eG/X2mpbSVY8jkQyz5WZGl94722o3jyRK8AK77k6/czyVEgrf97vXz@/3rY2d0uJA@eWeH6rnVx37gHcIKr7AaCLBaa7sOicZRa9BP2/ISxkdVDjjwmgEAMDTJO8C/CCFNXwTnUxMQgDMEccUaa4Qbpl80IhLrWAu3mQBJRIhNuGkCeBFRnWqF6yeAExE8o3Rd8czQB1/0AWVVsZFF4gSQlupk8sgM4I3HRYBDpxYBRhkoAGhqap2vDSoA2IC5jUFRtHTYVtsD2UjqNjGzYYjiG7E/d8RXHhm6cx/vKRYzwD2Fd@0jQ8YQrnLxFcplsygByJ1a7gP3uuyDcGueVjEs2TrP8y7GnTGEGVMQRlbVMucKyv1LWlkVsz4WtJdVsW7sTDi59Fh5VEgvY0iu3lLdM/3z0S8 "Bash – Try It Online") This was difficult for many reasons: * Clean *requires* a file header `module <filename>` be present at the start, *and only the start* of the file. Unfortunately, this means that for the rotations of the mirrored program to be valid it also has to appear at the bottom of the file. To make this worse, `module ..` is invalid for global, `let .. in`, `where ..` and `with ..` definitions; and the token `module` appearing if it hasn't been defined causes an error. * Both block comments and line comments nest: `/* /* */` leaves one level of comment open, and so does `/* // */` (as well as commenting the rest of the line out). * The same function can be defined multiple times, but only directly after itself. Fortunately, we *can* define `module` as something in a `#..` (let-before) expression, which is all we need. Because Clean doesn't type-check alternatives that are never used (and a variety of other equally unused things), the requisite second definition of `Start` can be complete garbage. This allows us to use the second `Start` to consume the module header at the bottom of the file because Clean treats `m module m` as calling the function `m` on `module` and `m` (which since we've defined `module` and `m`, doesn't cause an error). It doesn't matter that `m` is a string and not a function, because the `Start` alternative never gets type-checked. This is easier to see if you look at it through the compiler's eyes: ``` module m; Start#module=0#m="left"=m; Start#module=0#m="right"=m module m ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 341 bytes ``` Ẹw"thgir"∧"left"wẸ w" "w " " t t f h e g l i " r ∧ " " ∧ r " i l g e h f t t " " w" "w Ẹw"tfel"∧"right"wẸ ``` [Try it online!](https://tio.run/##bdDBCcMwDAXQ@5@iaIRu1ARbMggKwmCyQTbpCiHbtIs4pj5Fto6Pjy39xV6rbPrmZ63f8yiUhZPRb/@QhpipNEShx22owEkzZE8Z0ZMgeGKopzQ@b2grjX8OuZaCjbnkScGeAsRTnB01OX1SUC8zBv13aYmll1nrBQ "Brachylog – Try It Online") [!enilno ti yrT](https://tio.run/##jdDBCcMwDAXQ@5@iaIRs1BRbMggKwmCyQTbJCiHbtIs4pjlV9iECXx7G1v@zPV@y6JunWj/HXijHoPRdN7LEkqk0RKHH31CBk2bInjLEUwR7CkieFNY/3/3YlkQ7N24a1FNC8MSInmQUahB9UNBVpnCyX5sa4lVmrSc) Takes advantage of Brachylog taking the main predicate to be the one on the first line and not much caring about the other lines beyond requiring that they can compile. Unreflected, it prints an empty string followed by "left" on the same line, and reflected it prints an empty string followed by "right" on the same line. I'm tempted to think there might be a way to make a (usefully) non-square version using `ṇ`, but that might be plenty tricky without trying to make it work differently under reflection. [Answer] # [Ruby](https://www.ruby-lang.org/), 181 bytes ``` #########tpt# t=:left##=u=# puts t###:t:# t=:right#rsl# #### i e# ###t gtf# #t#h h#t# #ftg t### #e i #### #lsr#thgir:=t #:t:###t stup #=u=##tfel:=t #tpt######### ``` [Try it online!](https://tio.run/##NY5LCgAhDEP3PYWQWwheZsAfuJAaF3N6xxYmqz5C0uh@3nPwi5MQpjhyIZB2gszNFS4gMrqnvTZC14BYJJh6yE50qiyXiObU7iUorE7WJMg3YYLTWAq22jUmiv@xpsU9xTeAJQ/3bN@vcz4 "Ruby – Try It Online") This is a port of Curtis Bechtel's Python answer to Ruby, golfed a little more. Actually, his Python program is a polyglot and runs on Ruby too, so my first answer was a copy-paste of it, but it seemed unfair. So I wrote a script that generates a new answer starting from a base script. You can try it here: [Build your own](https://tio.run/##dY/NDsIgDIDvPMWSLbJJhibOixlPYjygQTeDkxT2qz77BEVjNPYApd/XpkC97ceO5TmnWsnSBNFsDF@BDFtJsTc2U7XRgfE1KA@FCUeOUM86euIqnqx2BQedUAO80uqshS8fz2WV@BxEI0CLBA22yz@@Ucv6fwhJFsdzShePeZcrv3ZrviG9PW7EgewNWgdw4AI7gWReWXwqZLkhg@u2sx//k88Lp2mKkWi4DOQ0miEETL6WehrwI4IVxzs) [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~89~~ 55 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '…¸q©ƒ' ƒ … © ¸ q q ¸ © … ƒ 'ƒ©q¸…' ``` Very basic approach. Outputs in full lowercase. [Try it online](https://tio.run/##MzBNTDJM/f9f/VHDskM7Cg@tPDZJnevYJAUQAApxHVoJZh7awVUIZhRyHdoBEVnJBZQHM49N4lI/NunQysJDO4BC6v//AwA) or [try it online reflected](https://tio.run/##MzBNTDJM/f9f/dikQysLD@141LBMnQtIKIDAsUlch3aAWYdWchWCGYVch1ZCRHZwHZsEZgFVc6kDiUM7Cg@tPDZJ/f9/AA) (each rotation is the same). **Explanation:** ``` '…¸ '# Push the dictionary string "left" to the stack q # Stop the program (and output the top of the stack implicitly) # Everything else after it is ignored ``` Reversed: ``` 'ƒ© '# Push the dictionary string "right" to the stack q # Stop the program (and output the top of the stack implicitly) # Everything else after it is ignored ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `'…¸` is `"left"` and `'ƒ©` is `"right"`. [Answer] # [Stax](https://github.com/tomtheisen/stax), 131 bytes ``` .Cq"tfel" ""`KT?`qC". lC `C eq Kq f` T" t? ?t "T `f qK qe C` Cl ."Cq`?TK`"" "left"qC. ``` [Run and debug it](https://staxlang.xyz/#c=+.Cq%22tfel%22+%0A%22%22%60KT%3F%60qC%22.%0AlC+++++++%60C%0Aeq+++++++Kq%0Af%60+++++++T%22%0At%3F+++++++%3Ft%0A%22T+++++++%60f%0AqK+++++++qe%0AC%60+++++++Cl%0A.%22Cq%60%3FTK%60%22%22%0A+%22left%22qC.+&i=&a=1) This is the "right" variant. [Answer] ## Batch, ~~438~~ 321 bytes ``` :::::::::::::@@@: @echo left&: eee: @exit/b&: cxc: @echo right&:hih: : : oto: :: & / : :& t rbl: :t h i&e: :f:g g:f: :e&i h t: :lbr t &: : / & :: :oto : : :hih:&thgir ohce@ :cxc :&b/tixe@ :eee :&tfel ohce@ :@@@::::::::::::: ``` Explanation: A `:` is used to indicate a label, which is as good as a comment, so as the program has rotational symmetry the only difference between the two versions is which of the `@` lines is first, in which case either `left` or `right` is output before the script exits. I did try creatively overlapping the rotated lines with each other but my attempt actually ended up with a larger grid. Edit: Saved 117 bytes thanks to @ØrjanJohansen. [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 116 bytes ``` > \ !U\L ...@.. \.R""" @""trl "lrhie teiggf ffgiht ethrt" l"t""@ " "R.\ .\@.@. DR\!!/R !! ``` [Try it online!](https://tio.run/##Fcw9CsUwDAPgPaewdQC/G5QMHTsFunkr@YPQIbjnz3M0fQih@b39WesgJb71CiQiUYQCqSQAjgjYHA6M2Xp2WO61FkcptTdzZGvT9njAgLjHhCTqEI3@SOFMyvxL3uww01p/ "Runic Enchantments – Try It Online") [And reversed](https://tio.run/##Jcw7CkMxDETR3quQZgHKDoKKlK8ypFMX/AOTwuit35HJVKe4zLq/47P3ZW8mo2ciIRURSgQgiwXmckADZfQ1EaitjeIB76PVemJf3UtAAccMmGTQiUVF7RzmB7PlVyJm@m/vHw "Runic Enchantments – Try It Online") Not exactly a port, but utilized [Post Left Garf Hunter's Klein 000 answer](https://codegolf.stackexchange.com/a/172011/47990) as a starting point, given the typical near-compatibility of the two languages (most commands are the same and the edge wrapping in Runic is identical to Klein 000). The only issue was that Klein IPs always start from the top left and Runic's do not. As such the `.` are all part of the original code and still treated as NOP by Runic, while the are NOPs I had to add as part of controlling the flow. Prints `"left"` in all 4 rotations and `"right"` when mirrored (and in all four rotations thereof). Two middle columns were completely unused after my modifications, so I was able to remove them. In theory a rotation with lots of trailing whitespace could be used for a lower byte count (eg. [this variant](https://tio.run/##PYu5DYAwDAB7TxF7ALMBckFJZYnOHconRRRRmN@kiLj27vr71Nv9BGNqMQ0SY0W4mHrNZRDLhoBCo@TaSRkhsC4nOK@1BbNpbIYpNmKFPfwc7h8 "Runic Enchantments – Try It Online")), however the spaces are needed to correctly rotate the structure using external tools and so I included them. Below variants contain the unused chunks that were removed, but are otherwise identical: [All four lefts](https://tio.run/##TZE9jsQgDIV7n8J2P84NRhSTVFQodO5W@UGKtkDs@bOGRUuoDMbPz5/zz3f6um@PjwMqfG17YacSCKJwTsdZWNxEQI7LeaTMQQjBizhel9mz2o2U/bys7EQiAkrohY6qZhdF1ZpT09m3iyUgvEfvD8Lr9bIXRfIU1dtXERWTtCrzw8LMFjpm70q@LOQrz3ymzcKypWU9jt3CfT/WJZ3Fwq2cPOdSyy4uzjO7WoamFaS7aT0QPkEpEk3mqjsi@rNk1v7PGzAMRtWYYh9HFPDByHLxwchyg5HNRg9GQJOTXigRKAxGCs/9@D8/ZqzvC8NE5lrDx0Zpk@ighYMWN1ql0iqN1llp7Y3WUWltjVaqtK5GKw9aPGhh7VEX4jXalmxX7/v@BQ "Runic Enchantments – Try It Online"). Outputs `leftleftleftleft` (the fact that all four can be run like this is coincidence). [Right 1](https://tio.run/##Jc0rDgMxDARQnlPYPoB7g8qguygo2mVmVX5SVBC5508dddAjMzO/n/5eK@qNEUHhGYBBWJkZAhARU2J1jmkSicSZe6NjDnKWWq@zZ3Na6@dVS9k1mwc1y04himI0nMrJ12DXeD@I7ov0QLxR0ysAIvyz1g8 "Runic Enchantments – Try It Online"), [Right 2](https://tio.run/##TY07CsMwEET7PcVqDjC5QdgidqVK2N12wR@BSSGU8ysyGJzphse8Kd9Pfremf4kSEt1Q1@UAXcLDiLpvuYCzaGBCydteYaE3RxzGCUZG0Zk0TOMQ4Seza5aoou56KbtTE3Esa3f4yV73@7O1Hw "Runic Enchantments – Try It Online"), [Right 3](https://tio.run/##Jc07DsMwDAPQPaeQeAD1BoWGJpMnI9m0Ff4BQQfDPb@rpJzeQrJ/P@09J/3DTMsrGh/Mj0gLiamYqDhBEEQx54mhAVBnGhVrH3DmXPat1eEcqW17KfmqnX1FbcmpQNDRT6dJ9DVcNZH7wS@eZMSBDwtz/gA "Runic Enchantments – Try It Online"), [Right 4](https://tio.run/##TYw7CsMwEET7PcVqDjC5QdgidqVK2N12wR@BSSGU8ysyDiGvGx7zyvuVn63d9cdDRemGui4HmFScxLGsFep@uoSSt73CgkpwxGGcYOSsEknDNA4Rfrre2LdckNjXzO@Ndgu9eSXNmYJE/aO1Dw "Runic Enchantments – Try It Online") [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 342 bytes ``` 8A_ _A8 9 "" 9 A LR A _ EI _ FG TH "T " "TFEL" HH"RIGHT" "THGIR"HH "LEFT" " T" HT GF _ IE _ A RL A 9 "" 9 8A_ _A8 ``` Wow! That took longer than I expected, halfway through I realized the reflection was *vertically*, not horizontally like I had been coding for! I'm pretty sure that this works, but if I made a mistake please let me know. This can most likely be golfed a ridiculous amount more, I just took an extreme brute force method to do so. The shape itself is actually a square, it is technically symmetric, except on across the x-axis, so when it flips, it returns "RIGHT" instead!!! The character that made this program possible is the 'A', which allows for teleportation to the beginning of a certain line! [Try it online!](https://tio.run/##bZA7CsQwDER7n0LMKZLShW0ZXBn36fKBQIrcHweCpV1Wq2r0YCRmtutcj3vvnSa/kM7iJ3LzWIAhZueHKnUI78QVsnidXIlJlKLGBqEZRPggtBgKiBk1J254EadcwUwoIb7o1/f1EQax/ZiiIgmUgwaS2LVo7D/l2Aqp9wc "Gol><> – Try It Online") ]
[Question] [ Your task is to make a program that measures how fast you can type the letters of the English alphabet. * The program shall only accept lowercase letters `a` to `z` in alphabetical order. * Each letter is echoed as typed on the same line (without new line or any other separators between letters). * If you type an invalid character the program shall output `Fail` *on a new line* and exit. * If you type all 26 letters the program shall, *on a new line*, output the time in milliseconds it took from the first to the last letter and exit. * The timer starts when you type the first letter, `a`. Example outputs: ``` b Fail abcdefgg Fail abcdefghijklmnopqrstuvwxyz 6440 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] ## HTML (JavaScript (ES6)), ~~129~~ ~~126~~ 117 bytes ``` <input id=i onfocus=l=0,n=Date.now onkeypress=event.which-97-l?i.outerHTML='Fail':24<l?i.outerHTML=n()-t:t=l++?t:n()> ``` Click in the input and start typing! Also, my typing sucks; I take about 5 seconds even with practice. Edit: Saved 2 bytes thanks to @HermanLauenstein by switching language. Saved 3 bytes thanks to @qw3n. Saved 9 bytes thanks to @tsh. [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64 PAL), 189 165 bytes ``` 00 C0 A9 17 8D 18 D0 A9 40 85 FE E6 FE 20 E4 FF F0 FB 20 D2 FF C5 FE 38 D0 38 C9 5A 18 F0 33 C9 41 D0 E8 A9 00 85 FC 85 FD A9 18 85 FB A9 7F 8D 0D DD A9 7F 8D 18 03 A9 C0 8D 19 03 A9 D8 8D 04 DD A9 03 8D 05 DD A9 01 8D 0E DD A9 81 8D 0D DD D0 B9 A9 7F 8D 0D DD A9 47 8D 18 03 A9 FE AD 19 03 CE 0E DD B0 14 A9 0D 20 D2 FF A4 FC A5 FD 20 91 B3 20 DD BD A9 01 A8 D0 04 A9 9D A0 C0 4C 1E AB 48 AD 0D DD 29 01 F0 14 E6 FC D0 02 E6 FD C6 FB D0 0A A9 18 85 FB CE 0E DD EE 0E DD 68 40 0D C6 41 49 4C 00 ``` * -24 bytes by inlining functions and not caring for other CIA2 interrupts **[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22fasttype.prg%22:%22data:;base64,AMCpF40Y0KlAhf7m/iDk//D7INL/xf440DjJWhjwM8lB0OipAIX8hf2pGIX7qX+NDd2pf40YA6nAjRkDqdmNBN2pA40F3akBjQ7dqYGNDd3Qual/jQ3dqUeNGAOp/q0ZA84O3bAUqQ0g0v+k/KX9IJGzIN29qQGo0ASpnaDATB6rSK0N3SkB8BTm/NAC5v3G+9AKqRiF+84O3e4O3WhADcZBSUwA%22%7D,%22vice%22:%7B%22-autostart%22:%22fasttype.prg%22%7D%7D)** (Usage: `sys49152`) [![Screenshot](https://i.stack.imgur.com/O1aly.png)](https://i.stack.imgur.com/O1aly.png) --- ### Explanation: This would be a tiny program if it wasn't for the problem of an exact measurement of milliseconds on the C64. The system interrupt occurs *roughly* 60 times per second, which isn't even close. So we have to use a hardware timer here that gets its input ticks from the system clock. On a PAL machine, the system clock is exactly 985248 Hz. Initializing the timer to 985 therefore gives something *close* to millisecond ticks, but it's a bit too fast, we'd have to count 986 cycles for every fourth tick, or hold the timer for a single cycle. This isn't possible, but we can hold the timer for 6 cycles with the sequence `DEC $DD0E`, `INC $DD0E`: `$DD0E` is the timer control register with bit 0 switching it on and off, and both instructions take 6 cycles, so the exact writes that stop and start the timer are exactly 6 cycles apart. Therefore we have to execute this sequence every 6\*4 = 24th tick. This still isn't *absolutely* exact, the timer will lag 1 millisecond behind after 8 minutes and 12 seconds, but it's probably good enough -- compensating for that one would take a *lot* of code. **edit**: The start value for the timer must be 984, not 985, because these timers fire "on underflow", so a value of 0 will count one more cycle before firing. Code fixed, byte count unchanged. Here's the commented disassembly listing: ``` 00 C0 .WORD $C000 ; load address .C:c000 A9 17 LDA #$17 ; mode for upper/lower text .C:c002 8D 18 D0 STA $D018 ; set in graphics chip .C:c005 A9 40 LDA #$40 ; initialize expected character .C:c007 85 FE STA $FE ; to 'a' - 1 .C:c009 .mainloop: .C:c009 E6 FE INC $FE ; increment expected character .C:c00b .getchar: .C:c00b 20 E4 FF JSR $FFE4 ; read character from keyboard .C:c00e F0 FB BEQ .getchar ; until actual character entered .C:c010 20 D2 FF JSR $FFD2 ; output this character .C:c013 C5 FE CMP $FE ; compare with expected .C:c015 38 SEC ; set carry as marker for error .C:c016 D0 38 BNE .result ; wrong character -> output result .C:c018 C9 5A CMP #$5A ; compare with 'z' .C:c01a 18 CLC ; clear carry (no error) .C:c01b F0 33 BEQ .result ; if 'z' entered, output result .C:c01d C9 41 CMP #$41 ; compare with 'a' .C:c01f D0 E8 BNE .mainloop ; if not equal repeat main loop .C:c021 A9 00 LDA #$00 ; initialize timer ticks to 0 .C:c023 85 FC STA $FC .C:c025 85 FD STA $FD .C:c027 A9 18 LDA #$18 ; counter for adjusting the timer .C:c029 85 FB STA $FB .C:c02b A9 7F LDA #$7F ; disable all CIA2 interrupts .C:c02d 8D 0D DD STA $DD0D .C:c030 A9 7F LDA #<.timertick ; set NMI interrupt vector ... .C:c032 8D 18 03 STA $0318 .C:c035 A9 C0 LDA #>.timertick .C:c037 8D 19 03 STA $0319 ; ... to our own timer tick routine .C:c03a A9 D9 LDA #$D8 ; load timer with ... .C:c03c 8D 04 DD STA $DD04 .C:c03f A9 03 LDA #$03 .C:c041 8D 05 DD STA $DD05 ; ... 985 (-1) ticks (see description) .C:c044 A9 01 LDA #$01 ; enable timer .C:c046 8D 0E DD STA $DD0E .C:c049 A9 81 LDA #$81 ; enable timer interrupt .C:c04b 8D 0D DD STA $DD0D .C:c04e D0 B9 BNE .mainloop ; repeat main loop .C:c050 .result: .C:c050 A9 7F LDA #$7F ; disable all CIA2 interrupts .C:c052 8D 0D DD STA $DD0D .C:c055 A9 47 LDA #$47 ; set NMI interrupt vector ... .C:c057 8D 18 03 STA $0318 .C:c05a A9 FE LDA #$FE .C:c05c AD 19 03 LDA $0319 ; ... back to system default .C:c05f CE 0E DD DEC $DD0E ; disable timer .C:c062 B0 14 BCS .fail ; if carry set, output fail .C:c064 A9 0D LDA #$0D ; load newline .C:c066 20 D2 FF JSR $FFD2 ; and output .C:c069 A4 FC LDY $FC ; load timer value in .C:c06b A5 FD LDA $FD ; A and Y .C:c06d 20 91 B3 JSR $B391 ; convert to float .C:c070 20 DD BD JSR $BDDD ; convert float to string .C:c073 A9 01 LDA #$01 ; load address of .C:c075 A8 TAY ; string buffer .C:c076 D0 04 BNE .out ; and to output .C:c078 .fail: .C:c078 A9 9D LDA #<.failstr ; load address of "Fail" string .C:c07a A0 C0 LDY #>.failstr ; in A and Y .C:c07c .out: .C:c07c 4C 1E AB JMP $AB1E ; done; OS routine for string output .C:c07f .timertick: .C:c07f 48 PHA ; save accu .C:c080 AD 0D DD LDA $DD0D ; load interrupt control register .C:c083 29 01 AND #$01 ; to know whether it was a timer NMI .C:c085 F0 14 BEQ .tickdone ; if not -> done .C:c087 E6 FC INC $FC ; increment timer ticks ... .C:c089 D0 02 BNE .adjusttick .C:c08b E6 FD INC $FD ; high byte only on overflow .C:c08d .adjusttick: .C:c08d C6 FB DEC $FB ; decrement counter for adjusting .C:c08f D0 0A BNE .tickdone ; not 0 yet -> nothing to do .C:c091 A9 18 LDA #$18 ; restore counter for adjusting .C:c093 85 FB STA $FB .C:c095 CE 0E DD DEC $DD0E ; halt timer for exactly .C:c098 EE 0E DD INC $DD0E ; 6 cycles .C:c09b .tickdone: .C:c09b 68 PLA ; restore accu .C:c09c 40 RTI .C:c09d .failstr: .C:c09d 0D C6 41 .BYTE $0D,"Fa" .C:c0a0 49 4C 00 .BYTE "il",$00 ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, ~~103~~ ~~99~~ 98 bytes ``` for((;c==p%26;r=`date +%s%3N`-(s=s?s:r),c=62#$c-9,p++)) { read -N1 c } ((c==p))||r=Fail echo " $r" ``` Must be run in a terminal. ### Test run ``` $ bash type.sh abcdefghijklmnopqrstuvwxyz 3479 $ bash type.sh abcz Fail $ bash type.sh 2>&- # typing '@' would print to STDERR ab@ Fail $ bash type.sh A Fail ``` [Answer] # Python 2 + [getch](https://pypi.python.org/pypi/getch), 116 bytes ``` import time,getch t=[i+97-ord(getch.getche())and exit("Fail")or time.time()for i in range(26)] print(t[-1]-t[0])*1e3 ``` Thanks to ovs and ElPedro for fixing the code and saving 57 bytes. [Answer] # [Pascal (FPC)](https://www.freepascal.org/), 176 bytes ``` Uses CRT,SysUtils;Var c:char;a:Real;Begin for c:='a'to'z'do if c=ReadKey then begin Write(c);if c='a'then a:=Now;end else begin Write('Fail');Halt;end;Write((Now-a)*864e5) End. ``` [Try it online!](https://tio.run/##Jcu9DoIwGIXhvVfRrWLESY2hYdFoTEwcVHT@bL9KtbZI6w/cPIKs73lOAV6AiVUhmibz6OlyfxwdKp8FbTw/QUlFInIoOSR7BMMXeNWWKNf1lAELjtVMOqIVFWkr5BYrGnK05NJJei51wIGI@B90h3ajkKQ79@FoJUHjsbekt2wN2rCIb8CETvA@D9pDDNFwPpvgNCIrK8dNAxchUV1zfbubh3XFs/Th9f58q/oH "Pascal (FPC) – Try It Online") Some tricks used in code for golfing: * Use `Real` as a shorter alternative to `TDateTime`, because as defined [here](https://www.freepascal.org/docs-html/rtl/system/tdatetime.html), `TDateTime` = `Double`, which is floating-point type. * Instead of using `MilliSecondsBetween` for calculating time gap, this code multiply the difference between two floating-point values by `864e5`, which works because of the way Free Pascal encode `TDateTime` described [here](https://www.freepascal.org/~michael/articles/datetime/datetime.pdf). Note: * `ReadKey` function doesn't actually print the key on the console, so manual writing to console with `Write(c)` is necessary. * TIO get a score near `0` for typing the alphabet for obvious reason. * The program prints time in floating-point notation, I guess that's allowed. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 35 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` "ζ¦F‘→I ]I!}Su[I:lzm≠?■Fail←z=?Suκ← ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIyJXUwM0I2JUE2RiV1MjAxOCV1MjE5MkklMEElNURJJTIxJTdEU3UlNUJJJTNBbHptJXUyMjYwJTNGJXUyNUEwRmFpbCV1MjE5MHolM0QlM0ZTdSV1MDNCQSV1MjE5MA__) - click run, and enter the alphabet in the input box. Note that it may be a little laggy because SOGL only pauses for input every 100 executed tokens (and SOGL is quite slow). If that bothers you, run `sleepBI=true` in the console. **note:** don't run this in the compatibility mode - it'll just loop forever. Explanation: ``` "ζ¦F‘ push "inputs.value" (yes, that is a word in SOGLs english dictionary) → execute as JS, pushing the inputs contents I named function I ] } do while POP is truthy I execute I ! negate it - check if it's empty Su push the current milliseconds since start [ loop I execute I : duplicate the result l let its length zm mold the alphabet to that size ≠? if that isn't equal to one of the result copies ■Fail push "Fail" ← and exit, implicitly outputting that z=? if the other copy is equal to the alphabet Su push the milliseconds since start κ subtract the starting milliseconds from that ← and exit, implicitly outputting the result ``` [Answer] # Java, ~~404~~ ~~388~~ ~~354~~ ~~348~~ ~~320~~ 318 bytes ``` import java.awt.*;import java.awt.event.*;interface M{static void main(String[]a){new Frame(){{add(new TextArea(){{addKeyListener(new KeyAdapter(){long t,i=64;public void keyPressed(KeyEvent e){t=t>0?t:e.getWhen();if(e.getKeyChar()!=++i|i>89){System.out.print(i>89?e.getWhen()-t:"Fail");dispose();}}});}});show();}};}} ``` And here I thought Java Console was already verbose.. Since Java has no way to raw listen for key-presses in the Console a.f.a.i.k., I use a GUI with `java.awt`. -78 bytes thanks to *@OlivierGrégoire*. **Explanation:** ``` import java.awt.*; // Required import for Frame and TextField import java.awt.event.*; // Required import for KeyAdapter and KeyEvent interface M{ // Class static void main(String[]a){ // Mandatory main-method new Frame(){ // Create the GUI-Frame { // With an initialization-block add(new TextArea(){ // Add an input-field { // With it's own initialization-block addKeyListener(new KeyAdapter(){ // Add a KeyAdapter to the input-field long t, // Long to save the time i=64; // Previous character, starting at code of 'a' -1 public void keyPressed(KeyEvent e){ // Override the keyPressed-method: t=t>0? // If `t` is already set: t // Leave it the same : // Else: e.getWhen(); // Save the current time (== start the timer) if(e.getKeyCode()!=++i // As soon as an incorrect character is pressed, |i>89){ // or we've reached 'z': System.out.print(i>89? // If we're at 'z': e.getWhen()-t // Print the end-time in ms to the Console : // Else (an incorrect character was pressed) "Fail"); // Print "Fail" to the Console dispose();} // And exit the application } // End of keyPressed-method }); // End of KeyAdapter } // End of input-field initialization-block }); // End of input-field show(); // Initially show the Frame } // End of Frame initialization-block }; // End of Frame } // End of main-method } // End of class ``` **Example gif of success:** (Yes, I type the alphabet pretty slowly here..) *Note: This is an old gif. Current version no longer prints key-presses to Console. And it no longer prints the time with digits after the decimal point.* [![enter image description here](https://i.stack.imgur.com/qYPs4.gif)](https://i.stack.imgur.com/qYPs4.gif) **Example gif of fail:** *Note: This is an old gif. Current version no longer prints key-presses to Console.* [![enter image description here](https://i.stack.imgur.com/pgIAE.gif)](https://i.stack.imgur.com/pgIAE.gif) [Answer] # C# (.NET Core), ~~245 + 13~~ ~~183 + 41~~ 177 + 41 bytes +41 bytes for `using System;using static System.Console`. Untested since I am on mobile and this does not run on TIO. ``` n=>{int c=ReadKey().KeyChar,x=0;try{if(c!=97)x/=x;var s=DateTime.Now;while(c<149)if(ReadKey().KeyChar!=c++)x/=x;Write((DateTime.Now-s).TotalMilliseconds);}catch{Write("Fail");}} ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 184+13=197 173+13=186 bytes ``` ()=>{var s=DateTime.Now;var i=97;while(i<123&&Console.ReadKey().KeyChar==i)if(i++<98)s=DateTime.Now;Console.Write(i>122?$"\n{(DateTime.Now-s).TotalMilliseconds}":"\nFail");} ``` [Try it online!](https://tio.run/##XY5BS8NAFITP3V/xCFJ2KQ00HrRutxIqXqRSasGLl2XztA@2uyVvbSghvz0mB0G8zMDwzTCO5y7W2H8zhS94u3LCkxbOW2bYtaJ0iWKAEkwvlVm3F1sDmyeb8EAnzF9jo8eIzPJON0fyKGm1KG6n000MHD3me7TVC16lygfdHG1tDCn6lDSbrZb36t/Wb@u9pjRMrRdF8XiTfYRW/sXmrPJDTNZvyXtidDFU3GUPA/hsyWdKd70WgpNN5OASqYKtpSCVaMVkvHsGAwEb2EmlxeScl6N3out/AA "C# (.NET Core) – Try It Online") Unfortunately TIO can't run this, but it's handy for getting byte count. +13 for `using System;` -1 by changing `i==123` to `i>122`. I was tempted to make this `i>'z'`. ### Acknowledgements -10 bytes thanks to @raznagul ### Ungolfed ``` ()=>{ var s=DateTime.Now; var i=97; while(i<123&&Console.ReadKey().KeyChar==i) if(i++<98) s=DateTime.Now; Console.Write(i>122? $"\n{(DateTime.Now-s).TotalMilliseconds}": "\nFail" ); } ``` [Answer] # Node.js, 240 213 bytes ``` require('readline',{stdin:i,stdout:o,exit:e}=process).emitKeypressEvents(i) w=s=>o.write(s) n=0 i.on('keypress',c=>w(c)&&c.charCodeAt()-97-n?e(w(` Fail`)):!n++?s=d():n>25&&e(w(` `+(d()-s)))).setRawMode(d=Date.now) ``` EDIT: Saved 27 bytes thanks to Jordan Ungolfed version: ``` const readline = require('readline') let index = 0 let start readline.emitKeypressEvents(process.stdin) process.stdin.setRawMode(true) process.stdin.on('keypress', character => { process.stdout.write(character ) // Lookup character in ASCII table if (character !== String.fromCharCode(97 + index) { process.stdout.write('\nFail') process.exit() } index++ if (index === 1) { start = Date.now() } if (index === 26) { process.stdout.write('\n' + (Date.now() - start)) process.exit() } }) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 303 bytes Works on \*nix systems. Standalone code removing the current terminal's canonical mode to allow reading characters without waiting for newlines: /!\ Running this program will make the terminal almost unusable. ``` #import <stdlib.h> #import <termios.h> #define x gettimeofday(&t,0) #define r t.tv_sec*1000+t.tv_usec/1000 c,i=97;main(){long s=0;struct termios n;struct timeval t;cfmakeraw(&n);n.c_lflag|=ECHO;tcsetattr(0,0,&n);for(;i<'d';){c=getchar();if(c!=i++)puts("\nFail"),exit(0);x;s=s?:r;}x;printf("\n%ld",r-s);} ``` **Ungolfed and commented:** ``` // needed in order to make gcc aware of struct termios // and struct timeval sizes #import <stdlib.h> #import <termios.h> // gets the time in a timeval structure, containing // the number of seconds since the epoch, and the number // of µsecs elapsed in that second // (shorter than clock_gettime) #define x gettimeofday(&t,0) // convert a timeval structure to Epoch-millis #define r t.tv_sec*1000+t.tv_usec/1000 // both integers // c will contain the chars read on stdin // 97 is 'a' in ASCII c,i=97; main(){ long s=0; // will contain the timestamp of the 1st char entered struct timeval t; // will contain the timestamp read from gettimeofday // setting up the terminal struct termios n; cfmakeraw(&n);//create a raw terminal configuration n.c_lflag|=ECHO;//makes the terminal echo each character typed tcsetattr(0,0,&n);//applies the new settings // from 'a' to 'z'... for(;i<'{';){ // read 1 char on stdin c=getchar(); // if int value of the input char != expected one => fail&exit if(c!=i++)puts("\nFail"),exit(0); // macro x: get current timestamp x; // if not already set: set starting timestamp s=s?:r; } // get end of sequence timestamp x; // prints the end-start timestamps difference printf("\n%ld",r-s); } ``` **Alternative solution (218 bytes):** If configuring the terminal beforehand is allowed, then we can get rid of the portion of code handling that part. Here is the same code without terminal manipulation: ``` #import <stdlib.h> #define x gettimeofday(&t,0) #define r t.tv_sec*1000+t.tv_usec/1000 c,i=97;main(){long s=0;struct timeval t;for(;i<'{';){c=getchar();if(c!=i++)puts("\nFail"),exit(0);x;s=s?:r;}x;printf("\n%ld",r-s);} ``` To make it work: ``` $ gcc golf.c $ stty -icanon $ a.out ``` **runtime example:** [![enter image description here](https://i.stack.imgur.com/zs80w.gif)](https://i.stack.imgur.com/zs80w.gif) [Answer] # Commodore BASIC v2 - 113 bytes Capital letters must be shifted. Thanks to Felix Palmen for pointing out some typos, specs [try it](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22type.prg%22:%22data:;base64,AQgRCAAARLI2NDqZxygxNCkALQgBAJGrKEayMjYpiTU6oUEkOotBJLIiIqcxAEAIAgCLqCirtChGKSmnVLJUSQBYCAMARrJGqjE6i0Eks7HHKESqRimnNgBkCAQAmUEkOzqJMQB8CAUAmTqZKFRJq1QprTYwrDEwMDA6gACICAYAmSLGQUlMIgAAAA==%22%7D,%22vice%22:%7B%22-autostart%22:%22type.prg%22%7D%7D) ``` 0d=64 1on-(f=26)gO5:gEa$:ifa$=""tH1 2iff=0tHt=ti 3f=f+1:ifa$<>cH(d+f)tH6 4?cH(14)a$;:gO1 5?:?(ti-t)/60*1000:eN 6?"Fail" ``` [Answer] # Mathematica (notebook expression), 248 bytes ``` DynamicModule[{x={},s=0,t=0},EventHandler[Framed@Dynamic[If[x=={"a"}&&s<1,s=SessionTime[]];Which[x==a,If[t==0,t=SessionTime[]-s];1000t,x==a~Take~Length@x,""<>x,1>0,"Fail"]],Table[{"KeyDown",c}:>x~AppendTo~CurrentValue@"EventKey",{c,a=Alphabet[]}]]] ``` # How it works ``` DynamicModule[{x={},s=0,t=0}, EventHandler[ Framed@Dynamic[ If[x=={"a"} && s<1,s=SessionTime[]]; Which[ x==a,If[t==0,t=SessionTime[]-s];1000t, x==a~Take~Length@x,""<>x, 1>0,"Fail"]], Table[{"KeyDown",c}:>x~AppendTo~CurrentValue@"EventKey", {c,a=Alphabet[]}]]] ``` A `DynamicModule` with an `EventHandler` that responds to lowercase letter keypresses. The variables `x`, `s`, and `t` hold the letters pressed so far, the start time, and the end time, respectively. As soon as we notice `x` being equal to `{"a"}`, we start the time; we display either the total time spent, or the string built so far, or `"Fail"` depending on which condition is met. We could save another byte with `t<1` rather than `t==0` if we can assume that nobody is fast enough to type the alphabet in less than one second :) If you're trying this out in a Mathematica notebook, keep in mind that you have to click inside the frame before your keypresses will be registered. (This is the reason that we need the frame to begin with; if `Framed` is not there, then the entire object selected changes when a key is pressed, so it stops being selected and you'd have to click again.) [Answer] # MSX-BASIC, 126 characters ``` 1C=97:GOSUB3:TIME=0 2IFASC(C$)<>CTHEN?"Fail":ENDELSEIFC=122THEN?TIME*20:ENDELSEC=C+1:GOSUB3:GOTO2 3C$=INKEY$:IFC$=""GOTO3 4RETURN ``` `TIME` is an internal MSX-BASIC variable that increases by one every 20 milliseconds. [Answer] # Perl 5, ~~79~~ 93 +31 (-MTerm::ReadKey -MTime::HiRes=time) bytes ``` $|=1;map{ReadKey eq$_||exit print" Fail";$s||=time}a..z;print$/,0|1e3*(time-$s) ``` `$|=1` is not sufficient to set terminal in raw mode, `stty -icanon` should be run before or ``` ReadMode 3;map{ReadKey eq$_||exit print" Fail";print;$s||=time}a..z;print$/,0|1e3*(time-$s) ``` to see characters in the terminal after running command : `stty echo` or `stty echo icanon` [Answer] # [APL (Dyalog)](https://www.dyalog.com), [SBCS](https://github.com/abrudz/SBCS), 114 153 bytes Using a GUI form to handle keypress events: ``` t←⍬ a←819⌶⎕A f←{⍬≡t:f ⍵⊣t⊢←⎕AI⋄⊃a≠⍞←3⊃⍵:⎕EX⎕A⊣⎕←'Fail'⋄'z'=a~←⊃a:⎕←3⊃⎕AI-t} ⎕DQ⎕A⎕WC'Form'('Event' 'KeyPress' 'f') ``` (Golfed by [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m); I think it would be odd for him to be awarding a bounty for an answer which is now mostly his golf rewrite, so that's here, and my original is below. This version handles the "exit on failure" part of the spec, too.] ``` t←⍬ a←(819⌶)⎕A ∇w 'W'⎕WC'Form'('Event' 'KeyPress' 'f') ⎕DQ'W' ∇ ∇f e {26=≢a:t⊢←⎕TS}⍬ {e[3]=1↑a:{⍞←1↑a⋄a⊢←1↓a}⍬⋄⎕←'Fail'}⍬ {0=≢a:⎕←60 60 1e3⊥4↓⎕TS-t}⍬ ∇ w ``` Image of it (the first posted version) in use, Dyalog APL 17.1: [![Animated screen capture of this code working in Dyalog APL 17.1](https://i.stack.imgur.com/cTSRl.gif)](https://i.stack.imgur.com/cTSRl.gif) --- ### Explanation. It's a function `w` which loads a GUI form and adds an event handler to it, and starts listening for events, and the call back which handles the alphabet. Lambda functions are used to get guard pattern matching, instead of longer `:If ⋄ cond ⋄ code ⋄ :Else ⋄ code ⋄ :EndIF` syntax. Guards are `{cond: code}` pattern, and the `{}⍬` pattern is calling a function on an empty numeric vector just to make it run ``` t←⍬ ⍝ Variable for the time of starting typing a←(819⌶)⎕A ⍝ Variable for lowercase alphabet, cast from uppercase with I-beam 819 ⍝ Function "w" makes window of type 'Form', called 'W', with event handler. ⍝ Callback function "f", and starts event loop. ∇w 'W'⎕WC'Form'('Event' 'KeyPress' 'f') ⎕DQ'W' ∇ ⍝ event handler function "f" takes event "e" ∇f e {26=≢a:t⊢←⎕TS}⍬ ⍝ lambda function (dfn) ⍝ checks if there are 26 letters, ⍝ (i.e. started typing) starts the timer. ⍝ "t" is initialised first, for global scoping. {e[3]=1↑a:{⍞←1↑a⋄a⊢←1↓a}⍬⋄⎕←'Fail'}⍬ ⍝ guard, if event[3] (key pressed) ⍝ is the next alphabet letter (first of "a") ⍝ print 1 from "a", drop 1 from "a" ⍝ else print "Fail". {0=≢a:⎕←60 60 1e3⊥4↓⎕TS-t}⍬ ⍝ guard, if all the letters are gone, ⍝ subtract current timestamp from stored, ⍝ drop 4 elements (year, month, day, hour) ⍝ base-convert min, sec, ms to pure ms ⍝ and print. ∇ ⍝ run it by calling function "w" w ``` [Answer] # C#, 154 152 + 13 = 165 bytes Saved 2 bytes thanks to Ayb4btu's comments ``` x=>{ long t=0,c=97; for(;Console.ReadKey().KeyChar==c++&&c<123;t=t<1?DateTime.Now.Ticks:t); Console.Write(c>122?"\n"+(DateTime.Now.Ticks-t)/1e4:"\nFail"); } ``` The code above has whitespace to make it fit in SE without a scrollbar. Whitespace isn't part of the byte count and 13 bytes for `using System;` It's similar to Ayb4btu's version but with the following differences: * Storing datetime as a long, allows us to make `c` a long also, and short cut the declaration * Loop doesn't need a separate break * It's not actually shorter to use `$"interpreted strings"` versus adding a needed "\n" onto the milliseconds to make it a string for the inline if * Using a `for` loop sometimes allows us to save chars over a while, though I think this one wouldn't save over the equivalent `while` From Ayb4btu: * `s=s==0` can become `s=s<1`, and `c==123` can become `c>122` ### Ungolfed ``` long t=0,c=97; for (; //no loop vars declared Console.ReadKey().KeyChar == c++ && c < 123; //loop test t = t < 1 ? DateTime.Now.Ticks : t //post-loop assigns ) ; //empty loop body! //now just need to turn ticks into millis, 10,000 ticks per millis Console.Write(c>122?"\n"+(DateTime.Now.Ticks-t)/1e4:"\nFail"); ``` [Answer] # [Aceto](https://github.com/aceto/aceto), 70 bytes ``` d'|d 't9 $z=p zp1 != >#v d, 1 + cTpaXpn3 Io$'p"*F |'!=ilnu @ad,aF" ``` I start by setting a catch mark and mirroring horizontally(`@|`), if the value on the stack is truthy. It isn't initially, and later always will be. We will jump back here later if a wrong key is entered. Next, we push an a on the stack (`'a`), then we duplicate it and read a single character from the user (`d,`). If the two characters are not equal (`=!`), we "crash" (`$`) and jump back to the catch mark. Otherwise, we push another "a" and print it, then we set the current time (`'apT`). Then we enter our "main loop": We "increment" the current character and "increment" the character (`'apToIc`), then we duplicate it, read a new character, compare it, and "crash" if it the characters aren't identical (`d,=!$`). If we didn't crash, we compare the current character to "z" (`d'z=|`), if it isn't equal, we print the character, then we push a 1 and jump "conditionally" (in this case: always) to the only `o` in the code (the begin of our main loop). If it was equal to z, we mirrored horizontally to some empty space on top. We print "z", then push the current time (minus the starting time; `t`) and then multiply the number 1000 (gotten by raising 10 to the third power; `91+3F`) by it (because we get seconds, not milliseconds). Then we print a newline, the time, and exit (`pX`). If we ever crash (bad input by the user), we jump all the way to the beginning. Since we will now have some truthy value on the stack, we will mirror horizontally onto the `u`, which reverses the direction we're moving in. `n` prints a newline character, then we push `"Fail"` on the stack, print it, and exit (`pX`). [Answer] # Processing.org ~~133~~ 142 first code didn't exit ``` char k=97;int m;void draw(){if(key==k){m=m<1?millis():m;print(key=k++,k>122?"\n"+(millis()-m):"");}if(m>0&&key!=k-1){print("\nFail");exit();}} ``` [Answer] # GCC, windows, 98 bytes ``` t;main(i){for(;i++<27;t=t?:clock())if(95+i-getche())return puts("\nFail");printf("\n%d",clock()-t);} ``` Requires no instantly input for the first key [Answer] **Ruby: 194 bytes** ``` require 'io/console' a=[*"a".."z"] c=0 s= loop do i=STDIN.getch if i==a[c] print i s=Time.now if i=='a' else puts "\nFail" exit end if i=='z' puts "\n"+((Time.now-s)*1000).to_s exit end c+=1 end ``` [Answer] # Python 3, 107 bytes ``` from time import*;x=time();a=input();print((time()-x)*1000 if a=="abcdefghijklmnopqrstuvwxyz" else "Fail"); ``` Outputs a floating point number. Relies on lowercase alphabet. [Answer] # Java (Android), 709 bytes > > And here I thought Java Console was already verbose. > > > *Imagine complaining about AWT* :omegalul: ``` package a;import android.widget.*;import android.text.*;public class Z extends android.app.Activity{long g;long f(){return System.currentTimeMillis();}public void onCreate(android.os.Bundle b){super.onCreate(b);EditText t=new EditText(this);t.setSingleLine();t.setInputType(144);t.addTextChangedListener(new TextWatcher(){public void beforeTextChanged(CharSequence s,int a,int b,int c){if(g<1)g=f();}public void onTextChanged(CharSequence s,int a,int b,int c){}public void afterTextChanged(Editable s){}});t.setOnEditorActionListener((x,y,z)->{t.setError((""+t.getText()).equals("abcdefghijklmnopqrstuvwxyz")?f()-g+"":"Fail");return true;});addContentView(t,new android.view.ViewGroup.LayoutParams(-1,-2));}} ``` Commented version: ``` // Android requires all Activities to be in a package. package a; // EditText import android.widget.*; // TextWatcher, Editable import android.text.*; // just use full package names for the rest // yes, we need this entire signature. public class Z extends android.app.Activity { // timer long g; // Wrapper because it is shorter than calling this behemoth // Gets the current time long f() { return System.currentTimeMillis(); } // Activity entry point public void onCreate(android.os.Bundle b) { super.onCreate(b); // Android Studio doesn't have var. They abandoned Java 10 in favor of Kotlin. // geeeeeeeeee I wonder why ANYone would abandon programming for Android in Java... :P EditText t = new EditText(this); // This sets the enter key to a submit key, allowing us to catch OnEditorAction t.setSingleLine(); // no autocomplete 4 u // InputType.VISIBLE_PASSWORD t.setInputType(144); // The main reason this is so verbose is because the requirement needs us to start // timing on the first character TYPED. It would be much easier to add an onClick or onFocus // listener instead, but nooooo. :( t.addTextChangedListener(new TextWatcher() { // why public void beforeTextChanged(CharSequence s, int a, int b, int c) { // Start our timer the first time the user types something. if (g < 1) g = f(); } // three public void onTextChanged(CharSequence s, int a, int b, int c) { } // methods? public void afterTextChanged(Editable s) { } }); // When they hit submit, verify using the obvious way. // I _may_ be able to verify in TextWatcher, but TextWatcher is not char by char. IDK, I haven't experimented with it yet. t.setOnEditorActionListener((x, y, z) -> { // Show the result via setError, which is on a new line. :) t.setError(("" + t.getText()).equals("abcdefghijklmnopqrstuvwxyz") ? f() - g + "" : "Fail"); return true; }); // Append to the root view. // -1 == LayoutParams.MATCH_PARENT // -2 == LayoutParams.WRAP_CONTENT addContentView(t, new android.view.ViewGroup.LayoutParams(-1, -2)); } } ``` <https://streamable.com/7xb1xl> Edit: I have gotten very good at this by the way, [look at my mad skills.](https://streamable.com/8sx6t3) ]
[Question] [ Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, your program / function may result in undefined behaviour. Example: For `a = [2, 3, 3, 1, 5, 2]`, the output should be `firstDuplicate(a) = 3`. There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a smaller index than the second occurrence of 2 does, so the answer is 3. For `a = [2, 4, 3, 5, 1]`, the output should be `firstDuplicate(a) = -1`. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. BONUS: Can you solve it in O(n) time complexity and O(1) additional space complexity? [Answer] # [Python 2](https://docs.python.org/2/), 34 bytes *O(n2) time, O(n) space* Saved 3 bytes thanks to @vaultah, and 3 more from @xnor! ``` lambda l:l[map(l.remove,set(l))<0] ``` [Try it online!](https://tio.run/##TYqxDoJAEERr7iu2hOQ0gtpcpMTEysYOKQ5ZAnE5Luuh8PUnkpA4mWbePDu5pjeJr9O7J92VlQZSlHfahrRl7Po3yhe6kKLotCv8p2kJ4cYDKgFzHE9KBJS2xg4ujERguTUO6tlffhwfaB1cTIVjxtyzWpVN/C9k1/N6l4z66fNEwn5pLOEoISnEDx0WNO@4@AI "Python 2 – Try It Online") [Answer] ## JavaScript (ES6), ~~47~~ ~~36~~ ~~31~~ 25 bytes *Saved 6 bytes thanks to ThePirateBay* Returns `undefined` if no solution exists. Time complexity: *O*(n) :-) Space complexity: *O*(n) :-( ``` a=>a.find(c=>!(a[-c]^=1)) ``` ### How? We keep track of already encountered values by saving them as new *properties* of the original array ***a*** by using negative numbers. This way, they can't possibly interfere with the original entries. ### Demo ``` let f = a=>a.find(c=>!(a[-c]^=1)) console.log(f([2, 3, 3, 1, 5, 2])) console.log(f([2, 4, 3, 5, 1])) console.log(f([1, 2, 3, 4, 1])) ``` [Answer] # Mathematica, 24 bytes ``` #/.{h=___,a_,h,a_,h}:>a& ``` Mathematica's pattern matching capability is so cool! Returns the original `List` for invalid input. ### Explanation ``` #/. ``` In the input, replace... ``` {h=___,a_,h,a_,h} ``` A `List` with a duplicate element, with 0 or more elements before, between, and after the duplicates... ``` ... :>a ``` With the duplicate element. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Ṛœ-QṪ ``` [Try it online!](https://tio.run/##y0rNyan8///hzllHJ@sGPty56v///9FGOgrGYGSoo2Cqo2AUCwA "Jelly – Try It Online") ### How it works ``` Ṛœ-QṪ Main link. Argument: A (array) Ṛ Yield A, reversed. Q Unique; yield A, deduplicated. œ- Perform multiset subtraction. This removes the rightmost occurrence of each unique element from reversed A, which corresponds to the leftmost occurrence in A. Ṫ Take; take the rightmost remaining element, i.e., the first duplicate of A. ``` [Answer] # Pyth, 5 bytes ``` h.-Q{ ``` [Test suite](https://pyth.herokuapp.com/?code=h.-Q%7B&test_suite=1&test_suite_input=%5B2%2C+3%2C+3%2C+1%2C+5%2C+2%5D%0A%5B2%2C+4%2C+3%2C+5%2C+1%5D%0A%5B1%2C+2%2C+1%2C+2%5D&debug=0) Remove from Q the first appearance of every element in Q, then return the first element. [Answer] # [Haskell](https://www.haskell.org/), 35 bytes ``` f s(h:t)|h`elem`s=h|1<2=f(h:s)t f[] ``` [Try it online!](https://tio.run/##HchBCsMgEAXQvaf4hCwaMIFYuin1AD2DSJPF2JEaExyXubsthbd6vMqHUmotQC58r8PJCyXaFrF8zg9jw29lqCo43/CyVMpeum4c8XznvRAqR0GKmSal1LbGDIujxFzRI8B5OKNx/Zs1bhrGty8 "Haskell – Try It Online") Crashes if no duplicate is found. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` UÞ⊍h ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwiVcOe4oqNaCIsIiIsIlsyLCAxLCA0LCAxLCA0XSJd) Takes the multi-set symmetric difference, which outputs the duplicate values in order that they occur. Outputs `0` if nothing is found. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` xŒQ¬$Ḣ ``` [Try it online!](https://tio.run/##y0rNyan8/7/i6KTAQ2tUHu5Y9P9w@6OmNf//R0cb6SgYg5GhjoKpjoJRrA6XAkjQBCwIFDEEiwBlISpNYCKmYK4RWI1JbCwA) Returns the first duplicate, or 0 if there is no duplicate. ## Explanation ``` xŒQ¬$Ḣ Input: array M $ Operate on M ŒQ Distinct sieve - Returns a boolean mask where an index is truthy for the first occurrence of an element ¬ Logical NOT x Copy each value in M that many times Ḣ Head ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 bytes ``` æ@bX ¦Y ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=5kBiWCCmWQ==&input=WzIsIDMsIDMsIDEsIDUsIDJd) ### Explanation ``` æ@ bX ¦ Y UæXY{UbX !=Y} Ungolfed Implicit: U = input array UæXY{ } Return the first item X (at index Y) in U where UbX the first index of X in U !=Y is not equal to Y. In other words, find the first item which has already occured. Implicit: output result of last expression ``` --- Alternatively: ``` æ@¯Y øX ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=5kCvWSD4WA==&input=WzIsIDMsIDMsIDEsIDUsIDJd) ### Explanation ``` æ@ ¯ Y øX UæXY{Us0Y øX} Ungolfed Implicit: U = input array UæXY{ } Return the first item X (at index Y) in U where Us0Y the first Y items of U (literally U.slice(0, Y)) øX contains X. In other words, find the first item which has already occured. Implicit: output result of last expression ``` [Answer] # Dyalog APL, ~~27~~ ~~24~~ ~~20~~ ~~19~~ ~~13~~ ~~12~~ 11 bytes ``` ⊢⊃⍨0⍳⍨⊢=⍴↑∪ ``` Now modified to not depend on v16! [Try it online!](http://tryapl.org/?a=%28%u22A2%u2283%u23680%u2373%u2368%u22A2%3D%u2374%u2191%u222A%29%201%201&run) # How? (With input **N**) * `⊢⊃⍨...` - **N** at this index: + `⍴↑∪` - **N** with duplicates removed, right-padded with `0` to fit **N** + `⊢=` - Element-wise equality with **N** + `0⍳⍨` - Index of the first `0`. ` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` a⊇=bh ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P/FRV7ttUsb//9FGOgrGYGSoo2Cqo2AU@z8KAA "Brachylog – Try It Online") ## Explanation ``` a⊇=bh Input is a list. a There is an adfix (prefix or suffix) of the input ⊇ and a subsequence of that adfix = whose elements are all equal. b Drop its first element h and output the first element of the rest. ``` The adfix built-in `a` lists first all prefixes in increasing order of length, then suffixes in decreasing order of length. Thus the output is produced by the shortest prefix that allows it, if any. If a prefix has no duplicates, the rest of the program fails for it, since every subsequence of equal elements has length 1, and the first element of its tail doesn't exist. If a prefix has a repeated element, we can choose the length-2 subsequence containing both, and the program returns the latter. [Answer] # [Python 3](https://docs.python.org/3/), ~~94~~ 92 bytes O(n) time and O(1) extra memory. ``` def f(a): r=-1 for i in range(len(a)):t=abs(a[i])-1;r=[r,i+1][a[t]<0>r];a[t]*=-1 return r ``` [Try it online!](https://tio.run/##PY5BDsIgEEXXcopZgtJEWt204kUIC1RQkoY2w7jw9EhravIXP28yL3/@0GtKXSkPHyBwJ3oGqBvFIEwIEWICdOnp@ehTvYqetLtl7ky0olEDaoMyHpQ1zpC9HK9oh6XtVwV6emMVFPKZ7i77rA3bmVZCt0ZJOEtorfzB0worUZVYtgzYHpcdf0k/Y0zEA9@IEOUL "Python 3 – Try It Online") [Source of the algorithm](http://www.geeksforgeeks.org/find-duplicates-in-on-time-and-constant-extra-space/). ### Explanation The basic idea of the algorithm is to run through each element from left to right, keep track of the numbers that have appeared, and returning the number upon reaching a number that has already appeared, and return -1 after traversing each element. However, it uses a clever way to store the numbers that have appeared without using extra memory: to store them as the sign of the element indexed by the number. For example, I can represent the fact that `2` and `3` has already appeared by having `a[2]` and `a[3]` negative, if the array is 1-indexed. [Answer] # [Perl 6](https://perl6.org), 13 bytes ``` *.repeated[0] ``` [Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszZVbqaCWlllUXKKbUlqQk5mcWJKqYPtfS68otSAVyE6JNoj9D1blkKhgq2Cko2AMRoY6CqY6CkbWXMWJlQpo@jUcEjWtFZQVjLnA@pIg@kzA@oCaDHFoSgJr8svM@Q8A "Perl 6 – Try It Online") --- ## Explanation * The `*` is in a Term position so the whole statement is a [WhateverCode](https://docs.perl6.org/type/WhateverCode) lambda. * The `.repeated` is a method that results in every value except for the first time each value was seen. ``` say [2, 3, 3, 3, 1, 5, 2, 3].repeated.perl; # (3, 3, 2, 3).Seq # ( 3, 3, 2, 3).Seq ``` * `[0]` just returns the first value in the [Seq](https://docs.perl6.org/type/Seq). If there is no value [Nil](https://docs.perl6.org/type/Nil) is returned. ([Nil](https://docs.perl6.org/type/Nil) is the base of the [Failure](https://docs.perl6.org/type/Failure) types, and all types are their own undefined value, so [Nil](https://docs.perl6.org/type/Nil) different than an undefined value in most other languages) --- Note that since the [implementation of `.repeated`](https://github.com/rakudo/rakudo/blob/51e59eeb5e48917ed3e825947989f91a219ce2cc/src/core/Any-iterable-methods.pm#L1595-L1628) generates a [Seq](https://docs.perl6.org/type/Seq) that means it doesn't start doing any work until you ask for a value, and it only does enough work to generate what you ask for. So it would be easy to argue this has at worst *O(n)* time complexity, and at best *O(2)* time complexity if the second value is a repeat of the first. Similar can probably be said of memory complexity. [Answer] # [J](http://jsoftware.com/), 12 bytes ``` ,&_1{~~:i.0: ``` [Try it online!](https://tio.run/##y/r/P03B1kpBRy3esLquzipTz8CKiys1OSNfQcM6TVPNTsFIwRgIDRVMgSxrIDYB8kwVDP//BwA "J – Try It Online") ## Explanation ``` ,&_1{~~:i.0: Input: array M ~: Nub-sieve 0: The constant 0 i. Find the index of the first occurrence of 0 (the first duplicate) ,&_1 Append -1 to M {~ Select the value from the previous at the index of the first duplicate ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 20 bytes ``` ⊃n/⍨(,≢∪)¨,\n←⎕,2⍴¯1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdLbOouMSltOD/o67mPP1HvSs0dB51LnrUsUrz0AqdmLxHbRMe9U3VMXrUu@XQekOQhv8KYADTx2Wko2AMRoY6CqY6CkZcmPImYHmgpCG6pLGOkQ4YAwA "APL (Dyalog Unicode) – Try It Online") `2⍴¯1` negative one **r**eshaped into a length-two list `⎕,` get input (mnemonic: console box) and prepend to that `n←` store that in *n* `,\` prefixes of *n* (lit. cumulative concatenation) `(`…`)¨` apply the following tacit function to each prefix  `,` [is] the ravel (just ensures that the prefix is a list)  `≢` different from  `∪` the unique elements[?] (i.e. is does the prefix have duplicates?) `n/⍨` use that to filter *n* (removes all elements until the first for which a duplicate was found) `⊃` pick the first element from that [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 11 bytes As per [the new rules](https://codegolf.stackexchange.com/questions/136713/find-the-first-duplicated-element/136797?noredirect=1#comment334435_136713), throws an error if no duplicates exist. ``` ⊢⊃⍨⍬⍴⍳∘≢~⍳⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3y2zqLjEpbTgUduER12LHnU1P@pd8ah3zaPeLY96Nz/qmPGoc1EdiNW74v9/BTCA6VAw0lEwBiNDHQVTHQUjLjR5Yx0jHTDmwtRoAtYI1GUIAA "APL (Dyalog Unicode) – Try It Online") `⍳⍨` the indices of the first occurrence of each element `~` removed from `⍳∘≢` of all the indices `⍬⍴` reshape that into a scalar (gives zero if no data is available) `⊃⍨` use that to pick from (gives error on zero) `⊢` the argument [Answer] ## APL, 15 ``` {⊃⍵[(⍳⍴⍵)~⍵⍳⍵]} ``` Seems like we can return 0 instead of -1 when there are no duplicates, (thanks Adám for the comment). So 3 bytes less. A bit of description: ``` ⍵⍳⍵ search the argument in itself: returns for each element the index of it's first occurrence (⍳⍴⍵)~⍵⍳⍵ create a list of all indexes, remove those found in ⍵⍳⍵; i.e. remove all first elements ⊃⍵[...] of all remaining elements, take the first. If the array is empty, APL returns zero ``` For reference, old solution added -1 to the list at the end, so if the list ended up empty, it would contain -1 instead and the first element would be -1. ``` {⊃⍵[(⍳⍴⍵)~⍵⍳⍵],¯1} ``` Try it on [tryapl.org](http://tryapl.org/?a=%7B%u2283%u2375%5B%28%u2373%u2374%u2375%29%7E%u2375%u2373%u2375%5D%7D2%203%203%201%205%202&run) [Answer] # [Retina](https://github.com/m-ender/retina), ~~26~~ 24 bytes ``` 1!`\b(\d+)\b(?<=\b\1 .*) ``` [Try it online!](https://tio.run/##K0otycxL/P/fUDEhJkkjJkVbE0jZ29jGJMUYKuhpaf7/b6RgDISGCqYKRgA "Retina – Try It Online") Explanation: `\b(\d+)\b` matches each number in turn, and then the lookbehind looks to see whether the number is a duplicate; if it is the `1`st match is `!` output, rather than the count of matches. Unfortunately putting the lookbehind first doesn't seem to work, otherwise it would save several bytes. Edit: ~~Added 7 bytes to comply with the `-1` return value on no match.~~ Saved 2 bytes thanks to @MartinEnder. [Answer] # PHP, ~~56 44 38~~ 32 bytes ``` for(;!${$argv[++$x]}++;);echo$x; ``` Run like this: ``` php -nr 'for(;!${$argv[++$x]}++;);echo$x;' -- 2 3 3 1 5 2;echo > 3 ``` # Explanation ``` for( ; !${ // Loop until current value as a variable is truthy $argv[++$x] // The item to check for is the next item from input }++; // Post increment, the var is now truthy ); echo $x; // Echo the index of the duplicate. ``` # Tweaks * Saved 12 bytes by using variables instead of an array * Saved 6 bytes by making use of the "undefined behavior" rule for when there is no match. * Saved 6 bytes by using post-increment instead of setting to 1 after each loop # Complexity As can be seen from the commented version of the code, the time complexity is linear `O(n)`. In terms of memory, a maximum of `n+1` variables will be assigned. So that's `O(n)`. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 11 bytes ``` *(~':?',\)# ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs9LSqFO3slfXidFU5uJKi9YwUjAGQhMFUwUjzViIAIgDEoQLQOTNNGMBn9wMqw==) ``` *(~':?',\)# ( )# keep the elements where the left function returns true (when applied to the whole array): ,\ prefixes ?' uniquify each ~': is it the same as previous? * first element ``` [Answer] # R, 34 bytes ``` c((x=scan())[duplicated(x)],-1)[1] ``` Cut a few characters off the answer from @djhurio, don't have enough reputation to comment though. [Answer] # J, ~~17~~ 16 bytes ``` (*/{_1,~i.&0)@~: ``` ### How? ``` (*/{_1,~i.&0)@~: @~: returns the nub sieve which is a vector with 1 for the first occurrence of an element in the argument and 0 otherwise i.&0 returns the first index of duplication _1,~ appends _1 to the index */ returns 0 with duplicates (product across nub sieve) { select _1 if no duplicates, otherwise return the index ``` [Answer] # [R](https://www.r-project.org/), 28 bytes ``` (x=scan())[duplicated(x)][1] ``` [Try it online!](https://tio.run/##K/r/X6PCtjg5MU9DUzM6pbQgJzM5sSQ1RaNCMzbaMPa/KZcxEBpymXIZcf0HAA "R – Try It Online") [Answer] ## Dyalog APL Classic, 18 chars Only works in `⎕IO←0`. ``` w[⊃(⍳∘≢~⍳⍨)w←¯1,⎕] ``` Remove from the list of indices of the elements of the argument with a prepended "-1" the list indices of its nub and then pick the first of what's left. If after the removal there only remains an empty vector, its first element is by definition 0 which is used to index the extended argument producing the desired -1. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~28~~ 36 bytes Misunderstood the challenge the first time. `O(n)` time, `O(n)` space. ``` ->a{d={};a.find{|e|b=d[e];d[e]=1;b}} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9cusTrFtrrWOlEvLTMvpbomtSbJNiU6NdYaRNgaWifV1v4vz8jMSVVITy0p5ipQSItOLUvMUVCJj@VKzUv5H22ko2AMRoY6CqY6CkaxXCAhE7AQkG8YCwA "Ruby – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~65~~ ~~117~~ 109 bytes Previous 65 byte solution: ``` r->{for(int a,b=0,z,i=0;;b=a)if((a=b|1<<(z=r[i++]))==b)return z;} ``` New solution. 19 bytes are included for `import java.math.*;` *-8 bytes thanks to @Nevay* ``` r->{int z,i=0;for(BigInteger c=BigInteger.ZERO;c.min(c=c.setBit(z=r[i++]))!=c;);return z;} ``` [Try it online!](https://tio.run/##dVJNb9swDD3Hv4K7SasjdCm2i@sA6z6AHooB7U4retBs2ZNnS4ZEB02K/PaUkuO5xVLAMCW@R@mJj43cyKXtlWnKvwfd9dYhNJQTncQ/4krX1wZVrVyWvAQH1K347Jzc@hNANZgCtTXi@3FxguPRKdkJOv0urt6mTHjSD79bXUDRSu/hRmqTPCWLY9KjRAobq0voCGJUpU19/wDS1Z4nC6IuUHlkqxQu4vchhY8prHg2IZQYwfCf0xf/pSvrgGmDoCGH8xQaCquMdpfwicLZGYdwXSy/laZWrIl1iwbeByYt9wl9pN7pjUT1Sv5cFa7weqdeyh@7IWzF/rVOuMD@0lqvyvCIWJLCjBN5SnNRtRJvZP/TEs7GFi/XY@QCbTSV8aCXNL6tMIgTQgCFqb13W4@KbhtQUJXB1rBxROjY0Q4W2bEXJ8iVNuXXoSc76cJrU6rHmT9qeeV16M7pEnLdPR5FTSN4GfOxK2Gc11CRaQe3XD@Fc3apzs8z8pXNEw9FPm/Er2@3P7JCdDRaRV4Ir/BKI9vl7p78fuD8XV5kPHMKB2dgl@0P4ZHHbSVk37dbRqLiU/bJ4Rk "Java (OpenJDK 8) – Try It Online") # Edit The algorithm in my original program was fine, but the static size of the datatype used meant that it broke fairly quickly once the size went above a certain threshold. I have changed the datatype used in the calculation to increase the memory limit of the program to accommodate this (using `BigInteger` for arbitrary precision instead of `int` or `long`). However, this makes it debatable whether or not this counts as `O(1)` space complexity. I will leave my explanation below intact, but I wish to add that I now believe it is impossible to achieve `O(1)` space complexity without making some assumptions. # Proof Define `N` as an integer such that `2 <= N` . Let `S` be a list representing a series of random integers `[x{1}, ..., x{N}]`, where `x{i}` has the constraint `1 <= x{i} <= N`. The time complexity (in Big-O notation) required to iterate through this list exactly once per element is `O(n)` The challenge given is to find the first duplicated value in the list. More specifically, we are searching for the first value in `S` that is a duplicate of a previous item on the list. Let `p` and `q` be the positions of two elements in the list such that `p < q` and `x{p} == x{q}`. Our challenge becomes finding the smallest `q` that satisfies those conditions. The obvious approach to this problem is to iterate through S and check if our `x{i}` exists in another list `T`: If `x{i}` does not exist in `T`, we store it in `T`. If `x{i}` does exist in `T`, it is the first duplicate value and therefore the smallest `q`, and as such we return it. This space efficiency is `O(n)`. In order to achieve `O(1)` space complexity while maintaining `O(n)` time complexity, we have to store unique information about each object in the list in a finite amount of space. Because of this, the only way any algorithm could perform at `O(1)` space complexity is if: 1. N is given an upper bound corresponding to the memory required to store the maximum number of possible values for a particular finite datatype. 2. The re-assignment of a single immutable variable is not counted against the complexity, only the number of variables (a list being multiple variables). 3. (Based on other answers) The list is (or at least, the elements of the list are) mutable, and the datatype of the list is preset as a signed integer, allowing for changes to be made to elements further in the list without using additional memory. 1 and 3 both require assumptions and specifications about the datatype, while 2 requires that only the number of variables be considered for the calculation of space complexity, rather than the size of those variables. If none of these assumptions are accepted, it would be impossible to achieve both `O(n)` time complexity and `O(1)` space complexity. # Explanation Whoo boy, this one took ~~an embarrassingly long time to think up~~ a bit of brain power. So, going for the bonus is difficult. We need both to operate over the entire list exactly once **and** track which values we've already iterated over without additional space complexity. Bit manipulation solves those problems. We initialize our `O(1)` 'storage', a pair of integers, then iterate through the list, OR-ing the ith bit in our first integer and storing that result to the second. For instance, if we have `1101`, and we perform an OR operation with `10`, we get `1111`. If we do another OR with `10`, we still have `1101`. Ergo, once we perform the OR operation and end up with the same number, we've found our duplicate. No duplicates in the array causes the program to run over and throw an exception. [Answer] # Java 8, 82 78 76 bytes No longer viable, 75 67 64 bytes below in edit As a lambda function: ``` a->{Set<Long>s=new HashSet<>();for(long i:a)if(!s.add(i))return i;return-1;} ``` Probably can be made much smaller, this was very quick. ### Explanation: ``` a->{ //New lambda function with 'a' as input Set<Long>s=new HashSet<>(); //New set for(long i:a) //Iterate over a if(!s.add(i)) //If can't add to s, already exists return i; //Return current value return-1; //No dupes, return -1 } ``` # \*Edit\* 75 67 64 bytes using the negation strategy: ``` a->{int i=0,j;while((a[j=Math.abs(a[i++])-1]*=-1)<0);return++j;} ``` [Try it online!](https://tio.run/##bVDBbsIwDD03X5FjO9yoSaGASjlNk3bgxBFxyCCFdCWtGpcJIb69Swubpm1RIsfPst/zK@RZhlWtTLF/7/SprhqkhcNYi7pkeWt2qCvDXh6flJC6fSv1ju5KaS1dSW3I1SPeA7Uo0YVzpff05Gr@GhttDpstlc3BBsS7EvrroLLocxAwhnh4SZASz/uGe3ACCUxhBnPgEXAOXACPgY@BT4AnwKfAZ8DnICIQrkeAiEGMQUxAJCCmIGYg5hBHEHOI3cjY3Z7lRv5I1wZprs3@ua2V75JBejMo97wvGxZDAeirQXVQzZLmNKOdDJfXvl1nERTpx1GXyvflpshWEo9MvlmX6NFoG4R8@5SFPFhEQdoobBszGhXprev3vuc0Z7Kuy4vfc/8vdPB4cMlxMsZ65fahc32xqE6sapHVzn8sjf9zJxvcZ95I9wk "Java (OpenJDK 8) – Try It Online") (-3 bytes thanks to @Nevay) ### Explanation: ``` a->{ //New lambda expression with 'a' as input int i=0,j; //Initialise i and declare j while((a[j=Math.abs(a[i++])-1]*=-1)<0); //Negate to keep track of current val until a negative is found return++j; //Return value } ``` Loops over the array, negating to keep track. If no dupes, just runs over and throws an error. Both of these work on O(n) time and O(n) space complexity. [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` ←Ṡ-u ``` Returns `0` if no input contains no duplicate, [try it online!](https://tio.run/##yygtzv7/qKmx6Nzi8v@P2iY83LlAt/T////RRjoKxmBkqKNgqqNgFAsA "Husk – Try It Online") ### Explanation ``` ←Ṡ-u -- takes a list X as input & returns 0 or first duplicate Ṡ- -- compute X - ... u -- ... deduplicate X ← -- get first element or 0 if empty ``` [Answer] # [Haskell](https://www.haskell.org/), 34 bytes ``` import Data.List f x=head$x\\nub x ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrTaHCNiM1MUWlIiYmrzRJoeK/rq4CSEBPQyMmRtNGyw4oqsmVm5iZp2CrUFCUmVeioKKQFm2oY6RjDIRAOvY/AA "Haskell – Try It Online") For an input `x = [2,3,3,1,5,2]`, `nub x` removes duplicates `[2,3,1,5]` and `x\\nub x` removes the elements of `nub x` from x, thus keeping the duplicates `[3,2]`. `head` returns the first element of hat list. --- Point-free is the same byte count: `head.((\\)<*>nub)`. [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` &=Rsqf1) ``` Gives an error (without output) if no duplicate exists. Try at [**MATL Online!**](https://matl.io/?code=%26%3DRsqf1%29&inputs=%5B2%2C+3%2C+3%2C+1%2C+5%2C+2%5D&version=20.2.2) ### Explanation ``` &= % Implict input. Matrix of all pairwise equality comparisons R % Keep the upper triangular part (i.e. set lower part to false) s % Sum of each column q % Subtract 1 f % Indices of nonzero values 1) % Get first. Gives an error is there is none. Implictly display ``` ]
[Question] [ For today's challenge, you must write a program or function that alternates the case of a string. However, you must ignore non-alphabetic characters. This means that every alphabetic character must have a different case than the preceding *and* following alphabetic character. This is slightly more complex than uppercasing every other letter for example. If you take a string such as ``` hello world ``` and convert every other character to uppercase, you'll get: ``` hElLo wOrLd ``` As you can see, the lowercase `o` is followed by a lowercase `w`. This is invalid. Instead, you must ignore the space, giving us this result: ``` hElLo WoRlD ``` All non-alphabetic characters must be left the same. The output can start with upper or lowercase, as long as it consistently alternates. This means the following would also be an acceptable output: ``` HeLlO wOrLd ``` Your program should work regardless of the case of the input. The input string will only ever contain [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters), so you don't have to worry about unprintable characters, newlines or unicode. Your submission can be either a full program or a function, and you may take the input and output in any reasonable format. For example, function arguments/return value, STDIN/STDOUT, reading/writing a file, etc. ## Examples: ``` ASCII -> AsCiI 42 -> 42 #include <iostream> -> #InClUdE <iOsTrEaM> LEAVE_my_symbols#!#&^%_ALONE!!! -> lEaVe_My_SyMbOlS#!#&^%_aLoNe!!! PPCG Rocks!!! For realz. -> PpCg RoCkS!!! fOr ReAlZ. This example will start with lowercase -> tHiS eXaMpLe WiLl StArT wItH lOwErCaSe This example will start with uppercase -> ThIs ExAmPlE wIlL sTaRt WiTh UpPeRcAsE A1B2 -> A1b2 ``` Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), standard loopholes apply and the shortest answer in bytes wins! [Answer] ## JavaScript (ES6), ~~66~~ 63 bytes Starts with uppercase. ``` s=>s.replace(/[a-z]/gi,c=>c[`to${(s=!s)?'Low':'Upp'}erCase`]()) ``` ### Test cases ``` let f = s=>s.replace(/[a-z]/gi,c=>c[`to${(s=!s)?'Low':'Upp'}erCase`]()) console.log(f("ASCII")) console.log(f("42")) console.log(f("#include <iostream>")) console.log(f("LEAVE_my_symbols#!#&^%_ALONE!!!")) console.log(f("PPCG Rocks!!! For realz.")) console.log(f("This example will start with lowercase")) console.log(f("This example will start with uppercase")) console.log(f("A1B2")) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 8 bytes ### Code: ``` lvyJ¤aiš ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@59TVul1aEli5tGF///7uDqGucbnVsYXV@Ym5ecUKysqq8Wpxjv6@Pu5KioqAgA "05AB1E – TIO Nexus") ### Explanation: ``` l # Lowercase the input vy # For each element.. J # Join the entire stack into a single string ¤a # Check if the last character is alphabetic iš # If true, swapcase the entire string ``` [Answer] # GNU Sed, 33 * 5 bytes saved thanks to @TobySpeight Score includes +1 for `-r` flag to sed. ``` s/([a-z])([^a-z]*.?)/\U\1\L\2/gi ``` [Try it online](https://tio.run/nexus/sed#fYvRCoIwGEbv9xQbUlSgonQZhYlFICUV3WjJspGj2WT/xOrhWwZdd/WdA@cz4A5Sar@Ow0F6@u7ImQ3drMm8TGS@e@XGBLtwtUJjH1n8XojmwvCES9CK0WqK4ig4RHn1zOFZnaUAi1j9Uy8P4s06IoSgJAmXeCuLG3SGF1Lh7ideDtqXHDB70KoWDLdcCAyaKt2hLrGQLVMFBfY/a@r6lwXe3H/LWnN5B2OrDw). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` nŒsTm2 ŒlŒuǦ ``` [Try it online!](https://tio.run/nexus/jelly#@593dFJxSK4R19FJOUcnlR5uP7Ts/8PdWw63P2paE/n/v2Ows6cnl4kRl3JmXnJOaUqqgk1mfnFJUWpirh1XQICzu0JQfnJ2saKiooJbfpECUDynSo/Lx9UxzDU@tzK@uDI3KT@nWFlRWS1ONd7Rx9/PFaiUKyQjs1ghtSIxtyAnVaE8MydHobgksagEyCzJUCgtKEgtSk4sTgUA "Jelly – TIO Nexus") ### How it works ``` ŒlŒsǦ Main link. Argument: s (string) Œl Cast to lowercase. Ǧ At indices returned by the helper link... Œu apply uppercase. nŒsTm2 Helper link. Argument: s (string) Œs Apply swapcase to s. n Perform vectorizing not-equal comparison. T Compute the truthy indices. m2 Select every other one, starting with the first. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~16~~ 14 bytes ``` r"%l"_m"uv"gT° ``` [Try it online!](https://tio.run/nexus/japt#@1@kpJqjFJ@rVFqmlB5yaMP//0qOwc6enkoA) ### Explanation ``` r // RegEx replace input "%l" // [A-Za-z] as first arg to replace _ // created function Z=>Z as second arg to replace "uv"gT° // alternates "u" & "v" m // map Z to either "u" upper or "v" lower ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~86~~ ~~76~~ ~~68~~ ~~66~~ 63 bytes -2 bytes thanks to DJMcMayhem -3 bytes thanks to Cyoce ``` x=0 for i in input():print(end=(2*i).title()[x]);x^=i.isalpha() ``` [Try it online!](https://tio.run/nexus/python3#DcJBCoAgEAXQfadwOdNComXhSaIg0PDDoGITeXvr8Xpz03DlamCQ/uVR4qVUJKWQvKN5BFuFSiDe2s5rOxws7lNKPIl7j0EkmzdX8R8 "Python 3 – TIO Nexus") or [Try all test cases](https://tio.run/nexus/python3#hZBPa8JAEMXvfooJwe5ukVCkJ20KQaII0kotvYiGbbIhQzfZZWfF2C@fbmjvvQzz5/0evBkqVUPNSSwm0KcPE6iNAwTsgBbWYee56qqUz@9RJB69Vlwc@5NY9ucUEySpbSO5GEaKRurIssNqu2Uz9jgPJcau1JdKwRMa8k7J9jlsd3n2kRftraBb@2k0xVF8d54W2e71JY@iKCj2@9UG3kz5RWGGdXAPrP5Owum9QQLVy9ZqBVfUGshL50PrG9DmqlwpSf0nvFj7JzyF5OMDlr9xGRPDDw "Python 3 – TIO Nexus") [Answer] # [Alice](https://github.com/m-ender/alice), 18 bytes ``` /olZlYuN @iy.u..// ``` [Try it online!](https://tio.run/nexus/alice#@6@fnxOVE1nqx@WQWalXqqenr///v0dqTk6@Qnl@UU6KIgA "Alice – TIO Nexus") ### Explanation This program follows a lesser-known template for odd-length programs that run entirely in ordinal mode. The linearized version of this code is: ``` il.l.uN.YuZyo@ ``` Explanation of code: ``` i - push input onto stack ["Hello world!"] l - convert to lowercase ["hello world!"] . - duplicate ["hello world!", "hello world!"] l - convert to lowercase (should be no-op, but avoids what seems to be a bug in the TIO implementation) . - duplicate again ["hello world!", "hello world!", "hello world!"] u - convert to uppercase ["hello world!", "hello world!", "HELLO WORLD!"] N - difference between sets ["hello world!", "helloworld"] . - duplicate reduced string ["hello world!", "helloworld", "helloworld"] Y - unzip (extract even positions) ["hello world!", "helloworld", "hlool", "elwrd"] u - convert to uppercase ["hello world!", "helloworld", "hlool", "ELWRD"] Z - zip evens back into string ["hello world!", "helloworld", "hElLoWoRlD"] y - perform substitution ["hElLo WoRlD!"] o - output [] @ - terminate ``` Without using `l` on the duplicate, the stack after `N` would be `["helloworld", "helloworld"]`. I strongly suspect this is a bug. [Answer] # Ruby, ~~57~~ ~~55~~ ~~47~~ 41 bytes Byte count includes two bytes for command line options. Run it for example like this: `$ ruby -p0 alternate_case.rb <<< "some input"` ``` gsub(/\p{L}/){($&.ord&95|32*$.^=1).chr} ``` With the `p0` option, the entire input is consumed in one go, and the magical global `$.` is incremented to 1. This is later toggled between 0 and 1 and used for keeping the state. Works with multiline input; [Try it online!](https://tio.run/nexus/ruby#fYtPC4IwHEDv@xQTTSzIyuoQVGBhEUhJRadITEeOphv7TfrrV888dO72HrxXXaA4W52jePllp/myDNPmMjFHw3ffaRn2adJr2nEqy6pyd/PVCg0cpNM8ZkVC8JhyUJJE2RT5nnvwwuwRwiM7cwa6ppunRuj6m7WnaRoKgvkSb3l8hdrwgktcf@xpo31KAZN7lAlG8I0yhkFFUtWoUsz4jcg4AvI/K4T4ZW5v5ny4UJTnULVF9ws "Ruby – TIO Nexus") Thanks to Ventero for amazing input -- check the comments for details. [Answer] # [C (tcc)](http://savannah.nongnu.org/projects/tinycc), ~~60~~ ~~57~~ 56 bytes Thanks to DigitalTrauma for noticing bit 5 is the only difference for ASCII upper/lower case. Special thanks to zch for golfing off three more bytes. Save one more byte from RJHunter's idea ``` l;f(char*s){for(;*s=isalpha(*s)?*s&95|++l%2<<5:*s;s++);} ``` [Try it online!](https://tio.run/nexus/c-tcc#bU5da8IwFH3vr0gtSpKywWQ@bKmOTrohyBQHPlqy2NKym0ZylaGuP9vnWn0RIffhwD1fnAZETlUhLUd2zI2lguOwRAmbQtKWe@PYexn8hyF0@1E0eOUoMAyZqBsty4oy7@iR9i4NhBMtrt8VcqqHnSIDMOTPWFh3mNjstkg1Ezc9/h5PJk7lue@kg7JSsFtnJCoNbm0m9cjpmybxMkn1PsW9/jGAgR/0Vt00ns6@Et/3nZn5fPxJFkb9YusgH8aSth8Oj@7lT@93C2uvOVXmQUlVZGc "C (tcc) – TIO Nexus") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~16~~ 15 bytes ``` Xktkyy-f2L))5M( ``` [Try it online!](https://tio.run/nexus/matl#@x@RXZJdWambZuSjqWnqq/H/v3pGak5OvkJ5flFOijoA) Or [verify all test cases](https://tio.run/nexus/matl#hYtNC4IwHMbvfYr/kFoeCpK6RWBmIdgLJdEpW7ZwuDXZJra@vO3UtcvD8/J7bt2lMpW1o2eQ@v5sO@xWWYfDU5QkuIengROPvQrePCjMmdRGUSIWrk3j8Bznwubairvk2kPe4NrPw3S/ixFCjjgcog0cZVFpl2EtFbgv/4zdlJVMA30TUXMKLeMctCHKOGtK4LKlqiCa/gObuv6B4WQZ4C8). ### Explanation Consider input 'hello world' ``` Xk % To upper case % STACK: 'HELLO WORLD' t % Duplicate top element % STACK: 'HELLO WORLD', 'HELLO WORLD' k % To lower case % STACK: 'HELLO WORLD', 'hello word' yy % Duplicate top two elements % STACK: 'HELLO WORLD', 'hello word', 'HELLO WORLD', 'hello word' - % Difference (of code points; element-wise) % STACK: 'HELLO WORLD', 'hello word', [-32 -32 -32 -32 -32 0 -32 -32 -32 -32 -32] f % Indices of nonzeros % STACK: 'HELLO WORLD', 'hello word', [1 2 3 4 5 7 8 9 10 11] 2L) % Keep only even-indexed values (*) % STACK: 'HELLO WORLD', 'hello word', [2 4 7 9 11] ) % Reference indexing (get values at indices) % STACK: 'HELLO WORLD', 'elwrd' 5M % Push (*) again % STACK: 'HELLO WORLD', 'elwrd', [2 4 7 9 11] ( % Assignment indexing (write values at indices). Implicit display % STACK: 'HeLlO wOrLd ``` ' [Answer] # Java 8, 99 bytes ``` a->{String r="";int i=0;for(int c:a)r+=(char)(c>64&c<91|c>96&c<123?i++%2<1?c|32:c&~32:c);return r;} ``` **Explanation:** [Try it here.](https://tio.run/nexus/java-openjdk#lZFRT8IwFIXf@RV3I5AtxMUNQoJjI5OgIUEkYnwxSkop0ti1pO3ECfOvY4c86sNebk5ve79z2mKGlII7RPm@BkC5JnKNMIFpuQSYa0n5G2AHb5B8fgHkhqZf1ExRGmmKYQocIjiii3h/Piwj2w4NCWh0Ga6FdEqNr5ArW9GJ4zo47naauN/zDzjudY3yg/aAtlqNoO8P8KEdXOHmd1ndUBKdSQ4yLI5habvNlszYnt0/BF1BatI7v@aniOfoudIk9USmva3Z0ow73MOOncyH47HtaTE0URIpUe647ula/890gooDdcoxy1YE@lQoLQlK44qEySh5Gi3SfKHydCmYqlv15mtjkUzupyPLsirSZrPhLTwI/K7MLNwICSYT@/IqYh43VAH5ROmWEdhRxsp/kNpIvQEmdkRipEhFaOJf//28Ra04/gA) ``` a->{ // Lambda with char-array parameter and String return-type String r=""; // Result-String int i=0; // Flag for alteration for(int c:a) // Loop over the characters of the input r+=(char) // And append the result-String with the following (converted to char): (c>64&c<91|c>96&c<123? // If it's a letter: i++%2<1? // And the flag states it should be lowercase: (c|32) // Convert it to lowercase : // Else (should be uppercase): (c&~32) // Convert it to uppercase : // Else: c); // Simply append the non-letter character as is // End of loop (implicit / single-line body) return r; // Return result-String } // End of method ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 25 bytes ``` {ḷ|ụ}ᵐ.{ḷ∈Ạ&}ˢ¬{s₂{∈Ạ}ᵐ}∧ ``` [Try it online!](https://tio.run/nexus/brachylog2#@1/9cMf2moe7l9Y@3DpBD8R51NHxcNcCtdrTiw6tqS5@1NRUDREBKah91LH8/3@ljNScnHyF8vyinBSl/1EA "Brachylog – TIO Nexus") This is both long and slow. ### Explanation ``` { }ᵐ. The Output is the result of mapping on each char of the Input: ḷ Lowecase the char | Or ụ Uppercase the char { }ˢ In the Ouput, select the chars that: ḷ∈Ạ& when lowercased are in "abc...xyz" (ie are letters) ¬{ }∧ In that new string, it is impossible to find: s₂ a substring of 2 consecutive chars {∈Ạ}ᵐ where both of them are in the lowercase alphabet ``` [Answer] # Pyth, 11 bytes ``` srR~xZ}dGrZ ``` [Try it here](https://pyth.herokuapp.com/?code=srR~xZ%7DdGrZ&test_suite=1&test_suite_input=%27ASCII%27%0A%2742%27%0A%27%23include+%3Ciostream%3E%27%0A%27LEAVE_my_symbols%23%21%23%26%5E%25_ALONE%21%21%21%27%0A%27PPCG+Rocks%21%21%21+For+realz.%27%0A%27This+example+will+start+with+lowercase%27%0A%27This+example+will+start+with+uppercase%27%0A%27A1B2%27&debug=0) ### Explanation ``` # Z = 0; Q = eval(input()) srR~xZ}dGrZQ # Auto-fill variables rZQ # lowercase the input rR # Apply the r function to each letter of the input with ~xZ}dG # ... this as the other argument ~ # use the old value of the variable Z, then update it with the value of ... xZ # Z xor ... }dG # the variable d is a lowercase letter # because of how mapping works in pyth, d will contain the current letter # This causes Z to flip between 0 and 1, alternately upper and lower casing # the current character if it is a letter ``` [Answer] # [Perl 6](https://perl6.org), ~~32~~ 30 bytes ``` {S:g/<:L><-:L>*<:L>?/$/.tclc()/} ``` [Try it](https://tio.run/nexus/perl6#jZFdS8MwFIbv8yvOmLpOtxaHeLGPalaqFKorW6dMhqNmcQumbWjSfSj@Mu/8YzMdKgiKOxfhnJznPTm8ySWFxalJWihewwFJpxQ6m5dBc2a1m77druvjsMjOrD3LVIQTo2q9bjR7rqhU0AHOEiqN6vubKQVnyqjU7UpRqYzFLZTr8aEGW0jwKIGjraqFHtPsc0DdBmPMEpGrGozpSlCi6LQKLwiASSj2Mbbdag2@ujXY3piCZhy9bvDA8Tz4P/RLgKXDPHTSgJ2iUJw0UJklhOfamDZLpcpoFNt/4mUvcfhw6mq2J8PMja5s5Lv4xp3E64lcxw8pl@VS@eB@f4L93rVbKpV@6H2KF5odTeQo7qb@N8t7ScGiIHAuoZ@SJ1koL7SNeh/@bP62SyCcmWadp0HBPvYy6FPM70wUzrW1dBXFglNYMs5BqihTOlVzyIX2lUT637ZDwrknwV3hOOAuLD3ugwyjvoJbFs5hKALaJ1i6CB93G7taio8fGh8 "Perl 6 – TIO Nexus") ``` {S:g{<:L><-:L>*<:L>?}=$/.tclc} ``` [Try it](https://tio.run/nexus/perl6#jZHfSsMwFMbv8xRnTF2nW8UhXritmpUqhepKV5XJcNQsurC0DU26P449mXe@2EyLCoKi5yKck/P7Tg5fcklhfmKSNopXsEfSCYXudj04fV53Tj2r09THfpGdbbo7h6YinGy2mjxXVCroAmcJlUb97dWUgjNl1JpWrahUxuI2yvXwUINtJHiUwEGpaqOnNPsY0LTAGLFE5KoBI7oUlCg6qcMaATAJxTZG2a034LPbgPLGFDTjaLPFA9t14e/QLwGWNnPRcQv@FYXiuIWqLCE817Z0WCpVRqPY@hWvuonNbyaOZvsyzJzoykKeg2@dcbway1X8mHJZrVT3HnbH2OtfO5VK5Zveo3iu2eFYDuNe6n2xvJ8ULPJ9@xKClMxkobzQNup9@Iv50y6@sJ81a88GBfvUzyCgmN@bKJxqa@kyigWnsGCcg1RRpnSqppAL7SuJ9L@VQ8KpK8FZ4tjnDixc7oEMo0DBHQuncCN8GhAsHYSPeq3/WoqPHlvv "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 S # string replace (not in-place) implicitly against 「$_」 :global { <+ :L > # a letter <- :L >* # any number of non-letters <+ :L >? # an optional letter } = $/.tclc() # uppercase the first letter, lowercase everything else } ``` [Answer] # q/kdb+, ~~51~~ ~~42~~ 38 bytes **Solution:** ``` {@[x;;upper]1#'2 cut(&)x in .Q.a}lower ``` **Example:** ``` q){@[x;;upper]1#'2 cut(&)x in .Q.a}lower"hello world" "HeLlO wOrLd" ``` **Notes:** ``` .Q.a // abcde...xyz lowercase alphabet (&) x in // where, returns indices for where x (hello world) is an alpha 2 cut // splits list into 2-item lists 1#' // takes first item of each 2-item list; ie the indices to uppercase @[x;;upper] // apply (@) upper to x at these indices ``` [Answer] # Google Sheets, 264 bytes ``` =ArrayFormula(JOIN("",IF(REGEXMATCH(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1),"[A-Za-z]"),CHAR(CODE(UPPER(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1)))+MOD(LEN(REGEXREPLACE(LEFT(A1,ROW(OFFSET(A1,0,0,LEN(A1)))),"[^A-Za-z]","")),2)*32),MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1)))) ``` It's a big mess but it's a little easier if you expand it out: ``` =ArrayFormula( JOIN( "", IF(REGEXMATCH(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1),"[A-Za-z]"), CHAR( CODE(UPPER(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1))) + MOD(LEN(REGEXREPLACE(LEFT(A1,ROW(OFFSET(A1,0,0,LEN(A1)))),"[^A-Za-z]","")),2)*32 ), MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1) ) ) ) ``` The pseudo-logic would run like this: ``` For each character { // ArrayFormula() If (character is a letter) { // REGEXMATCH(MID()) Return CHAR( // CHAR() CODE(UPPER(letter)) // CODE(UPPER(MID())) + If (nth letter found and n is odd) {32} else {0} // MOD(LEN(REGEXREPLACE(LEFT()))) ) } else { Return character // MID() } } ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~17~~, 13 bytes ``` VUÍშáü$©/ì& ``` [Try it online!](https://tio.run/nexus/v#ATcAyP//VlXDjcOhwoPCqMOhw7wkwqkvw6wm//9MRUFWRV9teV9zeW1ib2xzIyEjJl4lX0FMT05FISEh "V – TIO Nexus") Or [Verify all test cases!](https://tio.run/nexus/v#@x/mHnq49/DCQ82HVhxeeHiPyqGV@ofXqP3/7xjs7OnJZWLEpZyZl5xTmpKqYJOZX1xSlJqYa8fl4@oY5hqfWxlfXJmblJ9TrKyorBanGu/o4@/nqqioyBUQ4OyuEJSfnF0M5Cm45RcpAPXlVOlxhWRkFiukViTmFuSkKpRn5uQoFJckFpUAmSUZCjn55alFyYnFqfiVlRYUQJU5GjoZAQA) HeXdUmP: ``` 00000000: 5655 cde1 83a8 e1fc 24a9 2fec 26 VU......$./.& ``` Explanation: This uses a *compressed regex*™️, so before explaining it, let's expand the regex out: ``` :%s/\v\a.{-}(\a|$)/\l& ``` The `VU` converts everything to uppercase. Then we run this: ``` :% " On every line: s/\v " Substitute: \a " A letter .{-} " Followed by as few characters as possible (\a|$) " Followed by either another letter or an EOL / " With: \l " The next character is lowercased & " The whole text we matched ``` --- Old/more interesting answer: ``` :se nows Vuò~h2/á ``` [Answer] # PHP, 71 Bytes ``` for(;a&$c=$argn[$i++];)echo ctype_alpha($c)?(ul[$k++&1].cfirst)($c):$c; ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVfJIzcnJ11EIzy/KSVFUsv6fll@kYZ2oppJsC1YQrZKprR1rrZmanJGvkFxSWZAan5hTkJGooZKsaa9RmhOtkq2trWYYq5eclllUXKIJErdSSbb@/x8A "PHP – TIO Nexus") [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~26~~ 24 bytes ``` qeu{_'[,65>&,T^:T{el}&}% ``` [Try it online!](https://tio.run/nexus/cjam#@1@YWlodrx6tY2Zqp6YTEmcVUp2aU6tWq/r/f0hGZrFCakVibkFOqkJ5Zk6OQnFJYlEJkFmSoZCTX55alJxYnAoA "CJam – TIO Nexus") ### Explanation ``` q e# Read all input. eu e# Uppercase it. { e# For each character: _ e# Duplicate it. '[,65>& e# Set intersection with the uppercase alphabet. , e# Length (either 0 or 1 in this case). T^:T e# XOR with T (T is initially 0), then store the result back in T. {el}& e# If The result of the XOR is true, lowercase the character. }% e# (end for) ``` [Answer] **C 64 bytes** ``` B;R(char *s){for(;*s=isalpha(*s)?(B=!B)?*s|=32:*s&=~32:*s;s++);} ``` Takes advantage of ascii encoding where upper and lower case letters are offset by 0x20. [Answer] # [Retina](https://github.com/m-ender/retina), 32 bytes ``` T`l`L 01T`L`l`[A-Z][^A-Z]*[A-Z]? ``` [Try it online!](https://tio.run/nexus/retina#fYtBC4IwAEbv@xUbUoegSOkYxRILYZSUdEhSlw0cbU22idWftxWdu3y8D97r01KUBEz9tCSOMjw@nbP8s6MvL/seH8I4BrMAePxeifbK4JwrYzWjcgFIhI9RIZ@FecqLEsZD3jAfFJjsthFCCCRJuIF7Vd2Me3CtNHSdeE1AWnMD2YPKRjDYcSGgsVRbh7aGQnVMV9Sw/1rbND8N@6vgDQ "Retina – TIO Nexus") First converts the input to uppercase, and then groups the input into matches containing up to two capital letters. The only time it will contain only one letter is if the last letter doesn't have a pair. Then it lowercases the first letter of each of these matches. The `01` in the second stage translates roughly to: do not change the behaviour of this stage based on the match number, but only apply the changes to the first character of each match. [Answer] ## PowerShell, 86 bytes ``` -join($args[0]|%{if($_-match"[a-z]"-and($i=!$i)){"$_".toupper()}else{"$_".tolower()}}) ``` Input is a `[char[]]` array. ### Comments in code for explanation ``` # Join the array of string and char back together. -join # Take the first argument and pass each element ([char]) down the pipe. ($args[0]|%{ # Check if this is a letter. Second condition is a boolean that changes at every pass # but only if the current element is a letter. If not the condition never fires if($_-match"[a-z]"-and($i=!$i)){ # Change the character to uppercase "$_".toupper() }else{ # Output the character to lowercase. # Special characters are not affected by this method "$_".tolower() } }) ``` [Answer] # Haskell, ~~105~~ 83 + ~~2~~ 4 + 1 byte of separator = ~~108~~ ~~86~~ 88 Bytes ``` import Data.Char f#(x:y)|isLetter x=([toUpper,toLower]!!f)x:(1-f)#y|1>0=x:f#y _#l=l ``` Function is `(1#)`, starts lowercase. [Try it online!](https://tio.run/nexus/haskell#bYqxCoMwFAB3vyKaDgptaaRTaARrF8FNOpVSgiY0oCY8nzSC/26XDh288e5W0zsLSG4S5bF4Swg0jT2fk8WMlUJUQLyIH2jvzinYo63sR8EzDHXiecwOOqHzwrKT8FzTOXjRTnRrL80gWkvchDVCNewYjfK6KMsoID/@0znd9tQMTTe1ilyMHRGU7LPtMWfXNFq/ "Haskell – TIO Nexus") ~~The sad thing is that this is longer than the Java and C# answers~~ Thanks to Ørjan Johansen for saving 22 bytes by merging three lines into one! [Answer] # [Perl 5](https://www.perl.org/), 24 bytes **23 bytes + 1 byte for `-p`.** Thanks to [@Dada](https://codegolf.stackexchange.com/users/55508/dada) for -2 bytes. ``` s/\pl/--$|?uc$&:lc$&/eg ``` [Try it online!](https://tio.run/##fYvNCoJAFEb3PsWI1s6soE2/mFgIUlLRKhKzIYeuzjB3xAyfvclF6zYf58D5BJUw0Xa7GM40uhcBruPY7arK7P4UunHpQ2vv6IehYbEyg@pOyZxxVJKmxdKIAu8cJEWTYFPcOKBlWv1rL/Gi/S4wTdOIY39LDjx7YmdkwyXpfvAeGKecIaGvtBBASc0ACKpUqg5VToDXVGYp0v9ZJcQv80br8YcLxXiJ2hFf "Perl 5 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, 17 bytes ``` s/\pL/<`>|uc$&/ge ``` [Try it online!](https://tio.run/##fYtBC4IwGIbv@xXfWHkrSeomgomFICUVnSKzNVLa2tgmZvTfbYfOnd7ngedVTPPFQLByCxM1GP@kcj@8RJ@Wjjz/zoYh3idZhuYBIs2T8vbGIGyksZpVIkJ5Gh/TUvSl6cVVckMw8c7jMs63mxRjjIoiWcNO0odxBiupwf34e4oOdWOAvSqhOIOu4RyMrbR1aGvgsmOaVob9z1qlflk8WwbwBQ "Perl 5 – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), 46 bytes ``` T`L`l T`l`L`.(?=([^a-z]*|[a-z][^a-z]*[a-z])*$) ``` [Try it online!](https://tio.run/nexus/retina#fYvNCoJAGEX38xQzWJFCQtKyH0wsBCkpaSOpkw049NmIo5jSu5uF61bnHji382M3BuTH0FOfblbTIKSz9qq9gy8G@W1VG6ldZ54tx0ELAyn8mUB1Z3jJhSwLRrM1cm3zYkdZE8kmuwmQClEm4Tgy3ePBJoQgz7P2@CSSh@wN70SB@x@0OvJTLjF70SwHhmsOgGVJi7KfZYpB1KxIqGT/syrPh8ycb40P "Retina – TIO Nexus") Includes test cases. [Answer] # PHP 5, 54 bytes ``` <?=preg_filter('/\pL/e','($0|" ")^a^aA[$i^=1]',$argn); ``` [Answer] # C#, 100 bytes ``` s=>{var r="";int m=0;foreach(var c in s)r+=char.IsLetter(c)?(char)(++m%2>0?c|32:c&~32):c;return r;}; ``` [Answer] # Groovy, 79 bytes ``` {x=0;it.toUpperCase().collect{(it==~/\w/)?x++%2?it:it.toLowerCase():it}.join()} ``` [Answer] # [Python 3](https://docs.python.org/3/), 192 bytes ``` x=list(input()) s=[] for i in x[1::2]: s.append(i) x.remove(i) s.reverse() while len(x)<len(s): x.append("") while len(x)>len(s): s.append("") for i in range(len(x)): print(end=x[i]+s[i]) ``` [Try it online!](https://tio.run/nexus/python3#ZZDNDoIwDMfvPkXDqYsJiR6J@CKEA0qBJliWFXBvj5OBidrD@pHfv1271NSAmwRNdoBgPu9ZR2Sx04jGrDXNi3INmsEBAwv44pRl5zJKQNPKWpIaOfLgU0ePYaa9oCGfySlhzJ8d9wQ9CXpzeTvdpgfl1ipJ/tHrF6q/6Od3rpKWMGp22jqWEQOe@4LLo4bHLOveS3W7hyO0Hb8A) ]
[Question] [ What general tips do you have for golfing in The Shakespeare Programming Language? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to SPL (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] (Well... since this is my *adopted* language 1, I feel like I'm obliged to add something here) ## Use short variable names Yeah, yeah, yeah, that's pretty standard to code-golf, you just use one-letter-length variable names, no news here. Or is there? Because the chaps that created SPL were wacky enough not to allow any name for their language's variables: they **must** come from Shakesperian plays which, in terms of character length, is a pain in the royal tush - but, if you're coding in SPL, you already know that. So, my advice would be to use characters with short names, like *Ajax*, *Ford*, *Page* or *Puck*, instead of *The Archbishop of Canterbury*, per instance. That's all I got, I'm afraid. --- 1- since my Java skills are equivalent of those of a newborn. [Answer] # Any Roman numeral is a valid scene number That means, that instead of: ``` Scene I Scene II Scene III Scene IV Scene V ``` You can do: ``` Scene L Scene I Scene C Scene X Scene V ``` [Answer] (after doing the previous one, I just remembered a few things) ## Choose your code carefully An example, to try and explain what this mean. ``` Ajax: You are as warm as a big red rich fair cute bold cat! ``` and ``` Ajax: Thou art as blossoming as an embroidered trustworthy bottomless peaceful charming handsome chihuahua! ``` produce the exact same result, which is make the *character* being spoken to assume the value 64 (since, assuming you [read my long battle with SPL](https://codegolf.stackexchange.com/a/44766/32139), you know that both lines are equivalent to 2\*2\*2\*2\*2\*2\*1); however, the first one has 59 bytes, while the second one has a bytecount of 107. Still, no one is going to be demented enough to enter a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge with SPL, so... [Answer] # Remove unneeded words Look at this (inserting newlines and whitespace for readability): ``` Puck:You is a big big cat! Open your heart! Ajax:Be you worse than I? If so, let us return to Scene V! If not, you is a cat. You is the sum of I and the sum of a cat and you Speak thy mind! [Exeunt] ``` Looks pretty golfed eh? Here's an even more stripped down unintelligible form: ``` Puck:You big big cat! Open heart! Ajax:Be you worse I? If solet usScene V! If notyou cat. You is the sum ofI the sum ofa cat you. Speak thy! ``` [Try it online!](https://tio.run/##VY/BCoMwDIbvPkW8Sx/Ay3Cwg6cNhIEMD10Xp9O1YlOmT981m0NXSAnJ9/ejdui9b0T2kFMiTk51icgUQZ6KQqFGbi4HTTgCIyD1DZiqIr7T0ji4tvdPKUlxBL9zHFBDg3JchpxO9whzSLzMaMPLu5XOa7CmRwJnv9pz/LfUhjgYFGKds7y1QA2CdU8wdb7pJcNs2wSKAWUXmDmOFgt/bkKnqfL@DQ) For reference, here's a list of easily removable words from code: * **Speak thy mind** -> **Speak thy** * **Open your heart** -> **Open heart** **\*** * **Listen to thy heart** -> **Listen tothy** * **Open your mind** -> **Open mind** **\*** * **You is a cat** -> **You cat** **\*** * Only applies to constants such as `big cat`, otherwise you still need the 'is' * **Let us return to** -> **Let us** * **Be X [op] than Y?** -> **Be X [op] Y?** * **You is [op] of X** -> **You is [op] ofX** * **You is [op] of X and Y** -> **You is [op] ofX Y** * **[Exeunt]** -> (removed entirely) Legend: * `X` and `Y` are constants like `cat`, `I` or `you` * `[op]` are operations like `nicer`, `the sum of` * **\*** means you can remove the punctuation if it's the last sentence of the play If I come across any others I'll add it to the list. For extra reference, here's the shortest header to start off a program: ``` ,.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck] ``` [Try it online!](https://tio.run/##Ky7I@f9fR88xK7FCRy@gNDkbSCampwJFkksUPK30gpNT81JBjGjXvJLUIgWQQoXEvBQFkNrY//8B "Shakespeare Programming Language – Try It Online") Add Page and Ford as extra characters as necessary. [Answer] # Use short words So here they are: * Use `a` instead of `an` or `the`, except the expressions `the sum of` and similar, since they won't work with `a`. * Use `am`, `be` or `is` instead of `are` or `art`. * Use `I` instead of `me` or `myself`. * Use `you` instead of `thee`, `thou`, `thyself` or `yourself`. * Use `big` for adjectives. * Use `cat` for positive numbers. * Use `pig` for negative numbers. * Use `zero` for zero. * Use `worse` for `A < B` (instead of `smaller` or `punier`). * Use `nicer` for `A > B` (instead of `better`, `bigger`, `fresher`, `friendlier` or `jollier`). * Character names: + 4 letters: Ajax, Ford, Page, Puck + 5 letters: Egeus, Helen, Julia, Lucio, Mopsa, Paris, Pinch, Priam, Regan, Robin, Romeo, Timon, Titus, Venus, Viola + 6 letters: Adonis, Aegeon, Alonso, Angelo, Arthur, Banquo, Bianca, Brutus, Cicero, Dorcas, Duncan, Emilia, Fenton, Hamlet, Hecate, Hector, Helena, Hermia, Imogen, Juliet, Lennox, Oberon, Olivia, Orsino, Portia, Thaisa, Thurio, Tybalt + 7 letters: Adriana, Aemilia, Agrippa, Antonio, Capulet, Cassius, Claudio, Dionyza, Escalus, Goneril, Horatio, Leonato, Luciana, Macbeth, Macduff, Malcolm, Mariana, Miranda, Octavia, Ophelia, Orlando, Othello, Pantino, Proteus, Publius, Shallow, Shylock, Slender, Solinus, Theseus, Titania, Troilus, Ulysses + 8 letters: Achilles, Beatrice, Benedick, Benvolio, Claudius, Cordelia, Cressida, Dogberry, Don John, Falstaff, Gertrude, Hermonie, Isabella, Lysander, Mercutio, Montague, Pericles, Polonius, Pompeius, Prospero, Rosalind, Stephano + 9 letters: Agamemnon, Antiochus, Autolycus, Balthazar, Brabantio, Cassandra, Cleopatra, Cornelius, Demetrius, Desdemona, Donalbain, Don Pedro, Ferdinand, Francisca, Hippolyta, King John, King Lear, Lychorida, Sebastian, The Ghost, Valentine, Vincentio + 10 letters: Andromache, Cymberline, Fortinbras, Friar John, King Henry + 11 letters: Mark Antony + 12 letters: Doctor Caius, King Richard, Lady Capulet, Lady Macbeth, Lady Macduff, Prince Henry, Queen Elinor + 13 letters: John of Gaunt, Julius Caesar, Lady Montague, Mistress Ford, Mistress Page + 14 letters: Friar Laurence, The Apothecary + 15 letters: Christopher Sly, Octavius Caesar + 17 letters: John of Lancaster, Mistress Overdone, The Duke of Milan + 18 letters: The Duke of Venice + 24 letters: The Abbot of Westminster + 28 letters: The Archbishop of Canterbury + If you really need more, you definitely should consider using the stack of each character. [Answer] # Use only one scene Normally, you can't reuse the first scene of an act, since it always has `[Enter Ajax and Puck]` first thing. However, you can preface this with `[Exeunt]` to be able to reuse the first scene of a play. `[Exeunt]` is one byte shorter than declaring a new scene, and jumping to an Act is two bytes less than jumping to a Scene. E.g: A simple cat program ``` ,.Ajax,.Page,.Act I:.Scene I:.[Enter Page and Ajax]Scene V:.Ajax:Open mind!Speak thy!Let usScene V! ``` [Try it online!](https://tio.run/##Ky7I@f9fR88xK7FCRy8gMT0VyE4uUfC00gtOTs1LBTGiXfNKUosUQJIKiXkpCiC1sRDZMCuwTiv/gtQ8hdzMvBTF4ILUxGyFkoxKRZ/UEoXSYqg6xf//E5OSAQ "Shakespeare Programming Language – Try It Online") To: ``` ,.Ajax,.Page,.Act I:.Scene I:.[Exeunt][Enter Page and Ajax]Ajax:Open mind!Speak thy!Let usAct I! ``` [Try it online!](https://tio.run/##Ky7I@f9fR88xK7FCRy8gMT0VyE4uUfC00gtOTs1LBTGiXStSS/NKYqNd80pSixRAihQS81IUQHpiQYSVf0FqnkJuZl6KYnBBamK2QklGpaJPaolCaTHYLMX//xOTkgE "Shakespeare Programming Language – Try It Online") [Answer] # You don't have to switch people in conditionals. For example, ``` Ajax:Is you better than the sum of a fat fat fat fat cat and a fat cat? Puck:If so,let us return to Scene I. ``` is longer than ``` Ajax:Is you better than the sum of a fat fat fat fat cat and a fat cat?If so,let us return to Scene I. ``` [Answer] # Remove redundant spaces Apart from the trivial ones (two adjacent spaces, adjacent to a punctuation, adjacent to a newline, at the end) (with some exceptions), the space after the following tokens can be removed: * `the sum of` * `let us` * `the ghost` ([like this](https://tio.run/##Ky7I@f9fR88xK7FCRy8kI1XBPSO/uAQokFyi4GmlF5ycmpcKYkS75pWkFinAVSTmpSiANMVygUgrLoXI/FKF5MQSPS6FSiArsShVoQSotrg0VyE/DcRKB@mCM4DK/AtS8xQyUhOLSvT@/09MSgYA)) (but who would use this character anyway) * `if so` and `if not` (remove the `,` after this, and don't need to add any space. Example: `if solet usact I`) * `listen to` (so `listen tothy` works, [like this](https://tio.run/##Ky7I@f9fR88xK7FCRy@gNDkbSCampwJFkksUPK30gpNT81JBjGjXvJLUIgWQQoXEvBQFkNpYEM/KJ7O4JDVPoSS/JKNSL78AyMxITSwq@f/f0MgYAA)) * and basically any multi-word [tokens](https://github.com/TryItOnline/spl/blob/master/makescanner.c#L110-L142). Note: This does not work with the [Perl interpreter](https://metacpan.org/pod/distribution/Lingua-Shakespeare/lib/Lingua/Shakespeare.pod). It's probably just an unintended effect caused by Flex's parsing behavior. The ["language standard"](http://shakespearelang.sourceforge.net/report/shakespeare/) is not clear about that. [Answer] # Jumps can be shorter You can use `return to` even if the scene is ahead, and vice versa. In fact, the interpreter doesn't even care if you omit it entirely. This means these four statements are 100% equivalent: ``` Let us proceed to Scene X. Let us return to Scene X. Let us Scene X. Let usScene X. ``` [Answer] The "let us return to scene X" can be used even if the character being spoken to is off stage. So instead of: ``` Puck:Am I as fat as the sum of a big big big big big big cat and a cat? Ajax:If not,let us return to scene III. [Exit Puck] [Enter Page] Ajax:You is a big big big big big big cat. ``` You can do: ``` Puck:Am I as fat as the sum of a big big big big big big cat and a cat? [Exit Puck] [Enter Page] Ajax:If not,let us return to scene III.You is a big big big big big big cat. ``` [Answer] # `If (so|not)` does not have to immediately follow the comparison. ``` Am I as big as you?You big big big big big cat.If so, you is the sum of you and a big big cat. ``` [Answer] # Instead of substracting, add constants ``` You is the difference between I and a big cat. ``` is longer than ``` You is the sum of I and a big pig. ``` [Answer] # Use 'square', 'cube', 'product' and 'factorial' The operations `the square of`, `the cube of`, `the factorial of` and `the product of` exist but are only mentioned in passing (if at all) in the documentation. They can save you bytes to define (large-ish) constants. For instance, to get the number 64, ``` a big big big big big big cat ``` is 5 bytes longer than ``` the cube ofa big big cat ``` Similarly, the shortest way of getting 49 is with \$49=7^2\$ i.e. ``` the square ofthe sum ofa big big big cat a pig ``` and you can get 24 as \$4!\$ i.e. ``` the factorial ofa big big cat ``` There can be situations where viewing a number as the product of two smaller existing constants can make `the product of` useful. Finally, note that there is also `the square root of`and `the quotient between`. Both round down, as the only type in SPL is integers: a short way to get 200 is as \$200 = \lfloor \sqrt{8!} \rfloor\$: ``` the square root ofthe factorial ofa big big big cat ``` [Answer] # Use shorter words Examples: `Thy` and `thyself` are shorter than `your` and `yourself`. `Is` is shorter than `are`. and more... [Answer] # Gotos aren't the only commands usable with `If (so|not)` ``` Am I as big as you?If so,you is the sum of you and a big big cat.If not,you is the sum of you and twice I. ``` [Answer] # All newlines are ignored ``` ,.Ajax,.Puck,.Page,.Act:.Scene:.[Enter Ajax and Puck]Ajax:You Puck.[Exeunt] ``` [Answer] # You don't need the ending `.` or `!`. [Try it online!](https://tio.run/##Ky7I@f9fR88xK7FCRy8gMT0VyE4uUfC00gtOTs1LBTGiXfNKUosUQEoUEvNSFECqYkE8q8j8UoXkxJL//xOTkgE "Shakespeare Programming Language – Try It Online") This can also be used before a `[`. (thanks jimmy23013) ``` ,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:You cat[Exeunt] ``` Examples: * `,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:You cat` * `,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Open mind[Exeunt]` Doesn't work in: * `,.Ajax,.Page,.Act I:.Scene I:[Enter Ajax]` (right after `Scene {number}:`) (however [this](https://tio.run/##Ky7I@f9fR88xK7FCRy8gMT0VyE4uUfC00gtOTs1LBTIqFKJd80pSixRAahQS81IUQMpiwVwrBf@C1DyFjNTEopL//w0B) works, I don't know why) * `,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Listen to your heart` (and shorter variants) * `,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Let us return to scene I` (and shorter variants) * `,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Recall` (only after empty `Recall`, `Recall x` or `Recall@` etc. works) * `,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Speak thy` (without `mind`) [Answer] # Use ‘twice’ and the distributive property Instead of: ``` You is the sum ofa big big big big cat a big big big cat. ``` Use: ``` You is twice twice twice the sum ofa big cat a cat. ``` This saves 2 bytes per `twice` since 2 uses of `big` is 8 bytes (counting spaces) and `twice` is only 6 bytes. [Answer] # Use `<` or `>` instead of `==` Not applicable to every situation, but it's quite a bit shorter: ### Puck == Ajax ``` Puck:Is I as bad as you? ``` ### Puck < Ajax or Puck > Ajax ``` Puck:Is I worse you? Puck:Is I nicer you? ``` 4 bytes shorter for both! ]
[Question] [ You'll be given the name of one of the 20 biggest objects in the Solar System. Your task is to return an approximation of its radius, expressed in kilometers. This is a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'") where your score consists of the length of your code (in bytes) multiplied by a penalty ratio \$\ge 1\$, based on your worst approximation. Therefore, **the lowest score wins**. *"As we travel the universe" is the last line of the song [Planet Caravan by Black Sabbath](https://en.wikipedia.org/wiki/Planet_Caravan), also later [covered by Pantera](https://youtu.be/kWChhdIgT6Q).* ## The Solar System objects Source: [Wikipedia](https://en.wikipedia.org/wiki/List_of_Solar_System_objects_by_size#List_of_objects_by_radius) NB: The rank is given for information only. The input is the **name** of the object. ``` n | Object | Radius (km) ----+----------+------------- 1 | Sun | 696342 2 | Jupiter | 69911 3 | Saturn | 58232 4 | Uranus | 25362 5 | Neptune | 24622 6 | Earth | 6371 7 | Venus | 6052 8 | Mars | 3390 9 | Ganymede | 2634 10 | Titan | 2575 11 | Mercury | 2440 12 | Callisto | 2410 13 | Io | 1822 14 | Moon | 1737 15 | Europa | 1561 16 | Triton | 1353 17 | Pluto | 1186 18 | Eris | 1163 19 | Haumea | 816 20 | Titania | 788 ``` Or as copy-paste friendly lists: ``` 'Sun', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Earth', 'Venus', 'Mars', 'Ganymede', 'Titan', 'Mercury', 'Callisto', 'Io', 'Moon', 'Europa', 'Triton', 'Pluto', 'Eris', 'Haumea', 'Titania' 696342, 69911, 58232, 25362, 24622, 6371, 6052, 3390, 2634, 2575, 2440, 2410, 1822, 1737, 1561, 1353, 1186, 1163, 816, 788 ``` ## Your score Let \$R\_n\$ be the expected radius of the \$n^{th}\$ object and let \$A\_n\$ be the answer of your program for this object. Then your score is defined as: $$S=\left\lceil L\times\max\_{1\le i \le20}\left({\max\left(\frac{A\_i}{R\_i},\frac{R\_i}{A\_i}\right)^2}\right)\right\rceil$$ where \$L\$ is the length of your code in bytes. *Example:* If the size of your code is \$100\$ bytes and your worst approximation is on the Moon with an estimated radius of \$1000\$ km instead of \$1737\$ km, then your score would be: $$S=\left\lceil 100\times{\left(\frac{1737}{1000}\right)^2}\right\rceil=302$$ The lower, the better. Recommended header for your answer: ``` Language, 100 bytes, score = 302 ``` You can use [this script](https://tio.run/##ZVNhT9swEP3eX3GqELUhS5OmSdMxmNDUbkyUTS3bl1IJqzHgKXUyx0GtoH9qP2F/rLtzR8fggy@553fvni/OD3EvqrlRpX2ji0xuNmM4hum0Oal100v6SdTtzLxp83NdKisNQf0wJGQibG2QE6edyFG@GaHrqul14ihxwIUsba0lIt2k45CBMPYONaKek/guXUESxG53JAxmUdQPKPso9GohMypHE4RcKis06fdiR5dmXpsVyXddxQeR56qyBSGhQ87wPUy3vUdFgcVhL@o5J7UpSoF5nDgrl0ZZtx/FEeVf85qEwjBNHN2oirLEbX4S9UJicRomO18K816azmZHjcb03APf909hhrM08metjGStm6rFfSNFNlS5nKz0nLXambxvVzZTGrdsMbFG6VvG/arMlWWtK4IXomQajk/gUPOjxk1hFsKirIM0Fg3VUmasw/1SZAOdsTBA2kIskROgl7GPJQMxv2NsqsVCemBEpupq5oHmpPHQAJgXuipy6efFLSPSk1afwyE04S2uQ9i2ZgaFS/xScpgXmJ5O9YwTjanqQlwww@HxEQy8w/bwHpgRVhVYEkIbAg@ag/H4y7jJSbOUWuR2BU8U9qzLSNg7PPqSbd2ia9ek2YZXJKVfkvjvXyhHxF37f3roY0d3TwI4HBxAh@/GGXOOU4S/1k6A5rm/D2w7V4d6UOZCS/ctcGRIX@NqqBscxFBp/FuIjYZeDvj6So/E0oeXx997QP4zB2s6JqLbNutrZ@g/ocm8MBIr51LlbO/hfA3L1yrcSbvzO945HNBxuBNcN2ReyVcW8ead6XuRqwyvb1XnFq8ukjebMAgaSRIH9Egpxv0eRvwlKXZjwrcwhqhLYLIL0VMIUwrEC6kidFiHAumnXVxh8Ac) to compute your score (first line = code length, next 20 lines = your outputs, from Sun to Titania). ## Rules * You may take the name of the object in either full lowercase, full uppercase or exactly as described above (title case). Other mixed cases are not allowed. * The input is guaranteed to be one of the 20 possible names. * You may return either integers or floats. In both cases, the penalty must be computed directly with these values (not rounded values in case of floats). * You must return positive values. * Empty programs are not allowed. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 3 bytes, score [3637](https://tio.run/##vVPRTtswFH3PV1xFiNqQpU1D0nQMJjS1GxNlU8v2UiphJQY8uU7mOKgV9Kf2Cfux7tpdGQPtdZXc9h6fe@7xifON3bE616Iyr1RZ8PV6DEcwnfqTRvlB2k/jg@4smPofm0oYri3UjyKLTJhpNHKSrBs7yhfNVFP7QTeJUwec88o0iiNykHYdMmDa3KJG3HMSX7lrSDuJ2x0xjVUc9zu2es/Ucs4L244mLHIhDFNWv5c4Otd5o5dW/sB1vGNSitqUFokccor/o2wze1SW2Bz14p5z0uiyYlgnqbNyoYVx@3ES2/qzbKxQFGWpo2tR2yp1mx9YM@fYnEXpoy@BdS/LZrNDz5ueBRCG4QnMMEvNvzdCc9K6rls01JwVQyH5ZKly0moX/K5dm0Io3DLlxGihbggN60oKQ1qXFp6ziig4OoZ9RQ@9OVugZgeHjMPrUg9YfkvIVLE5D0CzQjT1LABFLf/eA8hLVZeSh7K8IZYUVqwYqIL0KeyDD69x7QMhGjUrTJ8PZckMOZmqGXUMn247oo4FiKjP2TnRFB4eQMMbtAJvgWhmRIkaEbShE4A/GI8/jX1q9SuumDRL2FKImzhi5hZPtiAbz@j92bjM1W14whbqn@yeq@nPHzjAdWyn/ZmDzh673a8FKOztQddGPxQLXpCEUswYfps9Bpv27i6QTeoODaCSTHGDtQ0U6StcnrjGaIZC4Uti2Zje8/ivLtWILUJ4HsjOPfKfOFgBPldEN2NWV87QX0KTvNQcO3MuJNm5P1vB4qUKddLu/I53Bnv2ONQJrjwua/7CIl64U3XHpCjw1taNNHhjkbxex163g5////0L "JavaScript (Node.js) – Try It Online") ``` 2e4 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/3yjV5P///@rBpXnqAA "PowerShell – Try It Online") Very naive, boring, implementation; just returns `20000` no matter the input. Experimentation with things like special-casing the sun or using floating-point values instead of `2` all resulted in worse scores because the length of code increased enough to offset any size-comparison gains. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes, [score = 37](https://tio.run/##jVRdb9s2FH3XryCMopESj@G3yHXtUBTJ1iHJBrvbi2ughM00HGRKo6TAQeo/1Z/QP5Zd0mvWJXnYgyDdw3PPPbzi5Z/22var6Lvhu9Cu3d3dDL1Ei8VkPobJVBnFBVtOF5Nfxs4PLibIUJqQuR3GCBypGc@U36MNYz@ZMslVBi5cN4zBASIUy8iJjcMVaPA6S/zhcoIiMq@e2wgR54ak6CcbbjZundLBRELe@cGGpF/LTHdxNcabJC9yxhvbNL4f2oTQjLyFb6r3tc/bFpJpzevsZIxtZyGWKlt5F/2Q17nkKf6tGZMQpVplevR9ilRe/NmOGwfJmqp7Xx7iWuvl8kVRLM6mCGP8Gi2hl9H9NfroyoPL/qDC0dn1qW/c/CasyoPjtbs@7oe1D7A0tPMh@vCxrHDfNX4oD94neGO7MqCXr9BRqF4Ul23c2AFkMxQg6dRv3bpkFe7s@iSsS0qAtrFb4BDwMsOQcmJXV2W5CHbjpijatR/75RSFKmncFgit2tC3jcNN@7FMpK9apkJHaIK@h@cI7UuXEYQ7@FPutGkhfL0IyyrRSt9f2IsyVujTJxTRD1Ae/YjKaAffQgpFx4hM0eRkNvt1NqmSZueCbYYb9JVSflPl3A5XsPVtuXcLrnORyTF6RPLhIan68hnkEvG@/L964OOent8JqNDhIWLVfTtlVUEX0T/WXqHUz@fPUbnva0anqGtscPlfQMuAvoOn8JfQiFMfYFoSGww9bPCH9@HcbjF6uP1nt8D/xsEubRPQfZndh2zoP0LzVRsdZK6cb8pnt2c7tH2sUmXpvP/MO0OHaTtVFtwVrundI4tw8t6Ga9v4NRzffmwGOLpAvrvjolBakZpgpmFUKNdEFXBLSI6VkRIibjgrYEKVxITXCq4LYbSQBQwp5ZgayeuaC03ME4gSTONa1lwRzpVQhdRCYM6ErjkgVIiCM6OxUYYwIw0jioqC1UxhAd8aZpmzGuozUWssQU4aJbTg/wOAQWcY7goCEtJIplhBlWFYG1CEPSktAJEcqhu4ogzXmnBNCwrfmGhhiJZcyNqYgsKlgiFBUiMkIUo9gdTa4FpAzxRkCMGfQP4G) ``` OḌ“⁸|5/!‘%ƒị“RNFLOJMjs⁽\u[USJ‘1.1* ``` Input is in uppercase, output is the power of 1.1 with the least error. [Try it online!](https://tio.run/##JYuhbgJBEED9fAUVmIoSBB8wgQH2cjt7mZ1pcmltDcE1FU0Qd5iKolAIPqESQUJQJP2P2x/ZHql87@Wt3tbrz5xDd96l5pja82YyekjNYfi77y7fvRKel6Hwq/fUXl8/XiwWfR0/jR9zdzkNbl9p@zOoc47GUFjllAQiqgmDCbJFYKrUmIBQdAnPdHceJcICufY0I1CnyOBJpiY1TLEsXdQALoAPgYFMQoWg4rSnqrS@kbgISzRP@L87/AM "Jelly – Try It Online") ### How it works ``` OḌ“⁸|5/!‘%ƒị“RNFLOJMjs⁽\u[USJ‘1.1* Main link. Argument: s (string) O Ordinal; map the char in s to their code points. "ERIS" -> [69,82,73,83] Ḍ Undecimal; treat the result as an array of digits in base 10 and convert it to integer. [69,82,73,83] -> 69000+8200+730+83 = 78013 “⁸|5/!‘ Literal; yield [136, 124, 53, 47, 33]. %ƒ Fold the array by modulus, using the computed integer as initial value. 78013 -> 78013%136%124%53%47%33 = 32 “RNFLOJMjs⁽\u[USJ‘ Literal; yield [82, 78, 70, 76, 79, 74, 77, ... 106, 115, 141, 92, 117, 91, 85, 83, 74]. ị Retrieve the element from the array to the right, at the index to the left. Indexing is 1-based and modular. 32 = 16 (mod 16) -> 'J' = 74 1.1* Raise 1.1 to the computed power. 74 = 1.1**74 = 1156.268519450066 ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 90 bytes, [score = 97](https://tio.run/##dVTRbtpAEHznK1ZWFO4S19gYjGmaVFUFbaqQVpD2hSDlhC/JVebsns8RKOGn@gn9Mbq3lDRN1Aev2dnZ2fFy9ndxJ6q5UaV9pYtMbjZjOIbp1JvU2vOTfhJ32jN/6n2qS2WlcVA/ihwyEbY2yOmm7ZgoX43QdeX57W6cEHAuS1triUgnaRMyEMbeokbcI4lvkhqSsEvVkTCYxXE/dNkHoVcLmbl2NOGQC2WFdvq9LtGlmddm5eQ71PFe5LmqbOGQiJBT/B2l29mjosDmqBf3yEltilJg3k3IyoVRlupxN3b5l7x2QlGUJkQ3qnJZQsWPol5IbE6j5NGXwryXprPZUaMxPfMhCIJ3MMNdGvmjVkay5nXV5IGRIhuqXE5Wes6arUzetSqbKY0lW0ysUfqG8aAqc2VZ89LBC1EyDccncKj5UWMhlqgZ4pBxcF2YgZjfMjbVYiF9MCJTdTXzQXPHv28AzAtdFbkM8uKGOVJQimygM9bncAgevMbrEBgzqFni9uUwL4Rl76Z6xonh8V1HFDqAqepcnDPD4eEBDLxBK/AWmBFWFagRQQtCH7zBePx57HGnX0otcruCHYXRxJGwt/hkS7b1jN6fjUspb8ETttL/Zfco579@4gDq2E37OwedPXbT3QEcDg6g7VY/VEuZsS7nuGP4Y/YE3Lb394Ftt06oD2UutLSYu4UifY1XQ13jaoZK40vi2Li95@u/utQjsQzg@UL27pH/xMEa8H9FdDtmfUWG/hGazAsjsXMuVc727s/WsHypwkmanp94Z3DgHoeT4Loh80q@sIgH7lTfiVxleGqrOrd4YpG82fTDhvsUhO7Wx4jvPEZ80V3sJA6nYoghJjChOpV3IUpd6LngqhFh7V1It9dv) ``` s->("ýCĄ (ᬺ!˂Fɍ".charAt(s.substring(2).chars().sum()%96%49%25)-7)*100 ``` [Try it online!](https://tio.run/##lVFNa1QxFF0@mE0XRbSrXh88SErmMS1@0I4tlDKtFUaFGd2Iiztv8tqMeUlIbgYGmY106z/xFwiudCP@Cn/JGN/UTRXRVbjn3JNzcjLDOXZn0zcr1TjrCWZpLiMpXdbRVKSsKXf6HRcnWlVQaQwBhqgMvO0AXKOBkNIxt2oKTeLYiLwyF69eA/qLwNtVgLE9N3R6feej9coR1HC4Ct0jlm/d/vxp887Jl6vN7BZss@3vHz5uZHezb@82TrPs6/u8rC7RHxMLZYiT0KrZHm/RwHgCG8aL/QfFvf1i7z7vPuQ7u73eqt9az9FDJbUMpFA/m8xkRQEOIR9FI55Ep0h6MUKK3ogXHk0M4ql0FI0UA/R0KV7Kn9gwOYkzNItGTqUYK0IjhtJX0S/ECWqtAllxbsXQWiMG0VuHYuwVpem5jokbeBXEY4yNxLVcYV4GpxWxXOS832nD1tazPwQ@@O0Fv4oFGC0Cyaa0kUqXiqGa5cVuLxxAMS1MLm4qBdQlOqcXxyF9CbvBcr4ubfl/aeDvcdZB/tV32VmufgA "Java (JDK) – Try It Online") * This entry uses both undisplayable and multi-byte Unicode characters (but Java accepts them nevertheless). Check the TIO for the accurate code. * The input must be title-case. * This code rounds the values to the best multiple-of-100 (sometimes up, sometimes down) so that the last two digits can be skipped when encoded, and the value can then be approximated by multiplying by 100. * This entry uses various hashes to fit a 25 codepoints string (shortest string I could find). ## Credits * -48 score (-45 bytes) thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) by encoding the radiuses (divided by 100) directly in a `String` instead of hardcoding them in an explicit `int` array.. [Answer] # Wolfram Language ~~114 103 97 88 86~~ 82 bytes. score = ~~114 103 97 89 87~~ 83 points ``` (#&@@EntityValue[Interpreter["AstronomicalObject"]@#,"Radius"]/._String->507)1.61& ``` At least 6 points saved thanks to `Dennis`, several more thanks to `lirtosiast`, and 6 more thanks to `user202729`. Although Mathematica can fetch solar system data (as well as much additional astronomical data), some minor tweaks are needed, as explained below. `Interpreter[#,"AstronomicalObject"]&` will return the entity (i.e. the machine computable object) associated with the term represented by `#`. `EntityValue[AstronomicalObject[],"Radius"]` returns the radius, in miles, of the entity. In the case of "Haumea", the value, 816.27 (i.e. 507\*1.61), is returned. Multiplication of the radius by `1.61` converts from miles to km. Decimal values, rather than integers, account for much less than 1% error, even in the most extreme case. `[[1]]` returns the magnitude without the unit, km. This was later changed to `#&@@`, yielding the same result. [Answer] # [Python 3](https://docs.python.org/3/), score 95, 95 bytes ``` lambda n:ord("ؙҢ򪀖ਏ𑄗ാᣣ४ঈ挒ឤ?̰ҋ??ۉՉ怮ܞ੊̔"[int(n,35)%87%52%24-1]) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKr8oRUPpxsxLiz6tapj2YEX/h4kt0x9s2fdw8eIHS1c9WNbxrGfSw3lL7M9suNRtb/@ud8ftzqudzxrW3Zn3YGXXmSlK0Zl5JRp5OsammqoW5qqmRqpGJrqGsZr/0/KLFPISc1MVMvMUNNSDS/PUdRTUvUoLMktSi0DM4MSS0iKwYGhRYl5pMYjll1pQUpqXCmK6JhaVZIAYYalQSd/EIjDtnphXmZuaAlYVklmSCDbDN7UoubSoEsR0TszJySwuyQexPcGkb34@WJFraVF@QSJYX1FmCUQsIKcUotS1KBNsvEdiaW5qItzwzER1TSsuBYWCIpA/0zRAXtLU/A8A "Python 3 – Try It Online") --- # [Python 3](https://docs.python.org/3/), score 133, 133 bytes ``` lambda n:int(f'00e0{10**18+10**6}10x1h2411j4?00??811i1207wazxmwuvko?mw??xc1ze1ldyujz6zysi4?ob??k9lym6w'[int(n,35)%87%52%24-1::23],36) ``` [Try it online!](https://tio.run/##PZDLTsMwEEX3fIU3VZJSJDtJ0xIJeYEiHlIRUoENsJg2juI2tiPXJg/EtwfZRWxmju7cudJMO5hayWSqbj6mBsSuBCRzLk1YBRgz/E3wfE7Wl65lPwT3pI5TQg4pxZjSNSGcxHjVwdiLzn4dFRUdpf2ejIw05WAPYzYOJ55StaP0eN0MIuuCdxcvF8kymq1Xs2U8i9Mrkudx8rlIsmiqlEYSBENcojDYWhksUPBoW26YdrgFY7UXXzVIe3L0xFpjJXNYgDa1gzf2N9yA9v0O5CBY6V0v3IDP2DC9t3pweAtNw09GOX7wdaOUNxVWqxb8nubmrD039mwtNPfx92AFg/9wDkGUXyDUav/N0J0URdMv "Python 3 – Try It Online") [Answer] # Powershell, ~~150~~ 141 bytes, score ~~163~~ 153 ``` ($args|% t*y|?{'Su6963J699S582U253N246Ea63V60Ma33G26Ti25Me24C24I18M17Eu15T13P12E12H8Titani8'-cmatch"$(($y+=$_))(\d+)"}|%{100*$Matches.1})[-1] ``` [Try it online!](https://tio.run/##jZLdbuIwEIXveQorCtuEAsV24oRKaFeqUH@06VaC9qZbVV5wi1chiRxbLQKenXUSE9O79U2c@TznzIymyD@YKFcsTQ/uG5iA7cFzqXgvd10ge5vd9@3ZTJExwXdkPJ6FMXpEIb5HAZlSgp/IKKEYXyMy5yhMGAquUHAL4wRGUwXDOcQPEE0huonnXNKMx2eDxZrKxcpxPc/dnE/cV9/3fi/PfWe/627haNRzk4qzcgj3/vMAvhz2HbdgGU3lRhf3w@sAffqeM1OZA@rTB1V5AfKP6E4VXDLhVEizMYQtmlGpRJ2okW4G26xHQTNVGqR7JBbds0KqjDWCunVk0ZQKuXKaMrQZjqzXEzN6DRqFNiuhoiE1wng8atE1zTZrttRmFUK6sRbVM2wFURiFVpCJhRIbx6AgsIJXNE15KXMjGECLbnMzwhrB@KSvJM8zWyGMcGRbViIvqHNEIbEtzwWXedYiHOIWPaRK5m3xEMbECgp@Mg0Iic26oWrNWi8QQ/J1GpyalkEUx37HBzvQBdv6iVv2XfZZsIVkS7057msTFaxUqdSBb3rb3dIEqeS5jj3r5Vu9XF4m9NMzLy9akT5orxcG@iZ90ij0mo8JdvTmlgvBC/mTZe9yVRXxNpznMyl49u75QxMeANSuuDbWz7zj7y5htFSCDX79@auNwUBzvlZrf2gulUMuWCX9xaoHThQ7zv@8cg7/AA "PowerShell – Try It Online") Test script: ``` $f = { ($args|% t*y|?{'Su6963J699S582U253N246Ea63V60Ma33G26Ti25Me24C24I18M17Eu15T13P12E12H8Titani8'-cmatch"$(($y+=$_))(\d+)"}|%{100*$Matches.1})[-1] } $penalty = @( ,("Sun" , 696342) ,("Jupiter" , 69911) ,("Saturn" , 58232) ,("Uranus" , 25362) ,("Neptune" , 24622) ,("Earth" , 6371) ,("Venus" , 6052) ,("Mars" , 3390) ,("Ganymede" , 2634) ,("Titan" , 2575) ,("Mercury" , 2440) ,("Callisto" , 2410) ,("Io" , 1822) ,("Moon" , 1737) ,("Europa" , 1561) ,("Triton" , 1353) ,("Pluto" , 1186) ,("Eris" , 1163) ,("Haumea" , 816) ,("Titania" , 788) ) | % { $s,$expected = $_ $result = &$f $s $ratio = [Math]::Max($result/$expected, $expected/$result) $ratio*$ratio } $scriptLength = $f.ToString().Length - 2 # -4 if CRLF mode $penaltyMax = ($penalty|Measure-Object -Maximum).Maximum $score = $scriptLength * $penaltyMax "$score = $scriptLength * $penaltyMax" ``` Output: ``` 152.731283431953 = 141 * 1.08320059171598 ``` Explanation: * Names contain letters only, radiuses contain digits and dots. So we can write all the data in a data string and perform a regexp search. * The script searches for all substrings from left to right and takes the last result found. * The input must be title-case to reduce the data string. * The `end of line mode` is LF only. Example: ``` Titania Triton Titan -------------- ------------- ------------- T -> 1.3 T -> 1.3 T -> 1.3 Ti -> 2.5 Tr -> Ti -> 2.5 Tit -> Tri -> Tit -> Tita -> Trit -> Tita -> Titan -> Triton -> Titan -> Titani -> .8 Titania -> Result is .8 Result is 1.3 Result is 2.5 ``` --- # Powershell, 178 bytes, score 178 ``` ($args|% t*y|?{'Su696342J69911S58232U25362N24622Ea6371V6052Ma3390G2634Ti2575Me2440C2410I1822M1737Eu1561T1353P1186E1163H816Titani788'-cmatch"$(($y+=$_))(\d+)"}|%{+$Matches.1})[-1] ``` [Answer] # Mathematica, 57 bytes, [score](https://tio.run/##dVTtThw3FP0/T2GtojADW@Pvj6ZJFUXQpgJaQdo/m5Vi7ZrgavBsPTMIRHipPEJejF6bkqbsdNEC9/rcc88947l/uivXr1LYDN/Fbu3v70/RS7RYzM7GOJsrq7hgy/li9su4CYNPOWUpzZkzN4wJMNIwXiC/JxfHfjZnkquSOPGbYYweMkKxkjlwabgADq4LxR@@FCgiy@mxSxBxbkmOfnLx5tKvczmIyJl3YXAx82tZ4D6txnST6UWpeOPaNvRDlzO0ZN7C/9Q89D7uOiimmuuiZEzdxkEsVZHyLoWhnHPJc/xbO2YiSo0q8BT6HKly@LMbLz0UG6q@6goQa2OWyxdVtTiaI4zxa7QEL5P/awzJ1zvn/U6Dk3frw9D6s5u4qnf21/5qvx/WIcLR0J0NKcSPdYP7TRuGeud9Tl@6TR3Ry1doLzYvqkt3DZwEmpzi8y4duNVFXS@iu/RzlNw6jP1yjmKT8bcVQqsu9l3rcdt9rDMIb9z6IK5r26A9NEPfw3cP1XUCzg247w/bzg3160VcNgUxax4rKMmJOvQn7qRODfr0CSX0A0hBP6I6uSF0wEHRPiJzNDs4Pf31dNZk/o2Prh1u0COkLh2P3XABk13XD5pB@5N2psT76Bt0iP@L1iVuvnyGBqXisdu/fUDZ1@ryNycatLuLWLb@MFz7dS2bBjxG/4h9hbLbz5@j@sH1kp2jTeuiHyDOhgL8Dr5VOAdrDkOElySjwb2n9n94H4/dNUZPDXl2C/hvFNwheK6QfWhz96EI@g/R2apLHipXPrT1s9ujO3S9zdIU6jJ/wR2h3TxOUwjvKt/2fksiXLi38cq1YQ23th/bAW4sgO/vpa6UlZoQTLY@tMorgWC7/anKbpiqoQreSm0EMZJTTgnTqip7YwJMpCRaC03gGFaBYpLJKq8UOtHTWAUvv5GMWCDWjEkF2mHfALF@CpZUUq4oFUZo0CA5h2GIpNjILRHCaiWMtppqYoSSXLKKc2OxnBoP8Ao0gHCYUmeTQDnFbAorhdLZBWU1gQkZq/KGmzKCUsaosEzAfAwEEWPBCG6x2jaCMsMJFTATo0oKwSVogLWI2cSD0txqS4U2inD4bbmqYG1SLOyWBiWIhn1suIXhwTAYsspLFYspuYJTDUYYpYUyxBpawcIl2EzMJgj8UEM5V0YzwwSrYBkzrLaxVlDFrDRAyZUigLAVbGqLt@US4OHUwo2AWyThIQuQAGt8yl4OT0oRqqXUmjNJDLMVrPgK1voUM7GWESGs0VksV1D2Nw) = ~~62~~ 58 *-4 bytes/score thanks to [lirtosiast](https://codegolf.stackexchange.com/users/39328)!* ``` #&@@WolframAlpha[#<>" size km","Result"]]/._Missing->816& ``` Just does a Wolfram Alpha lookup for the mean radius. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes, [score = 31](https://tio.run/##jVRdb9s2FH3XryCMopESj@G3yHXtUBTJ1iHJBrvbi2ughM00HGRKo6TAQeo/1Z/QP5Zd0mvWJXnYgyDdw3PPPbzi5Z/22var6Lvhu9Cu3d3dDL1Ei8VkPobJVBnFBVtOF5Nfxs4PLibIUJqQuR3GCBypGc@U36MNYz@ZMslVBi5cN4zBASIUy8iJjcMVaPA6S/zhcoIiMq@e2wgR54ak6CcbbjZundLBRELe@cGGpF/LTHdxNcabJC9yxhvbNL4f2oTQjLyFb6r3tc/bFpJpzevsZIxtZyGWKlt5F/2Q17nkKf6tGZMQpVplevR9ilRe/NmOGwfJmqp7Xx7iWuvl8kVRLM6mCGP8Gi2hl9H9NfroyoPL/qDC0dn1qW/c/CasyoPjtbs@7oe1D7A0tPMh@vCxrHDfNX4oD94neGO7MqCXr9BRqF4Ul23c2AFkMxQg6dRv3bpkFe7s@iSsS0qAtrFb4BDwMsOQcmJXV2W5CHbjpijatR/75RSFKmncFgit2tC3jcNN@7FMpK9apkJHaIK@h@cI7UuXEYQ7@FPutGkhfL0IyyrRSt9f2IsyVujTJxTRD1Ae/YjKaAffQgpFx4hM0eRkNvt1NqmSZueCbYYb9JVSflPl3A5XsPVtuXcLrnORyTF6RPLhIan68hnkEvG@/L964OOent8JqNDhIWLVfTtlVUEX0T/WXqHUz@fPUbnva0anqGtscPlfQMuAvoOn8JfQiFMfYFoSGww9bPCH9@HcbjF6uP1nt8D/xsEubRPQfZndh2zoP0LzVRsdZK6cb8pnt2c7tH2sUmXpvP/MO0OHaTtVFtwVrundI4tw8t6Ga9v4NRzffmwGOLpAvrtjulBakZpgpmFUKNdEFXBLSI6VkRIibjgrYEKVxITXCq4LYbSQBQwp5ZgayeuaC03ME4gSTONa1lwRzpVQhdRCYM6ErjkgVIiCM6OxUYYwIw0jioqC1UxhAd8aZpmzGuozUWssQU4aJbTg/wOAQWcY7goCEtJIplhBlWFYG1CEPSktAJEcqhu4ogzXmnBNCwrfmGhhiJZcyNqYgsKlgiFBUiMkIUo9gdTa4FpAzxRkCMGfQP4G "JavaScript (Node.js) – Try It Online") ``` “__ʋ7ṗ“RUu⁽NM\sOSJj[FL‘ḥ1.1* ``` This uses a configurable hashing built-in that I added to Jelly at @lirtosiast's suggestion. Input is in titlecase, output is the power of 1.1 with the least error. [Try it online!](https://tio.run/##y0rNyan8//9Rw5z4@FPd5g93Tgcyg0JLHzXu9fONKfYP9sqKdvN51DDj4Y6lhnqGWv8f7t6icLj9UdMahcj//4NL87i8SgsyS1KLuIITS0qL8rhCixLzSou5/FILSkrzUrlcE4tKMrjCUkFivolFxVzuiXmVuakpqVwhmSWJeVy@qUXJpUWVXM6JOTmZxSX5XJ75XL75@XlcrqVF@QWJXCFFmSVAXkBOKVDOtSizmMsjsTQ3NRGiPTMRAA "Jelly – Try It Online") ### How it works This answer consists of merely two parts. * First, `“__ʋ7ṗ“RUu⁽NM\sOSJj[FL‘ḥ` uses the new built-in to map each of the 20 possible inputs to 15 different integers. * Then, `1.1*` elevates 1.1 to the computed power. `“__ʋ7ṗ“RUu⁽NM\sOSJj[FL‘` is a literal; every non-quote character is replaced by it's 0-based index in Jelly's code page, yielding \$[95, 95, 169, 55, 242], [82, 85, 117, 141, 78, 77, 92, 115, 79, 83, 74, 106, 91, 70, 76]\$. The hashing built-in `ḥ` first maps \$[95, 95, 169, 55, 242]\$ to an integer by incrementing each number, then treating the result as the bijective base-250 digits integer and adding \$1\$. This yields \$376510639244\$. By halving and flooring this integer until the result is \$0\$, we get the sequence \$[376510639244, 188255319622, 94127659811, 47063829905, \dots, 5, 2, 1, 0]\$, which has the forward differences \$[188255319622, 94127659811, 47063829906, \dots, 3, 1, 1]\$. Next, we generate 64 64-bit integers by applying [SHAKE256-4096](https://en.wikipedia.org/wiki/SHA-3#Instances "SHA-3 - Wikipedia") to the string representation of the internal representation of `ḥ`'s right argument, then chopping the resulting 4096 bits into 64 64-bit chunks. `ḥ` now computes the dot product of the 39 differences and the first 39 generated 64-bit integers, modulo \$2^{64}\$. This yields an integer in \$[0, 2^{64})\$. The list \$[82, 85, 117, 141, 78, 77, 92, 115, 79, 83, 74, 106, 91, 70, 76]\$ has length 15, so we multiply the generated integer by 15 and take the 64 higher bits of the result. This yields an integer in \$[0, 15)\$, which we use to index into the list. To find the appropriate hash configuration, I've used a brute-forcer in C that is [part of the Jelly repo](https://github.com/DennisMitchell/jellylanguage/blob/master/utils/findhash2.c "jellylanguage/findhash2.c at master · DennisMitchell/jellylanguage"). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score ~~100~~ ~~[66](https://tio.run/##dVTRbtpAEHznK1ZWFO4S19gYjGmaVFUFbaqQVpD2hSDlhC/JVebsns8RKOGn@gn9Mbq3lDRN1Aev2dnZ2fFy9ndxJ6q5UaV9pYtMbjZjOIbp1JvU2vOTfhJ32jN/6n2qS2WlcVA/ihwyEbY2yOmm7ZgoX43QdeX57W6cEHAuS1triUgnaRMyEMbeokbcI4lvkhqSsEvVkTCYxXE/dNkHoVcLmbl2NOGQC2WFdvq9LtGlmddm5eQ71PFe5LmqbOGQiJBT/B2l29mjosDmqBf3yEltilJg3k3IyoVRlupxN3b5l7x2QlGUJkQ3qnJZQsWPol5IbE6j5NGXwryXprPZUaMxPfMhCIJ3MMNdGvmjVkay5nXV5IGRIhuqXE5Wes6arUzetSqbKY0lW0ysUfqG8aAqc2VZ89LBC1EyDccncKj5UWMhlqgZ4pBxcF2YgZjfMjbVYiF9MCJTdTXzQXPHv28AzAtdFbkM8uKGOVJQimygM9bncAgevMbrEBgzqFni9uUwL4Rl76Z6xonh8V1HFDqAqepcnDPD4eEBDLxBK/AWmBFWFagRQQtCH7zBePx57HGnX0otcruCHYXRxJGwt/hkS7b1jN6fjUspb8ETttL/Zfco579@4gDq2E37OwedPXbT3QEcDg6g7VY/VEuZsS7nuGP4Y/YE3Lb394Ftt06oD2UutLSYu4UifY1XQ13jaoZK40vi2Li95@u/utQjsQzg@UL27pH/xMEa8H9FdDtmfUWG/hGazAsjsXMuVc727s/WsHypwkmanp94Z3DgHoeT4Loh80q@sIgH7lTfiVxleGqrOrd4YpG82SRRw30KwhBvfYz4zmPEF93FTuJwKoYYYgITqlN5F6LUhZ4LrhoR1t6FdHv9Bg)~~ ~~[60](https://tio.run/##dVTbTttAEH3PV4wsRNbgOnYcX1IKVVUlLRWhVUL7EiKxihfYylm76zVKBPmpfkJ/LJ2dNJSC@uBx5syZM8eTtb/zO17PtazMK1XmYrMZwzFMp86kUY6X9JOo1515U@dTU0kjtIX6YWiRCTeNRk6cdSOifNVcNbXjdeMoIeBcVKZRApFe0iVkwLW5RY0oJYlvghqSIKbqiGvMoqgf2OwDV6uFyG07mrDIhTRcWf00JrrQ80avrHyPOt7zopC1KS0SEnKKv8NsO3tUltgcplFKThpdVhzzOCErF1oaqkdxZPMvRWOFwjBLiK5lbbOEih95sxDYnIXJoy@JeZpls9lRqzU988D3/Xcww11q8aORWrD2dd12fS14PpSFmKzUnLU7ubjr1CaXCkumnBgt1Q1z/boqpGHtSwsveMUUHJ/AoXKPWgu@RM0Ah4z961IP@PyWsaniC@GB5rls6pkHyrX8@xbAvFR1WQi/KG@YJfkVzwcqZ30XDsGB13gdAmMaNSvcvhgWJTfs3VTNXGI47q4jDCzAZH3Oz5l24eEBNLxBK/AWmOZGlqgRQgcCD5zBePx57LhWvxKKF2YFOwqjiSNubvHJlmzrGb0/G5dR3oEnbKn@y04pd3/9xAHUsZv2dw46e@ymuwVcODiArl39UC5FzmLXxR3DH7MnYLe9vw9su3VCPagKroTB3C4U6Wu8WvIaVzOUCl8Sy8btPV//1aUa8aUPzxeyd4/8Jw7WgP8rotsx6ysy9I/QZF5qgZ1zIQu2d3@2huVLFZek6fmJdwYH9nFcEly3RFGLFxbxwJ2qO17IHE9t3RQGTyySN5s4adlPQRDgrY8R33mM@KLb2EssTsUAQ0RgQnUq70KY2ZDaYKshYd1dyLbXbw)~~ [56](https://tio.run/##dVTbTttAEH3PV4wsRNbgOr7EjlMKVVUlLRWhVUL7EiKxihfYylm76zVKBPmpfkJ/LJ2dNJSC@uBx5syZM8eTtb/zO17PtazMK1XmYrMZwzFMp86kUY6X9tO4G828qfOpqaQR2kL9MLTIhJtGIyfJopgoXzVXTe14URKnBJyLyjRKINJNI0IGXJtb1Ih7JPFNUEMaJFQdcY1ZHPcDm33garUQuW1HExa5kIYrq99LiC70vNErK9@ljve8KGRtSouEhJzi7zDbzh6VJTaHvbhHThpdVhzzJCUrF1oaqsdJbPMvRWOFwjBLia5lbbOUih95sxDYnIXpoy@JeS/LZrOjVmt65oHv@@9ghrvU4kcjtWDt67rt@lrwfCgLMVmpOWt3cnHXqU0uFZZMOTFaqhvm@nVVSMPalxZe8IopOD6BQ@UetRZ8iZoBDhn716Ue8PktY1PFF8IDzXPZ1DMPlGv59y2AeanqshB@Ud4wS/Irng9UzvouHIIDr/E6BMY0ala4fTEsSm7Yu6maucRw3F1HGFiAyfqcnzPtwsMDaHiDVuAtMM2NLFEjhA4EHjiD8fjz2HGtfiUUL8wKdhRGE0fc3OKTLdnWM3p/Ni6jvANP2FL9l92j3P31EwdQx27a3zno7LGb7hZw4eAAIrv6oVyKnCWuizuGP2ZPwG57fx/YduuEelAVXAmDuV0o0td4teQ1rmYoFb4klo3be77@q0s14ksfni9k7x75TxysAf9XRLdj1ldk6B@hybzUAjvnQhZs7/5sDcuXKi5J0/MT7wwO7OO4JLhuiaIWLyzigTtVd7yQOZ7auikMnlgkbzZJ1LKfgiDAWx8jvvMY8UW3sZtanIoBhpjAlOpU3oUws6Fng62GhEW7kG2v3w) (~~100~~ ~~61~~ ~~56~~ 52 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) ``` •1∞²îc|I‰∍T‡sÇ3¡ò½в…»Ë••1ë£ñƒq£û¿’…•S£I¦¦ÇO96%49%èт* ``` Port of [*@OlivierGrégoire*'s Java answer](https://codegolf.stackexchange.com/a/177028/52210), so if you like this first answer, make sure to upvote him as well! Input in titlecase. [Verify all test cases.](https://tio.run/##JYs/S8NAGMb391OEQBfpoKiBdukgQStEhUQnl7fxwIP0Lt4fIdAhONiCuHRzEWohFATRrEWEO3DWr3BfJKY4PTzP7/dwiSNKGn9UKCL73n7Q9WTKBel7wbZ/CZPbYuB77n7u@YPGlS87bvZsavuWToaufHezx8SVC2mnu2Zha/P5U7uyMmv70Kob276apf34nt@0sTZfrnxqeQtisyxMZSo7Pe0Fnb1ex65@77aabhNrBsc6p4oIiFFpweBcINMSTkiuNCMQolDXcEE2W4RCwiGyYkyuCCRUIYOIiFSLAg4wy6hUHIYcIs4ZhFrwHCERVLXtLNMtCwWVcIR6TPD/TvEP) --- # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score ~~100~~ 99 (~~100~~ 99 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) ``` •*Òâ%ÌÜS…Ùb‹Úi{e!]ɸ·vÌBUSηHã£āðxyµŠ••3«8¹ØмS7Ç•S£.•WùηƵ@,Sº,ûεβʒóÃX\¹Θäáá’Ý)”Ωož∞-z.A±D•3ôI2£Iθ«kè ``` Input in full lowercase. Outputs the exact radius, so no penalty is added. [Verify all test cases.](https://tio.run/##JUw7S8NQGN3vr4gBByWWqoPiUhUH9yA61OG2XuzV5ibcRzHqEBF8QKdOrVixjYjSxVdpo@JwP@vgEPwN@SM1VThwXpzjClygZGgWfEnEgjGdzVqGKLqc/Gkzjw4rfs40kpOaYeaGSdCehBq0x6EKl3YS3EKjkAQRXNADMrYJ57qvexWoLq/ZcW8VQh1@HsHDnq@7g@t0mmJWd@Z1BPWfd3sOTtPA1mEmpXWI4t5Xd9Gy9asFb3E3fvquwTMcb@R1FNfhBlrQSoIGNCeSoBnfu4OP5Oxqaj@zpB9XRr/w4s/o0I/7urMLd0NrKBRDO8qjknAksFScIcUxUwIx4knFCCKYyxKqkFHmYC7QNma@Q7YIklRihhzCi4r7qIjLZSqki6iLHNdliCjuehhJTmXqvLJKO8KpQCWsHIL/5xT/Ag) **Explanation:** ``` •*Òâ%ÌÜS…Ùb‹Úi{e!]ɸ·vÌBUSηHã£āðxyµŠ• # Compressed integer 696342699115823225362246226371605233902634257524402410182217371561135311861163816788 •3«8¹ØмS7Ç• # Compressed integer 65555444444444444433 S # Converted to a list of digits: [6,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,3,3] £ # The first integer is split into parts of that size: ["696342","69911","58232","25362","24622","6371","6052","3390","2634","2575","2440","2410","1822","1737","1561","1353","1186","1163","816","788"] .•WùηƵ@,Sº,ûεβʒóÃX\¹Θäáá’Ý)”Ωož∞-z.A±D• # Compressed string "sunjursanursneeeahvesmasgaetinmeycaoioomoneuatrnploershaatia" 3ô # Split into parts of size 3: ["sun","jur","san","urs","nee","eah","ves","mas","gae","tin","mey","cao","ioo","mon","eua","trn","plo","ers","haa","tia"] I2£ # The first two characters of the input Iθ # The last character of the input « # Merged together k # Get the index of this string in the list of strings è # And use that index to index into the list of integers # (and output the result implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compression used works. [Answer] # [Python 2](https://docs.python.org/2/), 155 bytes, [score](https://tio.run/##dVTRTttAEHy/r1hZiJzBdeIYO04pVFWVtFSEVgntS4jEKT7gKufsns8oEeSn@gn9sXT3UigF9cFKdm52dm7jyXdxK@q5UZV9pctcbjZjOILp1Js02gvSfhofdGfB1PvUVMpKQ1A/igiZCNsY5CRZN3aUr0bopvaCbhKnDjiTlW20ROQg7TpkIIy9QY245yS@SdeQdhJ3OhIGqzjud6j6IPRqIXNqRxOEnCsrNOn3EkeXZt6YFckfuI73oihUbUtCIoec4Pco284elSU2R72455w0pqwE1knqrJwbZd15nMRUfykaEoqiLHV0o2qqUnf4UTQLic1ZlD76Ulj3smw2O2RsehpAGIbvYIa7NPJHo4zkrau65YdGinyoCjlZ6TlvtXN5265trjQe2XJijdLX3A/rqlCWty4IXoiKazg6hn3tH7KFWKJmB4eMw6vSDMT8hvOpFgsZgBG5aupZANon/h0DmJe6LgsZFuU1J1JYiXygc973YR88eI3PPnBuULPC7cthUQrL3031zHcMz3/oiDoEcFWfiTNufLi/BwNv0Aq8BW6EVSVqRNCGTgDeYDz@PPZ80q@kFoVdwQOFu4kjYW/wZku@9Yzen43LXN2GJ2yl/8vuudr/9RMHuI6HaX/noLPHbvdJgA97e9Cl1Q/VUuY88X3cMfwxewy07d1d4NutOzSAqhBaWqxpoUhf48PUFa5mqDSGhNi4vefrv7zQI7EM4flCdu6Q/8TBGvB3RXQ7Zn3pDP0jNJmXRmLnXKqC79ydrmH5UsV30u7@jncKe3Qd3wmumSxq@cIivnAn@lYUKse3tm4Ki28skjebKEnY9r@AufwzF3rmks5cuhllmlGSGQWYUWYZJZVROhkFklESGQWQUeoYRY1RwBjlimGYGAboNw) = 155 ``` lambda p:int('G11KK54222111111XXNM8MCO37WQ53YXHE93V8BIF2IMH1WU9KPU2MLN HGR'['uSJJaSrUNNrEnVsMeGtTMMoCoInMuErTuPsEaHTT'.find(p[7%len(p)]+p[0])/2::20],35) ``` [Try it online!](https://tio.run/##PY7NbsIwEIRfJZfKiRpR4hTxI/VS5CaBOqVNAlTAYVuMcJXYlmMfePqUmKpz2P20OztadTFnKXB3etp3NTRfR/DUjAvjoySKlsvRI8Y4ctpuczqh87d4vHkfxZ/blEzj9eQ5e8EZTaNNNV2uKkxfc@@qNPlAO2SLxQIKXeW5JmLdUpaYklI5l5mglujSrloCaVmiwYmLo69247uaCV8Fh3u1Gx6CBzyb4eEhjEdBp/T1KQ/tBRr8SC78BpTfGh16PZxCz0eFFSj00MIqbpjusQBjtRtWGoRte8qZMlawHgloc@5hzf6WFLTrCYhLw47OVXIDLoMy/W31pcc51DVvjew5c5VK6UzEaqnA3WlubrNVbW9WormLT8E2DP7DOaDgqu4X "Python 2 – Try It Online") Surprisingly well for this lazy solution... will look into improving as well. ;-) [Answer] # [Japt](https://github.com/ETHproductions/japt), 86 bytes, score = 94 ``` g5 ¥'i?788:[7*A³7*L6*LG²G²IIÉHÄDÑDÑCÑCÑGÄÄGÄGECC8]g`suj«a¨Ì¼và@ã/eÖô¶e©rp¤r`bU¯2)z)*L ``` [Try it for all inputs](https://ethproductions.github.io/japt/?v=1.4.6&code=ZzUgpSdpPzc4ODpbNypBszcqTDYqTEeyR7JJSclIxETRRNFD0UPRR8TER8RHRUNDOF1nYHN1aqthqMy8duBA4y9l1vS2ZalycKRylWBiVa8yKXopKkw=&input=WydzdW4nLCAnanVwaXRlcicsICdzYXR1cm4nLCAndXJhbnVzJywgJ25lcHR1bmUnLCAnZWFydGgnLCAndmVudXMnLCAnbWFycycsICdnYW55bWVkZScsICd0aXRhbicsICdtZXJjdXJ5JywgJ2NhbGxpc3RvJywgJ2lvJywgJ21vb24nLCAnZXVyb3BhJywgJ3RyaXRvbicsICdwbHV0bycsICdlcmlzJywgJ2hhdW1lYScsICd0aXRhbmlhJ10KLW0=), [Calculate the score](https://ethproductions.github.io/japt/?v=1.4.6&code=7Vs2OTYzNDIsNjk5MTEsNTgyMzIsMjUzNjIsMjQ2MjIsNjM3MSw2MDUyLDMzOTAsMjYzNCwyNTc1LDI0NDAsMjQxMCwxODIyLDE3MzcsMTU2MSwxMzUzLDExODYsMTE2Myw4MTYsNzg4XUBYL1kgd1kvWCBwMn0gcncgKlZs&input=WzcwMDAwMCw3MDAwMCw2MDAwMCwyNTYwMCwyNTYwMCw2NDAwLDYzMDAsMzMwMCwyNjAwLDI2MDAsMjQwMCwyNDAwLDE4MDAsMTcwMCwxNjAwLDE0MDAsMTIwMCwxMjAwLDgwMCw3ODhdCiJnNSClJ2k/Nzg4Ols3KkGzNypMNipMR7JHsklJyUjERNFE0UPRQ9FHxMRHxEdFQ0M4XWdgc3Vqq2GozLx24EDjL2XW9LZlqXJwpHKVYGJVrzIpeikqTCIKLVE=), or [Check the highest error](https://ethproductions.github.io/japt/?v=1.4.6&code=7VYsQFgvWSB3WS9YIApiVXJ3Ck9wV2dWO09wVWdW&input=WzcwMDAwMCw3MDAwMCw2MDAwMCwyNTYwMCwyNTYwMCw2NDAwLDYzMDAsMzMwMCwyNjAwLDI2MDAsMjQwMCwyNDAwLDE4MDAsMTcwMCwxNjAwLDE0MDAsMTIwMCwxMjAwLDgwMCw3ODhdCls2OTYzNDIsNjk5MTEsNTgyMzIsMjUzNjIsMjQ2MjIsNjM3MSw2MDUyLDMzOTAsMjYzNCwyNTc1LDI0NDAsMjQxMCwxODIyLDE3MzcsMTU2MSwxMzUzLDExODYsMTE2Myw4MTYsNzg4XQpbJ3N1bicsICdqdXBpdGVyJywgJ3NhdHVybicsICd1cmFudXMnLCAnbmVwdHVuZScsICdlYXJ0aCcsICd2ZW51cycsICdtYXJzJywgJ2dhbnltZWRlJywgJ3RpdGFuJywgJ21lcmN1cnknLCAnY2FsbGlzdG8nLCAnaW8nLCAnbW9vbicsICdldXJvcGEnLCAndHJpdG9uJywgJ3BsdXRvJywgJ2VyaXMnLCAnaGF1bWVhJywgJ3RpdGFuaWEnXQotUQ==) Very similar to Olivier's original answer. Input is all lowercase. After various improvements to the output values, the current highest error is Venus at just over 4%. Explanation now that things are a bit more stable: ``` ¤¥`Éa`? :If the fifth character of the input is 'i': 788 : Output 788. : :Otherwise: [...] : From the array representing radii g : Get the value at the index: `...` : In the string representing names b : Find the first index where this string appears: U¯2) : The first two characters of the input z) : And divide it by two *L : Multiply that value by 100 ``` The string for the names is `sujusaurneeavemagatimecaiomoeutrplerha` compressed using Japt's built-in compression. The numbers representing the radii are calculated like so: ``` My value | Actual value ---------+------------- 7 * 10 ^ 3 = 7000 * 100 = 700000 | 696342 7 * 100 = 700 * 100 = 70000 | 69911 6 * 100 = 600 * 100 = 60000 | 58232 16 * 16 = 256 * 100 = 25600 | 25362 16 * 16 = 256 * 100 = 25600 | 24622 64 = 64 * 100 = 6400 | 6371 64 - 1 = 63 * 100 = 6300 | 6052 32 + 1 = 33 * 100 = 3300 | 3390 13 * 2 = 26 * 100 = 2600 | 2634 13 * 2 = 26 * 100 = 2600 | 2575 12 * 2 = 24 * 100 = 2400 | 2440 12 * 2 = 24 * 100 = 2400 | 2410 16 + 1 + 1 = 18 * 100 = 1800 | 1822 16 + 1 = 17 * 100 = 1700 | 1737 16 = 16 * 100 = 1600 | 1561 14 = 14 * 100 = 1400 | 1353 12 = 12 * 100 = 1200 | 1186 12 = 12 * 100 = 1200 | 1163 8 = 8 * 100 = 800 | 816 788 = 788 | 788 ``` [Answer] # Japt, ~~77~~ ~~76~~ 75 bytes, score = 75 First pass at this; I wanted to try a 0 penalty solution to give myself a baseline to work off. Will come back to it tomorrow to see what improvements can be made, hopefully still for 0 penalty. Input is case-insensitive. ``` n35 %87%52 g"..."ò)mc ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=bjM1ICU4NyU1MiBnIiAgDz0LVlx1MDJiOFx1MDE1NhlLXHUwMmJiCyFaP0cYChgo/T48NCAgCBALPyAgICA66BElhwP2FhIWGlwiB1gi8iltYw==&input=IlN1biI=) or [test all inputs](https://ethproductions.github.io/japt/?v=1.4.6&code=bjM1ICU4NyU1MiBnIiAgDz0LVlx1MDJiOFx1MDE1NhlLXHUwMmJiCyFaP0cYChgo/T48NCAgCBALPyAgICA66BElhwP2FhIWGlwiB1gi8iltYw==&input=WyJTdW4iLCJKdXBpdGVyIiwiU2F0dXJuIiwiVXJhbnVzIiwiTmVwdHVuZSIsIkVhcnRoIiwiVmVudXMiLCJNYXJzIiwiR2FueW1lZGUiLCJUaXRhbiIsIk1lcmN1cnkiLCJDYWxsaXN0byIsIklvIiwiTW9vbiIsIkV1cm9wYSIsIlRyaXRvbiIsIlBsdXRvIiwiRXJpcyIsIkhhdW1lYSIsIlRpdGFuaWEiXQotbQ==) The `"..."` represents a string containing many unprintables. The codepoints are: ``` 32,32,15,61,11,86,696,342,25,75,699,11,33,90,63,71,24,10,24,40,253,62,60,52,32,32,8,16,11,63,32,32,32,32,58,232,17,37,135,3,246,22,18,22,26,34,7,88 ``` To offer a quick explanation: the string gets split into chunks of 2 characters. We then index into that array using part of [ovs' formula](https://codegolf.stackexchange.com/a/177031/58974) plus some index-wrapping and then map the 2 characters to their codepoints. * Saved a byte/point thanks to [ETH](https://codegolf.stackexchange.com/users/42545/ethproductions) ## 54 bytes, score = 58 A port of [Olivier's solution](https://codegolf.stackexchange.com/a/177028/58974). ``` "ýCĄ (ᬺ!˂Fɍ"cU¤¬xc %96%49)-7 *L ``` [Test all inputs](https://ethproductions.github.io/japt/?v=1.4.6&code=IhkX/RMYQ1x1MDEwNBMHFSAfKB9cdTFiM2EPByEHXHUwMmMyD0YHB1x1MDI0ZCJjVaSseGMgJTk2JTQ5KS03ICpM&input=WyJTdW4iLCJKdXBpdGVyIiwiU2F0dXJuIiwiVXJhbnVzIiwiTmVwdHVuZSIsIkVhcnRoIiwiVmVudXMiLCJNYXJzIiwiR2FueW1lZGUiLCJUaXRhbiIsIk1lcmN1cnkiLCJDYWxsaXN0byIsIklvIiwiTW9vbiIsIkV1cm9wYSIsIlRyaXRvbiIsIlBsdXRvIiwiRXJpcyIsIkhhdW1lYSIsIlRpdGFuaWEiXQotbQ==) [Answer] # [Ruby](https://www.ruby-lang.org/), 105 bytes, score 109 ``` ->n{7E5/('!)"0 r&zZ&1#}3Mfh-~~d@'[0,j=" =1&%)AM<I>2,-B#($D 7@".index((n[1,9].sum%50+34).chr)].sum-j*32)} ``` [Try it online!](https://tio.run/##PYxdT4MwFIbv/RXIHKUKCMNlMZFlfhCdCcZk6oWEi7qV0AUKObSJuLG/jmlnvDnnyXPe84L86oY8Gtw5383i6aWNTrHpG2D9fFrBqA@TvHAPh80Cpb6zjUwjCqwxvk1ulvOJ496N7LMHw5gtTI/xDf22bZ4GznXmtbIaT/2L8Ap76wKwFu72PJzgfmikaO0UrSRHjoGeZcMEBYUrIiRo@Q6Ey1bRC22E5FRhTEAUCj7o3zEhoPcj4V1FNzr1xgTRHQmFtYRO4T0pS9aKWvFSz6SudSiWUDdE/wETR/daymM0Bqbrn4isKPkvZwRlXkWa3Z7t85RlPT4ZfgE "Ruby – Try It Online") If we divide 700000 by the radii, we get a sequence which increases reasonably linearly (though rather erratically). The increments in the table below can be approximated by the ASCII values of characters. The problem with this approach is it requires the input to be decoded to a value which orders the different names by size. A minor issue is that the difference between Eris and Haumea is quite large. Three characters `~~d` are required to encode this increment in ASCII only format. The planet-to-index string has two "ghost planet"spaces in it to pad the index. ``` 700000/r increment from previous 0.994774 9.960407 8.965633 11.95806 1.997657 27.45612 15.49805 28.28129 0.825178 109.2987 81.0174 115.0598 5.761118 205.4106 90.3508 264.3667 58.95612 270.4241 6.057335 285.3861 14.96199 288.9386 3.552524 382.1855 93.24692 400.8877 18.70223 446.0871 45.19939 514.6652 68.57806 587.1349 72.46972 598.7463 11.61144 853.3603 254.6139 883.6827 30.32245 ``` [Answer] # T-SQL, ~~203 202 201~~ 196 bytes, score = ~~217 216 212~~ *208* ``` SELECT IIF(v='Titan',13,STUFF(value,1,2,''))*198 FROM i,STRING_SPLIT('Ca12,Ea32,Er6,Eu8,Ga13,Ha4,Io9,Ju353,Ma17,Me12,Mo9,Ne124,Pl6,Sa294,Su3517,Ti4,Tr7,Ur128,Ve31',',') WHERE LEFT(v,2)=LEFT(value,2) ``` Line breaks are for readability only. Input is taken via pre-existing table **i** with varchar column **v**, [per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). Joins the input table to an in-memory table on the first two characters, and returns the remaining digits x100. Treats "Titan" as a special case using `IIF`. **EDIT**: Saved 1 byte (and 1 point) by using `STUFF` to erase the first two characters instead of `SUBSTRING`. Thanks, t-clausen.dk! **EDIT 2**: I wanted to see what would happen if I tried to save another byte by multiplying each lookup value by 99 instead of 100, and found to my surprise that it actually *increased* the accuracy (of the least accurate estimate)!. This led me to some trial and error testing, and some fancy Excel what-if data tables, where I found an optimal solution using a multiplier of **89** (which of course changed all my stored values). So while this saves me only one byte, it actually improves my score by **4.6** from my prior solution. **EDIT 3**: Searched higher instead of lower, and found an even *better* multiplication factor, **198**. Values stay reasonably accurate while shortening my stored string by quite a few characters, which improves my score. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 203 bytes, score 203 ``` param($a)if($a-eq'Titan'){2575;exit}(696342,69911,58232,25362,24622,6371,6052,3390,2634,2440,2410,1822,1737,1561,1353,1186,1163,816,788)["SuJuSaUrNeEaVeMaGaMeCaIoMoEuTrPlErHaTi".indexOf(-join$a[0..1])/2] ``` [Try it online!](https://tio.run/##JY5BS8NAEIX/SykkgWnM7GRnN3gsoSpEhaZeSg8DbnElTdq1wYL429cFLx@P977DO0/fLnx9uGGI8SxBTvlSCn9MXLlL1vurjFnxo7TR9@7mr785N0y1Am4aRNBWkQKliRNrVqkng8CVVkDUVKCSnJY6pRorQJsUNGQANSMgaQJEywlMYJHBWFvsF9v5ad7KLjy7Vt5cJxvp3Foep25q5z68Dm14kN4vSj@@u9vLMV99Tn5cyr4qSzwUd@oQY/w/7yX7Aw "PowerShell – Try It Online") Very similar to Olivier's answer, now that I see it, but developed independently. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 101 bytes, score = 101 ``` I⍘§⪪“_″FJ⁼⦄b\l≕)T‹#⊙xO-nη⁻À↓ζ↥ς§%H8H“ρj✳Hρl× S↶…|UD⎇LkfZ”³⌕⪪”@/rjmq_↙§E▶νF↨oº⁷÷K⁻eDH:_Tbk¦�”²⁺§θ⁰§θχγ ``` [Try it online!](https://tio.run/##TU7LasMwAPsVkUPnFq/kcSghvWwh21JICDgLOwyKcd3W4Dld4mQ77N9dX1omkEACCYkzH0TPtXPNoIwlOR8teeajZNb7E3mypTnIX8IuWlkSfK1/Ho7zYvf3GWhPGUEssBfIOTKJbIWUI82RRIgzhCXWG9AadAPyAbINKJIlxYsyh9sgm3aKDe9TbYui66rh1bRtJXJdllVfXNq@aQr1Jlvuq7GvNnoa75@@KUKf/bNRuPSgOHnNnGOTcY@zvgI "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⁺§θ⁰§θχ ``` Take the 1st and 11th character (cyclically) of the input string and concatenate them. ``` ⌕⪪”@/rjmq_↙§E▶νF↨oº⁷÷K⁻eDH:_Tbk¦�”² ``` Look them up in the string `SuJiSrUuNtEEVVMrGnTTMcClIIMoEpToPPEiHeTa` split into pairs of characters. ``` §⪪“_″FJ⁼⦄b\l≕)T‹#⊙xO-nη⁻À↓ζ↥ς§%H8H“ρj✳Hρl× S↶…|UD⎇LkfZ”³ ``` Split the string `m.w'fv&J|\"l|\"e1 c& _c Ca ;e ;* 9a 9C 31 2; 0I .7 ,N ,7 (X (<` into groups of three characters and take the corresponding group. ``` I⍘ ... γ ``` Decode the result as a base-95 number using the printable ASCII character set as the digits. Example: `Io`'s 11th character is `I`, so we look up `II` and find it's the 13th largest object and its size is `31` which maps to `19 * 95 + 17 = 1822`. [Answer] # [Swift 4](https://developer.apple.com/swift/), 225 bytes, score = 241 Probably golfable a bunch more (maybe in the "Ga-Me-Ca" area?), but Swift is not often used (for a reason, maybe.) ``` func b(i:String){print(i=="Titan" ?2575:["Su":6963,"Ju":699,"Sa":582,"Ur":253,"Ne":246,"Ea":63,"Ve":60,"Ma":33,"Ga":26,"Me":24,"Ca":24,"Io":18,"Mo":17,"Eu":16,"Tr":14,"Pl":12,"Er":12,"Ha":8,"Ti":8][String(i.prefix(2))]!*100)} ``` and ungolfed ``` func size(ofAstralObject object: String) { let objectToRadius = // Map size/100 of all objects to the first two chars ["Su":6963, "Ju":699, "Sa":582, "Ur":253, "Ne":246, "Ea":63, "Ve":60, "Ma":33, "Ga":26, "Me":24, "Ca":24, "Io":18, "Mo":17, "Eu":16, "Tr":14, "Pl":12, "Er":12, "Ha":8, "Ti":8] // Ti is Titania, while Titan is treated differently print(object == "Titan" ? 2575 : // If "Titan", print the exact size objectToRadius[String(i.prefix(2))]!*100 // get the size from the map and multiply by 100 ) } ``` [Try It Online!](https://tio.run/##PVHBbsIwDL3zFZlP7VRNtNACldAOqAImFSG1cEEcAku3TCWtTKINIb69c9Jpl7xnv2c7Tq7fstLjrquMOrOTJ9NCo1Qf/r0l0J6cz6GUmitgr1E8idMDFAbSZJaMAnhzbBZAwSGNp1EAO4Q0iknaCCLjJICMJOvdUyIZBpBTPKJ4SRiRnjtjAAve47qBNJxS3uKE6mlGSL6SOoekb2tCmpRhjyuqI3spCY6H/vKefGlRVPLHi3z/@PQcDof@o6saZM3pi0nF7BIKAkYbtFILtLTg2qBL7pArc7VsI1ptlLA046g/LdmLPzHn6HDJ1e0i3p2rfyorCjwbvFm64HUtr7qxfO3OvGmcKTPYtNzVodR9blub3pqhdO1X3FwE/28uORzZfWB/ipbxB49B9ws) I tried different "key sizes" for the map, but of course 1 has many clashes and using three chars doesn't give me `i=="Titan" ?2575:`'s 17 chars, since there's "Io" to manage (and it'll take more than 3 chars, I think). [Answer] # JavaScript (ES6), 152 bytes, score = 163 Well, it's a pretty standard solution, but I enjoyed the challenge anyway! ``` s=>s=='Titan'?2575:[6963,699,582,254,246,64,60,34,26,24,24,18,17,16,14,12,12,8,8]["SuJuSaUrNeEaVeMaGaMeCaIoMoEuTrPlErHaTi".match(s[0]+s[1]).index/2]*100 ``` My Score: ``` Max. penalty ratio = 1.07068 for Triton Score = ceil(152 x 1.07068) = 163 ``` [Try it Online!](https://tio.run/##PZFdT8IwFIav5Vcs3gyk4jq2MsTphVn8SGZIQG@WXZxAkZrRLv0wGuNvx54hJO1z3r59e5KzfcAnmJUWrb2Uas33@01u8luT5@FSWJDhXZxO0uuKTdmYsOmUpFlM4jQhccIISwiLyNgfmD/johmhE0IZoV7HuDKS1dX5wj27BbzqF17AGy/hAUp@D0@qVIVb6nlT6EdYivPRDuxq2zdVVA9NRevBSMg1/7qK6wsaRftP0EHbgOTWBHlQhQsnQxKEz64VlmuUC7BOd@arBukMqhfeWic5ygK03aJ44/@XJeiuPoD83vF1lzoMjpdcr5z@RnkPTSOMVaifOpZKdaHCadVC904Le/DmjTtECy269o/gdhxOzQWE9ay3UbqPI4nATxPNfL05jTdquHy3W28Oh4Of3tlKSaMaPmrUe3/TP6YqUQ8Gs97v3n@dHmNphCVDptOJp/93yCRF/2B7jBM02QnjI2iGwBzFF7TzYgT2zxK/afQH) [Answer] # [FALSE](http://strlen.com/false-language/), 152 bytes, Score = 563 ``` [911*.]^$0\[~][1+^]#$$2=\$4=\8=||[2 0!]?$3=[764 0!]?$5=[\$$69=\86=|$[6\]?~[2]?0!]?$6=[\$$83=\85=|$[46\]?~[$72=$[1\]?~[2]?]?0!]?$7=[\$84=$[1\]?~[52]?0!]? ``` Lazy answer using word lengths and first letters but my excuse is that I'm using a weird language [Try it online!](http://www.quirkster.com/iano/js/false-js.html) (copy paste the code, hit show and then run) ``` [911*.] {defines a function that multiplies a number by 911 and then prints it} ^$0\[~][1+^]# {counts the length of the name as it's input, also records the first char} $$2=\$4=\8=||[1 0!]? {if the name is 2, 4, or 8 chars long print 911*2 (0! calls the function)} $3=[764 0!]? {if name is 3 long print 911*764} $5=[\$$69=\86=|$[6\]?~[2]?0!]? {5 long? print 911*6 if it starts with E or V, otherwise *2} $6=[\$$83=\85=|$[46\]?~[ {6 long? print 911*46 if it starts with S or U, otherwise:} $72=$[1\]?~[2]? {if name starts with H print 911*1 else *2 ]?0!]? $7=[\$84=$[1\]?~[26]?0!]? {7 long? print 1822*1 if it starts with NT otherwise *26 (for jupiter} ``` My results: ``` Sun : 696004.00 penalty ratio = (696342.00 / 696004.00 )² = 1.00097 Jupiter : 47372.00 penalty ratio = (69911.00 / 47372.00 )² = 2.17795 Saturn : 41906.00 penalty ratio = (58232.00 / 41906.00 )² = 1.93095 Uranus : 41906.00 penalty ratio = (41906.00 / 25362.00 )² = 2.73014 Neptune : 47372.00 penalty ratio = (47372.00 / 24622.00 )² = 3.70166 Earth : 5466.00 penalty ratio = (6371.00 / 5466.00 )² = 1.35855 Venus : 5466.00 penalty ratio = (6052.00 / 5466.00 )² = 1.22591 Mars : 1822.00 penalty ratio = (3390.00 / 1822.00 )² = 3.46181 Ganymede : 1822.00 penalty ratio = (2634.00 / 1822.00 )² = 2.08994 Titan : 1822.00 penalty ratio = (2575.00 / 1822.00 )² = 1.99737 Mercury : 1822.00 penalty ratio = (2440.00 / 1822.00 )² = 1.79342 Callisto : 1822.00 penalty ratio = (2410.00 / 1822.00 )² = 1.74959 Io : 1822.00 penalty ratio = (1822.00 / 1822.00 )² = 1.00000 Moon : 1822.00 penalty ratio = (1822.00 / 1737.00 )² = 1.10026 Europa : 1822.00 penalty ratio = (1822.00 / 1561.00 )² = 1.36236 Triton : 1822.00 penalty ratio = (1822.00 / 1353.00 )² = 1.81343 Pluto : 1822.00 penalty ratio = (1822.00 / 1186.00 )² = 2.36008 Eris : 1822.00 penalty ratio = (1822.00 / 1163.00 )² = 2.45435 Haumea : 911.00 penalty ratio = (911.00 / 816.00 )² = 1.24640 Titania : 911.00 penalty ratio = (911.00 / 788.00 )² = 1.33655 Max. penalty ratio = 3.70166 for Neptune Score = ceil(152 x 3.70166) = 563 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 118 bytes, score = 135 ``` i;f(char*s){i=exp((strchr("(~?_q#m#.(`(=*2,r-v.h2z2p3d3j6>Qb>a?{Qx]",(*s^s[1]*4)+(strlen(s)!=5)&127|32)[1]+55)/13.5);} ``` [Try it online!](https://tio.run/##VY5fT8IwFMWf3aeYI5p2/DFsTh8I8GCIYoKRoL4oau26rWbr5m1LQMSP7hwkK/p2fvfcc@6l7ZjSsuS9CNGEgCvxmvfZskBIKqAJIAd9D18@Glmjg15R3/Va0F50Eu/TK/zQfz8bTN8GZLieLudOC7nyWT525@4pbm7jKRNI4sN@gI@73vmX7@HKbAYBPun6nQD3NuUi56Ed7y7b1WlrbR0UwIWKkHMUPgmnZUdVA@5ZG8uqxnZGuEC7tRg5My2cytrKa11wxaDGGVEajHkPRGhZ0w0rlBasxhEBldTwwP4sTggYfUnEKmOhSd1xRUz/hAHVsKrxgqQplyqveWzUJM9NaKQhL4jpA6723m2q9/ERcPPGFdEZI/@e4DvclD80Skksy3aa/QI "C (gcc) – Try It Online") [Scoring](https://tio.run/##ZVPtTtswFP2fp7iKEHUgS@Ok@egYTNPUbkyUTS3bn1IJqzHgKXUyx0GtoC@1R9iLddcudAx@2Mk9Pvfc42v7J7tjzVyJWr@RVcE3mzEcw3TqTlrp@mk/jXvRzJ@6X9paaK4M1KfUIBOmW4WcJI9iS/mumGwb14@SOLXAOa91KzkivTSyyIApfYsacWYlfnCbkIaJXR0xhVEc90MTfWJyteCFSUcTBrkQmkmjnyWWztW8VSsj37MZH1lZikZXBqEWOcV/mm9rj6oKk2kWZ9ZJq6qaYZyk1sqFEtqux0ls4m9la4QozVNLV6IxUWoXP7N2wTE5p@nOl8A4y/PZ7Mhxpmc@BEHwAWbYS8V/tUJx0rluOl6gOCuGouSTlZyTTrfgd91GF0Likq4mWgl5Q7ygqUuhSefSwAtWEwnHJ3AovSPnulILplHWQhKThmLJCxJ5Qc2KgSwIDZG2YEvkhOhlHGDKgM1vCZlKtuA@KFaItpn5ID2jce8AzCvZVCUPyuqGGNKTVt@DQ3DhLY5D2JYmCoVrPCk@LCsMP0zlzDM0Ippzdk6UBw8PoOAdlof3QBTTosIUCl0IfXAH4/HXsesZzZpLVuoVPFHIsyojpm9x60uydYuubRG3C69IQr4keX9@o5wh7sr/00MfO7r9GsCDgwOIvF07E8/DLsKjtRMw/dzfB7Ltq0V9qEsmuT0LbBnS1zgccY2NGAqJr8Ww0dDLBl9dyhFbBvBy@3v3yH/mYG22iei2zPrKGvpPaDKvFMfMORcl2bs/W8PytYpnpe3@Le8MDsx2PCu4dnjZ8FcW8eadyjtWigKvb9OWGq8ukjcbfA9Omvb6NMSPmZMs7WdOFGdR@DinURI5SR6mThwhAV/r0xTn6XaiWdZzaNrLHZrEoUNj2ncojfPtlOWJGX8B "JavaScript (Node.js) – Try It Online") ## Rundown The object name is turned into a single-character hash through the cumbersome process ``` (((*s ^ s[1] << 2) + (strlen(s) != 5)) & 127) | 32 ``` whose bloat points to "Titan"/"Titania" as the main offenders. Including the last character in the hash was considered, but that still requires a `strlen()` in C. The first occurence of the hash character is searched for in the hash/data string. When found, the next character is taken and used to approximate the radius of the object in question. The data character holds the shifted, scaled natural logarithm of the radius. Generated like so: ``` for (int i = 0; i < 20; i++) data[i] = log(radii[i]) * 13.5 - 55; ``` The scale was chosen through highly scientific trial-and-error, and the shift for bringing the value within printable ASCII range while avoiding backslashes. Some rearrangement of the objects in the string was necessary due to some hash/data collisions. ``` i; Return value f(char*s){ s is object name i= Implicit return exp( Raise e to some power ( strchr( Find hash "...", Hash/data string (*s^s[1]*4)+ Calculate... (strlen(s)!=5)&127|32 ...hash ) [1] Char following hash holds the power +55 Shift it )/13.5 Scale it ); Use it } Exit ``` [Answer] # [Python 2](https://docs.python.org/2/), 89 bytes, Score = 234 ``` lambda(p):39**4/'zzuSJJaSrUNNrEnVsMeGtTMMoCoInMuErTuPsEaHTT'.find(p[7%len(p)]+p[0])**2.18 ``` [Try it online!](https://tio.run/##pVLLTuMwFN33K7ypnGQynTjOE4nNoAiolApNA5sSITNxwaPEjvyQpvx8sdOCijSLEdzFvdfH5x4/dMadfhY83m/P7/c9GR474o3@GS6DIPkBX17Merkka3m7WsmK36maXuqmrsWFuOa1qWRjblRFrpoGLraMd964yec95Vai/TZuotYPgniBiv2j6BhV4Bxs4NpwGAK4NCPTVLp2TbSRE3grCTfKdSs6asOpaysi9TMMZ@A94B090moip3pJ@G6g3cRvmCaTWk3lbyN3rr0gfc@UFh9lrsVEE2KiV0aKkUwKkukDdtMbPZEqydTH4StiBkreD2QEtjNJOsbcK7Myw0kcgqwsEQpBWsTYruIUZ64kWez2cI5OFLMotSDGZWQZdtrR89SxE4ckKDoho8IpoBznNqeZPQLhFNuMiszlDJ@QC2SxvCja2SgZ1wD@FN0OnMQve22jjotKaTYQTeEb@@F/As6e7LuPBlL@GYBzKzifRA/ZFuiyp@yXARh4KPrurKJ8PwTTx20OLllYI9G/Fm9DsHXbbxe553DxRzDuDWT0lJYhcM1TCLxPm@pLVvqEgf5lG9/G/hU "Python 2 – Try It Online") Most answers posted appear to have used a "encode/decode" strategy. I wondered how well I could do by estimating the diameter of celestial bodies using a simple equation. It's been a fun exercise, but the moderate byte savings are more than made up for by the accuracy penalty. The core of this solution is the estimating equation: ``` Radius = 39**4/x**2.18 ``` where x is twice the rank order of the radius of the body. I generate the value of x based on the input string using a modification of @Erik the Outgolfer's Python 2 solution. I saved a few bytes on his code by recasting my equations to work with [2..40] instead of [1..20]. The code for generating rank orders takes up more than 2/3 of the bytes of the whole solution. If anyone has a more compact way of generating ranks, this solution could be shortened further. Because of the accuracy penalty (around 2.6), the score would improve quite a bit. ## Generating the Equation I used statistical methods to search for simple equations to estimate the size of each body based on its rank. In part following up on the insights in @Level River St's Ruby solution and generalizing, I settled on equations of the form: ``` Radius = A/(Rank)**B ``` Working in R, I used linear models on the log of the radii to develop initial estimates, and then used non-linear optimization, seeding the optimization with the results of the linear models, to search for solutions that minimized the penalty function specified in the problem. The estimated value of A in the above equation is seven digits, so I searched for a simple expression to save a couple of bytes. I looked for expressions of the form ``` x**y ``` for two digit x and 1 digit y (for a total of five bytes, saving two bytes, or about five points, given the penalty) that was not too different from the optimum value of A and did not inflate the penalty much, and ended up with the (otherwise inexplicable): ``` 39**4 ``` [Answer] # TI-BASIC (TI-84), 285 bytes, Score = 285 ``` Ans→Str1:{696342,69911,58232,25362,24622,6371,6052,3390,2634,2575,2440,2410,1822,1737,1561,1353,1186,1163,816,788:Ans(-int(-.125inString("SUN JUPITER SATURN URANUS NEPTUNE EARTH VENUS MARS GANYMEDETITAN MERCURY CALLISTOIO MOON EUROPA TRITON PLUTO ERIS HAUMEA TITANIA",Str1 ``` A simple "index in string to list" program. Can be golfed further. Input is in `Ans` and is one of the objects' name in full uppercase. Output is in `Ans` and is automatically printed out. **Example:** ``` "MOON MOON prgmCDGFC 1737 "IO IO prgmCDGFC 1822 ``` **Explanation:** (Radii list and name string have been shortened for brevity. `...` is used to indicate the rest of the list/string.) ``` Ans→Str1:{696342,69911,5...:Ans(-int(-.125inString("SUN JU...",Str1 ;complete source Ans→Str1 ;store the input string ; in "Str1" {696342,69911,5... ;generate the list of ; radii and leave it in ; "Ans" inString("SUM JU...",Str1 ;get the index of the ; input string in the ; name string .125 ;multiply the index by 1/8 -int(- ;then round it towards ; positive infinity Ans( ;use the result as the ; index of the radii list ``` **Visual Model:** ``` Ans→Str1 ;Ans = "MOON" ;Str1 = "MOON" {696342,69911,5... ;Ans = {696232 69911 ... } ;Str1 = "MOON" inString("SUN JU...",Str1 ;Ans = {696232 69911 ... } ;Str1 = "MOON" ;current evaluation: 105 .125 ;Ans = {696232 69911 ... } ;current evaluation: 13.125 -int(- ;Ans = {696232 69911 ... } ;current evaluation: 14 Ans( ;Ans = 1737 ``` ]
[Question] [ *I found this sequence while working on [Evolution of OEIS](https://codegolf.stackexchange.com/q/49223/8478), but never got around to posting it as an answer. After writing a reference implementation in Mathematica, I thought this is a fun exercise to do as a separate challenge though, so here we go.* Let's build a numeric fission reactor! Consider a positive integer `N`. As an example, we'll look at `24`. To fission this number, we have to find the largest number of *consecutive* positive integers that sum to `N`. In this case, that's `7 + 8 + 9 = 24`. So we've split `24` into three new numbers. But this wouldn't be much of a fission reactor without chain reactions. So let's recursively repeat the process for these components: ``` 24 /|\ / | \ / | \ 7 8 9 / \ /|\ 3 4 / | \ / \ / | \ 1 2 2 3 4 / \ 1 2 ``` Notice that we stop the process whenever the number cannot be decomposed into smaller consecutive integers. Also note that we could have written `9` as `4 + 5`, but `2 + 3 + 4` has more components. The **Fission number** of `N` is now defined as the number of integers obtained in this process, including `N` itself. The above tree has 13 nodes, so `F(24) = 13`. This sequence is OEIS entry [A256504](http://oeis.org/A256504). The first 40 terms, starting from `N = 1`, are ``` 1, 1, 3, 1, 5, 6, 5, 1, 6, 7, 12, 10, 12, 11, 12, 1, 8, 16, 14, 17, 18, 18, 23, 13, 21, 18, 22, 23, 24, 19, 14, 1, 22, 20, 23, 24, 31, 27, 25, 26 ``` The first 1000 terms can be found [in this pastebin](http://pastebin.com/raw.php?i=dPScBiBk). ## The Challenge Given a positive integer `N`, determine its Fission number `F(N)`. (So you don't need to cover the leading `0` listed on OEIS.) You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. This is code golf, so the shortest answer (in bytes) wins. **Bonus question:** Can you find any interesting properties of this sequence? [Answer] # [Fission](http://esolangs.org/wiki/Fission), ~~1328~~ ~~989~~ ~~887~~ 797 bytes *This answer is a bit unreasonably long (I wish we had [collapsible regions](https://meta.stackexchange.com/q/5199/201409))... please don't forget to scroll past this and show the other answers some love!* Working on this code was what inspired this challenge. I wanted to add an answer in Fission to EOEIS, which led me to this sequence. However, actually learning Fission and implementing this took a few weeks working on it on and off. In the meantime, the sequence had really grown on me so I decided to post a separate challenge for it (plus, this wouldn't have been particularly far down the tree on EOEIS anyway). So I present to you, the Monstrosity: ``` R'0@+\ / Y@</ /[@ Y]_L [? % \ / \ J \$@ [Z/;[{+++++++++L UR+++++++++>/; 9\ ; 7A9 SQS {+L /$ \/\/\/\/\/ 5/ @ [~ &@[S\/ \ D /8/ ~4X /A@[ %5 /; & K } [S//~KSA / 3 \ A$@S S\/ \/\/\/ \/>\ /S]@A / \ { +X W7 X X /> \ +\ A\ / \ /6~@/ \/ / ~A\; +;\ /@ ZX [K / {/ / @ @ } \ X @ \AS </ \V / }SZS S/ X ;;@\ /;X /> \ ; X X ; \@+ >/ }$S SZS\+; //\V / \\ /\; X X @ @ \~K{ \0X / /~/V\V / 0W// \ Z [K \ //\ W /MJ $$\\ /\7\A /;7/\/ / 4}K~@\ &] @\ 3/\ / \{ }$A/1 2 }Y~K <\ [{/\ ;@\@ / \@<+@^ 1;}++@S68 @\ <\ 2 ; \ / $ ;}++ +++++++L %@A{/ M \@+>/ ~ @ SNR'0YK \ A!/ ``` It expects that there is no trailing newline on the input, so you might want to call it like `echo -n 120 | ./Fission oeis256504.fis`. The layout could probably still be more efficient, so I think there's still a lot of room for improvement here (for instance, this contains ~~911~~ ~~581~~ ~~461~~ 374 spaces). Before we get to the explanation, a note on testing this: the [official interpreter](https://github.com/C0deH4cker/Fission/) doesn't entirely work as is. a) `Mirror.cpp` doesn't compile on many systems. If you run into that problem, just comment out the offending line - the affected component (a random mirror) is not used in this code. b) There are a couple of bugs that can lead to undefined behaviour (and likely will for a program this complex). You can apply [this patch](https://github.com/C0deH4cker/Fission/pull/3/files) to fix them. Once you've done that, you should be able to compile the interpreter with ``` g++ -g --std=c++11 *.cpp -o Fission ``` Fun fact: This program uses almost every component Fission has to offer, except for `#` (random mirror), `:` (half mirror), `-` or `|` (plain mirror), and `"` (print mode). ## What on Earth? **Warning:** This will be quite long... I'm assuming you're genuinely interested in how Fission works and how one could program in it. Because if you're not, I'm not sure how I could possibly summarise this. (The next paragraph gives a general description of the language though.) Fission is a two-dimensional programming language, where both data and control flow are represented by *atoms* moving through a grid. If you've seen or used [Marbelous](https://github.com/marbelous-lang/docs) before, the concept should be vaguely familiar. Each atom has two integer properties: a non-negative mass and an arbitrary energy. If the mass ever becomes negative the atom is removed from the grid. In most cases you can treat the mass as the "value" of the atom and the energy as some sort of meta-property that is used by several components to determine the flow of the atoms (i.e. most sorts of switches depend on the sign of the energy). I will denoted atoms by `(m,E)`, when necessary. At the beginning of the program, the grid starts with a bunch of `(1,0)` atoms from wherever you place on of the four components `UDLR` (where the letter indicates the direction the atom is moving in initially). The board is then populated with a whole bunch of *components* which change the mass and energy of atoms, change their directions or do other more sophisticated things. For a complete list [see the esolangs page](http://esolangs.org/wiki/Fission), but I'll introduce most of them in this explanation. Another important point (which the program makes use of several times) is that the grid is toroidal: an atom that hits any of the sides reappears on the opposite side, moving in the same direction. I wrote the program in several smaller parts and assembled them at the end, so that's how I'll go through the explanation. ### `atoi` This component may seem rather uninteresting, but it's nice and simple and allows me to introduce a lot of the important concepts of Fission's arithmetic and control flow. Therefore, I will go through this part in quite meticulous detail, so I can reduce the other parts to introducing new Fission mechanics and pointing out higher-level components whose detailed control flow you should be able to follow yourself. Fission can only read byte values from individual characters, not entire numbers. [While that's acceptable practice](http://meta.codegolf.stackexchange.com/a/4719/8478) around here, I figured while I was at it, I could do it right and parse actual integers on STDIN. Here is the `atoi` code: ``` ; R'0@+\ / Y@</ /[@ Y]_L [? % \ / \ J \$@ [Z/;[{+++++++++L UR+++++++++>/; O ``` Two of the most important components in Fission are fission and fusion reactors. Fission reactors are any of `V^<>` (the above code uses `<` and `>`). A fission reactor can store an atom (by sending it into the character's wedge), the default being `(2,0)`. If an atom hits the character's apex, two new atoms will be sent off to the sides. Their mass is determined by dividing the incoming mass by the stored mass (i.e. halving by default) - the left-going atom gets this value, and the right-going atom gets the remainder of the mass (i.e. mass is conserved in the fission). Both outgoing atoms will have the incoming energy *minus* the stored energy. This means we can use fission reactors for arithmetic - both for subtraction and division. If a fission reactor is hit from the site, the atom is simply reflected diagonally and will then move in the direction of the character's apex. Fusion reactors are any of `YA{}` (the above code uses `Y` and `{`). Their function is similar: they can store an atom (default `(1,0)`) and when hit from the apex two new atoms will be sent off to the sides. However, in this case the two atoms will be identical, always retaining the incoming energy, and multiplying the incoming mass by the stored mass. That is, by default, the fusion reactor simply duplicates any atom hitting its apex. When hit from the sides, fusion reactors are a bit more complicated: the atom is *also* stored (independently of the other memory) until an atom hits the opposite side. When that happens a new atom is released in the direction of the apex whose mass and energy are the sum of the two old atoms. If a new atom hits the same side before a matching atom reaches the opposite side, the old atom will simply be overwritten. Fusion reactors can be used to implement addition and multiplication. Another simple component I want to get out of the way is `[` and `]` which simply set the atom's direction to right and left, respectively (regardless of incoming direction). The vertical equivalents are `M` (down) and `W` (up) but they're not used for the `atoi` code. `UDLR` also act as `WM][` after releasing their initial atoms. Anyway, let's look at the code up there. The program starts out with 5 atoms: * The `R` and `L` at the bottom simply get their mass increment (with `+`) to become `(10,0)` and then stored in a fission and a fusion reactor, respectively. We will use these reactors to parse the base-10 input. * The `L` in the top right corner gets its mass decremented (with `_`) to become `(0,0)` and is stored in the side of a fusion reactor `Y`. This is to keep track of the number we're reading - we'll gradually increase and multiply this as we read numbers. * The `R` in the top left corner gets its mass set to the character code of `0` (48) with `'0`, then mass and energy are swapped with `@` and finally mass incremented once with `+` to give `(1,48)`. It is then redirected with diagonal mirrors `\` and `/` to be stored in a fission reactor. We'll use the `48` for subtraction to turn the ASCII input into the actual values of the digits. We also had to increase the mass to `1` to avoid division by `0`. * Finally, the `U` in the bottom left corner is what actually sets everything in motion and is initially used only for control flow. After being redirected to the right, the control atom hits `?`. This is the input component. It reads a character and sets the atom's mass to the read ASCII value and the energy to `0`. If we hit EOF instead, the energy will be set to `1`. The atom continues and then hits `%`. This is a mirror switch. For non-positive energy, this acts like a `/` mirror. But for positive energy it acts like a `\` (and also decrements the energy by 1). So while we're reading the characters, the atom will be reflected upwards and we can process the character. But when we're done with the input, the atom will be reflected downwards and we can apply different logic to retrieve the result. FYI, the opposite component is `&`. So we've got an atom moving up for now. What we want to do for each character is to read its digit value, add that to our running total and then multiply that running total by 10 to prepare for the next digit. The character atom first hits a (default) fusion reactor `Y`. This splits the atom and we use the left-going copy as a control atom to loop back into the input component and read the next character. The right-going copy will be processed. Consider the case where we've read the character `3`. Our atom will be `(51,0)`. We swap mass and energy with `@`, such that we can make use of the subtraction of the next fission reactor. The reactor subtracts `48` off the energy (without changing the mass), so the it sends off two copies of `(0,3)` - the energy now corresponds to the digit we've read. The upgoing copy is simply discarded with `;` (a component that just destroys all incoming atoms). We'll keep working with the downgoing copy. You'll need to follow its path through the `/` and `\` mirrors a bit. The `@` just before the fusion reactor swaps mass and energy again, such that we'll add `(3,0)` to our running total in the `Y`. Note that the running total itself will therefore always have `0` energy. Now `J` is a jump. What it does is jump any incoming atom forward by its energy. If it's `0`, the atom just keeps moving straight on. If it's `1` it will skip one cell, if it's `2` it'll skip two cells and so on. The energy is spent in the jump, so the atom always ends up with energy `0`. Since the running total does have zero energy, the jump is ignored for now and the atom is redirected into the fusion reactor `{` which multiplies its mass by `10`. The downgoing copy is discarded with `;` while the upgoing copy is fed back into the `Y` reactor as the new running total. The above keeps repeating (in a funny pipelined way where new digits are being processed before the previous ones are done) until we hit EOF. Now the `%` will send the atom downwards. The idea is to turn this atom into `(0,1)` now before hitting the running total reactor so that a) the total is not affected (zero mass) and b) we get an energy of `1` to jump over the `[`. We can easily take care of the energy with `$`, which increments the energy. The issue is that `?` does not reset the mass when you're hitting EOF so the mass will still be that of the last character read, and the energy will be `0` (because `%` decremented the `1` back to `0`). So we want to get rid of that mass. To do that we swap mass and energy with `@` again. I need to introduce one more component before finishing up this section: `Z`. This is essentially the same as `%` or `&`. The difference is that it lets positive-energy atoms pass straight through (while decrementing the energy) and deflects non-positive-energy atoms 90 degrees to the left. We can use this to eliminate an atom's energy by looping it through the `Z` over and over - as soon as the energy is gone, the atom will be deflected and leave the loop. That is this pattern: ``` / \ [Z/ ``` where the atom will move upwards once the energy is zero. I will use this pattern in one form or another several times in the other parts of the program. So when the atom leaves this little loop, it will be `(1,0)` and swapped to `(0,1)` by the `@` before hitting the fusion reactor to release the final result of the input. However, the running total will be off by a factor of 10, because we've tentatively multiplied it for another digit already. So now with energy `1`, this atom will skip the `[` and jump into the `/`. This deflects it into a fission reactor which we've prepared to divide by 10 and fix our extraneous multiplication. Again, we discard one half with `;` and keep the other as output (here represented with `O` which would simply print the corresponding character and destroy the atom - in the full program we keep using the atom instead). ### `itoa` ``` / \ input -> [{/\ ;@ @\ <\ $ ;}++ +++++++L %@A{/ M \@+>/ ~ @ SNR'0YK \ A!/ ``` Of course, we also need to convert the result back to a string and print it. That's what this part is for. This assumes that the input doesn't arrive before tick 10 or so, but in the full program that's easily given. This bit can be found at the bottom of the full program. This code introduce a new very powerful Fission component: the stack `K`. The stack is initially empty. When an atom with non-negative energy hits the stack, the atom is simply pushed onto the stack. When an atom with negative energy hits the stack, its mass and energy will be replaced by the atom on the top of the stack (which is thereby popped). If the stack is empty though, the direction of the atom is reversed and its energy becomes positive (i.e. is multiplied by `-1`). Okay, back to the actual code. The idea of the `itoa` snippet is to repeatedly take the input modulo 10 to find the next digit while integer-dividing the input by 10 for next iteration. This will yield all the digits in reverse order (from least significant to most significant). To fix the order we push all the digits onto a stack and at the end pop them off one by one to print them. The upper half of the code does the digit computation: the `L` with the pluses gives a 10 which we clone and feed into a fission and a fusion reactor so we can divide and multiply by 10. The loop essentially starts after the `[` in the top left corner. The current value is split: one copy is divided by 10, then multiplied by 10 and stored in a fission reactor, which is then hit by the other copy at the apex. This computes `i % 10` as `i - ((i/10) * 10)`. Note also that the `A` splits the intermediate result after the division and before the multiplication, such that we can feed `i / 10` into the next iteration. The `%` aborts the loop once the iteration variable hits 0. Since this is more or less a do-while loop, this code would even work for printing `0` (without creating leading zeroes otherwise). Once we leave the loop we want to empty the stack and print the digits. `S` is the opposite of `Z`, so it's a switch which will deflect an incoming atom with non-positive energy 90 degrees to the right. So the atom actually moves over the edge from the `S` straight to the `K` to pop off a digit (note the `~` which ensures that the incoming atom has energy `-1`). That digit is incremented by `48` to get the ASCII code of the corresponding digit character. The `A` splits the digit to print one copy with `!` and feed the other copy back into the `Y` reactor for the next digit. The copy that's printed is used as the next trigger for the stack (note that the mirrors also send it around the edge to hit the `M` from the left). When the stack is empty, the `K` will reflect the atom and turn its energy into `+1`, such that it passes straight through the `S`. `N` prints a newline (just because it's neat :)). And then the atom goes thorugh the `R'0` again to end up in the side of the `Y`. Since there are no further atoms around, this will never be released and the program terminates. ### Computing the Fission Number: The Framework Let's get to the actual meat of the program. The code is basically a port of my Mathematica reference implementation: ``` fission[n_] := If[ (div = SelectFirst[ Reverse@Divisors[2 n], (OddQ@# == IntegerQ[n/#] && n/# > (# - 1)/2) & ] ) == 1, 1, 1 + Total[fission /@ (Range@div + n/div - (div + 1)/2)] ] ``` where `div` is the number of integers in the maximal partition. The main differences are that we can't deal with half-integer values in Fission so I'm doing a lot of things multiplied by two, and that there is no recursion in Fission. To work around this, I'm pushing all the integers in a partition in a queue to be processed later. For each number we process, we'll increment a counter by one and once the queue is empty, we'll release the counter and send it off to be printed. (A queue, `Q`, works exactly like `K`, just in FIFO order.) Here is a framework for this concept: ``` +--- input goes in here v SQS ---> compute div from n D /8/ ~4X | /~KSA / 3 +-----------> { +X initial trigger ---> W 6~@/ \/ 4 W ^ / | 3 ^ generate range | | from n and div <-+----- S6 | -then- +---- release new trigger ``` The most important new components are the digits. These are teleporters. All teleporters with the same digit belong together. When an atom hits any teleporter it will be immediately move the next teleporter in the same group, where *next* is determined in the usual left-to-right, top-to-bottom order. These are not necessary, but help with the layouting (and hence golfing a bit). There is also `X` which simply duplicates an atom, sending one copy straight ahead and the other backwards. By now you might be able to sort out most of the framework yourself. The top left corner has the queue of values still to be processed and releases one `n` at a time. One copy of `n` is teleported to the bottom because we need it when computing the range, the other copy goes into the block at the top which computes `div` (this is by far the single largest section of the code). Once `div` has been computed, it is duplicated - one copy increments a counter in the top right corner, which is stored in `K`. The other copy is teleported to the bottom. If `div` was `1`, we deflect it upwards immediately and use it as a trigger for the next iteration, without enqueuing any new values. Otherwise we use `div` and `n` in the section at the bottom to generate the new range (i.e. a stream of atoms with the corresponding masses which are subsequently put in the queue), and then release a new trigger after the range has been completed. Once the queue is empty, the trigger will be reflected, passing straight through the `S` and reappearing in the top right corner, where it releases the counter (the final result) from `A`, which is then teleported to `itoa` via `8`. ### Computing the Fission Number: The Loop Body So all that's left is the two sections to compute `div` and generate the range. Computing `div` is this part: ``` ; {+L /$ \/\/\/\/\/ 5/ @ [~ &@[S\/ \ /A@[ %5 /; & K } [S/ \ A$@S S\/ \/\/\/ \/>\ /S]@A / \ X X /> \ +\ A\ / \ / / ~A\; +;\ /@ ZX [K / {/ / @ @ } \ X @ \AS </ \V / }SZS S/ X ;;@\ /;X /> \ ; X X \@+ >/ }$S SZS\+; //\V / \\ /\; X X @ @ \~K{ \0X / /~/V\V / 0W// \ Z [K \ //\ \ /\7\A /;7/\/ ``` You've probably seen enough now to puzzle this out for yourself with some patience. The high-level breakdown is this: The first 12 columns or so generate a stream of divisors of `2n`. The next 10 columns filter out those that don't satisfy `OddQ@# == IntegerQ[n/#]`. The next 8 columns filter out those that don't satisfy `n/# > (# - 1)/2)`. Finally we push all valid divisors on a stack, and once we're done we empty the entire stack into a fusion reactor (overwriting all but the last/largest divisor) and then release the result, followed by eliminating its energy (which was non-zero from checking the inequality). There are a lot of crazy paths in there that don't really do anything. Predominantly, the `\/\/\/\/` madness at the top (the `5`s are also part of it) and one path around the bottom (that goes through the `7`s). I had to add these to deal with some nasty race conditions. Fission could use a delay component... The code that generates the new range from `n` and `div` is this: ``` /MJ $$\ 4}K~@\ &] @\ 3/\ \{ }$A/1 2 }Y~K <\ \@ / \@<+@^ 1;}++@ 2 ; \ / ``` We first compute `n/div - (div + 1)/2` (both terms floored, which yields the same result) and store for later. Then we generate a range from `div` down to `1` and add the stored value to each of them. There are two new common patterns in both of these, that I should mention: One is `SX` or `ZX` hit from below (or rotated versions). This is a nice way to duplicate an atom if you want one copy to go straight ahead (since redirecting the outputs of a fusion reactor can sometimes be cumbersome). The `S` or `Z` rotates the atom into the `X` and then rotates the mirrored copy back into the original direction of propagation. The other pattern is ``` [K \A --> output ``` If we store any value in `K` we can repeatedly retrieve it by hitting `K` with negative energy from the top. The `A` duplicates the value we're interested in and sends what copy right back onto the stack for the next time we need it. Well, that was quite a tome... but if you actually got through this, I hope you got the idea that Fission i͝s̢̘̗̗ ͢i̟nç̮̩r̸̭̬̱͔e̟̹̟̜͟d̙i̠͙͎̖͓̯b̘̠͎̭̰̼l̶̪̙̮̥̮y̠̠͎̺͜ ͚̬̮f̟͞u̱̦̰͍n͍ ̜̠̙t̸̳̩̝o ̫͉̙͠p̯̱̭͙̜͙͞ŕ̮͓̜o̢̙̣̭g̩̼̣̝r̤͍͔̘̟ͅa̪̜͇m̳̭͔̤̞ͅ ͕̺͉̫̀ͅi͜n̳̯̗̳͇̹.̫̞̲̞̜̳ [Answer] # Pyth, ~~23~~ ~~22~~ 21 bytes ``` Lh&lJfqbsT.:tUb)syMeJ ``` This defines a recursive function `y`. Try it online: [Demonstration](https://pyth.herokuapp.com/?code=Lh%26lJfqbsT.%3AtUb)syMeJ%0A%22N%3D24%3A+%22%0Ay24%0A%22First+40+terms%3A+%22%0Amyhd40&input=24&debug=0) ### Explanation: ``` L define a function y(b): return ... tUb the list [1, 2, ..., b-1] .: ) generate all consecutive sub-sequences f filter for sub-sequences T, which satisfy: qbsT b == sum(T) J and store them in J return lJ len(J) & and (if len(J) == 0 then 0 else ...) eJ last element of J (=longest sub-sequence) yM recursive calls for all these numbers s sum h incremented by one (counting the current node) ``` [Answer] # CJam, ~~42~~ 41 bytes ``` ri]{_{:X,:)_few:+W%{1bX=}=}%{,(},e_}h]e_, ``` A simple Breadth first traversal and a stopping condition of empty next level. **How it works**: ``` ri] e# This represents the root of the fissile tree { }h e# Now we run a do-while loop _{ }% e# Copy the nodes at the current level and map them e# via this code block to get next level nodes :X,:) e# Store the node value in X and get array [1..X] _few e# Copy the array and get continuous slices of e# length 1 through X from the array [1..X] :+W% e# Right now, we have an array of array with each e# array containing slice of same length. We join e# those arrays and reverse them to get slices of e# higher length in front of lower lengths {1bX=}= e# Choose the first slice whose sum is same as X e# The reversal above makes sure that we give e# preference to slice of higher length in case of e# multiple slices add up to X {,(}, e# Filter out slices of length 1 which basically e# mean that the current node cannot be split up e_ e# Join all slices in a single array. This is our e# next level in the Fissile tree. If this is empty e# it means that all no further node can be e# decomposed. In an {}h do-while loop, this fact e# itself becomes the stopping condition for the e# loop ]e_, e# Wrap all levels in an array. Flatten the array e# and take its length ``` [Try it online here](http://cjam.aditsu.net/#code=ri%5D%7B_%7B%3AX%2C%3A)_few%3A%2BW%25%7B1bX%3D%7D%3D%7D%25%7B%2C(%7D%2Ce_%7Dh%5De_%2C&input=43) [Answer] # Python 3, 112 bytes ``` def f(n,c=0): d=n-c;s=(n-d*~-d/2)/d return(s%1or s<1)and f(n,c+1)or+(d<2)or-~sum(f(int(s)+i)for i in range(d)) ``` 4 bytes saved thanks to @FryAmTheEggman. Explanation coming later... **Bonus fact:** Every power of 2 has a Fission number of 1. This is because the sum of an even length sequence is always the sum of the two middle numbers, which is odd, multiplied by half the length of the sequence, which is integer. The sum of an odd length sequence is the middle number multiplied by the sequence length, which is odd. So because a power of 2 doesn't have an odd divisor it can be only expressed as the sum of itself. [Answer] # Python 2, ~~111~~ ~~102~~ 97 bytes **Somewhat readable:** ``` def f(n,c=0):a=n-c;b=n-a*~-a/2;return 1/a or-~sum(map(f,range(b/a,b/a+a)))if b>b%a<1else f(n,c+1) ``` **Not-so-readable:** ``` def f(n,a=0):b=n-a*~-a/2;return b>0and(f(n,a+1)or b%a<1and(1/a or-~sum(map(f,range(b/a,b/a+a))))) ``` Both 97 bytes. `b` is the `n` minus the `(a-1)th` triangular number. If `b % a == 0`, then `n` is the sum of `a` consecutive numbers starting from `b`. [Answer] # Python 2, 86 ``` f=lambda n,R={1}:n-sum(R)and f(n,R^{[min(R),max(R)+1][n>sum(R)]})or-~sum(map(f,R-{n})) ``` Less golfed: ``` def f(n,R={1}): d=sum(R)-n if d==0:return (sum(map(f,R-{n})) if d<0:return f(n,R|{max(R)+1}) if d>0:return f(n,R-{min(R)}) ``` The idea is to test potential runs of consecutive integers that sum to `n`. The run is stored directly directly as a set `R` rather than via its endpoints. We check how the sum of the current run compares to the desired sum `n` via their difference. * If the sum is too large, we cut the smallest element in the run. * If the sum is too small, we extend the run by making its max bigger by 1. * If the sum is correct, we recurse, mapping `f` onto the run, summing, and adding 1 for the current node. If the run is `{n}`, we've tried all non-trivial possible sums, stop the recursion by removing `n` first. Thanks to Sp3000 for saving 3 chars. [Answer] # Python 2, 85 I am very proud of this answer because it already takes tens of seconds for n=9, and 5-10 minutes for n=10. In code golf this is considered a desirable attribute of a program. ``` f=lambda n,a=1,d=1:a/n or[f(a)+f(n-a,1+1%d*a)+1/d,f(n,a+d/n,d%n+1)][2*n!=-~d*(2*a+d)] ``` There is also a short-circuiting version that does not take so long and uses the same amount of bytes: ``` f=lambda n,a=1,d=1:a/n or~d*(2*a+d)+n*2and f(n,a+d/n,d%n+1)or f(a)+f(n-a,1+1%d*a)+1/d ``` It may be faster, but at least it exceeds the default recursion limit once n goes a little above 40. The idea is to do a brute force search for numbers `a` and `d` such that `a + a+1 + ... + a+d == n`, on values between 1 and `n`. The `f(n,a+d/n,d%n+1)` branch of the recursion loops through the `(a, d)` pairs. In the case that the equality is satisfied, I manage to avoid an expensive `map(range(...))` call by splitting into just two branches regardless of how long the sequence is. The numbers `a+1` through `d` are lumped into one call of `f` by setting the `a` parameter so that a different way to split up the sequence can't be used. [Answer] # Haskell, ~~76~~ 69 bytes ``` f x=head$[1+sum(map f[y..z])|y<-[1..x-1],z<-[y..x],sum[y..z]==x]++[1] ``` Usage: ``` *Main> map f [1..40] [1,1,3,1,5,6,5,1,6,7,12,10,12,11,12,1,8,16,14,17,18,18,23,13,21,18,22,23,24,19,14,1,22,20,23,24,31,27,25,26] ``` How it works: ``` [ [y..z] |y<-[1..x-1],z<-[y..x],sum[y..z]==x] make a list of lists with all consecutive integers (at least 2 elements) that sum up to x, sorted by lowest number, e.g. 9 -> [[2,3,4],[4,5]]. 1+sum(map f[...]) recursively calculate the Fission Number for each list [...]++[1] always append the 1 to the list of Fission Numbers. head take the first element, which is either the Fission Number of the longest list or if there's no list, the 1 appended in the step before. ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 66 bytes ``` ^|$ , (`,(1+?)(?=(?<1>1\1)+\D) $0; +)`,(1*);1\1 ,$1,1$1; ^,|1 . 1 ``` Takes input and prints output in unary. You can put each line in a single file or run the code as is with the `-s` flag. E.g.: ``` > echo -n 1111111|retina -s fission 11111 ``` Explanation: * We keep a comma-delimited list of the numbers to be splitted. * For every number we take the smallest starting value which can crate a valid splitup and delimit it from the rest with a semicolon. * If there is a semicolon inside a number we change it to a comma and delimit the next properly sized (length of previous element + 1) part of the number. * We repeat step 2 and 3 until changes happen. * We get a comma for every leaf and a semicolon for every inner node plus an extra comma because we started with two comma. So we remove a comma and the numbers' parts (`1`'s) and convert the rest to `1`'s. The states of the string throughout the process with input `11111111111111 (unary 14)`: ``` ,11111111111111, ,11;111111111111, ,11,1;11,1111,11;111;, ,11,1,11;,1111,11,1;11;;, ,11,1,11;,1111,11,1,11;;;, ,,;,,,,;;;, 11111111111 ``` Many thanks for @MartinButtner for the help in chat! [Answer] ## CJam (43 bytes) ``` qi,{):X),_m*{{_)*2/}/-X=}=~\,>0\{~$+}/)}%W= ``` [Online demo](http://cjam.aditsu.net/#code=qi%2C%7B)%3AX)%2C_m*%7B%7B_)*2%2F%7D%2F-X%3D%7D%3D~%5C%2C%3E0%5C%7B~%24%2B%7D%2F)%7D%25W%3D&input=40) I'm sure that I'm missing some tricks with the advanced loops, but this does neatly exploit the CJam property (which has previously annoyed me) that inside a `%` map the results remain on the stack, and can therefore be accessed using `$` with a negative offset. [Answer] # Go, 133 bytes ``` func 算(n int)int{Σ:=1;for i:=0;i<n;i++{for j:=0;j<n;j++{if i*i+i-j*j-j==2*n{for k:=j+1;k<=i;k++{Σ+=算(k)};j,i=n,n}}};return Σ} ``` This is my first code golf, sorry if I made any mistakes. This uses the idea that the fissile "composition" can also be seen as a difference between two sequences of ordered integers. For example take the fissile "composition" for the number 13. It is 6,7. But it can be seen as the sum of integers 1...7 minus the sum of integers 1...5 ``` A: 1 2 3 4 5 6 7 sum = 28 B: 1 2 3 4 5 sum = 15 A-B: 6 7 sum = 13, which is also 28-15 = 13 ``` Recall the formula from Gauss's school days,sum 1...n=(n^2+n)/2. So to find a composition of sequential integers for a given n, we could also say, we are searching for 'end points' p and q along the range 1...n so that (p^2+p)/2 - (q^2+q)/2 = n. In the above example, we would have been searching for 'end points' 5 and 7 because 7^2+7=56/2, 5^2+5=30/2, 56/2-30/2 = 28-15 = 13. Now there are multiple possible ways to fissile-compose a number, as Martin noted 9 = 2 + 3 + 4 but also 4 + 5. But it seems obvious that the "lowest" starting sequence will also be the longest, because it takes more little-numbers to sum up to a big number than it does medium-sized numbers. (I have no proof unfortunately) So to find the composition of 9, test every 'end point pair', p and q, iterating both p and q separately from 0 to 9, and test if p^p+p/2 - q^2+q/2 = 9. Or, more simply, multiply the equation by 2, to avoid the division issues of rounding and keep all math in integers. Then we are looking for p and q such that (p^p+p) - (q^q+q) = 9\*2. The first match we find will be the Fissile composition endpoints because, as noted, the lowest group of numbers will also be the longest, and we are searching low-to-high (0 to 9). We break out of the loop as soon as we find a match. Now the recursive function finds those 'fissile end points' p and q for the given n, then recalls-itself for each of the 'children' in the tree from p to q. For 9, it would find 1 and 4, (20-2=18) then it would re-call itself on 2, 3, and 4, summing the results. For numbers like 4 it simply never finds a match, and so returns '1'. This might be shortenable but this is like my third go program, and I am no recursion expert. Thanks for reading. [Answer] # [Husk](https://github.com/barbuz/Husk), 24 bytes ``` LΣΣU¡(fo¬εṁm₁);; ḟo=¹ΣQḣ ``` [Try it online!](https://tio.run/##ATIAzf9odXNr//9MzqPOo1XCoShmb8KszrXhuYFt4oKBKTs7CuG4n289wrnOo1HhuKP///8yNA "Husk – Try It Online") or [Verify first 40 values](https://tio.run/##yygtzv6f@6ip8eGOxSYG/33OLT63OPTQQo20/ENrzm19uLMRKNekaW3N9XDH/HzbQzvPLQ4Eqvz/HwA "Husk – Try It Online") ## Explanation ``` Function ₁: Get the longest slice of numbers ḟo=¹ΣQḣ ḣ range 1..n Q all subsequences ḟo get the first value which satisfies: Σ sum = equals ¹ argument? ``` Taking the first value works because Husk orders subsequences lexicographically, and the longest sequence will always be the one which is lexicographically smallest. ``` LΣΣU¡(fo¬εṁm₁);; ;; nest the input twice: 24 → [[24]] (conversion to node) ¡ iterate infinitely, producing intermediate results ṁ map each node list to m₁ it's elements converted to their fissions ṁ and join them fo filter using two functions ¬ε is it not of length <1? (this removes all nodes which cannot be broken down) U cut at first non-unique element ΣΣ join all the nested nodes into one list L length ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` →ṁ₀-¹ḟo=¹ΣQḣ ``` [Try it online!](https://tio.run/##ASQA2/9odXNr///ihpLhuYHigoAtwrnhuJ9vPcK5zqNR4bij////MTE "Husk – Try It Online") ## Explanation ``` →ṁ₀-¹ḟo=¹ΣQḣ Input is a number, say n=24. ḣ Range from 1: [1,2,3,..,23] Q All slices in increasing order of last element: [[1],[2],[1,2],[3],..,[1,2,..,24]] ḟ Find first slice for which this is truthy: o Composition of two functions: Σ Sum =¹ equals n. Result is [7,8,9]. -¹ Remove first occurrence of n (only relevant when the list is [n]). ṁ Map and sum ₀ this function recursively: 12 → Increment: 13 ``` [Answer] # CJam, ~~40~~ ~~35~~ 33 bytes ``` ri{__,f-_few:+{1b1$=}=|{F}*}:F~], ``` *Thanks to @Optimizer for suggesting `few`, which saved 2 bytes.* Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=ri%7B__%2Cf-_few%3A%2B%7B1b1%24%3D%7D%3D%7C%7BF%7D*%7D%3AF~%5D%2C&input=24). ### How it works ``` ri e# Read an integer from STDIN. { e# Define function F(X): _ e# Push X. _, e# Push [0 ... X-1]. f- e# Subract each from X. Pushes Y := [X ... 1]. _few e# Push all overlapping slices of Y of length in Y. :+ e# Consolidate the slices of different lenghts in a single array. { e# Find the first slice S such that... 1b e# the sum of its elements... 1$= e# equals X. }= e# Since Y is in descending order, the first matching slice is also the longest. | e# Set union with [X]. This adds X to the beginning of the S if S != [X]. {F}* e# Execute F for each element of S except the first (X). }:F e# ~ e# Execute F for the input. ], e# Count the integers on the stack. ``` ]
[Question] [ You must evaluate a string written in [Reverse Polish notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation) and output the result. The program must accept an input and return the output. For programming languages that do not have functions to receive input/output, you can assume functions like readLine/print. You are not allowed to use any kind of "eval" in the program. Numbers and operators are separated by one **or more** spaces. You must support at least the +, -, \* and / operators. You need to add support to negative numbers (for example, `-4` is not the same thing as `0 4 -`) and floating point numbers. **You can assume the input is valid and follows the rules above** ## Test Cases Input: ``` -4 5 + ``` Output: ``` 1 ``` --- Input: ``` 5 2 / ``` Output: ``` 2.5 ``` --- Input: ``` 5 2.5 / ``` Output: ``` 2 ``` --- Input: ``` 5 1 2 + 4 * 3 - + ``` Output: ``` 14 ``` --- Input: ``` 4 2 5 * + 1 3 2 * + / ``` Output: ``` 2 ``` [Answer] ## Ruby - 95 77 characters ``` a=[] gets.split.each{|b|a<<(b=~/\d/?b.to_f: (j,k=a.pop 2;j.send b,k))} p a[0] ``` Takes input on stdin. ### Testing code ``` [ "-4 5 +", "5 2 /", "5 2.5 /", "5 1 2 + 4 * 3 - +", "4 2 5 * + 1 3 2 * + /", "12 8 3 * 6 / - 2 + -20.5 " ].each do |test| puts "[#{test}] gives #{`echo '#{test}' | ruby golf-polish.rb`}" end ``` gives ``` [-4 5 +] gives 1.0 [5 2 /] gives 2.5 [5 2.5 /] gives 2.0 [5 1 2 + 4 * 3 - +] gives 14.0 [4 2 5 * + 1 3 2 * + /] gives 2.0 [12 8 3 * 6 / - 2 + -20.5 ] gives 10.0 ``` Unlike the C version this returns the last valid result if there are extra numbers appended to the input it seems. [Answer] ## Python - 124 chars ``` s=[1,1] for i in raw_input().split():b,a=map(float,s[:2]);s[:2]=[[a+b],[a-b],[a*b],[a/b],[i,b,a]]["+-*/".find(i)] print s[0] ``` **Python - 133 chars** ``` s=[1,1] for i in raw_input().split():b,a=map(float,s[:2]);s={'+':[a+b],'-':[a-b],'*':[a*b],'/':[a/b]}.get(i,[i,b,a])+s[2:] print s[0] ``` [Answer] ## Scheme, 162 chars (Line breaks added for clarity—all are optional.) ``` (let l((s'()))(let((t(read)))(cond((number? t)(l`(,t,@s)))((assq t `((+,+)(-,-)(*,*)(/,/)))=>(lambda(a)(l`(,((cadr a)(cadr s)(car s)) ,@(cddr s)))))(else(car s))))) ``` Fully-formatted (ungolfed) version: ``` (let loop ((stack '())) (let ((token (read))) (cond ((number? token) (loop `(,token ,@stack))) ((assq token `((+ ,+) (- ,-) (* ,*) (/ ,/))) => (lambda (ass) (loop `(,((cadr ass) (cadr stack) (car stack)) ,@(cddr stack))))) (else (car stack))))) ``` --- **Selected commentary** ``(,foo ,@bar)` is the same as `(cons foo bar)` (i.e., it (effectively†) returns a new list with `foo` prepended to `bar`), except it's one character shorter if you compress all the spaces out. Thus, you can read the iteration clauses as `(loop (cons token stack))` and `(loop (cons ((cadr ass) (cadr stack) (car stack)) (cddr stack)))` if that's easier on your eyes. ``((+ ,+) (- ,-) (* ,*) (/ ,/))` creates an association list with the *symbol* `+` paired with the *procedure* `+`, and likewise with the other operators. Thus it's a simple symbol lookup table (bare words are `(read)` in as symbols, which is why no further processing on `token` is necessary). Association lists have O(n) lookup, and thus are only suitable for short lists, as is the case here. :-P † This is not technically accurate, but, for non-Lisp programmers, it gets a right-enough idea across. [Answer] # MATLAB – 158, 147 ``` C=strsplit(input('','s'));D=str2double(C);q=[];for i=1:numel(D),if isnan(D(i)),f=str2func(C{i});q=[f(q(2),q(1)) q(3:end)];else q=[D(i) q];end,end,q ``` (input is read from user input, output printed out). --- Below is the code prettified and commented, it pretty much implements the [postfix algorithm](https://en.wikipedia.org/wiki/Reverse_Polish_notation#Postfix_algorithm) described (with the assumption that expressions are valid): ``` C = strsplit(input('','s')); % prompt user for input and split string by spaces D = str2double(C); % convert to numbers, non-numeric are set to NaN q = []; % initialize stack (array) for i=1:numel(D) % for each value if isnan(D(i)) % if it is an operator f = str2func(C{i}); % convert op to a function q = [f(q(2),q(1)) q(3:end)]; % pop top two values, apply op and push result else q = [D(i) q]; % else push value on stack end end q % show result ``` --- ## Bonus: In the code above, we assume operators are always binary (`+`, `-`, `*`, `/`). We can generalize it by using `nargin(f)` to determine the number of arguments the operand/function requires, and pop the right amount of values from the stack accordingly, as in: ``` f = str2func(C{i}); n = nargin(f); args = num2cell(q(n:-1:1)); q = [f(args{:}) q(n+1:end)]; ``` That way we can evaluate expressions like: ``` str = '6 5 1 2 mean_of_three 1 + 4 * +' ``` where `mean_of_three` is a user-defined function with three inputs: ``` function d = mean_of_three(a,b,c) d = (a+b+c)/3; end ``` [Answer] ## c -- 424 necessary character ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #define O(X) g=o();g=o() X g;u(g);break; char*p=NULL,*b;size_t a,n=0;float g,s[99];float o(){return s[--n];}; void u(float v){s[n++]=v;};int main(){getdelim(&p,&a,EOF,stdin);for(;;){ b=strsep(&p," \n\t");if(3>p-b){if(*b>='0'&&*b<='9')goto n;switch(*b){case 0: case EOF:printf("%f\n",o());return 0;case'+':O(+)case'-':O(-)case'*':O(*) case'/':O(/)}}else n:u(atof(b));}} ``` Assumes that you have a new enough libc to include `getdelim` in stdio.h. The approach is straight ahead, the whole input is read into a buffer, then we tokenize with `strsep` and use length and initial character to determine the class of each. There is no protection against bad input. Feed it "+ - \* / + - ...", and it will happily pop stuff off the memory "below" the stack until it seg faults. All non-operators are interpreted as floats by `atof` which means zero value if they don't look like numbers. **Readable and commented:** ``` #include <stdio.h> #include <stdlib.h> #include <string.h> char *p=NULL,*b; size_t a,n=0; float g,s[99]; float o(){ /* pOp */ //printf("\tpoping '%f'\n",s[n-1]); return s[--n]; }; void u(float v){ /* pUsh */ //printf("\tpushing '%f'\n",v); s[n++]=v; }; int main(){ getdelim(&p,&a,EOF,stdin); /* get all the input */ for(;;){ b=strsep(&p," \n\t"); /* now *b though *(p-1) is a token and p points at the rest of the input */ if(3>p-b){ if (*b>='0'&&*b<='9') goto n; //printf("Got 1 char token '%c'\n",*b); switch (*b) { case 0: case EOF: printf("%f\n",o()); return 0; case '+': g=o(); g=o()+g; u(g); break; case '-': g=o(); g=o()-g; u(g); break; case '*': g=o(); g=o()*g; u(g); break; case '/': g=o(); g=o()/g; u(g); break; /* all other cases viciously ignored */ } } else { n: //printf("Got token '%s' (%f)\n",b,atof(b)); u(atof(b)); } } } ``` **Validation:** ``` $ gcc -c99 rpn_golf.c $ wc rpn_golf.c 9 34 433 rpn_golf.c $ echo -4 5 + | ./a.out 1.000000 $ echo 5 2 / | ./a.out 2.500000 $ echo 5 2.5 / | ./a.out 2.000000 ``` Heh! Gotta quote anything with `*` in it... ``` $ echo "5 1 2 + 4 * 3 - +" | ./a.out 14.000000 $ echo "4 2 5 * + 1 3 2 * + /" | ./a.out 2.000000 ``` and my own test case ``` $ echo "12 8 3 * 6 / - 2 + -20.5 " | ./a.out -20.500000 ``` [Answer] ## Haskell (155) ``` f#(a:b:c)=b`f`a:c (s:_)![]=print s s!("+":v)=(+)#s!v s!("-":v)=(-)#s!v s!("*":v)=(*)#s!v s!("/":v)=(/)#s!v s!(n:v)=(read n:s)!v main=getLine>>=([]!).words ``` [Answer] ## Perl (134) ``` @a=split/\s/,<>;/\d/?push@s,$_:($x=pop@s,$y=pop@s,push@s,('+'eq$_?$x+$y:'-'eq$_?$y-$x:'*'eq$_?$x*$y:'/'eq$_?$y/$x:0))for@a;print pop@s ``` Next time, I'm going to use the recursive regexp thing. Ungolfed: ``` @a = split /\s/, <>; for (@a) { /\d/ ? (push @s, $_) : ( $x = pop @s, $y = pop @s, push @s , ( '+' eq $_ ? $x + $y : '-' eq $_ ? $y - $x : '*' eq $_ ? $x * $y : '/' eq $_ ? $y / $x : 0 ) ) } print(pop @s); ``` I though F# is my only dream programming language... [Answer] ### Windows PowerShell, 152 ~~181~~ ~~192~~ In readable form, because by now it's only two lines with no chance of breaking them up: ``` $s=@() switch -r(-split$input){ '\+' {$s[1]+=$s[0]} '-' {$s[1]-=$s[0]} '\*' {$s[1]*=$s[0]} '/' {$s[1]/=$s[0]} '-?[\d.]+' {$s=0,+$_+$s} '.' {$s=$s[1..($s.count)]}} $s ``` **2010-01-30 11:07** (192) – First attempt. **2010-01-30 11:09** (170) – Turning the function into a scriptblock solves the scope issues. Just makes each invocation two bytes longer. **2010-01-30 11:19** (188) – Didn't solve the scope issue, the test case just masked it. Removed the index from the final output and removed a superfluous line break, though. And changed double to `float`. **2010-01-30 11:19** (181) – Can't even remember my own advice. Casting to a numeric type can be done in a single char. **2010-01-30 11:39** (152) – Greatly reduced by using regex matching in the `switch`. Completely solves the previous scope issues with accessing the stack to pop it. [Answer] **[Racket](http://racket-lang.org) 131:** ``` (let l((s 0))(define t(read))(cond[(real? t) (l`(,t,@s))][(memq t'(+ - * /))(l`(,((eval t)(cadr s) (car s)),@(cddr s)))][0(car s)])) ``` Line breaks optional. Based on Chris Jester-Young's solution for Scheme. [Answer] ## Python, 166 characters ``` import os,operator as o S=[] for i in os.read(0,99).split(): try:S=[float(i)]+S except:S=[{'+':o.add,'-':o.sub,'/':o.div,'*':o.mul}[i](S[1],S[0])]+S[2:] print S[0] ``` [Answer] # Python 3, 119 bytes ``` s=[] for x in input().split(): try:s+=float(x), except:o='-*+'.find(x);*s,a,b=s;s+=(a+b*~-o,a*b**o)[o%2], print(s[0]) ``` Input: `5 1 1 - -7 0 * + - 2 /` Output: `2.5` (You can find a 128-character Python 2 version in the edit history.) [Answer] # JavaScript (157) This code assumes there are these two functions: readLine and print ``` a=readLine().split(/ +/g);s=[];for(i in a){v=a[i];if(isNaN(+v)){f=s.pop();p=s.pop();s.push([p+f,p-f,p*f,p/f]['+-*/'.indexOf(v)])}else{s.push(+v)}}print(s[0]) ``` [Answer] ## Perl, 128 This isn't really competitive next to the other Perl answer, but explores a different (suboptimal) path. ``` perl -plE '@_=split" ";$_=$_[$i],/\d|| do{($a,$b)=splice@_,$i-=2,2;$_[$i--]= "+"eq$_?$a+$b:"-"eq$_?$a-$b:"*"eq$_? $a*$b:$a/$b;}while++$i<@_' ``` Characters counted as diff to a simple `perl -e ''` invocation. [Answer] # flex - 157 ``` %{ float b[100],*s=b; #define O(o) s--;*(s-1)=*(s-1)o*s; %} %% -?[0-9.]+ *s++=strtof(yytext,0); \+ O(+) - O(-) \* O(*) \/ O(/) \n printf("%g\n",*--s); . %% ``` If you aren't familiar, compile with `flex rpn.l && gcc -lfl lex.yy.c` [Answer] Python, 161 characters: ``` from operator import*;s=[];i=raw_input().split(' ') q="*+-/";o=[mul,add,0,sub,0,div] for c in i: if c in q:s=[o[ord(c)-42](*s[1::-1])]+s else:s=[float(c)]+s print(s[0]) ``` [Answer] ## PHP, ~~439~~ ~~265~~ ~~263~~ ~~262~~ ~~244~~ 240 characters ``` <? $c=fgets(STDIN);$a=array_values(array_filter(explode(" ",$c)));$s[]=0;foreach($a as$b){if(floatval($b)){$s[]=$b;continue;}$d=array_pop($s);$e=array_pop($s);$s[]=$b=="+"?$e+$d:($b=="-"?$e-$d:($b=="*"?$e*$d:($b=="/"?$e/$d:"")));}echo$s[1]; ``` This code should work with stdin, though it is not tested with stdin. It has been tested on all of the cases, the output (and code) for the last one is here: <http://codepad.viper-7.com/fGbnv6> **Ungolfed, ~~314~~ ~~330~~ 326 characters** ``` <?php $c = fgets(STDIN); $a = array_values(array_filter(explode(" ", $c))); $s[] = 0; foreach($a as $b){ if(floatval($b)){ $s[] = $b; continue; } $d = array_pop($s); $e = array_pop($s); $s[] = $b == "+" ? $e + $d : ($b == "-" ? $e - $d : ($b == "*" ? $e * $d : ($b == "/" ? $e / $d :""))); } echo $s[1]; ``` [Answer] ## Python, 130 characters Would be 124 characters if we dropped `b and` (which some of the Python answers are missing). And it incorporates 42! ``` s=[] for x in raw_input().split(): try:s=[float(x)]+s except:b,a=s[:2];s[:2]=[[a*b,a+b,0,a-b,0,b and a/b][ord(x)-42]] print s[0] ``` [Answer] # Python 3, ~~126~~ 132 chars ``` s=[2,2] for c in input().split(): a,b=s[:2] try:s[:2]=[[a+b,b-a,a*b,a and b/a]["+-*/".index(c)]] except:s=[float(c)]+s print(s[0]) ``` There have been better solutions already, but now that I had written it (without having read the prior submissions, of course - even though I have to admit that my code looks as if I had copypasted them together), I wanted to share it, too. [Answer] # C, 232 229 bytes Fun with recursion. ``` #include <stdlib.h> #define b *p>47|*(p+1)>47 char*p;float a(float m){float n=strtof(p,&p);b?n=a(n):0;for(;*++p==32;);m=*p%43?*p%45?*p%42?m/n:m*n:m-n:m+n;return*++p&&b?a(m):m;}main(c,v)char**v;{printf("%f\n",a(strtof(v[1],&p)));} ``` ## Ungolfed: ``` #include <stdlib.h> /* Detect if next char in buffer is a number */ #define b *p > 47 | *(p+1) > 47 char*p; /* the buffer */ float a(float m) { float n = strtof(p, &p); /* parse the next number */ /* if the next thing is another number, recursively evaluate */ b ? n = a(n) : 0; for(;*++p==32;); /* skip spaces */ /* Perform the arithmetic operation */ m = *p%'+' ? *p%'-' ? *p%'*' ? m/n : m*n : m-n : m+n; /* If there's more stuff, recursively parse that, otherwise return the current computed value */ return *++p && b ? a(m) : m; } int main(int c, char **v) { printf("%f\n", a(strtof(v[1], &p))); } ``` ## Test Cases: ``` $ ./a.out "-4 5 +" 1.000000 $ ./a.out "5 2 /" 2.500000 $ ./a.out "5 2.5 /" 2.000000 $ ./a.out "5 1 2 + 4 * 3 - +" 14.000000 $ ./a.out "4 2 5 * + 1 3 2 * + /" 2.000000 ``` [Answer] # JavaScript ES7, 119 bytes I'm getting a bug with array comprehensions so I've used `.map` ``` (s,t=[])=>(s.split` `.map(i=>+i?t.unshift(+i):t.unshift((r=t.pop(),o=t.pop(),[r+o,r-o,r*o,r/o]['+-*/'.indexOf(i)]))),t) ``` [Try it online at ESFiddle](http://server.vihan.ml/p/esfiddle/?code=f%3D(s%2Ct%3D%5B%5D)%3D%3E(s.split%60%20%60.map(i%3D%3E%2Bi%3Ft.unshift(%2Bi)%3At.unshift((r%3Dt.pop()%2Co%3Dt.pop()%2C%5Br%2Bo%2Cr-o%2Cr*o%2Cr%2Fo%5D%5B'%2B-*%2F'.indexOf(i)%5D)))%2Ct)%3B%0A%0Af(%2211%203%20%2B%22)) [Answer] # C 153 Sometimes a program can be made a bit shorter with more golfing and sometimes you just take completely the wrong route and the much better version is found by someone else. **Thanks to @ceilingcat for finding a much better (and shorter) version** ``` double atof(),s[99],*p=s;y,z;main(c,v)char**v;{for(;--c;*p=z?z-2?~z?z-4?p+=2,atof(*v):*p/y:*p*y:*p-y:*p+y)z=1[*++v]?9:**v-43,y=*p--;printf("%f\n",s[1]);} ``` [Try it online!](https://tio.run/##HY7RCoIwGIVfJYRg@7chml3oGHsQ88JWK6F0qA1m1Kv/bd1858A5HI4RN2MQL9Pr/Lju@nWyhPKlreuOg1OLDHyTz34YieGemns/A3j5ttNMpBBGxs6mN1Hqb5JKO6ZK/l8BTxtweYiABJHAAt1U0QJjvtN1E7dEdeBBxVhINw/jakm2t6cxix@KjsoPIlZY4hEBGRZ4iD65/Ac "C (gcc) – Try It Online") My original version: ``` #include <stdlib.h> #define O(x):--d;s[d]=s[d]x s[d+1];break; float s[99];main(c,v)char**v;{for(int i=1,d=0;i<c;i++)switch(!v[i][1]?*v[i]:' '){case'+'O(+)case'-'O(-)case'*'O(*)case'/'O(/)default:s[++d]=atof(v[i]);}printf("%f\n",s[1]);} ``` If you are compiling it with mingw32 you need to turn off globbing (see <https://www.cygwin.com/ml/cygwin/1999-11/msg00052.html>) by compiling like this: ``` gcc -std=c99 x.c C:\Applications\mingw32\i686-w64-mingw32\lib\CRT_noglob.o ``` If you don't \* is automatically expanded by the mingw32 CRT into filenames. [Answer] ## PHP - 259 characters ``` $n=explode(" ",$_POST["i"]);$s=array();for($i=0;$i<count($n);$s=$d-->0?array_merge($s,!$p?array($b,$a,$c):array($p)):$s){if($c=$n[$i++]){$d=1;$a=array_pop($s);$b=array_pop($s);$p=$c=="+"?$b+$a:($c=="-"?$b-$a:($c=="*"?$b*$a:($c=="/"?$b/$a:false)));}}echo$s[2]; ``` Assuming input in POST variable *i*. [Answer] ## C# - 392 characters ``` namespace System.Collections.Generic{class P{static void Main(){var i=Console.ReadLine().Split(' ');var k=new Stack<float>();float o;foreach(var s in i)switch (s){case "+":k.Push(k.Pop()+k.Pop());break;case "-":o=k.Pop();k.Push(k.Pop()-o);break;case "*":k.Push(k.Pop()*k.Pop());break;case "/":o=k.Pop();k.Push(k.Pop()/o);break;default:k.Push(float.Parse(s));break;}Console.Write(k.Pop());}}} ``` However, if arguments can be used instead of standard input, we can bring it down to ## C# - 366 characters ``` namespace System.Collections.Generic{class P{static void Main(string[] i){var k=new Stack<float>();float o;foreach(var s in i)switch (s){case "+":k.Push(k.Pop()+k.Pop());break;case "-":o=k.Pop();k.Push(k.Pop()-o);break;case "*":k.Push(k.Pop()*k.Pop());break;case "/":o=k.Pop();k.Push(k.Pop()/o);break;default:k.Push(float.Parse(s));break;}Console.Write(k.Pop());}}} ``` [Answer] ### Scala 412 376 349 335 312: ``` object P extends App{ def p(t:List[String],u:List[Double]):Double={ def a=u drop 2 t match{ case Nil=>u.head case x::y=>x match{ case"+"=>p(y,u(1)+u(0)::a) case"-"=>p(y,u(1)-u(0)::a) case"*"=>p(y,u(1)*u(0)::a) case"/"=>p(y,u(1)/u(0)::a) case d=>p(y,d.toDouble::u)}}} println(p((readLine()split " ").toList,Nil))} ``` [Answer] # Python - 206 ``` import sys;i=sys.argv[1].split();s=[];a=s.append;b=s.pop for t in i: if t=="+":a(b()+b()) elif t=="-":m=b();a(b()-m) elif t=="*":a(b()*b()) elif t=="/":m=b();a(b()/m) else:a(float(t)) print(b()) ``` Ungolfed version: ``` # RPN import sys input = sys.argv[1].split() stack = [] # Eval postfix notation for tkn in input: if tkn == "+": stack.append(stack.pop() + stack.pop()) elif tkn == "-": tmp = stack.pop() stack.append(stack.pop() - tmp) elif tkn == "*": stack.append(stack.pop() * stack.pop()) elif tkn == "/": tmp = stack.pop() stack.append(stack.pop()/tmp) else: stack.append(float(tkn)) print(stack.pop()) ``` Input from command-line argument; output on standard output. [Answer] # ECMAScript 6 (131) Just typed together in a few seconds, so it can probably be golfed further or maybe even approached better. I might revisit it tomorrow: ``` f=s=>(p=[],s.split(/\s+/).forEach(t=>+t==t?p.push(t):(b=+p.pop(),a=+p.pop(),p.push(t=='+'?a+b:t=='-'?a-b:t=='*'?a*b:a/b))),p.pop()) ``` [Answer] ## C# - 323 284 241 ``` class P{static void Main(string[] i){int x=0;var a=new float[i.Length];foreach(var s in i){var o="+-*/".IndexOf(s);if(o>-1){float y=a[--x],z=a[--x];a[x++]=o>3?z/y:o>2?z*y:o>1?z-y:y+z;}else a[x++]=float.Parse(s);}System.Console.Write(a[0]);}} ``` Edit: Replacing the Stack with an Array is way shorter Edit2: Replaced the ifs with a ternary expression [Answer] # Python 2 I've tried out some different approaches to the ones published so far. None of these is quite as short as the best Python solutions, but they might still be interesting to some of you. ## Using recursion, 146 ``` def f(s): try:x=s.pop();r=float(x) except:b,s=f(s);a,s=f(s);r=[a+b,a-b,a*b,b and a/b]['+-*'.find(x)] return r,s print f(raw_input().split())[0] ``` ## Using list manipulation, 149 ``` s=raw_input().split() i=0 while s[1:]: o='+-*/'.find(s[i]) if~o:i-=2;a,b=map(float,s[i:i+2]);s[i:i+3]=[[a+b,a-b,a*b,b and a/b][o]] i+=1 print s[0] ``` ## Using `reduce()`, 145 ``` print reduce(lambda s,x:x in'+-*/'and[(lambda b,a:[a+b,a-b,a*b,b and a/b])(*s[:2])['+-*'.find(x)]]+s[2:]or[float(x)]+s,raw_input().split(),[])[0] ``` [Answer] ## Matlab, 228 ``` F='+-/*';f={@plus,@minus,@rdivide,@times};t=strsplit(input('','s'),' ');i=str2double(t);j=~isnan(i);t(j)=num2cell(i(j));while numel(t)>1 n=find(cellfun(@(x)isstr(x),t),1);t{n}=bsxfun(f{t{n}==F},t{n-2:n-1});t(n-2:n-1)=[];end t{1} ``` Ungolfed: ``` F = '+-/*'; %// possible operators f = {@plus,@minus,@rdivide,@times}; %// to be used with bsxfun t = strsplit(input('','s'),' '); %// input string and split by one or multiple spaces i = str2double(t); %// convert each split string to number j =~ isnan(i); %// these were operators, not numbers ... t(j) = num2cell(i(j)); %// ... so restore them while numel(t)>1 n = find(cellfun(@(x)isstr(x),t),1); %// find left-most operator t{n} = bsxfun(f{t{n}==F}, t{n-2:n-1}); %// apply it to preceding numbers and replace t(n-2:n-1)=[]; %// remove used numbers end t{1} %// display result ``` [Answer] # K5, 70 bytes ``` `0:*{$[-9=@*x;((*(+;-;*;%)@"+-*/"?y).-2#x;x,.y)@47<y;(.x;.y)]}/" "\0:` ``` I'm not sure when K5 was released, so this *might* not count. Still awesome! ]
[Question] [ # Challenge Write a non-empty program/function `p` that, given a non-empty input string `s`, outputs the position of the **first occurrence** of each character of `s` in the source code of `p`. For example, if your program is ``` main() { cout << magic << cin } ^0 ^5 ^10 ^15 ^20 ^25 ``` and it receives an input `abcd{`, the output should be ``` [1, x, 9, x, 7] (0-based) [2, x, 10, x, 8] (1-based) ``` Here, `x` represents any output that is not a valid output for a character position (e.g., a negative number, `0` if you use 1-based indexing, `NaN`, `Inf`, the string `potato`, a number greater than your program's length, etc). ## Restrictions Reading the source code is not allowed (like in a proper quine). The use of comments is allowed, but does count towards your score. Input and output can be done in a reasonable format, but must be **unambiguous** (only additional delimiters, no `rand` stream and claiming that the answer is somewhere in there), **consistent** (e.g., the `x` from above should always be the same value) and **human-readable**; for example, a string or a character array. You can assume that the input is a string (or array) of printable ASCII characters; no need to handle the entire Unicode set. --- ### Custom code-page or non-printable ascii in your code? If your language uses a custom code-page (Jelly, APL, etc), you must take that into account (so a program `€æÆ` must output `[1, x, 2]` for an input `€%æ`). Using only non-ASCII characters to output `-1` always (since the input is ASCII-only) is not a valid solution. You may assume that your program natively accepts your custom codepage, i.e., if your program has a method of converting a character `A` to an integer `65` (ASCII encoding), you may assume that it now converts the 65th character in your codepage to `65`. --- Inspired on the following challenge: [Positional Awareness](https://codegolf.stackexchange.com/questions/104017/positional-awareness) [Answer] ## Python2, 55 Bytes ``` a=" )dfi(+m,nprut.';";print map(('a="'+a).find,input()) ``` Starts with a string that contains all the characters used in the code, and then search the indexes [Answer] # [Lenguage](http://esolangs.org/wiki/Lenguage), 56,623 bytes Below is a hexdump of the first 256 bytes. The remaining bytes can be chosen arbitrarily. ``` 0000000: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ................ 0000010: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f ................ 0000020: 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f !"#$%&'()*+,-./ 0000030: 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 0123456789:;<=>? 0000040: 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f @ABCDEFGHIJKLMNO 0000050: 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f PQRSTUVWXYZ[\]^_ 0000060: 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f `abcdefghijklmno 0000070: 70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f pqrstuvwxyz{|}~. 0000080: 80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f ................ 0000090: 90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f ................ 00000a0: a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 aa ab ac ad ae af ................ 00000b0: b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 ba bb bc bd be bf ................ 00000c0: c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ca cb cc cd ce cf ................ 00000d0: d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 da db dc dd de df ................ 00000e0: e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 ea eb ec ed ee ef ................ 00000f0: f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 fa fb fc fd fe ff ................ ``` Output is in bytes, as customary for brainfuck et al. ### How it works This is a simple cat program, specifically `,[.,]`. The source code contains all 256 byte values in order, so each byte's index in it matches its value. [Answer] # [Lenguage](https://esolangs.org/wiki/Lenguage), 1.22e7 bytes Consists of `12263215` `NUL` bytes, *(Hex 0x00)*. Outputs a `NUL` for every character that doesn't appear in the source. > > The ruse is that the input will never contain a `NUL`, so we always output the amount of `NUL`s that there are characters in the input. > > > This translates to the following Brainfuck program ``` ,[[-].,] ``` And with a breakdown... ``` ,[[-].,] ,[ ,] #Basic Input loop. [-] #Zero out the cell. . #Print it (A NUL). ``` *This just shows the sheer power of Lenguage as a golfing language. Fear it.* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes ``` “ṾiЀƓv”v ``` [Try it online!](https://tio.run/nexus/jelly#@/@oYc7DnfsyD0941LTm2OSyRw1zy/7/V3cDCvtn@pc5AfmOZUHqAA "Jelly – TIO Nexus") ### How it works ``` “ṾiЀƓv”v Main link. No arguments. “ṾiЀƓv” Set the left argument and the return value to s := 'ṾiЀƓv'. v Execute the string s as a monadic Jelly program with argument s. Ṿ Uneval; yield a string representation of s, i.e., r := '“ṾiЀƓv”'. Ɠ Read one line from STDIN and evaluate it like Python would. iЀ Find the index of each character in the input in r. v Eval the list of indices as a monadic Jelly program with argument s. Why? This is the shortest way to add the character 'v' to the string s, meaning that we can use r without having to append anything. What? The v atom vectorizes at depth 1 for its left argument, meaning that it acts on arrays of numbers and/or characters. When fed an array of integers, it first converts them to strings, then concatenates the strings and evaluates them as a Jelly program. For example, the array [1, 2, 3] gets cast to the string '123', then evaluates, yielding 123. Something slightly different happens if the array starts with a 0. For example, the array [0, 1, 2] gets cast to '012' just as before, but Jelly views '0' and '12' as two separate tokens; numeric literals cannot start with a 0. Since the Jelly program is monadic, the first token – '0' – sets the return value to 0. Since the second token – '12' – is also a niladic link, the previous return value is printed before changing the return value to 12. Then, the program finishes and the last return value is printed implicitly. ``` [Answer] # pbrain, ~~402~~ ~~356~~ ~~340~~ ~~338~~ 329 bytes ``` [(:<>)+,-.](>>>>>>)+([-]<<[->+>+<<]>>[-<<+>>]>>[-<+<+>>]<[->+<]<[-<->]<)+([-]+++++++[>+++++++++++++<-]>)+([-]+++++[>++++++++<-]>)+(-:<+++[->++++++<]>)+(-:++)+(-:++)+(----:+)+(-:++)+(-:+)+(-:+)+(-:+)+([-]++:++)+([>[->+>+<<]>>[-<<+>>]<:>>+:[[-]>+<]>-[<<<<[-.>]>>>>>>+>>>>>]<<[-]<<+<-]>>>)[-]>>>>>>>,[<<<<<<++<+++++++++++++:>>>>>>,] ``` Phew, @KritixiLithos and I [have been working on this for 4 days now.](http://chat.stackexchange.com/rooms/50556/coding-bf) Prints `0x00` if input char isn't in program, index of the char (1-based) in hex otherwise. [Try it online!](https://tio.run/nexus/bash#bZDBbsMwCIbvewrLmqZUBFu9eogXQT6krZf20CZKdqi07dkz7FhaWu0/AOYDC0jH82DsIk0g3kGLLjZctINGMBIJMjAQRWZBImBeIyhhwZQdob7WJlglDFsRRt7wP1oBBspprHmqSYCNUwV4SD/Z8vsKhf8ZnQIzBNGyPDajEOUVXV4qC4ota6spo@kpBCvmtjQoAXpYLlQcF8vjNPRTd31J@bR4M/Z1b8238cP46cfD1F1u1ZlaqfB@PxkcZ43mpFEydvbO@Tfje7ss3eF4kvj1E97TR38GbB3xLw) ### Explanation: ``` [(:<>)+,-.] All chars listed here; like other submissions (>>>>>>) @KritixiLithos added this part; I don't know what it does but saves the program +([-]<<[->+>+<<]>>[-<<+>>]>>[-<+<+>>]<[->+<]<[-<->]<) Comparison ;calculates z=x!=y and puts it in between x and y Start; X _ _ _ Y ^ End; X Z _ _ Y ^ +([-]+++++++[>+++++++++++++<-]>) Function to add 91 to the tape +([-]+++++[>++++++++<-]>) Function to add 40 to the tape +(-:<+++[->++++++<]>) Function to add 58 to the tape +(-:++) Function to add 60 to the tape +(-:++) Function to add 62 to the tape +(----:+) Function to add 41 to the tape +(-:++) Function to add 43 to the tape +(-:+) Function to add 44 to the tape +(-:+) Function to add 45 to the tape +(-:+) Function to add 46 to the tape +([-]++:++) Function to add 93 to the tape +([>[->+>+<<]>>[-<<+>>]<:>>+:[[-]>+<]>-[<‌​<<<[-.>]>>>>>>+>>>>>]<<[-]<<+<-]>>>) ``` This last function is the loop. It loops through the selected characters `[(:<>)+,-.]` in order and compares the input with the character. Now I'm going to give a deeper explanation on how this loop works. ``` 12-n n+2 _ n+2: _ _ _ i _ _ _ _ _ _; n=loop counter ^ ; i=input ``` The stack looks like that while in a loop. The loop will run until `12-n` is `0`. Then we have the counter which is `n+2`. This counter is also the number of the function for each of the selected characters. So when `n=0`, `n+2` will be corresponding to the first character, ie `[`. `>[->+>+<<]>>[-<<+>>]<:` does just that, it converts the counter to the character. Once the pointer is where the caret is, we will compare the character produced from the counter variable with the input while preserving them. ``` 12-n n+2 _ n+2: Z _ _ i _ _ _ _ _ _; n=loop counter ^ ; i=input ``` `Z` is `0` when the character is equal to the input, or some other non-zero integer otherwise. Now we come up with an if-statement to check this equality. ``` [[-]>+<] ``` If `Z` is non-zero, ie the character and the input are *not* the same, we increment the next memory place. After we come out of this if-statement, we decrement the next memory place. Now this memory place contains `!Z`. Finally using this, we output the index of the character if it matches with the input and then exit the loop forcibly. Else, we continue on with the loop until either it is over or a match is found. ``` [-]>>>>>>> Clears first byte; goes to position to start program ,[<<<<<<++<+++++++++++++:>>>>>>,] Loops inputs ``` [Answer] ## [CJam](https://sourceforge.net/p/cjam), ~~14~~ 12 bytes ``` {sq\f#p_~}_~ ``` Uses 0-based indexing and `-1` for characters that don't appear in the source. [Try it online!](https://tio.run/nexus/cjam#@19dXBiTplwQX1cbX/f/f2JSYUGackxxNZAHAA "CJam – TIO Nexus") [Answer] # Javascript, 34 bytes ``` f=a=>a.map(v=>('f='+f).indexOf(v)) ``` It takes input as array of strings, `x` is `-1` (0-based indexing). [Answer] # C, ~~153~~ ~~152~~ 143 bytes ``` char s[99],p[]="odeflnrti%()*+-0;<={}\\";c;f(char*i){sprintf(s,"char s[99],p[]=\"%s",p);for(c=0;c<strlen(i);)printf("%d ",strchr(s,i[c++])-s);} ``` [Try it online!](https://tio.run/nexus/c-gcc#XYxBCoMwEADvfYUsBLIawausviTmkG4MBmyUxJv4dk2hp16Hmbl5sanKuu@N2rUZYXOzX2M6gpBYN21Hw3he0wTE5OVXrgOeeU8hHl5mBX/9BCKD2pH8liSPHfGQj7TOUQYk/GUgXAWqcF5SeQTNTWOwzUjX62NDlHgWyb7ZaSjsvh8 "C (gcc) – TIO Nexus") [Answer] ## Ruby, ~~41 88 86 71 69 67 61~~ 56 bytes ``` a='p$<.chrs{| #index};"';$<.chars{|c|p"a='#{a}".index c} ``` Thx Lynn for killing 6 bytes [Answer] # ><> (Fish) 70 bytes ``` #.0+4*a5;!?l|!?f4*b+l1--naolc3*1+0.01?!|~ed+0.0+2e-{:;!?+1:i-1:r}+2:" ``` Probably the longest ><> 1 liner I've ever made. It will print the output for each character found on a separate line (0 indexed). A non found character will always print the length of the code + 1 (I could change this if deemed not okay in it's current state) so in this case 71 will always be the "Not found" characters. I'll run up an explanation once I get the time. Some test cases; ##K = 1\n1\n71 #"# = 1\n69\n1 [Try it online](http://fish.tryitonline.net/#code=ICMuMCs0KmE1OyE_bHwhP2Y0KmIrbDEtLW5hb2xjMyoxKzAuMDE_IXx-ZWQrMC4wKzJlLXs6OyE_KzE6aS0xOnJ9KzI6Ig&input=IyIj) [><> language](https://fishlanguage.com/playground/TQT63MZyBDuhgn3To) [Answer] # [Perl 6](http://perl6.org/), ~~50~~ 52 bytes ``` {(('R~.index$_) for}\\'R~'{((\'').index($_) for $_)} ``` Translation of [G B's Ruby solution](https://codegolf.stackexchange.com/a/104178/14880) and [Rod's Python solution](https://codegolf.stackexchange.com/a/104184/14880). A lambda that inputs a list of characters and outputs a list of zero-based indexes (`Nil` for nonexistent characters). *EDIT: Fixed an oversight - required adding 2 bytes :(* [Answer] ## Clojure, ~~43~~ ~~56~~ 48 bytes Edit: Damn I forgot about `2`! Increased from 43 to 56. Edit 2: Updated the sample code below this text, updated the number of bytes not to include `(def f ...`) but just the hash-map part. ``` {\{ 0\\ 1\ 3\0 4\1 10\3 14\4 20\2 34 \} 43} ``` The hash-map consists only of characters `01234{\\}`, and it encodes their locations. In Clojure hash-maps can be used functions, as shown in this complete example (`f` could be replaced by the hash-map definition): ``` ; Keeping track of the zero-based index: ; 00000000001111111111222222222233333333334444444444 ; 01234567890123456789012345678901234567890123456789 (def f {\{ 0\\ 1\ 3\0 4\1 10\3 14\4 20\2 34 \} 43}) (map f "0123456789{} \\abcdef") ; (4 10 34 14 20 nil nil nil nil nil 0 43 3 1 nil nil nil nil nil nil) (apply str (keys f)) ; " 01234{\\}" ``` I guess this counts :) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes ``` "'ìsvDyk,"'"ìsvDyk, ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fSf3wmuIyl8psHSV1JRjz//9odSV1HQX1YhBhDCJMQMTh5WByDYgsAxEuIKISRGSDCB0goRScn5takpGZl66QmFRcWpSipxQLAA "05AB1E – Try It Online") This outputs -1 in place of missing chars. --- Luis Mendo posted this (slightly modified) on [Golf you a quine for great good!](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/97458#97458) , adding "s" and "k" to that quine results in this answer as well. However, I can't take credit for that trivial of a modification... Luis, you can message me if you'd like to repost this and I'll just delete it. If you want to see my progress before finding that question, view edits. Well... It ***was*** significantly like his at one point. [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 10 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` "Ṙs€Ȯ"Ṙs€Ȯ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWW5Qe7pxR_KhpzYl1CNaS4qTkYqiCBUuKI06sg7AB) #### Explanation ``` "Ṙs€Ȯ"Ṙs€Ȯ # Implicit input "Ṙs€Ȯ" # Push the string "Ṙs€Ȯ" Ṙ # Surround it by quotes s€Ȯ # Get the index of each character # of the input in the string # Implicit output ``` [Answer] # JavaScript, 39 bytes ``` p=s=>[...s].map(c=>`p=${p}`.indexOf(c)) console.log( p('mapP') ) ``` [Answer] # Pyth, 11 bytes ``` xL_+N"N+_Lx ``` A program that takes input of a `"quoted string"`, with any quotes in the string escaped with a preceding `\`, and prints a list of zero-indexed values with `-1` for characters not in the source. [Try it online!](https://tio.run/nexus/pyth#@1/hE6/tp@SnHe9T8f@/UmJSvE@MkrZfRYQSAA "Pyth – TIO Nexus") **How it works** ``` xL_+N"N+_Lx Program. Input: Q xL_+N"N+_Lx"Q Implicit quote closure and implicit input "N+_Lx" Yield the string "N+_Lx" +N Prepend a quote _ Reverse L Q Map over Q: x Yield the index of the character in the string Implicitly print ``` [Answer] # SmileBASIC, ~~128~~ ~~96~~ ~~88~~ 86 bytes ``` ?R<3+CD,4LINPUT(S$)WHILE""<S$?INSTR("?R<3+CD,4LINPUT(S$)WHILE"+CHR$(34),SHIFT(S$))WEND ``` An important thing to realize is that this is not *really* a quine challenge. You only need the source code up to the **last unique character**. I put at least 1 of each character at the beginning of the code: `?R<3+CD,4LINPUT(S$)WHILE"` so I only have to store a copy of the program up to the first quotation mark. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes input as a character array. Output is 0-based, using `-1` for invalid characters. String input *could* also be used but there would be no separator between the output indices, which shouldn't be an issue as it would be unambiguous seeing as they can only be `0` & `-1`. ``` bb ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=YmI&input=WyJiIiAiYSJd) ``` bb :Implicit map of each U in input array/string b :First 0-based index in U of b : Literal "b" ``` Alternatively: ``` aa ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=YWE&input=WyJiIiAiYSJd) `a` being `lastIndexOf`. [Answer] # Java 8, ~~172~~ ~~122~~ 119 bytes ``` a->/*.forEch(Systemupin"\dxO)+ ;:*/a.forEach(c->System.out.print("a->/*.forEch(Systemupin\"\\dxO)+ ;:".indexOf(c)+" ")) ``` 0-indexed, and gives `-1` for characters that aren't part of the source code. [Try it online.](https://tio.run/##jZJbT8IwGIbv@RVNrzYIxfOJSOIBFRVQ59l6UbqOFbZurh2Cht8@yzYlwxBN2qRf@/bt873pgIxINQiZGNjDhHpEStAmXHyWAOBCscghlIHOrARgFHAbUGOgr6BYcQ9JFTHio5ZQVroCxKxr5VRPPaQiilPQAQLsg4RUG7UycoKoSV3DmkjF/DjkAmJ73DUroL5XrpH0mOhzWm1kEhTECoWRRjHgEgcM8Y8HRFzYbNx1DGpWIICmmdQzmDDueRomZ0o78XWfhgbnov/ySsysR8Xk/576CxcvNcEzm7kRLkBjCLDGhmmQ3zhBsSTFEsOFGi/Ie9RmTt/lg6HniyB8i6SKR@/jyUdRd3B4dNw8OT1rnV9ctjvdq@sb6/bu/uHx6bmoW1ldW9/Y3Nre2S3uW27/98N5J9PS/EOk4aeKLHwg8@wFooZE1CWRNMzcaTFXTxi54TT5Ag) **Explanation:** ``` a-> // Method with character-array parameter and no return-type /*.forEch(Systemupin"\dxO)+ ;:*/ // Comment containing the remaining characters of the code a.forEach(c-> // Loop over the input-array: System.out.print( // Print "a->/*.forEch(Systemupin\"\\dxO)+ ;:" // from a String containing all the characters used in the code .indexOf(c)+" "))// the index of the char, plus a space as delimiter ``` [Answer] # Python, ~~90~~ 88 bytes ``` a,b,d=" ()+.7:[]efilmnor","a,b,d=\"",lambda e:[[b.find(d),a.find(d)+7][d in a]for d in e] ``` Test case: ``` print(d("a,b(]q")) #[0, 1, 2, 8, 15, -1] ``` [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), noncompeting, 36 bytes When I said this language was still in development, I meant it. Apparently, `prompt` used to consume the entire stack. This is why I can't have nice things. [Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html) ``` [tostr ':!' + prompt CS index out]:! ``` This is the standard quine framework. Basically, `:` duplicates the function `[...]` on the stack, which is then executed with `!`. Then, the inside of `[...]` executes with the function on the stack. It casts it to a string, appends `:!` (the program itself), then takes a string input with `prompt`. `CS` converts it to a character string. A character string is a bit different from a regular string in that it has operators vectorize over it. In this case, `index` vectorizes over the input, yielding each index of the input string in the program, finally being `out`putted. For input `Hello, World!`, this gives: ``` (-1 27 -1 -1 2 -1 6 -1 2 5 -1 26 9) ``` I tried using the one without a quine (i.e. encoding the string of characters that appear in your source), but there is only one type of quotation mark in Stacked, namely, `'`, so it would be longer to do that type of solution. [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` m€`:'""m€`:' ``` [Try it online!](https://tio.run/##yygtzv7/P/dR05oEK3UlJSjjP1woRiktPz8mBgA "Husk – Try It Online") ### Explanation The explanation is using `¨` to delimit strings and `'` to delimit characters: ``` m€`:'""m€`:' -- implicit input, for example: ¨m"a1`¨ "m€`:' -- string literal: ¨m€`:'¨ `:'" -- append character '"': ¨m€`:'"¨ m -- map function over each character (example with 'a'): € -- | index of first occurrence (1-indexed): 0 -- : [1,6,0,0,3] ``` [Answer] # [J](http://jsoftware.com/), ~~31~~ 22 bytes ``` 11|1+i.~&'11|1+i.~&''' ``` [Try it online!](https://tio.run/##y/r/389JT@FR22RDBRBpqgCmDA0glCmYMjLgSrPVUzA0rDHUztSrU1NHsNTV/6cmZ@QrpCkUl6Rk5ikY/gfKahsqZ6rr1QEA) 1-indexed, 0 for characters that aren’t present in the code. `''` stands for a single quote. Find each character in the string `11|1+i.~&'`, add 1, modulo 11. [Answer] # [><>](https://esolangs.org/wiki/Fish), 31 bytes ``` 'rd3*i:0(?;}{:}-&b0&?.75*l-nao] ``` [Try it online!](https://tio.run/##S8sszvj/X70oxVgr08pAw966ttqqVlctyUDNXs/cVCtHNy8xP5aggri4OAA "><> – Try It Online") Output is 1-indexed, with `32` meaning the character is not in the code. [Answer] ## [Perl 5](https://www.perl.org/) with `-pl`, 43 bytes Uses newline separated input and prints `-1` for characters not appearing in the program. ``` $s=q{$_=index"\$s=q{$s};eval\$s",$_};eval$s ``` [Try it online!](https://tio.run/##K0gtyjH9X1qcqlCeWJSXmZdebP1fpdi2sFol3jYzLyW1QikGwi2utU4tS8wB8pR0VOIhHJXi//9juFK5yrgSuXK4VP/lF5Rk5ucV/9ctyFHQ9TXVMzA0AAA "Perl 5 – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 19 bytes ``` "'sym[]I+"'"s+ym[]I ``` [Run and debug it](https://staxlang.xyz/#c=%22%27sym[]I%2B%22%27%22s%2Bym[]I&i=y%5E%27%22Bs&a=1) Outputs 0-based index, one character per line. Turns out it's shorter than modifying the `"34bL"34bL` quine I wrote earlier. [Answer] # SAS, 124 ~~60~~ bytes; The new answer is shift from pure SAS 4GL to SAS macrolanguage. The code: ``` %let S=%nrstr(%macro _(t);data;s=&t;do i=1to length(s);p=find(symget("S"),char(s,i));put p@;end;run;%mend;%_);%unquote(&S()) ``` To run it, insert your `'string'` enclosed in single quotes between brackets after `&S`, for example: ``` ...%unquote(&S('!#&%macro _sS@')) ``` and in the log you will see: ``` 0 0 20 1 2 3 4 5 6 7 8 18 57 77 ``` To escape single quote in the string write it doubled: `'AB''CD'`. --- [EDIT:] 60 bytes answer was suggested for rejection as "a snippet, meaning it cannot just assume variables are defined". In context of SAS 4GL programming I agree to disagree with that opinion. ;-) I keep it below for further comments. --- Code assume that the string is given in a variable `s` and the source code is stored in macroVariable `s`. The code: ``` do i=1to length(s);p=find(symget("S"),char(s,i));put p@;end; ``` Process goes as follows: 1. store source code in macrovariable `S` by runing: ``` data _null_; call symputX("S",'do i=1to length(s);p=find(symget("S"),char(s,i));put p@;end;',"G"); run; ``` 2. assign string `"i S;abcd{"` to variable `s` and resolve ( by `&S.` ) the macrovariable `S`: ``` data; s="i S;abcd{"; &S. run; ``` The Log says: ``` 1 data _null_; 2 call symputX("S",'do i=1to length(s);p=find(symget("S"),char(s,i));put p@ 2 ! ;end;',"G"); 3 run; NOTE: DATA statement used (Total process time): real time 0.00 seconds cpu time 0.00 seconds 4 5 data; 6 s="i S;abcd{"; 7 &S. 8 run; 4 3 35 19 41 0 39 1 0 NOTE: The data set WORK.DATA14 has 1 observations and 3 variables. NOTE: DATA statement used (Total process time): real time 0.00 seconds cpu time 0.00 seconds ``` You can run: ``` %put %length(%superq(S)); ``` to get source code length. [Answer] # JavaScript, ~~59~~ 57 bytes -2 Bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) ``` a=>(m='Opined.fx,"+)',a.map(x=>("a=>(m='"+m).indexOf(x))) ``` Without reading source. [Attempt This Online!](https://ato.pxeger.com/run?1=bVLLctMwFJ1hma-4DQFJxDFJaekjOKElKZRHwqOFQhpqociJwC9suRiCWfEXbLKALf8DX4NsOc10htWVj86959xj_fjpBxO--M0CP5bA1BkssH8l0mls_9mhVgd7FhqGwucT00mNap0gg5oeDXGq7qoloVr3iCn8CU-HDk4JIXrA3yvfbVNGwsOkXanwc-pi5FgI6oVQjmnZw0Gvf6J0m-0SGAyPzg6Gx4OeAhutCx6NmRAKQrBWvVq7dv0UYXKjbjTMm83W-q2Nzdtb2zu77TtWp2vv7d_r9Q_uPzh8-Ojxk8Hw6bPnL46OX746ef1m9G389uwufccm3JnOxPsPrucH4ccolsn5p_Tzl_nXDJlx6AqJEVp55GnImVTihYkiAQZWB-YVAM0oehQh360cwFQ_QMRlEvmAWgiEX9K6uo6aY9Pl_lTOVCg6ht3V9u1KtjJAmUyoq-Y7uLBAlmGFNI7zn1aba0pmg2UV39pzZmtm4HLTDaYYFw1dQKfJ-lZzEynF4rjBEDEjHnIqcatJcmXhAF7L6aRc2wmiPmUzjJkBglzeP385WnEkxu0LmOaZFcYuwWEOK6PAl9jSX_h_bwbYYRALKQIfAgdqc5aBiFXlmW1A0ZTTbTwNpEJpRmyiA9SPcbHQ9R8) [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 27 bytes ``` #Qup~-"#Q"j?+wd\[Ppm{pPjFi} ``` [Try it online!](https://tio.run/##SyotykktLixN/f9fObC0oE5XSTlQKcteuzwlJjqgILe6ICDLLbP2/38A "Burlesque – Try It Online") Returns list of indices with `-1` for each not present. ``` #Q #Push remaining code to stack up #Turn to string ~- #Remove brackets "#Q"j?+ #Add the "#Q" to the beginning wd\[ #Remove all spaces Pp #Push to virtual stack m{ #Map (apply to each char in input) pP #Pop from other stack jFi} #Find character in string ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~49~~ 48 bytes -1 byte thanks to Jo King ``` c='print map(("c=%r;ex"%c).find,input())';exec c ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9lWvaAoM69EITexQENDKdlWtcg6tUJJNVlTLy0zL0UnM6@gtERDU1MdKJqarJD8/78SqpYYmJ4Y3JrylQA "Python 2 – Try It Online") --- # [Python 3](https://docs.python.org/3/), ~~53~~ ~~52~~ 51 bytes -1 byte thanks to Jo King ``` c='print(*map(("c=%r;ex"%c).find,input()))';exec(c) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P9lWvaAoM69EQys3sUBDQynZVrXIOrVCSTVZUy8tMy9FJzOvoLREQ1NTUx0onJqskaxJlqZ8AA "Python 3 – Try It Online") ]
[Question] [ Given a palindrome generated according to [this challenge](https://codegolf.stackexchange.com/questions/98325/palindromize-this-string), depalindromize it. ### Test cases ``` abcdedcba -> abcde johncenanecnhoj -> johncena ppapapp -> ppap codegolflogedoc -> codegolf ``` As this is about depalindromizing, **your code cannot be a palindrome**. Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes wins. [Answer] # Julia, ~~21~~ 15 bytes ``` x->x[1:end/2+1] ``` [Try it online!](http://julia.tryitonline.net/#code=cHJpbnQoKHgtPnhbMTplbmQvMisxXSkoImFiY2RlZGNiYSIpKQ&input=) (extra code is for printing output) [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 3 bytes ``` 2ä¬ ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=MsOkwqw&input=YWJjZGVkY2Jh) [Answer] # Python 2, 23 bytes I am not able to test on my phone, but this should work: ``` lambda s:s[:-~len(s)/2] ``` [Answer] # Fuzzy Octo Guacamole, 4 bytes ``` 2.^/ ``` I spent a while searching for a language in which this challenge is short, and realized I was dumb and my own language did that. [Answer] # 05AB1E, 5 bytes ``` Dg;î£ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=RGc7w67Cow&input=am9obmNlbmFuZWNuaG9q) **Explanation:** ``` D Duplicate g;î Divide length by two and round up £ First b letters of a ``` [Answer] # Cheddar, ~~22~~ 18 bytes ``` @.head($0.len/2+1) ``` So simple I don't think needs explanation but I'll add one if wanted. [Try it online](http://cheddar.tryitonline.net/#code=bGV0IGY9IEAuaGVhZCgkMC5sZW4vMisxKTsKCnByaW50IGYoImpvaG5jZW5hbmVjbmhvaiIpOw&input=) [Answer] # Pyth - 4 bytes ``` hc2Q ``` [Test Suite](http://pyth.herokuapp.com/?code=hc2Q&test_suite=1&test_suite_input=%22abcdedcba%22%0A%22johncenanecnhoj%22%0A%22ppapapp%22%0A%22codegolflogedoc%22&debug=0). [Answer] # JavaScript (ES6), ~~32 26~~ 25 bytes 1 byte saved thanks to Neil: ``` s=>s.slice(0,-s.length/2) ``` ``` f= s=>s.slice(0,-s.length/2) ; console.log(f('abcdedcba')) console.log(f('johncenanecnhoj')) console.log(f('ppapapp')) console.log(f('codegolflogedoc')) ``` --- **Previous solutions** 26 bytes thanks to Downgoat: ``` s=>s.slice(0,s.length/2+1) ``` 32 bytes: ``` s=>s.slice(0,(l=s.length/2)+l%2) ``` [Answer] # WinDbg, ~~87~~ 71 bytes ``` db$t0 L1;.for(r$t1=@$t0;@$p;r$t1=@$t1+1){db$t1 L1};da$t0 L(@$t1-@$t0)/2 ``` *-16 bytes by not inserting NULL, instead passing length to `da`* Input is passed in via an address in psuedo-register `$t0`. For example: ``` eza 2000000 "abcdedcba" * Write string "abcdedcba" into memory at 0x02000000 r $t0 = 33554432 * Set $t0 = 0x02000000 * Edit: Something got messed up in my WinDB session, of course r $t0 = 2000000 should work * not that crazy 33554432. ``` It works by replacing the right of middle char (or right-middle if the string has even length) with a null and then prints the string from the original starting memory address. ``` db $t0 L1; * Set $p = memory-at($t0) .for (r $t1 = @$t0; @$p; r $t1 = @$t1 + 1) * Set $t1 = $t0 and increment until $p == 0 { db $t1 L1 * Set $p = memory-at($t1) }; da $t0 L(@$t1-@$t0)/2 * Print half the string ``` Output: ``` 0:000> eza 2000000 "abcdeedcba" 0:000> r $t0 = 33554432 0:000> db$t0 L1;.for(r$t1=@$t0;@$p;r$t1=@$t1+1){db$t1 L1};da$t0 L(@$t1-@$t0)/2 02000000 61 a 02000000 61 a 02000001 62 b 02000002 63 c 02000003 64 d 02000004 65 e 02000005 65 e 02000006 64 d 02000007 63 c 02000008 62 b 02000009 61 a 0200000a 00 . 02000000 "abcde" ``` [Answer] ## Haskell, 27 bytes ``` take=<<succ.(`div`2).length ``` Pointfree version of ``` \x->take(div(length x)2+1)x ``` which is also 27 bytes. [Answer] # [MATL](http://github.com/lmendo/MATL), ~~7~~ 6 bytes ``` 9LQ2/) ``` [Try it online!](http://matl.tryitonline.net/#code=OUxRMi8p&input=J2NvZGVnb2xmbG9nZWRvYyc) ### Explanation ``` 9L % Push array [1, 1j] Q % Add 1: transforms into [2, 1+1j] 2/ % Divide by 2: transforms into [1, 0.5+0.5j] ) % Apply as index into implicit input. The array [1, 0.5+0.5j] used as an index % is interpreted as [1:0.5+end*0.5] ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 4 bytes ``` œs2Ḣ ``` [Try it online!](http://jelly.tryitonline.net/#code=xZNzMuG4og&input=&args=J2FiY2RlZGJjYSc) ### Explanation ``` œs2 Split input into 2 chunks of similar lengths. For odd-length input, the first chunk is the longest Ḣ Keep the first chunk ``` [Answer] # [V](http://github.com/DJMcMayhem/V), 12 bytes Two *completely* different solutions, both 12 bytes. ``` ò"Bx$xh|ò"bP ``` [Try it online!](http://v.tryitonline.net/#code=w7IiQngkeGh8w7IiYlA&input=YWJjZGVkY2Jh) ``` Ó./&ò MjdGÍî ``` [Try it online!](http://v.tryitonline.net/#code=w5MuLybDsgpNamRHw43Drg&input=YWJjZGVkY2Jh) [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 4 bytes ``` @2tr ``` [Try it online!](http://brachylog.tryitonline.net/#code=QDJ0cg&input=InBwYXBhcHAi&args=Wg) ### Explanation ``` @2 Split in half t Take the second half r Reverse it ``` If the input has odd length, the second half generated by `@2` is the one that is the longest, that is the one we should return (after reversing it). [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 9 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) ``` ⊢↑⍨2÷⍨1+≢ ``` `⊢` the argument `↑⍨` truncated at `2÷⍨` half of `1+` one plus `≢` the length [TryAPL online!](http://tryapl.org/?a=f%u2190%u22A2%u2191%u23682%F7%u23681+%u2262%20%u22C4%20f%A8%27abcdedcba%27%20%27johncenanecnhoj%27%20%27ppapapp%27%20%27codegolflogedoc%27&run) [Answer] # Perl, 15 bytes Includes +2 for `-lp` Give input string on STDIN: ``` depal.pl <<< "HelleH" ``` `depal.pl`: ``` #!/usr/bin/perl -lp s/../chop/reg ``` The `-l` is not really needed if you input the palindrome without final newline, but I included it to be fair to the other perl solutions that use it. [Answer] # Java 7, 57 bytes ``` String c(String s){return s.substring(0,s.length()/2+1);} ``` [Answer] # TI-Basic, 14 bytes Standard function. Returns string from index 1 to index (length/2 + 1/2). ``` sub(Ans,1,.5+.5length(Ans ``` [Answer] # GameMaker Language, 59 bytes ``` a=argument0 return string_copy(a,1,ceil(string_length(a)/2) ``` [Answer] # PHP, 40 bytes ``` <?=substr($a=$argv[1],0,1+strlen($a)/2); ``` `strlen($a)/2` gets cast to int, with the input always having odd length, `+1` suffices to round up. **42 bytes** for any length: ``` <?=substr($a=$argv[1],0,(1+strlen($a))/2); ``` for unknown length, `(1+strlen)/2` gets cast to int, rounding up `strlen/2`. [Answer] # Dip, 8 bytes ``` H{C'0ÏEI ``` Explanation: ``` # Implicit input H # Push length of input { # Add 1 C # Divide by 2 ' # Convert to int 0Ï # Get string back E # Push prefixes of string I # Push prefixes[a] # Implicit print ``` This could probably be much improved. [Answer] # Perl, 23 + 2 (`-pl` flag) = ~~28~~ 25 bytes ``` perl -ple '$_=substr$_,0,1+y///c/2' ``` Ungolfed: ``` while (<>) { # -p flag chomp($_) # -l flag $_ = substr($_, 0, 1 + length($_) / 2); print($_, "\n") # -pl flag } ``` Thanx to @ardnew. [Answer] # [Befunge](http://github.com/catseye/Befunge-93), ~~24~~ 22 bytes ``` ~:0`!#v_\1+ 0:-2,\_@#` ``` [Try it online!](http://befunge.tryitonline.net/#code=fjowYCEjdl9cMSsKMDotMixcX0AjYA&input=Y29kZWdvbGZsb2dlZG9j) --- Befunge has no string or array type so the everything is done on the stack one character at a time. The first loop (on the top line) counts the number of characters read (swapping with less than 2 elements in the stack produces an initial 0). The second (on the middle line) prints characters while counting down twice as fast. As a result only the last half of the input is printed, but LIFO so it's in the correct order. Thanks to [Brian Gradin](https://codegolf.stackexchange.com/users/61606/brian-gradin) for a better version of the first loop. [Answer] # Perl, 14 + 3 (`-lF` flag) = ~~19~~ 17 bytes For 5.20.0+: ``` perl -lF -E 'say@F[0..@F/2]' ``` For 5.10.0+ (19 bytes): ``` perl -nlaF -E 'say@F[0..@F/2]' ``` Ungolfed: ``` while (<>) { # -n flag (implicitly sets by -F in 5.20.0+) chomp($_) # -l flag @F = split('', $_); # -aF flag (implicitly sets by -F in 5.20.0+) say(@F[0 .. (scalar(@F) / 2)]); } ``` Thanx to @simbabque. [Answer] ## Brainfuck, 20 bytes ``` , [ [>,] <[<] >.,>[>] << ] ``` [Try it online.](http://brainfuck.tryitonline.net/#code=LFtbPixdPFs8XT4uLD5bPl08PF0&input=YWJjZGVkY2JhCg) This saves a byte over the more straightforward approach of consuming the input before starting the main loop: ``` ,[>,] < [ [<] >.,>[>] <,< ] ``` [Answer] # [Pyth](https://pyth.readthedocs.io/en/latest/getting-started.html), ~~8~~ 7 bytes ``` <zh/lz2 ``` Saved 1 with thanks to @Steven H Not the shortest Pyth answer (by half) but I'm making an effort to learn the language and this is my first post using it. Posted as much for comments and feedback as anything. It's also the first Pyth program that I have actually got to work :) Now I just need to work out how the 4 byte answer from @Maltysen works :-) [Answer] # [Actually](http://github.com/Mego/Seriously), 5 bytes ``` l½KßH ``` [Try it online!](http://actually.tryitonline.net/#code=bMK9S8OfSA&input=ImpvaG5jZW5hbmVjbmhvaiI) *-1 byte thanks to Sherlock9* Explanation: ``` l½K@H l½K ceil(len(input)/2) ßH first (len(input)//2 + 1) characters of input ``` [Answer] # C, ~~31~~ 30 bytes Saving 1 byte thanks to Cyoce. ``` f(char*c){c[-~strlen(c)/2]=0;} ``` Usage: ``` main(){ char a[]="hellolleh"; f(a); printf("%s\n",a); } ``` [Answer] # Python 2, 23 bytes ``` lambda x:x[:len(x)/2+1] ``` [Answer] # MATLAB / Octave, ~~20~~ ~~19~~ ~~18~~ 16 bytes *1 byte off borrowing an idea from [Easterly Irk's answer](https://codegolf.stackexchange.com/a/98349/36398) (add `1` instead of `.5`)* *2 bytes off thanks to @StewieGriffin (unnecessary parentheses)* ``` @(x)x(1:end/2+1) ``` [Try it at Ideone](http://ideone.com/c4otjN). ]
[Question] [ [We already now how to strip a string from its spaces.](https://codegolf.stackexchange.com/q/50510/71426) However, as proper gentlemen/ladies, we should rather *undress* it. --- Undressing a string is the same as stripping it, only more delicate. Instead of removing all leading and trailing spaces at once, we remove them *one by one*. We also *alternate* between leading and trailing, so as not to burn steps. Example, starting with `" codegolf "` (five leading and trailing spaces): ``` codegolf codegolf codegolf codegolf codegolf codegolf codegolf codegolf codegolf codegolf codegolf ``` --- 1. First output the string unchanged. Then, output every step. Begin by removing a *leading* space (if applicable - see rule #2). 2. The input may have a different number of leading and trailing spaces. If you run out of spaces on one side, keep undressing the other until the string is bare. 3. The input may have no leading nor trailing spaces. If that's the case, output it as-is. 4. Use [PPCG's default I/O methods](https://codegolf.meta.stackexchange.com/q/2447/71426). [PPCG Default loopholes](https://codegolf.meta.stackexchange.com/q/1061/71426) are forbidden. 5. Undefined behaviour on empty input, or input that only contains spaces, is OK. 6. You can assume that the string will only contain characters from the ASCII printable space (`0x20` to `0x7E`). --- Examples - spaces are replaced by dots `.` for better readability: ``` 4 leading spaces, 5 trailing: "....Yes, Sir!....." ....Yes, Sir!..... ...Yes, Sir!..... ...Yes, Sir!.... ..Yes, Sir!.... ..Yes, Sir!... .Yes, Sir!... .Yes, Sir!.. Yes, Sir!.. Yes, Sir!. Yes, Sir! 6 leading, 3 trailing: "......Let's go golfing..." ......Let's go golfing... .....Let's go golfing... .....Let's go golfing.. ....Let's go golfing.. ....Let's go golfing. ...Let's go golfing. ...Let's go golfing ..Let's go golfing .Let's go golfing Let's go golfing 0 leading, 2 trailing: "Hello.." Hello.. Hello. Hello 0 leading, 0 trailing: "World" World 21 leading, 5 trailing: ".....................a....." .....................a..... ....................a..... ....................a.... ...................a.... ...................a... ..................a... ..................a.. .................a.. .................a. ................a. ................a ...............a ..............a .............a ............a ...........a ..........a .........a ........a .......a ......a .....a ....a ...a ..a .a a ``` A gentleman/lady is concise, so *the shortest answer in bytes wins*. [Answer] ## [Retina](https://github.com/m-ender/retina), 26 bytes ``` {m`^ (.+)\z $&¶$1 $ ¶$%` ``` [Try it online!](https://tio.run/##K0otycxL/K@qkRAXo6ddA8QqXCp6aipaCv@rcxPiFDT0tDVjqrhU1A5tUzHkUlDhUgAyVBP@a7oncKkC5bVrFGA69LiCE1T@64FAcn5Kanp@ThqYwwUiIlOLdRSCM4sUEUJ6ej6pJerFCun5CiC1mXnpIBmP1JycfCAdnl@UkwIA "Retina – Try It Online") (Test suite uses periods for clarity. The footer and header convert them to and from spaces for the main code.) ### Explanation It would be nice if we could just alternate between dropping a leading and a trailing space and printing the intermediate result each time. The problem is that currently Retina can't print conditionally, so it would even print this intermediate result if there are no leading or no trailing spaces left, generating duplicates. (Retina 1.0 will get an option that only prints the result if the string was changed by the operation, but we're not there yet...) So instead, we're building up a single string containing all intermediate results and printing that at the end. ``` {m`^ (.+)\z $&¶$1 ``` The `{` wraps both stages of the program in a loop which repeats until the string stops changing (which means there are no leading/trailing spaces left). The stage itself matches a leading space on the final line of the string, and that final line, and then writes back the match, as well as the stuff after the space on a new line (thereby dropping the leading space in the copy). ``` $ ¶$%` ``` Removing the trailing space is a bit easier. If we just match the final space, we can access the stuff in front of it (on the same line) with `$%`` which is a line-aware variant of the prefix substitution `$``. [Answer] # [Python 2](https://docs.python.org/2/), ~~122~~ ~~107~~ ~~103~~ ~~102~~ ~~98~~ ~~95~~ ~~93~~ ~~91~~ ~~90~~ ~~88~~ 87 bytes ``` s=input()+' ' a=0 while-a*s!=id: if a:id=s a=~a if'!'>s[a]:s=s[1+a:len(s)+a];print s ``` [Try it online!](https://tio.run/##JcjBCsIwDADQe78iO2WzCM5jJfuRsUOw3RYobTEd4sVfrwzf8ZVP3XO6t6YkqRy1HywCGqabee8Sw5Uv2pF4Z0BWYCee1ADTl8/ADiedeXFKOo@WXQyp18Hy8igvSRW0NYTTM/uw5bjCH/4A "Python 2 – Try It Online") --- # [Python 3](https://docs.python.org/3/), ~~97~~ ~~95~~ ~~93~~ 90 bytes ``` s=input() a=p=print p(s) while s!=a: a=s if'!'>s:s=s[1:];p(s) if'!'>s[-1]:s=s[:-1];p(s) ``` [Try it online!](https://tio.run/##NYo7CoAwEAX7PcVaqYVFsIusFxGL4DcgyeJGxNNHjTjV8ObxFVbv6hiFrOMjFCUYYuLdugBcSAnnarcJJSOjAQ0JoJ3zLG9FC0mndN@k2792lepT0Y@kFCO@DH6cFr/N@HED "Python 3 – Try It Online") [Answer] # [Perl 6](https://perl6.org), 55 bytes *Saved 3 bytes thanks to @nwellnhof.* ``` {($_,{$++%2??S/" "$//!!S/^" "//}...*)[^.comb*2].unique} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYKvwv1pDJV6nWkVbW9XI3j5YX0lBSUVfX1ExWD8OyNTXr9XT09PSjI7TS87PTdIyitUrzcssLE2t/W/NpZKmoaQAAsn5Kanp@TlpCkqaermJBRpaemm5JRrqNarFNeqaesWJlZrW/wE "Perl 6 – Try It Online") **Explanation**: `($_,{$++%2??S/" "$//!!S/^" "//}...*)` is a recursive infinite sequence that starts with the original string (`$_`) and the next element is given by the block called on the previous element. The block itself gets the string in the `$_` variable. The operator `S/(regex)/(string)/` will search for the first occurence of `(regex)` in `$_`, replaces it with `(string)`, and returns the result. If there is no match, it returns the content of `$_` unchanged. We use the ternary operator `?? !!` with the condition `$++%2`, which alternates between `False` and `True` (`$` is a free variable that conserves its contents across calls to the block.) In the worst case (all spaces on one side and 1 other character), we remove 1 space every 2 steps. So we can be sure that in 2\*(length of the string) steps, all spaces will have been removed. We take that many elements from the recursive sequence with `[^.comb*2]` and finally discard duplicates (which occur whenever a space should have been removed but it isn't there) with `.unique`. This returns the list of strings, progressively stripped of spaces. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ 15 bytes ``` =v¬ðQi¦=}¤ðQi¨= ``` [Try it online!](https://tio.run/##MzBNTDJM/f/ftuzQmsMbAjMPLbOtPbQEzFph@/@/Ahj4pJaoFyuk5wNRTlpmXjpQCAA "05AB1E – Try It Online") **Explanation**^ ``` = # print input v # for each character in input ¬ðQi } # if the first char in the current string is a space ¦= # remove it and print without popping ¤ðQi # if the last char in the current string is a space ¨= # remove it and print without popping ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~89~~ 84 bytes Recursive version is shorter ;-) ``` j;f(char*s){puts(s);*s^32||puts(++s);s[j=strlen(s)-1]<33?s[j]=0,f(s):*s^32||f(s+1);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/LOk0jOSOxSKtYs7qgtKRYo1jTWqs4ztiopgbM1dYGChRHZ9kWlxTlpOYBpXUNY22Mje2BYrG2BjppQBErqAYgW9tQ07r2f25iZp6GJlc1F5cCEACFS4pSSgs0lEC8yNRiHYXgzCJFEEdBSVPTGosiBQWf1BL1YoX0fCDKScvMS8eu1iM1Jycfq0x4flFOCk7T0UAiwi21/wE "C (gcc) – Try It Online") # [C (gcc)](https://gcc.gnu.org/), ~~107~~ ~~102~~ ~~101~~ ~~100~~ 99 bytes Saved 2 bytes thanks to @Jonathan Frech using spaces and ~ ``` i,j,k;f(char*s){for(i=~++k,puts(s);i^k;k=s[j=strlen(s)-1]<33?s[j]=0,puts(s):0)*s^32?i=0:puts(++s);} ``` [Try it online!](https://tio.run/##dY4xD4IwEIV3fkVlsaUlQdnAhtXBzcEYAwmBgqUVSAsTwb9ei4kxMfhyy/vu3csVfl0UxnDSEBFXsLjnytNoqjoFOX1iLEg/DhpqFPNMxILqW0P1oCRrLfN36SEME8tSGnyCUYA8nYX7hNMgejOM7flsHjlvIXImxwFWFbQ15dhDd3FXpgk4c7VZDHARildCAJzYsNWg7uzIirf1evbIpOxWN5dOyfJv@4/y7y@zeQE "C (gcc) – Try It Online") [Answer] # JavaScript (ES6) 92 @Upvoters: have a look at the other JS answer down below that is **76** bytes long ``` (s,q,l=2,p=0)=>{for(alert(s);l--;p=!p)s[+p&&s.length-p]<'!'&&alert(s=s.slice(!p,-p||q,l=2))} ``` A loop looking for a space at front or at end. If found, remove space and output string. If no space found 2 times, stop. ``` F= (s,q,l=2,p=0)=>{for(alert(s);l--;p=!p)s[+p&&s.length-p]<'!'&&alert(s=s.slice(!p,-p||q,l=2))} // some trick to show dots instead of spaces, for test alert=x=>console.log(x .replace(/^ +/g,z=>'.'.repeat(z.length)) .replace(/ +$/g,z=>'.'.repeat(z.length)) ) function go() {F(I.value.replace(/\./g,' '))} go() ``` ``` <input ID=I value='....yes Sir!....'> (use dot instead of space) <button onclick='go()'>Go</button> ``` [Answer] # Perl 5, 32 bytes *Saved 4 bytes due to [@Abigail](https://codegolf.stackexchange.com/posts/comments/351789?noredirect=1).* ``` 1while s/^ /!say/e+s/ $/!say/e ``` Requires `-pl` counted as 2, invoked with `-E`. **Sample Usage** ``` $ echo ' test ' | perl -plE'1while s/^ /!say/e+s/ $/!say/e' test test test test test test test ``` [Try it online!](https://tio.run/##S0oszvhfkFqUo6BbkOOq/t@wPCMzJ1WhWD9OQV@xOLFSP1W7WF9BBcr@r/5fAQgiU4t1FIIzixRBHC4FMPBJLVEvVkjPB6KctMy8dJCMR2pOTj6QDs8vykmBqkMDiWASAA "Bash – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~192~~ ~~183~~ ~~182~~ ~~181~~ ~~179~~ 178 bytes -3 bytes thanks to Kevin Cruijssen ``` n=>{var o=n+"\n";for(var e=1;n.Trim()!=n;){if(1>(e^=1))if(n[0]<33)n=n.Remove(0,1);else continue;else if(n.TrimEnd()!=n)n=n.Remove(n.Length-1);else continue;o+=n+"\n";};return o;} ``` [Try it online!](https://tio.run/##jY89a8MwEIZ3/4qrJ4kkJiajIi@l7ZJQaAsd0gSMfLYF9gkk2TQY/3ZXcSgEOjS33NfzHvcqt1LG4qSa3Dn4jobI@dxrBb3RBexzTcCct5qqwxFyWzkeEAjxfnYe2@S5I7W9Aku45gxKkBPJbOhzC0bSIv6iWJTGsssAZSoo@bC6ZfxBkuCDLlmaMTzJlPNQ02F93G42nCQlb9iaHtl6mXKBjUNQhrymDq/dhZ5PPVExX7sVUbJDqny9@qM1i9@nRmHRd5bAiHESt8YeDTnTYPJptcedJmQli8P6xTRlMBmqmPP/Fa81uFr7e/H9OXxZBGMOGkPVXRqYY0bHaJx@AA "C# (.NET Core) – Try It Online") [Answer] # Java 8, ~~150~~ ~~146~~ ~~145~~ 137 bytes ``` s->{String r=s;for(int f=0;s!=s.trim();f^=1)r+="\n"+(s=f+s.charAt(0)<33|!s.endsWith(" ")?s.substring(1):s.replaceAll(" $",""));return r;} ``` -4 bytes thanks to *@Nevay* changing `(f<1&s.charAt(0)<33)` to `f+s.charAt(0)<33`. -1 byte by using the `!s.trim().equals(s)` trick from [*@someone*'s C# .NET answer](https://codegolf.stackexchange.com/a/143380/52210) instead of `s.matches(" .*|.* ")`. -8 bytes thanks to *@Nevay* again by changing `!s.trim().equals(s)` to `s!=s.trim()`, because [`String#trim`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()) will return "*A copy of this string with leading and trailing white space removed, or **this string if it has no leading or trailing white space***", thus the reference stays the same and `!=` can be used to check if they are the same reference, instead of `.equals` to check the same value. **Explanation:** [Try it here](https://tio.run/##rZBNSwMxEIbv/RXTIJjQNrR4c43SmwftpUIRPyDNZtvUNFky2YLU/e1rtiwiQk/rHEImM/PkfWcnD3LiS@12@UejrESER2nccQBgXNShkErDok0BljEYtwFFuwuyLL3Xg3RglNEoWIADAQ1Obo9dTxCYFT7QBINCTDMcCuSptKcsK97FjIWRIK@OjCiKYoRcbWWYRzplN1dXX0Pk2uW4MnFLCRB2hxyrNZ7IdMaukQdd2qRwbm1quCBjQhjLgo5VcBCyuslacWW1tklcp/HgTQ775LGz8fIGknUGPzHqPfdV5GUqReuo4yqR21A@1xtvi1PSfnNu5HzlB/ascQxLE4b/AQN40PESYeOh1dduvRfzXlvre6p60hh7AFY@2Lz3Wv6E/L3selA33w) (or try a more visual version [here](https://tio.run/##rZBNa8MwDIbv/RWqM1jcD9My2GFZNnrbYeulgzL2Aa7jtO5cO1hOYbT57ZlTwhiDnjIfjGVJr55XW77nY1tIs80@a6E5IjxxZQ49AGW8dDkXEuZNCLDwTpk1iLh9IE3Cf9ULF3rulYA5GEihxvHdoa1xKSa5dXEQgzydJMh23IuNxJhEbHBkg4jQJP9Ip9QNU/JmyDDGNB8iExvuZj6e0Nur62MfmTQZLpXfhD5C75FhucLTiHhKb5A5WeiAOtM6FFyQESGUJk760hlwSVUnDWVRrnSgbGH3VmWwC2ZbP6/vwGnr9Au93DFbelaElNcmNkwE5eYIm8m11fkpaMacazmf@RF7kTiChXL9/xCLokfpLxHWFhq@YKmb5oPU2nakepboOwgsrdNZ57X8Ofz3sqteVX8D) with `#` instead of spaces). ``` s->{ // Method with String as both parameter and return-type String r=s; // Result-String (starting at the input) for(int f=0; // Flag-integer (starting at 0) s!=s.trim(); // Loop as long as `s` contains leading/trailing spaces f^=1) // And XOR(1) `f` after every iteration (0->1; 1->0) r+="\n" // Append the result with a new-line +( // Followed by: s=f+ // If `f` is 0, s.charAt(0)<33 // and `s` starts with a space |!s.endsWith(" ")? // Or doesn't end with a space s.substring(1) // Remove the first leading space : // Else: s.replaceAll(" $",""));// Remove the last trailing space // End of loop (implicit / single-line body) return r; // Return the result-String } // End of method ``` [Answer] # C, ~~91~~ 90 bytes ``` i,l;f(char*s){for(i=puts(s);i;i=(s[l=strlen(s)-1]*=s[l]>32)?i:puts(s))i=*s<33&&puts(++s);} ``` [Try it online!](https://tio.run/##dY4/D4IwEMV3PkVlwJY/g7JZq6uDm4MxhoEUipfUlrRlInz2WoyJicGXW97v3r0cLzrOvYdcUoH5ozapJaPQBgPrB2exJRQoMGzvkllnZKsCKjZVygKpDuWWHGH3SRJgqd2XZZK8QZaF48mDcuhZg8IkGiMUJHAoaoYex7O7tTZHFzCr2aCYELoQQujcurVFnQ4jBahuOXtqpdSLm6s2svnb/qP6@8vkXw) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` Ḋ=⁶Ḣ$¡UµÐĿ¹Ṛƭ€QY ``` [Try it online!](https://tio.run/##y0rNyan8///hji7bR43bHu5YpHJoYeihrYcnHNl/aOfDnbOOrX3UtCYw8v///wpgkAFUn69Qnl@UkwLkAQA "Jelly – Try It Online") -2 bytes thanks to Erik the Outgolfer -1 byte thanks to miles # Explanation ``` Ḋ=⁶Ḣ$¡UµÐĿ¹Ṛƭ€QY Main link µÐĿ While the results are unique (collecting intermediate results), apply the last link (`µ` creates a new monadic link): Ḋ=⁶Ḣ$¡ Remove a space from the beginning if there is one =⁶Ḣ$ If the first character is a space, then 1, else 0 = Compare each character to ⁶ ' ' Ḣ Get the first comparison Ḋ Then Dequeue the string (s -> s[1:]) ¡ That many times U And reverse the string (the next time this is called, it will remove spaces from the end instead) € For each string ƭ Alternate between two commands: ¹ Identity (do nothing), and Ṛ Reverse ¹Ṛƭ€ Correct all strings that are reversed to remove the trailing space Q Remove duplicates (where there was no space to remove) Y Join on newlines ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 63 bytes ``` ->s{*x=s;(s=~/^ /&&x<<s=$';s=~/ $/&&x<<s=$`)while s=~/^ | $/;x} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664WqvCtthao9i2Tj9OQV9NrcLGpthWRd0aJKCgAhdI0CzPyMxJVYCoqwHKWFfU/i8oLSlWSItWVwCB5PyU1PT8nDQFCFCP/Q8A "Ruby – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~161 147~~ 146 bytes ``` x->{for(int l=0,r=x.length(),k=-1,u,v;((u=32-x.charAt(l)>>k)*(v=32-x.charAt(r-1)>>-1))<1;x+="\n"+x.substring(l-=k&~u|v,r+=(k=~k)&~v|u));return x;} ``` [Try it online!](https://tio.run/##fZBNTwIxEIbv/oqRA9vKbiN6XErizYPigRhj1ENZylK2tJt2ulmi8NexfKghIU6aJvPOR9@nC9GIzNbSLKbVtg4TrQootPAeHoUy8HlxATE8CoyFmTJCwyKOsIBKs1kwBSpr2LMRbvVUSyfQusEYnTLlEEbAt202/JxZR5RB0Pw6dbxlWpoS54SmFc/6aUibnJDAb2@ylhVz4e6QaDocVvSKNCeqy/pRjxcd9PO2xzvvptNrmQ8Tv3@R6IxX3U34alLX46Tim4p2N81XoDR3EoMz0Obr7Q4oP3AdgY94jVVTWEZscgA9cLx9gHClp/Ev4BgoPZIOi/EqfQpj5S53CevQ/EwPYw8SEw@ljUfH1eXZ1nuptT1XeLFOT3/k9dG4U41AeeJ8333wDCd2xyuPcslsQBbnDGpDRkzUtV4Rz5ystSgkSViSQgIJpX8S7CQWpfy/Xb/O1ttv "Java (OpenJDK 8) – Try It Online") -1 byte thanks to *@Kevin Cruijssen*! ``` x -> { /* * l: left index (inclusive) * r: right index (exclusive) * k: side to remove from, -1:=left, 0:=right * u: left character 0:=space, <0:=no space (-1 if k is left side) * v: right character 0:=space, -1:=no space */ for (int l = 0, r = x.length(), k = -1, u, v; ((u = 32 - x.charAt(l) >> k) * (v = 32 - x.charAt(r - 1) >> -1)) < 1; // loop while left or right has space(s) x += "\n" + x.substring( // append newline and substring l -= k & ~u | v, // inc. left if k is left side // and left has space // or right has no space r += (k = ~k) & ~v | u)); // dec. right if k is right side // and right has space // or left has no space return x; } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ 17 bytes *-8 bytes by borrowing the [no-need-for-an-end-check idea from Emigna](https://codegolf.stackexchange.com/a/143382/73296)* ``` ,v2F¬ðQi¦DNiR},}R ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fp8zI7dCawxsCMw8tc/HLDKrVqQ36/18BG0gEkwA "05AB1E – Try It Online") I'm pretty sure a less straightforward approach can beat that solution easily. For now... **Explanations:** ``` ,v2F¬ðQi¦DNiR},}R Full Programm , Print the input string v For each char of the string (we don't really care, we only need to loop enough times to accomplish our task, since we print conditionally we can loop more times than necessary) 2F...........} Two times... ¬õQi Is 1st item a space? ¦D Remove 1st item + duplicate NiR} If on the second pass: reverse the list , Pop & print with newline } End If R Reverse the list ``` [Answer] # [R](https://www.r-project.org/), ~~145~~ ~~133~~ 111 bytes *-12 bytes thanks to @Giuseppe, by storing the result of `sub` in a new variable and testing for whether it has changed* *-22 bytes by returning a vector of strings rather than a string with newlines* ``` function(s){L=s while(grepl("^ | $",s)){if((x=sub("^ ","",s))!=s)L=c(L,x) if((s=sub(" $","",x))!=x)L=c(L,s)} L} ``` [Try it online!](https://tio.run/##LcsxDoMwDAXQPacIFoMt5Qq@QTYmlg5FSYmEKIqLGoly9jQu/Zu/3881co37Or3Sc0Whw7OY95yWgI8ctgXhZj@2BydER4qIhWW/awsOfm3HQp4n9K6QUSGX0FETRUX5C6HT@LPG9m0Zgzg7pNzpYYHqFw "R – Try It Online") Explanation on a partially ungolfed version: ``` function(s){ L=s # Initialise a vector with the original string while(grepl("^ | $",s)){ # While there are leading or trailing spaces... if((x=sub("^ ","",s))!=s){ # Check whether we can remove a leading space L=c(L,x) # If so, add the shortened string to the vector } if((s=sub(" $","",x))!=x){ # Check whether we can remove a trailing space L=c(L,x) # If so, add the shortened string to the vector } } L # Return the vector } ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~137~~ ~~125~~ ~~121~~ ~~120~~ 124 bytes ``` s->{int i=1;do System.out.println(s);while(s!=(s=s.substring(s.charAt(0)<33?i:(i=0),s.length()-(s.endsWith(" ")?i^=1:0))));} ``` [Try it online!](https://tio.run/##TY7BasMwEER/RfVJKrVwyC2KEko/IYcQSguqJNvryJLwrlOKybe7Ir10bjO8GWYwN1On7OPgriuMOU3EhpLJmSDIdo6WIEX5rCCSn1pjPbssbyniPPppf6IJYndgmWm2Yn1YCsVAb5RL7PSD5EeZZpK5UBQiR6G@ewie45PmqFHi/IWPCY7S9mZ6Jd6I/XZ7hB0H3YgXlMHHjnou6oL46PAMxVWsEkf41JtdI4rUfVVIhsCyWwLHRgOR/317/zBiydJY6zOV3j/Z5HyXQvswVRm5r78 "Java (OpenJDK 8) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~21~~ 16 bytes ``` tnE:"t@o&)w46-?x ``` This uses dots instead of spaces for greater clarity. For spaces replace `46` by `32`. [**Try it online!**](https://tio.run/##y00syfn/vyTP1UqpxCFfTbPcxEzXvuL/f3U9bCARTKoDAA) ### Explanation ``` tn % Input (implicit). Duplicate and push length, say L E % Multiply by 2 : % Push range [1 2 ... 2*L] " % For each k in that array t % Duplicate the string at the top of the stack @ % Push k o % Parity: gives 1 or 0 &) % Two-ouput indexing. Pushes the k-th entry of the string and then % the rest of the string. The 1-st output is the first, the 0-th % is the last (indexing is 1-based dand modular) w % Swap 46- % Subtract 46, which ias ACII for '.' ? % If non-zero x % Delete sub-string that was obained by removing that entry % End (implicit) % End (implicit) % Display stack (implicit) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~23~~ 22 bytes ``` u§↑L`G`I¢e₁ȯ↔₁↔ ?tI<"! ``` Thanks to Leo for -1 byte. [Try it online!](https://tio.run/##NYwxDsIwDEX3nuI3c8UBEBIjVGJjYmtUuTSipFXsssPQHYkTsDByh06coxcJIYCH5y/5fdc9H7zvx8c0XDfFqsjHO02X8@s5DbewA5Ol5AuVeoT5RmBNTUcOVW9LMa2dw9GxPRGMNWJ0A@50SbMkVoBYySs0xAyptQ0gsDhj91CpyqIIify/qoxjQVlrp0sh93OQR1LDFETpnYVmGJ55rz6HHXGGrXFp1NQb "Husk – Try It Online") ## Explanation The function ``G`I` should really be a built-in... ``` ?tI<"! Helper function: remove initial space. ? <"! If less than the string "!", t remove first character, I else return as is. u§↑L`G`I¢e₁ȯ↔₁↔ Main function. e List containing ₁ the helper function ȯ↔₁↔ and the composition reverse-helper-reverse. ¢ Repeat it cyclically. `G`I Cumulative reduce from left by function application using input string as initial value. §↑L Take first length(input) values. u Remove duplicates. ``` [Answer] ## C++, ~~196~~ ~~193~~ ~~189~~ ~~186~~ 183 bytes -10 bytes thanks to Jonathan Frech -3 bytes thanks to Zacharý ``` #include<iostream> #include<string> #define D std::cout<<s<<'\n' #define R ~-s.size() auto u=[](auto s){D;while(s[0]<33||s[R]<33){if(s[0]<33)s.erase(0,1),D;if(s[R]<33)s.erase(R),D;}}; ``` Compilation with MSVC requires the un-activation of SDL checks [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 176 170 bytes ``` using System;s=>{Action o=()=>Console.WriteLine(s);o();Func<int>l=()=>s.Length-1;while(s!=s.Trim()){if(s[0]<33){s=s.Remove(0,1);o();}if(s[l()]<33){s=s.Remove(l());o();}}} ``` [*Try it online!*](https://tio.run/##bZDLasNADEX3/golm85AYhKy9ANKoXThbppCKCELMx47gvEIRpO0xfjbXT9KwU20Ebr36IEUrxU53V0YbQX7b/a6jgJlcmb4CpqAfe5RwZWwgNccLQj2rkePJ8hdxbJHoI9H5ZFsPHkplJB0nKTNJAMlQibpE1kmo8ODQ68ztFqwjEjI6PliVYzWp2bkOMy0rfx5vY0@z2h6bJFw@O6wFlI2WAo@bk7xbicb7vU3XdNVi81qOw1rR8AIeYP02i/Stl00nl2K5ZBAUaErMuVYLOXM/NC8gj26xT0TINP@gaEiGPqHH86YF20MzZQDOVPcTPkX@d@uNmi7Hw) This is an alternative to [@someone's answer](https://codegolf.stackexchange.com/a/143380/61283 "@someone's answer"), and just outputs the strings directly. [Answer] # JavaScript (ES6), 76 bytes ``` f=(s,r,n,l=s.length)=>s[r?--l:0]<"!"?s+` `+f(s.slice(!r,l),!r):n?s:f(s,!r,1) ``` Outputs as a multiline string. ## Test Cases Using dots instead of spaces, as most answers are doing. ``` f=(s,r,n,l=s.length)=>s[r?--l:0]<"!"?s+` `+f(s.slice(!r,l),!r):n?s:f(s,!r,1) // converting to and from dots and spaces let dots=s=>s.replace(/^\.+|\.+$/gm,x=>" ".repeat(x.length)); let spaces=s=>s.replace(/^ +| +$/gm,x=>".".repeat(x.length)); ["....Yes, Sir!.....", "......Let's go golfing...", "Hello..", "World", ".....................a....."] .forEach(test=>O.innerHTML+=spaces( f(dots(test)) ) + "\n\n"); ``` ``` <pre id=O></pre> ``` [Answer] ## Sed, 24 bytes ``` p;:s s/ //p;s/ $//p;ts;D ``` [Try It Online !](https://tio.run/##K05N0U3PK/3/v8DaqlihWF9BX7/AGkipgOiSYmuX//8VFEpSi0sUFAA) [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~88~~ 83 bytes *5 bytes off thanks to [Stewie Griffin!](https://codegolf.stackexchange.com/users/31516/stewie-griffin)* ``` x=[input('') 0];for p=mod(1:sum(x),2)if x(~p+end*p)<33,disp(x=x(2-p:end-p)),end,end ``` [**Try it online!**](https://tio.run/##y08uSSxL/f@/wjY6M6@gtERDXV1TwSDWOi2/SKHANjc/RcPQqrg0V6NCU8dIMzNNoUKjrkA7NS9Fq0DTxthYJyWzuECjwrZCw0i3wAoorFugqakDpEH4/38lBRBIzk9JTc/PSQNzlAA) [Answer] # x86 machine code for Linux, 60 bytes ``` e8 1f 00 00 00 31 c0 80 3f 20 75 09 47 4d 74 10 e8 0f 00 00 00 80 7c 2f ff 20 74 05 84 c0 75 e5 c3 4d eb dc 6a 04 58 50 31 db 43 89 f9 89 ea cd 80 58 6a 0a 89 e1 89 da cd 80 58 c3 ``` This is a function for Linux x86. It takes as input pointer to the string in `edi` and string length in `ebp`. Ungolfed, with some infrastructure to test (compile with FASM, run with the string as program argument; look for `undress:` label for actual function code): ``` format ELF executable segment executable SYS_WRITE = 4 jmp callUndress ; -------------------- the function itself -------------------------------- ; Input: ; edi=string ; ebp=length undress: undressLoopPrint: call print undressLoop: xor eax, eax ; flag of having printed anything on this iteration cmp byte [edi], ' ' jne startsWithoutSpace inc edi dec ebp jz quit call print startsWithoutSpace: cmp byte [edi+ebp-1], ' ' je endsWithSpace test al, al ; if print has been called, then we have 0x0a in eax jnz undressLoop quit: ret endsWithSpace: dec ebp jmp undressLoopPrint print: push SYS_WRITE pop eax push eax xor ebx, ebx inc ebx ; STDOUT mov ecx, edi mov edx, ebp int 0x80 pop eax push 0x0a ; will print newline mov ecx, esp mov edx, ebx ; STDOUT=1, which coincides with the length of newline int 0x80 pop eax ret ; --------------------- end undress --------------------------------------- SYS_EXIT = 1 STDERR = 2 callUndress: pop eax ; argc cmp eax, 2 jne badArgc pop eax ; argv[0] pop edi mov al, 0 cld mov ecx, -1 repne scasb lea edi, [edi+ecx+1] ; argv[1] neg ecx sub ecx, 2 mov ebp, ecx ; strlen(argv[1]) call undress xor ebx, ebx exit: mov eax, SYS_EXIT int 0x80 ud2 badArgc: mov esi, eax mov eax, SYS_WRITE mov ebx, STDERR mov ecx, badArgcMsg mov edx, badArgcMsgLen int 0x80 mov ebx, esi neg ebx jmp exit badArgcMsg: db "Usage: undress YourString",0x0a,0 badArgcMsgLen = $-badArgcMsg segment readable writable string: db 100 dup(0) stringLen = $-string ``` [Answer] # [PHP](https://php.net/), 117 bytes I add an extra space at the start so it will take the space out and show the original without any extra code. Kinda new to this... would the <?php and the space at the start of the PHP file add 6 extra bytes or do I get that for free? ``` $s=" $argn";while($r!=$s){$r=$s;if($s[0]==" ")echo($s=substr($s,1))." ";if($s[-1]==" ")echo($s=substr($s,0,-1))." ";} ``` [Try it online!](https://tio.run/##dcrBCsIwDAbge5@ilh5WWGXT4yzefAnxMGddB6UpTWUH8dWtKejRQP7khy@6WA7HSCnRCC7HNAcxrG7xtpFpYySqp0x0huXeSDx3F0NMKDs5oG7wccWc6Gt7pbaCia/T/V/YtfpnX6XwOs56D3yF5G/UGG22mHes5r4CFoBPbgyzfUPMCwQs@vQB "PHP – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 28 bytes ``` QW<lrKQ6lQ=hZ?&%Z2qdhQ=tQ=PQ ``` **[Try it here!](https://pyth.herokuapp.com/?code=QW%3ClrKQ6lQ%3DhZ%3F%26%25Z2qdhQ%3DtQ%3DPQ&input=%22+++++codegolf+++++%22&test_suite_input=%22+++++codegolf+++++%22%0A%22world%22%0A%22++++Yes%2C+Sir%21+++++%22%0A%22Hello++%22&debug=0)** or **[Verify all test cases!](https://pyth.herokuapp.com/?code=QW%3ClrKQ6lQ%3DhZ%3F%26%25Z2qdhQ%3DtQ%3DPQ&input=%22+++++codegolf+++++%22&test_suite=1&test_suite_input=%22+++++codegolf+++++%22%0A%22world%22%0A%22++++Yes%2C+Sir%21+++++%22%0A%22Hello++%22&debug=0)** # Explanation ``` QW<lrKQ6lQ=hZ?&%Z2qdhQ=tQ=PQ ~ Full program. Q is autoinitialized to input. Q ~ Output the input. W<lrKQ6lQ ~ Loop while the condition is met. < ~ Is smaller? lrKQ6 ~ The length of the original input, stripped on both sides. lQ ~ The length of the current Q. =hZ ~ Increment a variable Z, initially 0 ?&%Z2qdhQ ~ If Z % 2 == 1 and Q[0] == " ", then: =tQ ~ Make Q equal to Q[1:] and output, else: =PQ ~ Make Q equal to Q[:-1] and output. ``` [Answer] # [Python 2](https://docs.python.org/2/), 79 bytes -1 byte thanks to @JonathanFrech ``` f=lambda s,i=1:[s]+(s>i*'!'and'!'>s[-1]and f(s[:-1])or'!'>s and f(s[1:],0)or[]) ``` [Try it online!](https://tio.run/##fYwxT8QwDIXn9le4U9qjRBxjpd52iAGJARZUVSi0ac9SSCInp@N@fXEqVbcgPNjPz9@zv8aTs4/LMrVGfX@NCkKN7b7pQn9XhgPuRCGUHbkfQne/71nDVIauYV05Wn3YzH3T1w/sdn21RLo2eXY5odHwTmfNS4bQAqnLJ1p/jmUlSXujBl0KKWoQICpmJkfgAC0/xCqFMk9oI7gbDYmWK61C0MRHaFtAGSKhL5O/ZnL9M2gf4fj6dCRyxN88Bxb5V6m150nkaUkqX2eRNNfgRj07M22glB861PCGVNwsKV90FAFmB4lFO/9/edbGuG3@Ag "Python 2 – Try It Online") The test suit replaces `"."` with `" "` before calling the function and replaces `" "` back to `"."` before printing the results for clarity. [Answer] # C# - yet again, 125 bytes ``` while(s.Trim()!=s){if(s[0]==' '){yield return s=s.Substring(1);}if(s.Last()==' '){yield return s=s.Substring(0,s.Length-1);}} ``` Cheers! [Try it online!](https://tio.run/##hVDRasIwFH3vV9z5YoIzuOeuexEZgttgDvYw9hDTVANp6nJTNyn9dpdYq3YKO5Byc3vPuTlH4FCg2JWozBLmW3Qyj6PzG5sp8xVHQnNE@IEqiuCAtVUb7iSg406JdnxcaC2FU4VB9iiNtEqw6cSUubR8oeU9OuvFHyAjTQVIj4rV7nultCTI3qzKCb1JkFbKT36MPpOkD31abZXUKVjpSmsAE2TzctEIkTsa12GYzTg6Qv8njG79rDRLtxoGbr2rT97KhfaeDtY2hUrhiStDzt56rAJaL3Gnu3cD5Kb5y6b4XGr9Yif52m0JQgJjn1KhJXuVPPU5S0Ip7Sh0twRkhZVcrIBsuIUClAlJ/mFdZwa0C9@tcnK/sTfswcALDcBXNL5g1VH3Fl2TO72/K9DEHqI9JRU@UVvsEeHFVt/gmGbhHGg8axpZCr8 "C# (Visual C# Compiler) – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 89 bytes ``` s=input('');while any(s([1,end])<33)if s(1)<33,s(1)=[],end,if s(end)<33,s(end)=[],end,end ``` [Try it online!](https://tio.run/##y08uSSxL/f@/2DYzr6C0RENdXdO6PCMzJ1UhMa9So1gj2lAnNS8lVtPG2FgzM02hWMMQxNQB0bbRsSA5HbAwkAGVALFgUkD8/7@SAgz4pJaoFyuk5wNRTlpmXjpQSAkA "Octave – Try It Online") I'll add an explanation later, when I have the time. I might be able to golf off some bytes if I change the approach completely, but I can't see how unfortunately. The last letters here spell out: "sendsendendend". I wish there was a way to store `end` as a variable and use that, but guess what ... [Answer] # Bash, ~~98~~ 94 bytes Saved 4 bytes using subshell instead of sequences (poor performances) ``` r()(s=$1;[[ $s = $b ]]||([[ $s = $a ]]||echo "$s" b=$a a=$s;((i=!i))&&r "${s# }"||r "${s% }")) ``` First answer ``` r(){ s=$1;[[ $s = $b ]]||{ [[ $s = $a ]]||echo "$s" b=$a a=$s;((i=!i))&&r "${s# }"||r "${s% }";};} ``` Note the `!` must be escaped in interactive mode ]
[Question] [ # Input A list of nonnegative integers. # Output The largest nonnegative integer `h` such that at least `h` of the numbers in the list are greater than or equal to `h`. # Test Cases ``` [0,0,0,0] -> 0 [12,312,33,12] -> 4 [1,2,3,4,5,6,7] -> 4 [22,33,1,2,4] -> 3 [1000,2,2,2] -> 2 [23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,35,73,42,12,10,15,35,23,12,42] -> 20 ``` # Rules You can write either a full program or a function, and anonymous functions are allowed too. This is code-golf, so the fewest byte count wins. Standard loopholes are disallowed. # Background The [h-index](http://en.wikipedia.org/wiki/H-index) is a notion used in academia which aims to capture the impact and productivity of a researcher. According to Wikipedia, a researcher has index *h*, if he or she has published *h* scientific articles, each of which has been cited in other articles at least *h* times. Thus, this challenge is about computing the h-index from a list of citation counts. --- # Update Wow, great answers all round! I have accepted the shortest one, but if someone else comes up with an even shorter one, I'll update my choice accordingly. # Winners by language Here's a table of winners by language that I'll also try to keep up to date. I have included all posts with nonnegative score. Please correct me if I have made a mistake here. * **APL**: 7 bytes by @MorisZucca * **Bash + coreutils**: 29 bytes by @DigitalTrauma * **C#**: 103 bytes by @LegionMammal978 * **C++**: 219 bytes by @user9587 * **CJam**: 15 bytes by @nutki * **GolfScript**: 13 bytes by @IlmariKaronen * **Haskell**: 40 bytes by @proudhaskeller * **J**: 12 bytes by @ɐɔıʇǝɥʇuʎs * **Java**: 107 bytes by @Ypnypn * **JavaScript**: 48 bytes by @edc65 * **Mathematica**: 38 bytes by @kukac67 * **Perl**: 32 bytes by @nutki * **Pyth**: 10 bytes by @isaacg * **Python**: 49 bytes by @feersum * **R**: 29 bytes by @MickyT * **Ruby**: 41 bytes by @daniero * **Scala**: 62 bytes by @ChadRetz * **SQL**: 83 bytes by @MickyT * **TI-BASIC**: 22 bytes by @Timtech [Answer] # Python 2, 49 Input should be typed in the same format as the examples. ``` i=0 for z in sorted(input())[::-1]:i+=z>i print i ``` [Answer] # Python, 52 ``` f=lambda s,n=0:n<sum(n<x for x in s)and f(s,n+1)or n ``` A recursive solution. Run this in [Stackless Python](http://www.stackless.com/) if you're worried about overflows. Starting from `n=0`, checks whether at least `n+1` of the numbers are at least `n+1`. If so, increments `n` and starts again. If not, outputs `n`. The conditional is done using Python's short-circuiting for Booleans. The expression `sum(n<x for x in s)` counts the number of values in `s` that are greater than `n` by adding the indicator Booleans, which are treated as `0` or `1`. For comparison, the iterative equivalent is 2 chars longer. It requires Python 2. ``` s=input() n=0 while n<sum(n<x for x in s):n+=1 print n ``` Unfortunately, the input need to be saved for a variable before being iterated over or else Python will try to read the input repeatedly. [Answer] # Pyth, ~~13~~ 10 bytes ``` tf<l-QUTT1 ``` Input in a form such as `[22,33,1,2,4]` on STDIN. [Try it here.](http://isaacg.scripts.mit.edu/pyth/index.py) How it works: `-QUT` is all of the numbers in the input (`Q`) at least as large as the number being checked, `T`. `<l-QUTT` is true if the the length of that list is less than `T`. `f<l-QUTT1` finds the first integer which returns true for the inner check, starting at `1` and going up. `tf<l-QUTT1` decrements that by one, giving the largest value for which the condition is false, which is the h-index. Starting at 1 ensures that `0` is returned when the test is always true, such as in the first test case. [Answer] # CJam, 15 bytes Direct translation of my Perl solution. ``` l~{~}${W):W>},, ``` [Answer] **APL 7** ``` +/⊢≥⍋∘⍒ ``` Can be tried online on tryapl.org ``` f←+/⊢≥⍋∘⍒ f¨(4⍴0)(12 312 33 12)(⍳7)(22 33 1 2 4)(1000 2 2 2)(23 42 12 92 39 46 23 56 31 12 43 23 54 23 56 73 35 73 42 12 10 15 35 23 12 42) 0 4 4 3 2 20 ``` [Answer] # J (~~13~~ 12) ``` [:+/i.@#<\:~ ``` Pretty similar to randomra's solution. Demonstration: ``` f=:[:+/i.@:#<\:~ f 0,0,0,0 0 f 12,312,33,12 4 f 1,2,3,4,5,6,7 4 f 22,33,1,2,4 3 f 1000,2,2,2 2 f 23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,35,73,42,12,10,15,35,23,12,42 20 ``` [Answer] # Mathematica, 44 42 40 38 bytes Anonymous function: ``` LengthWhile[i=0;SortBy[#,-#&],#>i++&]& ``` Run it by tacking the input on to the end like so: ``` In: LengthWhile[i=0;SortBy[#,-#&],#>i++&]&@{1,2,3,4,5,6,7} Out: 4 ``` [Answer] ## SQL, ~~81~~ ~~94~~ 83 Given a table (I) of values (V), the following query will return h. Tested in PostgreSQL and will also work in SQL Server. **Edit** Make it return 0 rather than NULL. Made better with a COUNT, thanks @nutki ``` SELECT COUNT(R)FROM(SELECT ROW_NUMBER()OVER(ORDER BY V DESC)R,V FROM I)A WHERE R<=V ``` [SQLFiddle](http://sqlfiddle.com/#!15/8ef5b/1/0) example Essentially it numbers the rows on a descending sort of the values. Then it returns the maximum row number where the row number is greater than equal to the value. [Answer] ## R, ~~39~~ ~~35~~ 29 ``` s=sort(i);sum(s>=length(s):1) ``` Given a vector of integers in i and using the logic of a reverse sort then returning the ~~length~~ of the vector where element number is less than s. Thanks to @plannapus for the nice tip. ``` > i=c(23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,35,73,42,12,10,15,35,23,12,42) > s=sort(i);length(s[s>=length(s):1]) [1] 20 > i=c(0,0,0,0) > s=sort(i);length(s[s>=length(s):1]) [1] 0 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ñÍè> ``` [Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8c3oPg&input=WzIzLDQyLDEyLDkyLDM5LDQ2LDIzLDU2LDMxLDEyLDQzLDIzLDU0LDIzLDU2LDczLDM1LDczLDQyLDEyLDEwLDE1LDM1LDIzLDEyLDQyXQ) ``` ñÍè> :Implicit input of array ñ :Sort by Í : Subtracting from 2 è :Count the elements that are > : Greater than their 0-based indices ``` [Answer] # CJam, 23 bytes ``` l~:I,),W%{_If>:!:+>}$0= ``` This takes the list as an array on STDIN, like ``` [23 42 12 92 39 46 23 56 31 12 43 23 54 23 56 73 35 73 42 12 10 15 35 23 12 42] ``` [Test it here.](http://cjam.aditsu.net/) You can use this to run all test cases: ``` [0 0 0 0] [12 312 33 12] [1 2 3 4 5 6 7] [22 33 1 2 4] [1000 2 2 2] [23 42 12 92 39 46 23 56 31 12 43 23 54 23 56 73 35 73 42 12 10 15 35 23 12 42]] {:I,),W%{_If>:!:+>}$0=N}/ ``` ## Explanation ``` l~:I,),W%{_If>:!:+>}$0= l~:I "Read input, evaluate, store in I."; , "Get length of input N."; ),W% "Create range from 0 to N, reverse."; { }$ "Sort stably."; _I "Duplicate candidate h, push input list."; f> "Map each number to 1 if it's less or 0 otherwise."; :! "Invert all results."; :+ "Sum them up."; > "Check if the sum is less than the candidate h."; 0= "Pick the first element."; ``` The logic is a bit backwards, but it saved a couple of bytes. Basically, the block passed to sort returns `0` for valid candidates and `1` otherwise. So the valid candidates come first in the sorted array. And because the sort is stable, and we begin with a list from N down to 1, this will return the largest valid h. [Answer] # Perl 5: 32 (30 + 2 for `-pa`) ``` #!perl -pa $_=grep$_>$i++,sort{$b<=>$a}@F ``` Takes space separated input on STDIN: ``` perl hidx.pl <<<'1 2 3 4 5 6 7' ``` [Answer] # Python (63) Basically a direct port of my J solution. Obviously, a lot longer, as one might imagine. ``` lambda x:sum(a>b for a,b in zip(sorted(x)[::-1],range(len(x)))) ``` [Answer] # Haskell, 40 ``` f s=[x-1|x<-[1..],x>sum[1|r<-s,r>=x]]!!0 ``` this searches for the first number to not fit the scheme and returns it's predecessor. [Answer] # Ruby ~~44~~ 41 Recursive, more or less same strategy as xnor's Python solution: ``` f=->a,n=0{a.count{|x|x>n}<n+1?n:f[a,n+1]} ``` # Ruby 52 Non-recursive: ``` f=->a{a.size.downto(0).find{|x|a.count{|y|y>=x}>=x}} ``` "Stabby" lambda/anonymous functions, require Ruby 1.9 or newer. Call with e.g. `f[[22,33,1,2,4]]` [Answer] # Bash + coreutils, 29 ``` sort -nr|nl -s\>|bc|grep -c 0 ``` Input taken from stdin as a newline-separated list. * `sort` the integers in descending order * `nl` prefixes each line with its 1-based line number, separating the line number and rest of the line with a greater-than `>` * Arithmetically evaluate each line with `bc`. Integers less than their line number result in 0. Otherwise 1. * `grep` counts the number of `0`s, i.e. the number of integers greater than or equal to `h` ### Example ``` $ for i in {23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,35,73,42,12,10,15,35,23,12,42}; do echo $i; done | ./atleasth.sh 20 $ for i in {1,2,3,4,5,6,7}; do echo $i; done | ./atleasth.sh 4 $ ``` [Answer] # JavaScript (ES6) 48 Recursive solution. ``` F=(l,h=-1)=>l.filter(v=>v>h).length>h?F(l,h+1):h ``` **Test** in FireFox/FireBug console ``` ;[ [0,0,0,0], [12,312,33,12], [1,2,3,4,5,6,7], [22,33,1,2,4], [1000,2,2,2], [23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,35,73,42,12,10,15,35,23,12,42] ].forEach(l=>console.log(l,F(l))) ``` *Output* ``` [0, 0, 0, 0] 0 [12, 312, 33, 12] 4 [1, 2, 3, 4, 5, 6, 7] 4 [22, 33, 1, 2, 4] 3 [1000, 2, 2, 2] 2 [23, 42, 12, 92, 39, 46, 23, 56, 31, 12, 43, 23, 54, 23, 56, 73, 35, 73, 42, 12, 10, 15, 35, 23, 12, 42] 20 ``` [Answer] # Java 8, 116 bytes. Full class: ``` import java.util.*; import java.util.stream.*; class H{ public static void main(String[]a){ System.out.println(new H().f(Stream.of(a[0].split(",")).mapToInt(Integer::parseInt).toArray())); } int i; int f(int[]n){ Arrays.sort(n); i=n.length; Arrays.stream(n).forEach(a->i-=a<i?1:0); return i; } } ``` Function: ``` import java.util.*;int i;int f(int[]n){Arrays.sort(n);i=n.length;Arrays.stream(n).forEach(a->i-=a<i?1:0);return i;}} ``` [Answer] # APL, 12 characters [`(+/⊢≥⍒)⊂∘⍒⌷⊢`](http://tryapl.org/?a=f%u2190%28+/%u22A2%u2265%u2352%29%u2282%u2218%u2352%u2337%u22A2%20%u22C4%20f%A8%284%u23740%29%2812%20312%2033%2012%29%28%u23737%29%2822%2033%201%202%204%29%281000%202%202%202%29%2823%2042%2012%2092%2039%2046%2023%2056%2031%2012%2043%2023%2054%2023%2056%2073%2035%2073%2042%2012%2010%2015%2035%2023%2012%2042%29&run) [Answer] **C++ ~~815~~ 219 from (wc -c main.cpp)** Alright here's some of the worst code I've ever written! :) ``` #include <iostream> #include <list> using namespace std;int main(int c,char** v){list<int>n(--c);int h=c;for(int&m:n)m=atoi(*(v+(h--)));n.sort();for(auto r=n.rbegin();r!=n.rend()&&*r++>++h;);cout<<(h==c?h:--h)<<endl;} ``` [Answer] # Jelly, 6 bytes ``` NỤỤ<’S ``` Explanation: ``` N Negate (so that repeated elements won't mess up the second grade down) Ụ Grade down Ụ Twice. <’ Predicate, check for each element if the new one (after grading) is lower than original array (minus 1 on each element) S Sum ``` [Answer] ## Haskell, ~~72~~ 59 bytes My C++ solution looked pretty verbose, and the recursive nature made me think of Haskell, so here's my attempt: ``` a!i|i<foldr(\x s->s+fromEnum(i<x))0 a=a!(i+1)|1<2=i H a=a!0 ``` Explanation: ``` foldr (\x s -> s + fromEnum(i < x)) 0 a ``` I'm sure there's a shorter way to do this, because I'm pretty new to haskell, but basically it counts how many elements of `a` are less than `x`. If this is greater than `i`, we can check `i+1`, otherwise, return `i`. And the `H` function is so that we don't need to pass in `0` to `h`. It adds ~~10~~ 8 bytes, so I'm pretty sure there's a better way. **-13 bytes** thanks to ovs [Answer] # CJam, 22 bytes ``` q~:Q,),{Q{1$>},,>!},W= ``` Takes the list as input: ``` [23 42 12 92 39 46 23 56 31 12 43 23 54 23 56 73 35 73 42 12 10 15 35 23 12 42] ``` Output: ``` 20 ``` [Try it here](http://cjam.aditsu.net/) [Answer] # C#, 103 Anonymous function. ``` a=>{try{return a.OrderBy(b=>-b).Select((b,c)=>new{b,c}).First(b=>b.b<b.c+1).c;}catch{return a.Length;}} ``` Indented: ``` a => { try { return a.OrderBy(b => -b).Select((b, c) => new { b, c }).First(b => b.b < b.c + 1); } catch { return a.Length; } } ``` [Answer] # GolfScript, 13 bytes ``` $-1%0\{1$>+}/ ``` [Test this code online.](http://golfscript.apphb.com/?c=IyBUZXN0IGNhc2VzOgpbWzAgMCAwIDBdClsxMiAzMTIgMzMgMTJdClsxIDIgMyA0IDUgNiA3XQpbMjIgMzMgMSAyIDRdClsxMDAwIDIgMiAyXQpbMjMgNDIgMTIgOTIgMzkgNDYgMjMgNTYgMzEgMTIgNDMgMjMgNTQgMjMgNTYgNzMgMzUgNzMgNDIgMTIgMTAgMTUgMzUgMjMgMTIgNDJdXQoKIyBSdW4gY29kZSBvbiB0ZXN0IGNhc2VzLCBwcmludCBvdXRwdXQ6CnsgICQtMSUwXHsxJD4rfS8gIHB9Lw%3D%3D)1 Takes input as an array on the stack. Uses the same algorithm as [feersum's Python solution](https://codegolf.stackexchange.com/a/42678), iterating over the numbers in the array and incrementing a counter from 0 until it equals or exceeds the current element of the array. 1) The online GolfScript server seems to be experiencing random timeouts again. If the program times out for you, try re-running it. [Answer] # TI-BASIC, 22 bytes ASCII representation: ``` Input L1:1:While Ans≤sum(Ans≥L1:Ans+1:End:Ans ``` Hex dump: ``` DC 5D 00 3E 31 3E D1 72 6D B6 72 6C 5D 00 3E 72 70 31 3E D4 3E 72 ``` Gets a list as input. Starting from Ans=0, checks whether at least Ans+1 of the numbers are at least Ans+1. If so, increments Ans and loops again. If not, outputs Ans. [Answer] # [JAGL](http://github.com/globby/jagl) Alpha 1.2 - 14 ***Doesn't count*** because the 'C' reverse array functionality was added after the question, but am answering for fun anyway. Assumes that the array is the first item on the stack, and puts the answer at the top of the stack. ``` 0SJC{Sd@>+1}/S ``` To print, just add `P` at the end, adding a byte. Explanation: ``` 0 Push the number 0 (the counter) SJC Swap to array, sort and reverse {Sd@>+1}/ For each item in the array, add 1 to counter if counter is less than item S Swap counter to top of stack ``` [Answer] ## J, ~~15~~ 11 chars (Current shortest J solution.) ``` [:+/#\<:\:~ ([:+/#\<:\:~) 1 2 3 4 5 6 7 4 ``` Compares `<:` sorted list `\:~` elements with 1..n+1 `#\` and counts true comparisons `+/`. Testing similarity against other J solution on 100 random test cases: ``` */ (([:+/#\<:\:~) = ([:+/i.@#<\:~))"1 ?100 100$100 1 ``` [Answer] # Reng v.3.2, 43 bytes ``` 1#xk#yaïí'1ø ~n-1$\ 1+)x(%:1,%1ex+y1-?^#y#x ``` [Try it here!](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) This code can be split into three parts: initial, computational, and final. ## Initial ``` 1#xk#yaïí'1ø ``` This stores `1` to `x`, the length of the input stack `k` to `y`, and gets all input (`aïí`) which is then sorted (`'`). `1ø` goes to the next line, i.e., the next part. ## Computational ``` 1+)x(%:1,%1ex+y1-?^#y#x ``` Reng has no built-in for inequality. Thus, an algorithm must be implemented. The shortest algorithm I found for `a < b` is `%:1,%1e`; this looks like this: ``` Command | Stack --- | a, b % | a/b : | a/b, a/b 1 | a/b, a/b, 1 , | a/b, (a/b)%1 e | (a/b) == ((a/b)%1) ``` I'm sure *that* cleared it up! Let me explain further. `x % 1`, i.e modulus with 1, maps `x` to `(-1,1)`. We know that `(a/b) % 1` is `a/b` when `a < b`. Thus, this expression is equal to `a < b`. However, this doesn't work quite as well because of problems with modulus with zero. So, we increment every member of the stack and the counter initially. After we get the inequality Boolean on the stack, `x+` adds it to x, but leaves it on the stack for the moment. `y1-` decrements `y`, and `?^` goes up iff `y == 0` and we proceed to the final phase. Otherwise, we put `y-1` into `y` and the new `x` into `x`. ## Final ``` ~n-1$\ ``` This pops the residual `y-1` from the stack, decrements the result, outputs it, and ends the program. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` {Rā@O ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/OuhIo4P////RRsY6JkY6hkY6lkY6xpY6JmY6QBFTMx1jQ5CgiTGYawIVNDfWMTYFkRAthgY6hqYgEaAsSLFRLAA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##LYyxDsIwDER3vqLqfEiO7aTqQhkQKxJr1QEkBiYGRib@rf8VzimybPnenf163@7PRy3n09R3@0PXT/VzXb/HS0WdBa2W3ZwUFm1IGhLc4cgoGKh1s0g9XBHhygqLOeUVRmZGeAFJLnwX0K1J/8PBYDnmdpIEKQdRa2Fdfg) **Explanation** ``` {R # sort descending ā@ # check each element if it's greater than or equal to its 1-based index O # sum ``` ]
[Question] [ The paint on the walls in my room has a random, almost fractal-like, 3-dimensional texture: ![Image A](https://i.stack.imgur.com/fQkU9.png) In this challenge you will write a program that generates random images that look like they could be part of my walls. Below I've collected 10 images of different spots on my walls. All have roughly the same lighting and all were taken with the camera one foot away from the wall. The borders were evenly cropped to make them 2048 by 2048 pixels, then they were scaled to 512 by 512. The image above is image A. **These are only thumbnails, click images to view at full size!** **A:** [![Image A](https://i.stack.imgur.com/fQkU9s.png)](https://i.stack.imgur.com/fQkU9.png) **B:** [![Image B](https://i.stack.imgur.com/POqvVs.png)](https://i.stack.imgur.com/POqvV.png) **C:** [![Image C](https://i.stack.imgur.com/Gz3WCs.png)](https://i.stack.imgur.com/Gz3WC.png) **D:** [![Image D](https://i.stack.imgur.com/x0T8fs.png)](https://i.stack.imgur.com/x0T8f.png) **E:** [![Image E](https://i.stack.imgur.com/N4aWPs.png)](https://i.stack.imgur.com/N4aWP.png) **F:** [![Image F](https://i.stack.imgur.com/Jmf7rs.png)](https://i.stack.imgur.com/Jmf7r.png) **G:** [![Image G](https://i.stack.imgur.com/qogGVs.png)](https://i.stack.imgur.com/qogGV.png) **H:** [![Image H](https://i.stack.imgur.com/v66T1s.png)](https://i.stack.imgur.com/v66T1.png) **I:** [![Image I](https://i.stack.imgur.com/CstUms.png)](https://i.stack.imgur.com/CstUm.png) **J:** [![Image J](https://i.stack.imgur.com/zGc38s.png)](https://i.stack.imgur.com/zGc38.png) Your task is to write a program that takes in a positive integer from 1 to 216 as a random seed, and for each value generates a distinct image that looks like it could have been the "eleventh image" of my wall. If someone looking at my 10 images and a few of yours can't tell which were computer generated then you've done very well! Please show off a few of your generated images so viewers can see them without having to run the code. I realize that the lighting in my images is not perfectly uniform in intensity or color. I'm sorry for this but it's the best I could do without better lighting equipment. Your images do not need to have variable lighting (though they could). The texture is the more important thing to focus on. # Details * You may use image processing tools and libraries. * Take the input in any common way you desire (command line, stdin, obvious variable, etc). * The output image can be in any common lossless image file format, or it can just be displayed in a window/bowser. * You may programmatically analyze my 10 images but **don't assume that everyone running your code has access to them.** * You must generate the images programmatically. You may not hard-code a slight variant of one of my images or some other stock image. (People would vote you down for this anyway.) * You may use built-in pseudorandom number generators and assume the period is 216 or more. # Scoring This is a popularity contest so the highest-voted answer wins. [Answer] # GLSL (+ JavaScript + WebGL) ![enter image description here](https://i.stack.imgur.com/VpCyf.png) [**Live demo**](http://m-ender.github.io/webgl-wallpaint/public/) **|** [**GitHub repository**](https://github.com/m-ender/webgl-wallpaint) ## How to use Reload the page for a new random image. If you want to feed in a particular seed, open your browser's console and call `drawScreen(seed)`. The console should display the seed used on load. I haven't really tested this on a lot of platforms, so let me know if it doesn't work for you. Of course, your browser needs to support WebGL. Errors are displayed either in the column on the left, or in the browser's console (depending on the type of error). **New:** You can now bring the walls to life a bit, by ticking the "movable light source" checkbox. ## What is this sorcery? I've got this WebGL boilerplate code [floating around my GitHub account](https://github.com/m-ender/webgl-boilerplate), which I use every now and then to quickly prototype some 2D graphics things in WebGL. With some shader magic, we can also make it look slightly 3D, so I thought that was the quickest way to get some nice effects going. Most of the setup is from that boilerplate code, and I'm considering that a library for this submission and won't include it in this post. If you're interested, have a look at the [main.js](https://github.com/m-ender/webgl-wallpaint/blob/master/public/main.js) on GitHub (and the other files in that folder). All the JavaScript does is to set up a WebGL context, store the seed in a uniform for the shader, and then render a single quad over the entire context. The vertex shader is a simple passthrough shader, so all the magic happens in the fragment shader. That's why I called this a GLSL submission. The largest part of the code is actually to generate the Simplex noise, which [I found on GitHub](https://github.com/ashima/webgl-noise/blob/master/src/noise2D.glsl). So I'm omitting that as well in the code listing below. The important part is, it defines a function `snoise(vec2 coords)` which returns simplex noise without using a texture or array lookup. It's not seeded at all, so the trick to getting different noise is to use the seed in determining where to do the lookup. So here goes: ``` #ifdef GL_ES precision mediump float; #endif #extension GL_OES_standard_derivatives : enable uniform float uSeed; uniform vec2 uLightPos; varying vec4 vColor; varying vec4 vPos; /* ... functions to define snoise(vec2 v) ... */ float tanh(float x) { return (exp(x)-exp(-x))/(exp(x)+exp(-x)); } void main() { float seed = uSeed * 1.61803398875; // Light position based on seed passed in from JavaScript. vec3 light = vec3(uLightPos, 2.5); float x = vPos.x; float y = vPos.y; // Add a handful of octaves of simplex noise float noise = 0.0; for ( int i=4; i>0; i-- ) { float oct = pow(2.0,float(i)); noise += snoise(vec2(mod(seed,13.0)+x*oct,mod(seed*seed,11.0)+y*oct))/oct*4.0; } // Level off the noise with tanh noise = tanh(noise*noise)*2.0; // Add two smaller octaves to the top for extra graininess noise += sqrt(abs(noise))*snoise(vec2(mod(seed,13.0)+x*32.0,mod(seed*seed,11.0)+y*32.0))/32.0*3.0; noise += sqrt(abs(noise))*snoise(vec2(mod(seed,13.0)+x*64.0,mod(seed*seed,11.0)+y*64.0))/64.0*3.0; // And now, the lighting float dhdx = dFdx(noise); float dhdy = dFdy(noise); vec3 N = normalize(vec3(-dhdx, -dhdy, 1.0)); // surface normal vec3 L = normalize(light - vec3(vPos.x, vPos.y, 0.0)); // direction towards light source vec3 V = vec3(0.0, 0.0, 1.0); // direction towards viewpoint (straight up) float Rs = dot(2.0*N*dot(N,L) - L, V); // reflection coefficient of specular light, this is actually the dot product of V and and the direction of reflected light float k = 1.0; // specular exponent vec4 specularColor = vec4(0.4*pow(Rs,k)); vec4 diffuseColor = vec4(0.508/4.0, 0.457/4.0, 0.417/4.0, 1.0)*dot(N,L); vec4 ambientColor = vec4(0.414/3.0, 0.379/3.0, 0.344/3.0, 1.0); gl_FragColor = specularColor + diffuseColor + ambientColor; gl_FragColor.a = 1.0; } ``` That's it. I might add some more explanation tomorrow, but the basic idea is: * Choose a random light position. * Add up a few octaves of noise, to generate the fractal pattern. * Square the noise to keep the bottom rough. * Feed the noise through `tanh` to level off the top. * Add two more octaves for a little bit more texture on the top layer. * Compute the normals of the resulting surface. * Run a simple Phong shading over that surface, with specular and diffuse lights. The colours are chosen based on some random colours I picked from the first example image. [Answer] # Mathematica Spackling The app below applies speckling to a random image. Clicking on "new patch" generates a new random image to work with, and then applies the effects according to current settings. The effects are oil painting, Gaussian filter, posterization, and embossing. Each effect can be independently tweaked. The seed for the random number generator can be any integer from 1 to 2^16. **Update**: The Gaussian filter, which softens the edges, is now the last image effect applied. With this modification, the posterization effect was no longer needed and thus removed. ``` Manipulate[ GaussianFilter[ImageEffect[ImageEffect[r, {"OilPainting", o}], {"Embossing", e, 1.8}], g], Button["new patch", (SeedRandom[seed] r = RandomImage[1, {400, 400}])], {{o, 15, "oil painting"}, 1, 20, 1, ContinuousAction -> False, Appearance -> "Labeled"}, {{e, 1.64, "embossing"}, 0, 5, ContinuousAction -> False, Appearance -> "Labeled"}, {{g, 5, "Gaussian filter"}, 1, 12, 1, ContinuousAction -> False, Appearance -> "Labeled"}, {{seed, 1}, 1, 2^16, 1, ContinuousAction -> False, Appearance -> "Labeled"}, Initialization :> (SeedRandom[seed]; r = RandomImage[1, {400, 400}])] ``` ![end result](https://i.stack.imgur.com/VIPr5.png) --- ## Explanation The explanation is based on a slightly different version, in which posterization was employed and `GaussianFilter` was applied early on. But it still serves to clarify how each image effect alters an image. The end result is a paint texture with sharper edges. When the Gaussian filter is only applied at the end, the result will be smoother, as the above picture shows. Let's look at some image effects, one at a time. Generate a starting image. ``` r = RandomImage[1, {200, 200}] ``` ![random image](https://i.stack.imgur.com/WjFzR.png) --- Lena will show us how each image effect transforms a life-like picture. ``` Lena = ExampleData[{"TestImage", "Lena"}] ``` ![Lena](https://i.stack.imgur.com/OzD8F.png) --- An oil painting effect applied to Lena. ``` ImageEffect[Lena, {"OilPainting", 8}] ``` ## lena oil An oil painting effect applied to our random image. The effect was intensified (16 instead of 8). ``` r1 = ImageEffect[r, {"OilPainting", 16}] ``` ![oil](https://i.stack.imgur.com/DtPdB.png) --- A Gaussian filter effect applied to Lena (not to the oil painting effect version of Lena). The radius is 10 pixels. (In the final version, at the top of this entry, GaussianFilter is applied as the final effect.) ``` GaussianFilter[Lena, 10] ``` ![lena gaussian.](https://i.stack.imgur.com/t5fgQ.png) --- A somewhat milder Gaussian filter effect applied to r1. The radius is 5 pixels. ``` r2 = GaussianFilter[r1, 5] ``` ![gauss](https://i.stack.imgur.com/vjbit.png) --- An intense posterization effect applied to Lena. (In the final version of the app, I removed posterization. But we'll leave it in the analysis, since the examples in the analysis were based on an earlier version with posterization.) ``` ImageEffect[Lena, {"Posterization", 2}] ``` ![lena posterize](https://i.stack.imgur.com/mYiSo.png) --- A posterization effect applied to r2. ``` r3 = ImageEffect[r2, {"Posterization", 4}] ``` ![posterize](https://i.stack.imgur.com/TyWoq.png) --- Embossing Lena ``` ImageEffect[Lena, {"Embossing", 1.2, 1.8}] ``` ![lena embossing](https://i.stack.imgur.com/99TKS.png) --- Embossing r3 completes the image processing. This is intended to look something like the OP's ceiling. ``` ceilingSample = ImageEffect[r3, {"Embossing", 1.2, 1.8}] ``` ![emboss](https://i.stack.imgur.com/mcLBa.png) --- For the curious, here is Lena with the same image effects applied. ![lena4](https://i.stack.imgur.com/RX6hS.png) [Answer] # POV-Ray A lot of golfing potential, run with `povray /RENDER wall.pov -h512 -w512 -K234543` ![enter image description here](https://i.stack.imgur.com/RX2lr.jpg) First it creates a random texture, but instead of stopping there it transforms the texture into a 3D-heightfield to make the radial shadows from the camera flash more realistic. And for good measure it adds another texture of little bumps on top. The only way apart from hardcoding the random seed is to use the `clock` variable meant for animations, this is passed with the `-K{number}` flag ``` #default{ finish{ ambient 0.1 diffuse 0.9 }} camera {location y look_at 0 right x} light_source {5*y color 1} #declare R1 = seed (clock); // <= change this #declare HF_Function = function{ pigment{ crackle turbulence 0.6 color_map{ [0.00, color 0.01] [0.10, color 0.05] [0.30, color 0.20] [0.50, color 0.31] [0.70, color 0.28] [1.00, color 0.26] }// end color_map scale <0.25,0.005,0.25>*0.7 translate <500*rand(R1),0,500*rand(R1)> } // end pigment } // end function height_field{ function 512, 512 { HF_Function(x,0,y).gray * .04 } smooth texture { pigment{ color rgb<0.6,0.55,0.5>} normal { bumps 0.1 scale 0.005} finish { phong .1 phong_size 400} } // end of texture translate< -0.5,0.0,-0.5> } ``` ]
[Question] [ Given an Integer array: 1. Start from the first number 2. Jump forward n positions where n is the value of the current position 3. Delete the current position, making what was the next position the current position. 4. Goto step 2 until there is one number remaining 5. Print that number **Rules** The array wraps-around (the next number after the last number in the array is the first number). A zero removes itself (Obviously). Negative numbers are not allowed as input. **Test Cases** ``` [1] => 1 [1,2] => 1 [1,2,3] => 3 [1,2,2] => 1 [1,2,3,4] => 1 [6,2,3,4] => 4 [1,2,3,4,5] => 5 [0,1] => 1 [0,0,2,0,0] => 0 ``` --- **Step-by-step example** ``` [1,4,2,3,5] ^ start from the first position ^ jump 1 position (value of the position) [1, 2,3,5] remove number in that position ^ take next position of the removed number (the 'new' 'current' position) ^ jump 2 positions [1, 2,3 ] remove number in that position ^ take next position (looping on the end of the array) ^ jump 1 position [1, 3 ] remove number in that position ^ take next position (looping) ^ jump 3 positions (looping on the end of the array) [ 3 ] remove number in that position print 3 ``` **Example #2** ``` [4,3,2,1,6,3] ^ start from the first position ^ jump 4 positions [4,3,2,1, 3] remove number in that position ^ take next position ^ jump 3 positions [4,3, 1, 3] remove number in that position ^ take next position ^ jump 1 positions [4,3, 1 ] remove number in that position ^ take next position ^ jump 4 positions [4, 1 ] remove number in that position ^ take next position ^ jump 1 position [ 1 ] remove number in that position print 1 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins! [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes This returns the result as a singleton list ``` ΩεSotṙ← ``` [Try it online!](https://tio.run/##yygtzv6vcGhbrsajpsYizUPb/p9beW5rcH7Jw50zH7VN@P//f7RhLFe0oY4RhNQxhtJwvo4JkGUGZ0HFdEyBbAMdQzBpABQDkrEA "Husk – Try It Online") ### Explanation ``` Ω Until ε the result is a singleton list ṙ Rotate left by S ← the first element ot Then remove the first element ``` [Answer] # [Haskell](https://www.haskell.org/), ~~54~~ ~~50~~ 48 bytes ``` f[x]=x f(x:r)=f$snd<$>zip r(drop(x+1)$cycle$x:r) ``` [Try it online!](https://tio.run/##TY1NDoIwFIT37xRv0UWJxVD5WRjhBp6g6YIAjUTABlxUjWevBRtgM52ZvnxzK6d703XWKmFkbkBRcx6DXJFpqC@keLcaR1qPD03NgQekelVdQ@YT25ftgDn2pb4i1WM7PPGIKkAhuGSCs9NfWezfNbPEuWx1vmOp8xHji0aucyolwCcEB8S8QA4LdbMOPYcYPH//49A@ZruYwG5uLlJYNv3pNjwXEYRf@wM "Haskell – Try It Online") **Explanation:** * `f[x]=x`: If the given list is a singleton list, return its element. * `f(x:r)=f$ ...`: Otherwise recursively apply `f` to the following list: + The elements of the current list cycled infinitely (`cycle$x:r`), + with the first `x+1` elements removed (`drop(x+1)$`), + and truncated to length of `r`. (`snd<$>zip r` is a shorter alternative to `take(length r)`). --- ### Previous 54 byte version: ``` f=(%)=<<head _%[x]=x n%(x:r)|n<1=f r|s<-r++[x]=(n-1)%s ``` [Try it online!](https://tio.run/##TY1BCoMwFET3/xR/E4gYi6nWRTG9QU8QQglUUapBYhdC7dltYoO6mczMD28aPb6qrluWWlASibJsKv2EB5GTEhMYQqerjWZTclGjnccysXHsb9QkPCLj0uvWoMBeD3ekg23NG09YRyglV0xydv4ry8K7ZZY7V2wudOzifMr4qqnrnCoF8EnAAVHckMNK3a1D@5BB4B8vDh1icYg5HOZ8cYF1M3zdh32RQvJdfg "Haskell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 37 bytes ``` ->r{r.rotate!(r[0]).shift while r[1]} ``` Modifies the array in-place, which appears to be acceptable as output. [Try it online!](https://tio.run/##ZY/RCoJAEEXf/YpJEAqmZU3tTX9kkTBZU5SU3dUK9dtt2ofY6GW499w7DKPG62ur0u2YqVkx1ZvCyN1eCZ4fmK6bysCjbjoJSoT5us0eAAlIMwjRajz9Ooysj77@L8fYIWeHxG4HE8sSyzi6Nzly6tC0jKO3MlmUNcxLi9MCw2g0@IH@hIFGkM9Blqa538j5EIBomekvFFSizRfagYk@ewM "Ruby – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~54~~ 51 bytes ``` f=lambda x:x and f((x+x*x[0])[x[0]:][1:len(x)])or x ``` Output is a singleton list. [Try it online!](https://tio.run/##RY5BCoMwEEXX7SlmIyZ2BKOplEB7kZCFxYYKNoq6mJ4@TdTi5s2bz2eY8bu8B1d5b@9983m2DZAiaFwLljG6UEa6MFxHKqOF6l@OETd8mIC8jYTOgRYGA7DcB1Z/ORKUUetD9xSvcSlQbKMIaeBWkGtlLcggJQqsw211Po1T5xaWJrm4zZA/IJlTSIARQmbDg5z7Hw "Python 3 – Try It Online") [Answer] ## [CJam](https://sourceforge.net/p/cjam), 15 bytes ``` l~_,({_0=m<1>}* ``` [Try it online!](https://tio.run/##S85KzP1f/T@nLl5HozrewDbXxtCuVut/bF6tpdb/aMNYrmhDBSMIqWAMpeF8BRMgywzOgoopmALZBgqGYNIAKAYkYwE "CJam – Try It Online") ### Explanation Instead of keeping track of a pointer, I just shift the array cyclically so that the current element is always at the front. ``` l~ e# Read and evaluate input. _,( e# Get its length L and decrement to L-1. { e# Run this block L-1 times... _0= e# Get the first element X. m< e# Rotate the array left by X positions. 1> e# Discard the first element. }* e# The final element remains on the stack and gets printed implicitly. ``` A fun alternative which unfortunately doesn't save any bytes: ``` l~_{;m<1>_0=}*; ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 21 bytes ``` 1`yy)+ynX\[]w(5Mynq]x ``` [Try it online!](https://tio.run/##y00syfn/3zChslJTuzIvIiY6tlzD1LcyrzC24v//aEMdEx0jHWMd01gA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8N8wobJSU7syLyImOrZcw9S3Mq8wtuK/S8j/aEMdEx0jHWMd01iuaBMgbaRjqGOmYxwLAA). ### Explanation ``` 1 % Push 1: current position in the array ` % Do...while yy % Duplicate top two elements in the stack. Takes input implicitly % in the first iteration. % STACK: array, position, array, position ) % Get specified entry in the array % STACK: array, position, selected entry + % Add % STACK: array, position (updated) y % Duplicate from below % STACK: array, position, array n % Number of elements of array % STACK: array, position, number of elements or array X\ % 1-based modulus % STACK: array, position (wrapped around) [] % Push empty array % STACK: array, position, [] w % Swap % STACK: array, [], position ( % Write value into specified entry in array. Writing [] removes % the entry % STACK: array (with one entry removed) 5M % Push latest used position. Because of the removal, this now % points to the entry that was after the removed one % STACK: array, position y % Duplicate from below % STACK: array, position, array n % Number of elements of array % STACK: array, position, number of elements of array q % Subtract 1 % STACK: array, position, number of elements of array minus 1 ] % End. If top of the stack is nonzero, proceed with next iteration % STACK: array (containing 1 entry), position x % Delete. Implicitly display % STACK: array (containing 1 entry) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ṙḷ/ḊµḊ¿ ``` [Try it online!](https://tio.run/##y0rNyan8///hzpkPd2zXf7ij69BWELH/////0YY6CkY6CsY6CiY6CqaxAA "Jelly – Try It Online") Full program. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ṙḷ/ḊµL’$¡ ``` [Try it online!](https://tio.run/##y0rNyan8///hzpkPd2zXf7ij69BWn0cNM1UOLfx/uP1R05r//6MNY3WiDXWMIKSOMZSG83VMgCwzOAsqpmMKZBvoGIJJA6AYkIwFAA "Jelly – Try It Online") -2 bytes thanks to user202729 # Explanation ``` ṙḷ/ḊµL’$¡ Main Link L’$¡ Repeat <length - 1> times ṙ Rotate left by ḷ/ The first element (from JHT; thanks to user202729) Ḋ Take all but the first element ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 88 bytes ``` ([[]]()){({}<(({})){({}<({}<([]){({}{}<>)<>([])}{}>)<>{({}[<>[]])<>}<>>[()])}{}{}>())}{} ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6OjZWQ1OzWqO61kYDSMCYIBwdC@YAmXaaNnYgLpANYoJEo23sgFqBHKCsXbSGJlgSKA00DEj9/2/IZcJlxGXMZQoA "Brain-Flak – Try It Online") ### Explanation ``` ([[]]()) Push negative N: the stack height - 1 {({}< … >())}{} Do N times (({})) Duplicate M: the top of the stack {({}< … >[()])}{} Do M times Rotate the stack by 1: ({}< … >) Pop the top of the stack and put it back down after ([]){({}{}<>)<>([])}{} Pushing the rest of the stack on to the other one, in reverse, with the stack height added to each element (to ensure that all are positive) <>{({}[<>[]])<>}<> Push the rest of the stack back, unreversing, and subtracting the stack height from each element {} Pop the top of stack ``` [Answer] # [Python 2](https://docs.python.org/2/), 55 bytes ``` def f(a): while a[1:]:l=a[0]%len(a);a[:]=a[-~l:]+a[:l] ``` [Try it online!](https://tio.run/##HYk7CoAwDED3nCKLoFjB7xLxJCVDwBaFUEVEcfHqtbi9z/6cyxbaGGfn0edSEOC9rOpQbENMOomtOVMX0hvFEqdQvUpcJlGOlxw4oW1Mb1rTmYEBfJ5iAbAfazh/jh8 "Python 2 – Try It Online") Outputs as a singleton list, as [allowed by default](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/11884#11884). Saved a few bytes thanks to [Dennis](https://codegolf.stackexchange.com/users/12012), by reminding me that modifying the function argument is allowed. ### How it works * `def f(a)` - Defines a function with a parameter `a`. * `while a[1:]:` - While `a` with the first element removed is truthy, run the block of code to follow. A list with one element or more is truthy, and empty lists are falsy in Python, hence this will stop once `a` reaches a length of 1. * `l=a[0]%len(a)` - Take the first element, and get the remainder of its division by the length of `a`. Assign the result to `l`. * `a[:]=a[-~l:]+a[:l]` - Rotate `a` to the left by `l` elements, and remove the first one, while assigning this to `a` in place. --- **[Python 2](https://docs.python.org/2/), 63 bytes** ``` f=lambda a,i=0:a[1:]and f(a,a.pop(((a*-~i)[i]+i)%len(a))+1)or a ``` [Try it online!](https://tio.run/##bcyxCsIwEIDh3afIItzZU7w0dij0SUKGkxo8qEkoXVx89ShFhILrx89fnss9J1trHCZ5XEcxQjqce/HcB0mjiSAkp5ILAMjh@FL0GhrF/XRLIIgNY56N1DJrWiCCZ3JkqaVLQNz91H3EElNH7cZ5bd3Guj/27dZrfQM "Python 2 – Try It Online") Although longer, this seems much more elegant. Also thanks to ovs for helping in chat. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~20~~ 18 bytes ``` {1<≢⍵:∇1↓⊖∘⍵⊃⍵⋄⊃⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqQ5tHnYse9W61etTRbviobfKjrmmPOmYABR51NYPI7hYIoxaoXsGQC4gVjCCkgjGUhvMVTIAsMzgLKqZgCmQbgPUaAKERiAQA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 60 bytes ``` def f(a):b=a[0]%len(a);return f(a[-~b:]+a[:b])if a[1:]else a ``` [Try it online!](https://tio.run/##ZY5BT4QwEIXP8CtmSUjaWA3IrgcMHj172FvTwyDTbCMB0hZxL/51bDGua7xM5r1v8uZNZ38ah2pdO9KgGfK6bVAWKu9pCOrRkp/tEIm8/WxrdYOybhU3GlCWtaLeEeC6nExPcLQz1Wni7TnMxAgYoQEzTLNn/M5NvfEsg@YJMv6LNaN37JnhXIRTz8aNaTDQNCBHFZOSyUaUHcl5eEHnqNttGfH7v4NnDF26HbBx9uE1LOggd9CGFQe3kAUTDZ5BDiy24CGKPl5p8jGrtYRvqyxVbFqmshT3V6uoNlF9i79E7H/kw5XcX6g4bMYhlYW4xBeiCDTMzSi@AA "Python 3 – Try It Online") -3 bytes thanks to ovs [Answer] # [J](http://jsoftware.com/), 21 17 bytes -4 bytes thanks to FrownyFrog ``` ((1<#)}.{.|.])^:_ ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYGXwX0PD0EZZs1avWq9GL1Yzzir@vyaXkp6CepqtnrqCjkKtlUJaMVdqcka@QpqCIZyhYITEVDBG5qDKKJjAuGaoXKisgilMwABhvAEQGoHI/wA "J – Try It Online") Original: `([:}.{.|.])^:(1<#)^:_` # How it works: `^:_` repeat until the result stops changing `^:(1<#)` if the length of the list is greater than 1 `{.|.]` rotate the list to the left its first item times `[:}.` drop the first element and cap the fork [Try it online!](https://tio.run/##y/qfVmyrp2CgYGXwXyPaqlavWq9GL1YzzkrD0EYZSMX/1@RS0lNQT7PVU1fQUai1Ukgr5kpNzshXSFMwhDMUjJCYCsbIHFQZBRMY1wyVC5VVMIUJGCCMNwBCIxD5HwA "J – Try It Online") [Answer] # JavaScript (ES6), ~~54~~ 60 bytes *Saved 1 byte thanks to @Shaggy* *Fixed version (+6 bytes)* [Modifies the input array](https://codegolf.meta.stackexchange.com/a/4942/58563), which is reduced to a singleton. ``` f=(a,p=0)=>1/a||f(a,p=(p+a[p%(l=a.length)])%l,a.splice(p,1)) ``` ### Test cases ``` f=(a,p=0)=>1/a||f(a,p=(p+a[p%(l=a.length)])%l,a.splice(p,1)) ;[ [1], // [1] [1,2], // [1] [1,2,3], // [3] [1,2,2], // [1] [1,2,3,4], // [1] [6,2,3,4], // [4] [1,2,3,4,5], // [5] [0,1], // [1] [0,0,2,0,0], // [0] [3,5,7,9] // [5] ].forEach(a => f(a) && console.log(JSON.stringify(a))) ``` ### How? We recursively apply the algorithm described in the challenge. Only the stop condition `1/a` may seem a bit weird. When applying an arithmetic operator: * Arrays of more than one element are coerced to `NaN` and `1/NaN` is also `NaN` (falsy). * Arrays of exactly one integer are coerced to that integer, leading to either `1/0 = +Infinity` or `1/N = positive float` for **N > 0** (both truthy). ``` f = (a, p = 0) => // a = input array, p = pointer into this array 1 / a || // if a is not yet a singleton: f( // do a recursive call with: a, // a p = ( // the updated pointer p + a[p % (l = a.length)] // ) % l, // a.splice(p, 1) // the element at the new position removed ) // end of recursive call ``` [Answer] # [Julia 0.6](http://julialang.org/), 46 42 bytes ``` !x=length(x)>1?!circshift(x,-x[])[2:end]:x ``` [Try it online!](https://tio.run/##PY1BCoMwFET3nuJHXCTwBWNbF4L2ICGLYLX@EmJJI@T2aWjFzZs3s5nXbsl0KbE42Nk9w8qjGOWdTeSnz0pL4BHrqLRQbT@7h@5jWjYPBsiBUlKjktj@iZcjz47XbN1px4a37A3KH5u8ZWpdALw9uWAdLysDwwgVZ0aUosi36Qs "Julia 0.6 – Try It Online") Straightforward recursive Julia version. `x[]` accesses the first element of x. [Answer] # Java 8, 79 bytes This lambda accepts a `Stack<Integer>` and returns an `int` or `Integer`. ``` l->{for(int i=0,s=l.size();s>1;)l.remove(i=(i+l.get(i%s))%s--);return l.pop();} ``` [Try It Online](https://tio.run/##dVBNawIxED3rr5iLkNDdUNvSy7qCUAot7clj6SHdjdvRmITMrMXK/vZtXCyC4CHkMXlfk7Xe6dwH49b1pg/tl8UKKquJ4F2jg8N4dBoSa07XCp22sE4q1TJatWpdxeidej6B2fltybrazF4cm8bEeQb/COq22jyl8@rJhO@WoOxtPj@sfBToGLC8zai0ivDXCFnQfFpIq6LZ@p0RWAq8saoxLHBCUk4oz2URDbfRgVXBhyTp@lExvqy@81jDNm0llhzRNR@foGND8rjk6FprQBdahhKc@YFrpJSYLAam0nW9sFacqYsY9Z6UpjckFkebkyzlHx4yuM/gLoNpBo8Jd3KwWu6JzVb55BdSVbZOXP6Z0iHYvRhCB1E37vo/) ## Ungolfed ``` l -> { for ( int i = 0, s = l.size() ; s > 1 ; ) l.remove( i = (i + l.get(i % s)) % s-- ); return l.pop(); } ``` ## Acknowledgments * -2 bytes thanks to Nahuel Fouilleul [Answer] # [Pyth](https://github.com/isaacg1/pyth), 9 bytes ``` .WtHt.<Zh ``` **[Try it here!](https://pyth.herokuapp.com/?code=.WtHt.%3CZh&input=%5B1%2C+2%2C+3%2C+4%2C+5%5D&test_suite=1&test_suite_input=%5B1%5D%0A%5B1%2C2%5D%0A%5B1%2C2%2C3%5D%0A%5B1%2C2%2C2%5D%0A%5B1%2C2%2C3%2C4%5D%0A%5B6%2C2%2C3%2C4%5D%0A%5B1%2C2%2C3%2C4%2C5%5D%0A%5B0%2C1%5D%0A%5B0%2C0%2C2%2C0%2C0%5D&debug=0)** This outputs the result as a singleton list, as [allowed by default](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/11884#11884). ### How it works ``` .WtHt.<Zh ~ Full program. .W ~ Functional while. It takes three arguments, two functions: A and B and a starting value, which in this case is automatically assigned to the input. While A(value) is truthy, value is set to B(value). Returns the ending value. A's argument is H and B's is Z. tH ~ A (argument H): Remove the first element of H. A singleton list turns into [], which is falsy and thus breaks the loop. Otherwise, it is truthy and the loops goes on until the list reaches length 1. .<Zh ~ B (argument Z): Cyclically rotate Z by Z[0] places, whereas Z[0] represents the first element of Z. t ~ And remove the first element. ``` **Note:** If you don't want to see those brackets, just add `h` or `e` in front of the whole code. [Answer] # [Swift](https://swift.org), 87 bytes ``` func f(a:inout[Int]){var i=0,c=0;while(c=a.count,c>1).1{i=(i+a[i%c])%c;a.remove(at:i)}} ``` Returns as a [singleton list](https://codegolf.meta.stackexchange.com/a/11884/70894) by [modifying the input](https://codegolf.meta.stackexchange.com/a/4942/70894). [Try it online!](https://tio.run/##Fc1BCoMwEADAe16RiyVLFzFVelDSe98QPCyL0oU2KWnUg/j2FD8w89tkzl0p8xJYz4Z6CXHJ/hnyCPtKSYtrkF0zbC95T4Yd1RyXkJEfFmq7izNyJS8Vj1DxQHWaPnGdDOVe4DjKSZB22nfY4g0t3rEdlTqnC4FS3yQhG4LyBw "Swift 4 – Try It Online") ## Explanation ``` func f(a:inout[Int]){ var i=0,c=0; // Set the index i to 0 while(c=a.count,c>1).1{ // While the length of the list > 0: i=(i+a[i%c])%c; // Add a[i] to i and loop back using modulo a.remove(at:i) // Remove a[i] } } ``` [Answer] # Mathematica, 36 bytes uses Martin's algorithm ``` #//.l:{x_,__}:>Rest@RotateLeft[l,x]& ``` -5 bytes from Misha Lavrov && Martin Ender [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1lfX8/KLii1uMQhKL8ksSTVJzWtJLq6QqeyVqcyOtowNjZW7X9AUWZeiUNadLVhbSwXgqNjhMbVMUYXwFShY4IsZIYpBFWlY4osaKBjiMo1AKoCkrWx/wE "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 104 bytes *H.PWiz has a shorter answer [here](https://codegolf.stackexchange.com/a/150471/56656) that I helped to make, you should check it out.* ``` ([[]]()){({}()<(({})){({}[()]<({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}{}>)}{} ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6OjZWQ1OzWqO6VkPTRgNIQTjRGpqxNkAaKBQdq2lTDZQGcuw0bexA/FoQG8QBYRTlEEGoPJCqrgVT//8bKhgpGCuYKJgqmAEA "Brain-Flak – Try It Online") ## Explanation ``` ([[]]()) #Push 1 minus stackheight {({}()< #N times (({})) #Get a copy of the top {({}[()]< #N times ({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<> #Roll the top to the bottom (From the wiki) >)}{} #End loop {} #Remove one value >)}{} #End loop ``` [Answer] # [Perl 6](http://perl6.org/), ~~46~~ 45 bytes (-1 byte thanks to Brad Gilbert) ``` {($_,{(|$_ xx*)[.[0]+(1..^$_)]}...1)[*-1][0]} ``` [Try it online!](https://tio.run/##RYrLCsIwFER/ZShBkloviY9uavMjIQYXZqUoddMS8@3xFivdzJw5zOs23NvymLCJ6EuSIjRJfkTAONbKkdN@Kw3RRQTlMxEZ5eqd8exz6fC@Tqj43FukCBFyhfgccDa24cB@KRz@sBocZ2xXXCxO89Awv9JsOW1Xvg "Perl 6 – Try It Online") `($_, { ... } ... 1)` generates a sequence of lists, starting with the input list `$_`, each successive element being generated by the brace expression, and terminating when the list smart-matches `1`--ie, has a length of 1. The trailing `[* - 1]` obtains the final element, and the final `[0]` takes the sole element out of that singleton list. `(|$_ xx *)` generates a flat, infinitely replicated copy of the current element. This list is indexed with the range `.[0] + (1 ..^ $_)` to extract the next finite list in the series. [Answer] # [Perl 5](https://www.perl.org/), ~~47~~ ~~43~~ 41 + 2 (`-ap`) = 43 bytes ``` $\=splice@F,($_+=$F[$_%@F])%@F,1while@F}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lxra4ICczOdXBTUdDJV7bVsUtWiVe1cEtVhNI6BiWZ2TmAOVqq///N1QwUjBWMFEw/ZdfUJKZn1f8X9fXVM/A0OC/bmIBAA "Perl 5 – Try It Online") Takes input as space separated numbers. [Answer] # [Haskell](https://www.haskell.org/), 56 bytes ``` f[x]=x f l|m<-head l`mod`length l=f$drop(m+1)l++take m l ``` [Try it online!](https://tio.run/##ZYo7DoMwEAV7TvGKFCA7EeRDFR8hJ0CWsIQdEGtjERcUubtDKMiHrWZmX6sevSaK0VSTFFNiQE973bdaNaDaDk1N2t1DCxJm14yDTy0rMmIsqF7DgqJVnYOAVf6G1I@dCzjAZEgwX4WqkAvxmTiOP8Jx@vPNn@O8pnKbPiuOy1pzjuJb8mX1BgkZXw "Haskell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~57~~ 56 bytes ``` f=lambda a,*b:f(*([a,*b]*-~a)[a+1:a-~len(b)])if b else a ``` [Try it online!](https://tio.run/##XY/BDoIwDIbvPkVvbFiSIeCBZL7IssMWt0iCQNg8eOHV54ZR0B6a/l//pu309LdxqEKwvFd3fVWgMNetJTkRqZJ5sSgq1LFsVbH0ZiCaStpZ0GB6Z0AFb5x3wEEIUUqEmCTGEk8/Aqskq6/872K9gfMG6r0Dm4SaFTHcLWPIoiPmhJiU8mDHGdJhCLNxj95DN6zatQeIMc3d4El8MjHK@dsk0vw6lfFLhp82DS8 "Python 3 – Try It Online") [Answer] # [Java 8](http://www.oracle.com/technetwork/java/javase/overview/java8-2100321.html), 325 Bytes Golfed: ``` static void n(Integer[]j){Integer[]h;int a=0;h=j;for(int i=0;i<j.length-1;i++){if(h.length==a){a=0;}a=(a+h[a])%h.length;h[a]=null;h=m(h);}System.out.print(h[0]);}static Integer[] m(Integer[]array){Integer[]x=new Integer[array.length-1];int z=0;for(int i=0;i<array.length;i++){if(array[i]!=null){x[z]=array[i];z++;}}return x;} ``` Ungolfed: ``` interface ArrayLeapFrog { static void main(String[] z) throws Exception { Integer[] j = {6, 2, 3, 4}; n(j); } static void n(Integer[] j) { Integer[] h; int a = 0; h = j; for (int i = 0; i < j.length - 1; i++) { if (h.length == a) { a = 0; } a = (a + h[a]) % h.length; h[a] = null; h = m(h); } System.out.print(h[0]); } static Integer[] m(Integer[] array) { Integer[] x = new Integer[array.length - 1]; int z = 0; for (int i = 0; i < array.length; i++) { if (array[i] != null) { x[z] = array[i]; z++; } } return x; } } ``` [Answer] # APL+WIN, 36 bytes ``` ¯1↑⍎¨(1⌈¯1+⍴v←,⎕)⍴⊂'v←(1<⍴v)↓v[1]⌽v' ``` Explanation: Prompts for screen input. ``` 'v←(1<⍴v)↓v[1]⌽v' Loop logic as a string (1<⍴v)↓ only drop the first when number of elements n>1 (1⌈¯1+⍴v←,⎕)⍴⊂ create a nested vector of logic of length 1 max n-1 ⍎¨ execute each element of the nested vector in turn ¯1↑ take answer from executing final element ``` [Answer] # Python 2, 61 bytes ``` def f(x): while x[1:]:y=x[0]%len(x);x=x[y+1:]+x[:y] print x ``` [Answer] # JavaScript, ~~58~~ ~~56~~ 59 bytes ``` let f = a=>{for(i=0,k=a.length;k>1;)i+=a[i%=k],a.splice(i%=k--,1)} ``` ``` <h2>Test</h2> Enter or paste a valid array literal within square brackets and click Run. <blockquote> <input id = "array" type="text" length="20"> <button type="button" onclick="run()">Run</button> </blockquote> Result: <pre id="o"></pre> <script> function run() { let a = JSON.parse(array.value); f(a); o.textContent = a; } </script> ``` Returns the result as the only element remaining in the input array which is updated in place. Two bytes saved by using a comma separated statement instead of a block statement in the for loop body! Three bytes lost to skip from an element deleted at end of array (: **Less golfed:** ``` a => { for(i=0,k=a.length;k>1;) // once less than array length i+=a[i%=k], // the new index a.splice( // delete an element i%=k--, // ensuring index is within array, // and post decrement loop count 1 ) } ``` [Answer] # [Clean](https://clean.cs.ru.nl), 78 bytes Uses the same method as [Laikoni's Haskell answer](https://codegolf.stackexchange.com/a/150460/18730). ``` import StdEnv f[e]=e f[x:r]=f(take(length r)(drop(x+1)(flatten(repeat[x:r])))) ``` [Try it online!](https://tio.run/##HYyxDsIgEEB3v4LxiDrU0YRNBxO3jg3DBY5KBEroaerPexLf8paX5xJhkbz4VyKVMRaJuS6N1cj@Wt67MJE11LWdmzUBGJ8EicrMD9U0@LZU2PaDhpCQmQo0qoT8z3VHRsZ@MyqoaTicrHxdL@dVjre7XD4Fc3TrDw "Clean – Try It Online") [Answer] # [R](https://www.r-project.org/), 111 ~~117~~ ~~126~~ bytes Thanks to @Giuseppe for golfing off 11 bytes by changing to a while loop, got another 4 by removing the function and reading user input directly. I don't feel great about what it took to get there - I'm sure a more elegant solution exists. ``` i=scan();m=1;while((l=sum(i|1))-1){j=i[m];p=`if`(j+m>l,j%%l+!m-1,j+m);p=`if`(!p,m,p);i=i[-p];m=`if`(p-l,p,1)};i ``` [Try it online!](https://tio.run/##NYzLCsJADEX38xddFCY0s4iPVYg/UgoVUcwwkWApLqrfPg6Cy3sO5z5rVVku50cENiF@3bVcYyyyrBb1TQCJYMuio03sMuttjnmwU8Hc92XoLBG2DX/XORo6sLYi@dQ@f9hTQUeCD2ulcAi7sA/H@gU "R – Try It Online") Ungolfed code ``` i=scan() m=1 while((l=sum(i|1))-1){ j=i[m] p=`if`(j+m>l,j%%l+!m-1,j+m) p=`if`(!p,m,p) i=i[-p] m=`if`(p-l,p,1) } i ``` ]
[Question] [ # Challenge Given a tic-tac-toe board in any format, determine if it is valid or not. If a board can be the result of a tic-tac-toe game, then it is valid. For example, this board is valid: ``` X O X O X O X O X ``` On the contrary, this board is invalid: ``` X X X X X O O O O ``` # Input * A full (9/9) tic tac toe board (the outcome, not the game). # Rules * The input format must be able to depict all 512 possible input boards. It must be specified, along with the instructions to create it if it is obscure/unclear. **You must state the marks of the board individually though.** * There must be two possible outputs, one for validity and one for invalidity. * You can assume the board does not have empty spots. # Test cases Valid: ``` X O X O X O X O X X O X X O X O X O X O O O O X O X X O X O X O X O X O ``` Invalid: ``` X X X X X X X X X O O O O O O O O O X X X O O O X X X O O O O O X X X X X X O O X O O O X ``` # A little help? A board is considered valid (for this challenge) if and only if the following two conditions hold: * There are 5 X and 4 O, or 4 X and 5 O. For example, ``` X X X O X O X X X ``` is considered invalid, because there are 7 Xs and 2 Os. * Only the player with 5 marks has won, or none of them have won. For example, ``` X X X O O O O O X ``` is considered invalid, since either the row of `O`s or the row of `X`s will be formed first. The two players can't have their turn simultaneously. # The current winner is... ...[ais523's Jelly answer](/a/103053/41024), at an astounding 26 bytes! [Answer] ## JavaScript (ES6), ~~88~~ 87 bytes ``` s=>(a=[...s]).sort()[5]-a[3]&[7,56,73,84,146,273,292,448].every(j=>j&i,i=`0b`+s^~-a[4]) ``` Takes input as a string of 9 `0` and `1` characters and returns `1` for valid, `0` for invalid. We sort the characters into order. If the middle three characters are now the same then the board is invalid as there are too many of one piece. Otherwise, we convert the original board into binary, flipping the bits if there are more `0`s than `1`s. At this point the board is valid if `0` does not have a line of three, so we simply test all eight lines via an array of bitmasks. Edit: Saved 1 byte thanks to @ETHproductions. [Answer] # Python 3, ~~131~~ ~~127~~ ~~125~~ ~~100~~ 96 bytes For a different algorithmic approach (and one that will be really suited to these multi-byte golfing languages with built-in compression), instead of calculating if the board is valid, let's have a 512-bit number where each bit represents whether or not a particular board is valid or not, and pass in a binary value representing the board. Furthermore, due to symmetry, the second half of the table can be eliminated, along with a bunch of zeros: ``` def z(b):return int('agqozfx67wwye6rxr508ch2i8qicekpreqkap0725pk',36)<<24&1<<b+(b>255)*(511-b-b) ``` The test value: ``` X X X O X O X X X ``` Is represented as the binary value `0b111010111`, and the function returns a non-zero value if the board is valid. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes ``` ṢŒrṪ4=$$Ðfx3ðœ-µẆm€6R¤;/µL ``` [Try it online!](https://tio.run/nexus/jelly#@/9w56Kjk4oe7lxlYquicnhCWoXx4Q1HJ@se2vpwV1vuo6Y1ZkGHlljrH9rq8////4gI/6I8fzDhHwEA "Jelly – TIO Nexus") The input format is a little unusual; it's a string representing the board, but with Windows newlines (carriage return followed by newline). For example, `XXO\r\nOXO\r\nOOX`. (Actually, any two-character padding string between the lines works, but Windows newlines are much more defensible than the other options.) The basic idea is that we look for characters that appear 4 times in the input, but don't have three evenly spaced occurrences in the original string. With two or more characters of padding between the lines of a 3×3 grid, all horizontal, vertical, and diagonal lines are evenly spaced, but no other evenly spaced line can have three elements. Explanation: The `ð` and `µ`s are *chain separators*, which split the program into multiple parts that are each independent. I've replaced them with spaces below, to make things a bit clearer. ``` ṢŒrṪ4=$$Ðfx3 œ- Ẇm€6R¤;/ L Ṣ sorted version of the input Œr run-length-encode it Ðf keep only elements where Ṫ delete the last element, and it was 4= equal to 4 $$ parse Ṫ4= as a group x3 repeat each element three times Ẇ all sublists of the input m€ take every nth element of each (€) sublist 6R for each n in 1..6 ¤ parse 6R as a group ;/ flatten one level (m€ creates a nested structure) œ- multiset difference L length of that difference ``` In other words, we find the list of characters that appear exactly four times in the input, and make a list consisting of three copies of each of those; we find the list of all subsequences that are evenly spaced in the original string; and if we subtract the second from the first, we want the result to have length 1 (i.e. a player played four times but didn't win). Note that as we're on a 3×3 grid and every square is full, it's impossible for *both* players to have played four times. In Jelly, 1 is truthy, 0 is falsey, so we don't need to do anything special to convert the resulting list to a boolean. (The `µL` is required, though, because otherwise both `“XXX”` and `“OOO”` would be possible truthy output values, and the question requires that all valid boards give the same output.) [Answer] ## Batch, 140 bytes ``` @set/aXXX=OOO=O=0 @for %%l in (%* %1%2%3 %1%4%7 %1%5%9 %2%5%8 %3%5%7 %3%6%9 %4%5%6 %7%8%9)do @set/a%%l+=1 @cmd/cset/a!XXX*!(O-=5)+!OOO*!~O ``` Takes input as nine separate command-line arguments and outputs `1` for valid and `0` for invalid. Works by tracking the number of times it sees an `O` and a orthogonal line of `OOO` or `XXX`. Conveniently Batch allows us to perform integer arithmetic indirectly, so we're not incrementing `%%l` but some variable instead (although we're only interested in the three variables mentioned). We then need to test that either `X` has not won and there are five `O`s or that `O` has not won and there are four `O`s. [Answer] # Mathematica, ~~82~~ 75 bytes *Thanks to Martin Ender for saving 7 bytes!* ``` t=Total;3<(b=#~t~2)<6&&{t[c=If[b>4,1-#,#]],t/@c,Tr@c,Tr@Reverse@c}~FreeQ~3& ``` Unnamed function taking a 3x3 nested list of 1s and 0s as input and outputting `True` or `False`. Uses some handy flexibility of the `Total` function (here golfed to `t`): given an example array `e = { {1,2,3} , {4,5,6} , {7,8,9} }`, the command `t[e]` sums the three vectors (here yielding `{12,15,18}`); the command `t/@e` sums each sublist individually (here yielding `{6,15,24}`); and the command `e~t~2` sums all nine elements (here yielding `45`). So first we test, with `3<(b=#~t~2)<6`, whether the total number of 1s is 4 or 5; if not we exit with `False`. If so, we use `c=If[b>4,1-#,#]` to force there to be four 1s, not five. Then we compute the column sums `t[c]`, the row sums `t/@c`, the sum of the main diagonal `Tr@c`, and the sum of the opposite diagonal `Tr@Reverse~c`, and use `~FreeQ~3` to check that `3` fails to appear at any level in those computed sums. Amusing side note: unlike most appearances on this site, here `Tr` is not used to sum a one-dimensional list but is actually used as designed—to calculate the trace of a two-dimensional matrix! [Answer] # Pyth - 36 bytes I include diagas and use two ternaries instead. ``` JsM+sCBQm@VdU3_BQ?q5KssQ*FJ?qK4!}3JZ ``` [Test Suite](http://pyth.herokuapp.com/?code=JsM%2BsCBQm%40VdU3_BQ%3Fq5KssQ%2aFJ%3FqK4%21%7D3JZ&test_suite=1&test_suite_input=%5B1%2C0%2C+1%5D%2C+%5B0%2C1%2C0%5D%2C+%5B1%2C0%2C1%5D%0A%5B0%2C0%2C0%5D%2C+%5B0%2C0%2C1%5D%2C+%5B1%2C1%2C1%5D%0A%5B1%2C0%2C1%5D%2C+%5B0%2C1%2C0%5D%2C+%5B0%2C0%2C1%5D&debug=0) [Answer] ## JavaScript (ES6), 101 bytes Takes input as a 9-bit binary mask where `X = 1` and `O = 0` (MSB = top left cell, LSB = bottom right cell). ``` n=>[7,56,73,84,146,273,292,448,o=x=0].map((m,i)=>(c-=n>>i&1,m&n^m?m&n||o++:m&&x++),c=4)&&!(c|x&&~c|o) ``` ### Test cases ``` let f = n=>[7,56,73,84,146,273,292,448,o=x=0].map((m,i)=>(c-=n>>i&1,m&n^m?m&n||o++:m&&x++),c=4)&&!(c|x&&~c|o) // valid console.log(f(0b101010101)); console.log(f(0b101101010)); console.log(f(0b100001011)); console.log(f(0b010101010)); // invalid console.log(f(0b111111111)); console.log(f(0b000000000)); console.log(f(0b111000111)); console.log(f(0b000001111)); console.log(f(0b110010001)); ``` [Answer] ## Python 2, ~~158~~ ~~132~~ ~~109~~ ~~92~~ ~~91~~ 123 bytes ``` def v(b):f=sum(b,());w={x[0]for x in b+zip(*b)+[f[::4],f[-3:1:-2]]if len(set(x))==1};return sum(map(`b`.count,w))==len(w)*5 ``` Input is a list/tuple of rows, each a three-tuple of strings, e.g.: `[('X', 'O', 'X'), ('O', 'X', 'O'), ('X', 'O', 'X')]` ~~Saved some bytes by ignoring diagonals per @Maltysen's answer, which also shortened the following expression.~~ ~~Thanks @vaultah for saving ~~17~~ 18 bytes.~~ Checking diagonals turns out to be necessary, which removed a lot of the savings above. [Try it here.](https://repl.it/Ensu/5 "repl.it") ### Explanation ``` def v(b): f=sum(b,()) w={x[0]for x in b+zip(*b)+[f[::4],f[-3:1:-2]]if len(set(x))==1} return sum(map(`b`.count,w))==len(w)*5 ``` `f` is the flattened input for slicing. `w` contains the characters with winning sequences. Count the occurrences of each winning character, which will either be 0 if `w` is empty or 5 if `len(w)` is 1. The 10 sum when both have a winning sequence is impossible. The winner having 5 implies the loser has 4. You can't have >5 without a winning sequence. [Answer] ## R, ~~88~~ 82 bytes ``` x=scan();`if`(sum(x)%in%4:5,all(apply(combn(which(x==(sum(x)<5)),3),2,sum)!=15),F) ``` All combinations of three integers from 1 to 9 that sum up to 15 are the rows/columns/diagonals of the square shown below. ``` 2 7 6 9 5 1 4 3 8 ``` The function takes input as a vector of booleans, T for "X", F for "O", which is the flattened representation of the board. BUT, these are reordered so that their index is the same as the number in the square, in the the order (2,7,6,9,5,1,4,3,8). That order might be achieved by flattening the board in the normal way, and then slicing by c(6,1,8,7,5,3,2,9,4). So this ``` X O X O X O X O X ``` is represented as: ``` c(T, F, T, F, T, F, T, F, T)[c(6,1,8,7,5,3,2,9,4)] ``` which is: ``` c(F, T, F, T, T, T, F, T, F) ``` The function first determines whether there is a player with exactly four marks. If so, the function uses the fact-of-things-that-add-up-to-15 to determine whether that player has a three-in-a-row (the board is invalid iff that player does). If you wanted to take a conventionally-flattened board as input, the code would look like this instead: ``` f=function(x)ifelse(sum(x)%in%4:5,all(apply(combn(c(2,7,6,9,5,1,4,3,8)[which(x==(sum(x)<5))],3),2,sum)!=15),F) ``` I'm new at this, advice would be appreciated. [Answer] # JavaScript (ES6), ~~145~~ ~~139~~ ~~131~~ 127 bytes ``` s=>!(q="XO"[s.split`O`.length-5])|![...s].some((c,i)=>c==q&!/(.)(\1|..(\1|.(\1|.\1.).)..)\1/.test(s.slice(0,i)+0+s.slice(i+1))) ``` Input as a space-separated string, such as `"XOX OXO XOX"`. Outputs `1` for an invalid board, `0` for a valid one. This obviously isn't the best technique, at least not with JavaScript... This basically checks whether both the following hold: * There are exactly 4 or 5 `O`s, AND * there is at least one of the 5-instance piece which creates an undecided game when removed. The regex is to check whether a game has been decided. It matches a board iff there are any runs of length three of one character with 0 (row), 2 (down-right diagonal), 3 (column), or 4 (down-left diagonal) chars separating each pair. ### Test snippet ``` f=s=>!(q="XO"[s.split`O`.length-5])|![...s].some((c,i)=>c==q&!/(.)(\1|..(\1|.(\1|.\1.).)..)\1/.test(s.slice(0,i)+0+s.slice(i+1))) g=s=>console.log(f(s)) // Valid boards (outputs 0) g("XOX OXO XOX") g("XOX XOX OXO") g("XOO OOX OXX") g("OXO XOX OXO") // Invalid boards (outputs 1) g("XXX XXX XXX") g("OOO OOO OOO") g("XXX OOO XXX") g("OOO OOX XXX") g("XXO OXO OOX") ``` [Answer] # Ruby, ~~104 99~~ 91 bytes ``` ->x{[7,56,448,292,146,73,84,273].none?{|y|b=x.to_i 2;((a=x.count'1')==4?b:a==5?~b:7)&y==y}} ``` Input format: binary string of 9 symbols (0s and 1s) representing the board, for example the first test case is `101010101`. First convert it to a binary number, check if popcount is 4 or 5, if it's 5 invert the number so we always have 4. Check if three of them are aligned (masking witn horizontal, vertical, diagonal). **TL;DR**: Return false if player with 4 marks won, true otherwise. Thanks Jordan for the comments, *I can't reproduce the UTF-8 string which would save another byte.* [Answer] ## [Perl 6](http://perl6.org/), ~~103~~ 99 bytes ``` {my \c=%(.flat.Bag.invert)<5>;?all c,|(.[0]===c if [eq] $_ for |.flat[<0 4 8>,<2 4 6>],|$_,|.&zip)} ``` A lambda that accepts a list of lists like `(('X','O','X'), ('O','X','O'), ('X','O','X'))`, and returns a Bool. It works like this: 1. Check which mark appears exactly 5 times, and store it in `c`. *(If no mark appears exactly 5 times, this will contain a falsy value)* 2. Iterate over all diagonals, rows, and columns, and filter out the "winning" ones *(i.e. those where all three letters are equal)*. 3. Check if `c` is truthy, **and** each winning line is of type `c`. [Answer] # PHP, 125 bytes ``` for($p=$n=$argv[1];$p;$p/=2)$i+=$p&1;foreach([7,56,448,73,146,292,273,84]as$m)$n&$m^$m?$n&$m||$o++:$x++;echo!$x|!$o&&2>$i^=4; ``` I had the same idea as [Arnauld](https://codegolf.stackexchange.com/a/103024#103024): The board is valid if there are either 4 or 5 bits set and either `X` or `O` or nobody has a streak (but not both). To generate input from field replace `X` with `1` and `O` with `0`, join lines and convert binary to decimal, provide as command line argument. prints `1` for valid; empty output for invalid. Run with `-r`. **breakdown** ``` // count set bits for($p=$n=$argv[1];$p;$p/=2)$i+=$p&1; /* ($p/=2 takes longer than $p>>=1, but eventually $p will come close enough to 0 for the loop to finish */ // count streaks for X and O foreach([7,56,448,73,146,292,273,84]as$m) $n&$m^$m // ($n masked with streak)!=streak <=> no streak for X ?$n&$m||$o++ // true: O has a streak if ($n masked with streak) is empty :$x++; // false: X has a streak echo!$x|!$o&&2>$i^=4; // valid if not both have a streak // AND $i is 4 or 5 (toggle 4 -> result 0 or 1) ``` [Answer] # Swift, 178 bytes ``` func t(i:String)->Bool{let r=i.characters.filter({$0=="X"}).count;let g=i.characters.split(separator:"\n").map(String.init).contains;return(r==5||r==4)&&(!g("XXX") && !g("OOO"))} ``` [Answer] # ES6 (Javacript), ~~130~~, ~~138~~, 117 bytes EDITS: * 21 bytes off thanks to excellent advice from @Neil ! * Initial version was prone to a bug, which should now be fixed at cost of +8 bytes. (Thanks @ETHproductions for pointing it out) An extremelly straighforward approach. Can probably be golfed a bit further. Accepts input as 9 separate arguments, 1es and 0es * **1** is for **X** * **0** is for **O** Arguments: 1-3 - first row, 4-6 - second row, 7-9 - third row. **Golfed** ``` (a,b,c,d,e,f,g,h,j)=>![a+b+c,d+e+f,g+h+j,a+d+g,b+e+h,c+f+j,a+e+j,g+e+c,7].some(x=>x=="7777307777"[a+b+c+d+e+f+g+h+j]) ``` **Interactive "Test Bed"** ``` var a=b=c=d=e=f=g=h=j=0; T=(a,b,c,d,e,f,g,h,j)=>![a+b+c,d+e+f,g+h+j,a+d+g,b+e+h,c+f+j,a+e+j,g+e+c,7].some(x=>x=="7777307777"[a+b+c+d+e+f+g+h+j]); function test() { if(T(a,b,c,d,e,f,g,h,j)) { grid.style.backgroundColor='green'; msg.innerHTML="GOOD" } else { grid.style.backgroundColor='red'; msg.innerHTML="BAD" } } ``` ``` <table id=grid style="background: red"> <thead> <tr> <td id=msg align="center" colspan="3">BAD</td> </tr> </thead> <tr> <td><input type="checkbox" onchange="a=this.checked*1;test();" id="ca"/></td> <td><input type="checkbox" onchange="b=this.checked*1;test();" id="cb"/></td> <td><input type="checkbox" onchange="c=this.checked*1;test();" id="cc"/></td> </tr> <tr> <td><input type="checkbox" onchange="d=this.checked*1;test();" id="cd"/></td> <td><input type="checkbox" onchange="e=this.checked*1;test();" id="ce"/></td> <td><input type="checkbox" onchange="f=this.checked*1;test();" id="cf"/></td> </tr> <tr> <td><input type="checkbox" onchange="g=this.checked*1;test();" id="cg"/></td> <td><input type="checkbox" onchange="h=this.checked*1;test();" id="ch"/></td> <td><input type="checkbox" onchange="j=this.checked*1;test();" id="cj"/></td> </tr> </table> ``` ]
[Question] [ Shifty-eyes ASCII guys like to shift ASCII `Ii`'s: ``` >_> <_< >_< <_> ``` Given a string of shifty-guys, spaced apart or separate lines, shift the `Ii`'s side to side, left the wall and right the skies: ``` Ii ``` The shortest shifter wins the prize. # Say What? Write a program or function that takes in a string of an arbitrary list of these four ASCII emoticons, either space or newline separated (with an optional trailing newline): ``` >_> <_< >_< <_> ``` > > For example, the input might be > > > > ``` > >_> >_> <_> > > ``` > > or > > > > ``` > >_> > >_> > <_> > > ``` > > (The method you support is up to you.) > > > Each emoticon performs a different action on the `I` and `i` characters, which always start like this: ``` Ii ``` * `>_>` shifts `I` to the right by one, if possible, and then shifts `i` to the right by one. * `<_<` shifts `I` to the left by one, if possible, and then shifts `i` to the left by one, if possible. * `>_<` shifts `I` to the right by one, if possible, and then shifts `i` to the left by one, if possible. * `<_>` shifts `I` to the left by one, if possible, and then shifts `i` to the right by one. `I` cannot be shifted left if it is at the left edge of the line (as it is initially), and cannot be shifted right if `i` is directly to its right (as it is initially). `i` cannot be shifted left if `I` is directly to its left (as it is initially), but can always be shifted right. Note that with these rules, `I` will always remain to the left of `i`, and `I` is attempted to be shifted before `i` for all emoticons. Your program or function needs to print or return a string of the final `Ii` line after applying all the shifts in the order given, using spaces () or periods (`.`) for empty space. Trailing spaces or periods and a single trailing newline are optionally allowed in the output. Don't mix spaces and periods. > > For example, the input > > > > ``` > >_> > >_> > <_> > > ``` > > has output > > > > ``` > I...i > > ``` > > because the shifts apply like > > > > ``` > start |Ii > >_> |I.i > >_> |.I.i > <_> |I...i > > ``` > > **The shortest code in bytes wins.** Tiebreaker is higher voted answer. # Test Cases ``` #[id number] [space separated input] [output] ``` Using `.` for clarity. ``` #0 [empty string] Ii #1 >_> I.i #2 <_< Ii #3 >_< Ii #4 <_> I.i #5 >_> >_> .I.i #6 >_> <_< Ii #7 >_> >_< .Ii #8 >_> <_> I..i #9 <_< >_> I.i #10 <_< <_< Ii #11 <_< >_< Ii #12 <_< <_> I.i #13 >_< >_> I.i #14 >_< <_< Ii #15 >_< >_< Ii #16 >_< <_> I.i #17 <_> >_> .I.i #18 <_> <_< Ii #19 <_> >_< .Ii #20 <_> <_> I..i #21 >_> >_> <_> I...i #22 <_> >_> >_> >_> <_> <_< .I...i #23 <_> >_> >_> >_> <_> <_< >_< <_< >_< ..Ii #24 >_> >_< >_> >_> >_> >_> >_> >_> <_> <_> <_< ...I.....i ``` [Answer] # Perl, ~~59~~ ~~56~~ 54 bytes Includes +1 for `-p` Run with the input on STDIN, e.g. `perl -p shifty.pl <<< ">_> <_< >_< <_>"` `shifty.pl`: ``` s%^|<|(>)%y/iI/Ii/or$_=Ii;$1?s/i |i$/ i/:s/ i/i /%reg ``` ## Explanation The control string alternates instructions for `i` and `I` and the rule is the same for both of them if you formulate them as: * `<` Move left if there is a space to the left * `>` Move right if there is a space or end of string to the right So I'm going to swap `i` and `I` in the target string at each step so I only need to apply the rule to one letter ever. This is the `y/iI/Ii/` I will walk the control string looking for `<` and `>` using a substitution which is usually the shortest way in perl to process something character by character. To avoid having to write `$var =~` I want the control string in the perl default variable `$_`. And I also want an easy way to distinguish `<` from `>`. All this can be accomplished using ``` s%<|(>)% code using $1 to distinguish < from > %eg ``` The target string I also want to manipulate using substitutions and for the same reason I want that in `$_` too. `$_` being two things at once seems impossible. However I can have my cake and eat it too because the `$_` inside the body of a substitution does not have to remain the same as the `$_` being substituded. Once perl started substituting a string this string will not change even if you change the variable the string originally came from. So you can do something like: ``` s%<|(>)% change $_ here without disturbing the running substitution %eg ``` I want to replace the original `$_` by the initial `"Ii"` only the very first time the substitution body gets executed (otherwise I keep resetting the target string). This replacement however also has to happen for an empty control string, so even for the empty control string the body needs to be executed at least once. To make sure the substition runs an extra time at the start of the control string (even for empty control strings) I change the substitution to: ``` s%^|<|(>)% change $_ here without disturbing the running substitution %eg ``` I will run the `y/iI/Ii/` as the first thing inside the substitution code. While `$_` is still the control string this won't yet contain any `Ii`, so if the transliteration indicates nothing was changed that is my trigger initialize `$_`: ``` y/iI/Ii/or$_=Ii ``` Now I can implement the actual moving of the letters. Since I start with a swap all moves should be done on `i`, not `I`. If `$1` is set move `i` to the right: ``` s/i |i$/ i/ ``` If `$1` is not set move `i` to the left ``` s/ i/i / ``` Notice that at the start of the control string when I match `^` `$1` will not be set, so it tries to move `i` to the left on the initial string `Ii`. This won't work because there is no space there, so the intial string remains undisturbed (this is why I put the `()` around `>` instead of `<`) Only one problem remains: at the end of the outer substitution `$_` is set to result of the outer substitution regardless of what you did to `$_` inside the substitution body. So the target string with the proper placement of `i` and `I` gets lost. In older perls this would be a fatal flaw. More recent perls however have the `r` modifier which means "make a copy of the original string, do your substitution on that and return the resulting string (instead of number of matches)". When I use that here the result is that the modified command string gets discarded while the original `$_` is not disturbed by perl and left after the substitution. However the disturbing **I** do on `$_` is still done after perl left `$_` alone. So at the end `$_` will be the proper target string. The `-p` option makes sure the original string is in `$_` and also prints the final `$_`. [Answer] ## [LittleLua](https://www.dropbox.com/s/v5lswhe6puyphxi/LittleLua.zip?dl=0) - 178 Bytes ``` r()l=sw(I)o=1 D='.'f q=1,#l do i l[q]:s(1,1)=='>'t i z+1~=o t z=z+1 e else i z-1>0 t z=z-1 e e i l[q]:s(3)=='>'t o=o+1 else i o-1~=z t o=o-1 e e e p(D:r(z).."I"..D:r(o-z-1)..'i') ``` Straight forward implementation. Ungolfed: ``` r() --call for input l=sw(I) --Split input by spaces o=1 --Hold i position (z holds I position) D='.' --Redundant character f q=1,#l do --Foreach table entry i l[q]:s(1,1)=='>' t --If the first eye points right i z+1~=o t z=z+1 e --Verify no collision and move the I else i z-1>0 t z=z-1 e --If it points left.. .same... e --yatta yatta... i l[q]:s(3)=='>' t o=o+1 else i o-1~=z t o=o-1 e e e p(D:r(z).."I"..D:r(o-z-1)..'i')--String repeats to print correct characters. ``` **What is LittleLua?** LittleLua is a work in progress to try to level the playing fields between my language of choice for these challenges and esoteric languages that often have extremely powerful built-ins. LittleLua is a Lua 5.3.6 interpreter with an additional module (LittleLua.Lua), as well as function and module names shrunk. These changes will expand over the next day or two, until I'm happy, but as it stands several of the largest changes between LittleLua and a the standard Lua interpreter are: **Functions and modules are shrunk:** ``` io.read() -> r() (Value stored in built in variable "I") string -> s string.sub -> s.s or stringvalue:s etc. ``` **Built in variables** LittleLua has several built in variables to shrink some tasks: ``` z=0 o=10 h1="Hello, World!" h2="Hello, World" h3="hello, world" h4=hello, world!" etc. ``` **Built in Functions** Currently a depressingly small list, but here it is: ``` d(N) -> Prints NxN identity matrix sw(str) -> Splits string at spaces and returns table of results sc(str) -> Splits string at commas and returns table of results sd(str) -> Removes white space from a string (not including tabs) ss(str,n) -> Swap N characters from beginning and end of string sr(str,n) -> Swap N characters from beginning and end of string retaining order sd(str) -> Split string into array of characters co(ta) -> Concatenate table with no delimiter co(ta, delim) -> Concatenate table with delimiter: delim ``` [Answer] # [Retina](https://github.com/mbuettner/retina), ~~101~~ 86 ``` $ ¶Ii (`^¶ s`^>(.*)I( )? $1$2I s`^<(.*?)( )?I $1I$2 s`^_>(.*)i $1 i s`^_<(.*?) ?i $1i ``` [Try it online](http://retina.tryitonline.net/#code=JArCtklpCihgXsK2CgpzYF4-KC4qKUkoICk_CiQxJDJJCnNgXjwoLio_KSggKT9JCiQxSSQyCnNgXl8-KC4qKWkKJDEgaQpzYF5fPCguKj8pID9pCiQxaQ&input=Pl8-Cj5fPAo-Xz4KPl8-Cj5fPgo-Xz4KPl8-Cj5fPgo8Xz4KPF8-CjxfPA) Saved 15 bytes thanks to daavko! Takes input separated by newlines and outputs with the eyes separated by spaces. ### Explanation: I will explain stage by stage as usual. All of these stages are in Retina's Replace mode. That means the first line is a regular expression and the second line is a replacement string. ``` $ ¶Ii ``` Add the initial `Ii` to the end of the input. ``` (`^¶ ``` The backtick separates the stage from the options. The option character `(` indicates that this stage is the start of a loop of stages to be executed repeatedly in order until a full cycle is completed without changing the input. Since this open parenthesis is never closed, all of the remaining stages are a part of this loop. The actual stage is very simple, if the first character of the string is a newline then delete it. This is just to help make handling the empty input easier, otherwise it'd be golfier to add it on to the two last stages. ``` s`^>(.*)I( )? $1$2I ``` Here, the option `s` causes the Regex metacharacter `.` to match newlines. This stage causes a leading `>` to match the `I` followed by an optional space. Then it replaces that match with the stuff after the `>`, followed by the optional space (so the empty string if the space couldn't be matched), and then the `I`. ``` s`^<(.*?)( )?I $1I$2 ``` This stage is very similar to the previous one, only the optional space is before the `I`, and the order and eye are reversed. ``` s`^_>(.*)i $1 i ``` The handling of `i` is actually often simpler, because we don't have to worry about optionally adding or removing as `i` can always move right. For the `i` cases we match away the underscore as well as the greater/less than sign, but otherwise do similar logic. This one adds a space before the `i`. ``` s`^_<(.*?) ?i $1i ``` Again similar to the above, but it deletes the character before the `i` if that character is a space, otherwise it only removes the emoticon. [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~56~~ ~~55~~ ~~50~~ ~~49~~ 47 bytes ``` 1Hj3\q4ZC"w@1)+lhX>yqhX<w@3)+yQhX>]tZ"105b(73b( ``` [**Try it online!**](http://matl.tryitonline.net/#code=MUhqM1xxNFpDIndAMSkrbGhYPnlxaFg8d0AzKSt5UWhYPl10WiIxMDViKDczYig&input=Pl8-ID5fPCA-Xz4gPl8-ID5fPiA-Xz4gPl8-ID5fPiA8Xz4gPF8-IDxfPA) ``` 1 % push 1: initial position of 'I' H % push 2: initial position of 'i' j % take input as a string 4\q % modulo 3 and subtract 1: this gives -1 for '<', 1 for '>' 4Zc % arrange blocks of length 4 as columns of 2D array. This pads last % block with a zero (because the separating space won't be there). % Only first and third and last rows will be used " % for each column w % swap: move position of 'I' to top of stack @1) % first number (+/-1) of current column: tells where the 'I' moves + % add lhX> % max with 1: 'I' cannot move left past position 1 y % duplicate position of 'i' qhX< % max with that number minus 1: 'I' cannot collide with 'i' w % swap: move position of 'i' to top of stack @3) % last number (+/-1) of current column: tells where the 'i' moves + % add y % duplicate position of 'I' QhX> % max with that number plus 1: 'i' cannot collide with 'I' ] % end for each t % duplicate position of 'I'. This is the output string length Z" % string with that many spaces 105b( % set 'i' at its computed position in that string 73b( % set 'I' at its computed position in that string ``` [Answer] ## Python, ~~142~~ ~~141~~ ~~134~~ ~~122~~ 121 bytes Saved 19 bytes thanks to xnor. ``` def f(l,I=0,i=1): for a,_,b in l.split():I-=[I>0,-(i!=I+1)][a>'='];i-=[i!=I+1,-1][b>'='] return'.'*I+'I'+'.'*(i+~I)+'i' ``` Example: ``` >>> assert f('<_> >_> >_> >_> <_> <_<') == '.I...i' >>> ``` Explanation: ``` def f(l, I=0, i=1): for a, _, b in l.split(): I-= -(i!=I+1) if a == '>' else I > 0 i-= -1 if b == '>' else i!=I+1 return '.'*I + 'I' + '.'*(i-I-1) + 'i' ``` [Answer] # GNU sed, 81 bytes (including +1 for `-r` flag) ``` #!/bin/sed -rf s!<!s/ I/I /;!g s!>!s/I / I/;!g s!_(.{9})!\L\1!g s!i !i!g s/.*/echo Ii|sed '&'/e ``` This creates a new sed program from the input (which you can see by removing the last line), and applies it to the start state `Ii`. ## Explanation * The first two lines convert `<` and `>` to 'substitute' commands that shift `I` left and right respectively. * Then we change the one following `_` to work on `i` rather than `I` * `i` is not bounded by any right-hand edge, so don't add or consume space following it * Finally, apply the created command to the input `Ii`. `s///e` always uses `/bin/sh` as its shell, so I couldn't shorten this to `sed '&'<<<Ii` as I wanted (that's a Bash redirection syntax). ## Test results ``` $ for i in '' '>_>' '<_<' '>_<' '<_>' '>_> >_>' '>_> <_<' '>_> >_<' '>_> <_>' '<_< >_>' '<_< <_<' '<_< >_<' '<_< <_>' '>_< >_>' '>_< <_<' '>_< >_<' '>_< <_>' '<_> >_>' '<_> <_<' '<_> >_<' '<_> <_>' '>_> >_> <_>' '<_> >_> >_> >_> <_> <_<' '<_> >_> >_> >_> <_> <_< >_< <_< >_<' '>_> >_< >_> >_> >_> >_> >_> >_> <_> <_> <_<' > do printf '%s => ' "$i"; ./74719.sed <<<"$i" | tr \ .; done | cat -n 1 => Ii 2 >_> => I.i 3 <_< => Ii 4 >_< => Ii 5 <_> => I.i 6 >_> >_> => .I.i 7 >_> <_< => Ii 8 >_> >_< => .Ii 9 >_> <_> => I..i 10 <_< >_> => I.i 11 <_< <_< => Ii 12 <_< >_< => Ii 13 <_< <_> => I.i 14 >_< >_> => I.i 15 >_< <_< => Ii 16 >_< >_< => Ii 17 >_< <_> => I.i 18 <_> >_> => .I.i 19 <_> <_< => Ii 20 <_> >_< => .Ii 21 <_> <_> => I..i 22 >_> >_> <_> => I...i 23 <_> >_> >_> >_> <_> <_< => .I...i 24 <_> >_> >_> >_> <_> <_< >_< <_< >_< => ..Ii 25 >_> >_< >_> >_> >_> >_> >_> >_> <_> <_> <_< => ...I.....i ``` [Answer] # Javascript (ES6) 176 171 168 155 148 147 142 141 bytes ``` //v8 - I was sure saving off math was saving a byte, thanks ETF _=>_.split` `.map(m=>(I=m<'='?I-1||0:Math.min(i-1,I+1))+(i=m[2]=='<'?Math.max(I+1,i-1):i+1),i=1,I=0)&&'.'.repeat(I)+'I'+'.'.repeat(--i-I)+'i' //v7 - not checking first char when I can check whole string - changed how I create end string (stolen from edc65) _=>_.split` `.map(m=>(I=m<'='?I-1||0:M.min(i-1,I+1))+(i=m[2]=='<'?M.max(I+1,i-1):i+1),i=1,I=0,M=Math)&&'.'.repeat(I)+'I'+'.'.repeat(--i-I)+'i' //v6 - one more byte _=>_.split` `.map(m=>(I=m[0]=='<'?M(0,I-1):Math.min(i-1,I+1))+(i=m[2]=='<'?M(I+1,i-1):i+1),i=1,I=0,M=Math.max)+((a=Array(i))[I]='I')&&a.join`.`+'i' //v5 - not filling array with '.', just joining with . later _=>_.split` `.map(m=>(I=m[0]=='<'?M(0,I-1):Math.min(i-1,I+1))+(i=m[2]=='<'?M(I+1,i-1):i+1),i=1,I=0,M=Math.max)&&((a=Array(i))[I]='I')&&a.join`.`+'i' //v4 - realized I didn't need to split >_> on _, just use the 0th and 2nd index _=>_.split` `.map(m=>(I=m[0]=='<'?M(0,I-1):Math.min(i-1,I+1))+(i=m[2]=='<'?M(I+1,i-1):i+1),i=1,I=0,M=Math.max)&&((a=Array(i).fill`.`)[I]='I')&&a.join``+'i' //v3 - saving Math to a var (thanks @Verzio) _=>_.split` `.map(m=>(I=(m=m.split`_`)[0]=='<'?M(0,I-1):Math.min(i-1,I+1))+(i=m[1]=='<'?M(I+1,i-1):i+1),i=1,I=0,M=Math.max)&&((a=Array(i).fill`.`)[I]='I')&&a.join``+'i' //v2 - as a single expression! (thanks @Downgoat) _=>_.split` `.map(m=>(I=(m=m.split`_`)[0]=='<'?Math.max(0,I-1):Math.min(i-1,I+1))+(i=m[1]=='<'?Math.max(I+1,i-1):i+1),i=1,I=0)&&((a=Array(i).fill`.`)[I]='I')&&a.join``+'i' //version 1 _=>{I=0;i=1;_.split` `.map(m=>(I=(m=m.split`_`)[0]=='<'?Math.max(0,I-1):Math.min(i-1,I+1))+(i=m[1]=='<'?Math.max(I+1,i-1):i+1));(a=Array(i).fill`.`)[I]='I';return a.join``+'i'} ``` Usage ``` f=_=>_.split` `.map(m=>(I=m<'='?I-1||0:Math.min(i-1,I+1))+(i=m[2]=='<'?Math.max(I+1,i-1):i+1),i=1,I=0)&&'.'.repeat(I)+'I'+'.'.repeat(--i-I)+'i' f(">_> >_< >_> >_> >_> >_> >_> >_> <_> <_> <_<") //"...I.....i" ``` Degolfed (v6, v7 isn't much different) ``` //my solution has changed slightly, but not significantly enough to redo the below _=> //take an input _.split` ` //split to each command <_< .map( //do something for each command (each command being called m) m=> (I= //set I to.... 'I will be the index of the letter I' m[0]=='<'? //is the first char of the command '<'? Math.max(0,I-1) //yes => move I to the left (but don't move past 0) : Math.min(i-1,I+1) //no => move I to the right one, but keep it one less than i ) + //also we need to mess with i (i= m[2]=='<'? //is the 3rd char of the command '<'? Math.max(I+1,i-1) //yes => move i to the left, but keep it one right of I : i+1 //move i to the right (no bounds on how far right i can go) ) ,i=1,I=0 //set I to 0 and i to 1 initially ) + //this just lets us chain commands into one expression, not really adding ( (a=Array(i))[I]='I') //create an array of length i (will be one shorter than we really need) //set element I to 'I' && //last chained command, we know the array creation will be true //so javascript will just output the next thing as the return for the function a.join`.`+'i' //join the array with '.' (into a string) and append i //i will always be the last element ``` [Answer] # Retina, ~~91~~ 86 bytes I probably didn't take the best approach, so it can probably be golfed more. And no, I did not copy FryAmTheEggman (I know they're really similar in our approaches). I didn't even see his answer until after I posted mine. ``` $ ¶Ii (`^¶ sr`^<_(.*)( |)I $1I$2 s`^>_(.*)I( ?) $1$2I sr`^<(.*) ?i $1i s`^>(.*)i $1 i ``` [**Try it online**](http://retina.tryitonline.net/#code=JArCtklpCihgXsK2CgpzcmBePF8oLiopKCB8KUkKJDFJJDIKc2BePl8oLiopSSggPykKJDEkMkkKc3JgXjwoLiopID9pCiQxaQpzYF4-KC4qKWkKJDEgaQ&input=Pl8-Cj5fPAo-Xz4KPl8-Cj5fPgo-Xz4KPl8-Cj5fPgo8Xz4KPF8-CjxfPA) [Answer] ## Javascript (ES6) 166 bytes Using Charlie Wynn's answer, I managed to save 10 bytes by defining Math.max as M and calling M each time his script uses ``` _=>{I=0;i=1;_.split` `.map(m=>(I=(m=m.split`_`)[0]=='<'?M=Math.max;M(0,I-1):M(i-1,I+1))+(i=m[1]=='<'?M(I+1,i-1):i+1));(a=Array(i).fill`.`)[I]='I';return a.join``+'i'} ``` (I didn't write this golf, Charlie Wynn did [here](https://codegolf.stackexchange.com/questions/74719/shifty-eyes-shifting-is#answer-74723). I merely modified it to make it shorter) [Answer] ## CJam, 33 bytes ``` 0Xq2%{'=-_3$+[2$W]-,*@+}/S*'i+'It ``` Uses the same algorithm as [my Python answer](https://codegolf.stackexchange.com/a/74927/21487), except with 0-indexing. Essentially: * Only look at the arrows in the input, converting `<` to -1 and `>` to 1 * Only apply an update if it doesn't move us to position -1 and doesn't move us to the position of the other char * Since the arrows alternate between applying to `I` and applying to `i`, we alternate which position we update after each arrow Thanks to @MartinBüttner for golfing the output step, taking off 5 bytes. [Try it online](http://cjam.aditsu.net/#code=0Xq2%25%7B'%3D-_3%24%2B%5B2%24W%5D-%2C*%40%2B%7D%2FS*'i%2B'It&input=%3E_%3E%20%3E_%3C%20%3E_%3E%20%3E_%3E%20%3E_%3E%20%3E_%3E%20%3E_%3E%20%3E_%3E%20%3C_%3E%20%3C_%3E%20%3C_%3C) | [Test suite](http://cjam.aditsu.net/#code=qN%2F%20%20%20%20%20%20e%23%20Read%20input%20and%20split%20by%20newlines%0A%0A%7B%0A%0A0X%402%25%7B'%3D-_3%24%2B%5B2%24W%5D-%2C*%40%2B%7D%2FS*'i%2B'It%0A%0A%7D%25%20%20%20%20%20%20%20e%23%20Apply%20program%20to%20each%20line%20(%40%20instead%20of%20q%0A%20%20%20%20%20%20%20%20%20e%23%20since%20the%20input%20is%20already%20on%20the%20stack)%0AN*%20%20%20%20%20%20%20e%23%20Join%20by%20newlines&input=%0A%3E_%3E%0A%3C_%3C%0A%3E_%3C%0A%3C_%3E%0A%3E_%3E%20%3E_%3E%0A%3E_%3E%20%3C_%3C%0A%3E_%3E%20%3E_%3C%0A%3E_%3E%20%3C_%3E%0A%3C_%3C%20%3E_%3E%0A%3C_%3C%20%3C_%3C%0A%3C_%3C%20%3E_%3C%0A%3C_%3C%20%3C_%3E%0A%3E_%3C%20%3E_%3E%0A%3E_%3C%20%3C_%3C%0A%3E_%3C%20%3E_%3C%0A%3E_%3C%20%3C_%3E%0A%3C_%3E%20%3E_%3E%0A%3C_%3E%20%3C_%3C%0A%3C_%3E%20%3E_%3C%0A%3C_%3E%20%3C_%3E%0A%3E_%3E%20%3E_%3E%20%3C_%3E%0A%3C_%3E%20%3E_%3E%20%3E_%3E%20%3E_%3E%20%3C_%3E%20%3C_%3C%0A%3C_%3E%20%3E_%3E%20%3E_%3E%20%3E_%3E%20%3C_%3E%20%3C_%3C%20%3E_%3C%20%3C_%3C%20%3E_%3C%0A%3E_%3E%20%3E_%3C%20%3E_%3E%20%3E_%3E%20%3E_%3E%20%3E_%3E%20%3E_%3E%20%3E_%3E%20%3C_%3E%20%3C_%3E%20%3C_%3C) ``` 0X Initialise the two positions a = 0, b = 1 q2% Read input and take every second char, leaving just the arrows { ... }/ For each arrow in the input... '=- Subtract '=, leaving -1 for '< and 1 for '> _3$+ Duplicate and add a. Stack looks like [a b diff a+diff] [2$W]- Perform setwise subtraction, [a+diff] - [b -1] The result is empty list if a+diff is either b or -1, else [a+diff] , Length, yielding 0 or 1 respectively 0 means we don't want to update the char, 1 means we do * Multiply diff by this result @+ Add to a. Stack now looks like [b a'] where a' is a updated After the above loop, the stack ends with [(I position) (i position)] S* Create (i position) many spaces 'i+ Stick an 'i at the end - this is the right place due to 0-indexing 'It Set (I position) to 'I ``` [Answer] # Retina, ~~61~~ 58 bytes *3 bytes saved thanks to @FryAmTheEggman.* ``` ^ Ii (`( ?)I(.*i) <|I( ?)(.*i) > $3I$1$2$4 ?i_< i i_> i ``` Explanation comes a bit later. [Try it online!](http://retina.tryitonline.net/#code=XgpJaSAKKGAoXC4_KUkoLippKSA8fEkoXC4_KSguKmkpID4KJDNJJDEkMiQ0ClwuP2lfPAppCmlfPgouaQ&input=PF8-ID5fPiA-Xz4gPl8-IDxfPiA8XzwK) [Modified code with batch test.](http://retina.tryitonline.net/#code=TSFgKD88PVxuKVs8Pl8gXSsoPz1cbikKbWBeCklpIAptKGAoXC4_KUkoLippKSA8fEkoXC4_KSguKmkpID4KJDNJJDEkMiQ0ClwuP2lfPAppCmlfPgouaQ&input=IzEKPl8-CkkuaQoKIzIKPF88CklpCgojMwo-XzwKSWkKCiM0CjxfPgpJLmkKCiM1Cj5fPiA-Xz4KLkkuaQoKIzYKPl8-IDxfPApJaQoKIzcKPl8-ID5fPAouSWkKCiM4Cj5fPiA8Xz4KSS4uaQoKIzkKPF88ID5fPgpJLmkKCiMxMAo8XzwgPF88CklpCgojMTEKPF88ID5fPApJaQoKIzEyCjxfPCA8Xz4KSS5pCgojMTMKPl88ID5fPgpJLmkKCiMxNAo-XzwgPF88CklpCgojMTUKPl88ID5fPApJaQoKIzE2Cj5fPCA8Xz4KSS5pCgojMTcKPF8-ID5fPgouSS5pCgojMTgKPF8-IDxfPApJaQoKIzE5CjxfPiA-XzwKLklpCgojMjAKPF8-IDxfPgpJLi5pCgojMjEKPl8-ID5fPiA8Xz4KSS4uLmkKCiMyMgo8Xz4gPl8-ID5fPiA-Xz4gPF8-IDxfPAouSS4uLmkKCiMyMwo8Xz4gPl8-ID5fPiA-Xz4gPF8-IDxfPCA-XzwgPF88ID5fPAouLklpCgojMjQKPl8-ID5fPCA-Xz4gPl8-ID5fPiA-Xz4gPl8-ID5fPiA8Xz4gPF8-IDxfPAouLi5JLi4uLi5p) [Answer] # JavaScript (ES6), 115 ~~118~~ **Edit:** 3 bytes saved thx CharlieWynn ``` a=>a.split` `.map(x=>x[x>'='?q&&(--q,++p):p&&(--p,++q),2]>'='?++q:q&&--q,p=q=0)&&'.'.repeat(p)+`I${'.'.repeat(q)}i` ``` `p` is the number of spaces before `I`; `q` is the number of spaces between `I` and `i`. Neither can be negative. **Less golfed** ``` a=>( a.split(' ').map( x=> ( x>'='?q&&(--q,++p):p&&(--p,++q), // try to move I based on 1st char of x x[2]>'='?++q:q&&--q // try to move i based on 3rd char of x ) , p=q=0), // starting values of p and q '.'.repeat(p)+'I' + '.'.repeat(q) +'i' // return value ) ``` **Test** ``` f=a=>a.split` `.map(x=>x[x>'='?q&&(--q,++p):p&&(--p,++q),2]>'='?++q:q&&--q,p=q=0)&&'.'.repeat(p)+`I${'.'.repeat(q)}i` console.log=x=>O.textContent+=x+'\n' ;[['','Ii'], ['>_>','I.i'], ['<_<','Ii'], ['>_<','Ii'], ['<_>','I.i'], ['>_> >_>','.I.i'], ['>_> <_<','Ii'], ['>_> >_<','.Ii'], ['>_> <_>','I..i'], ['<_< >_>','I.i'], ['<_< <_<','Ii'], ['<_< >_<','Ii'], ['<_< <_>','I.i'], ['>_< >_>','I.i'], ['>_< <_<','Ii'], ['>_< >_<','Ii'], ['>_< <_>','I.i'], ['<_> >_>','.I.i'], ['<_> <_<','Ii'], ['<_> >_<','.Ii'], ['<_> <_>','I..i'], ['>_> >_> <_>','I...i'], ['<_> >_> >_> >_> <_> <_<','.I...i'], ['<_> >_> >_> >_> <_> <_< >_< <_< >_<','..Ii'], ['>_> >_< >_> >_> >_> >_> >_> >_> <_> <_> <_<','...I.....i']] .forEach(t=>{ var i=t[0],k=t[1],r=f(i) console.log(i +' -> '+r + (r==k?' OK':' KO (exp '+k+')')) }) ``` ``` <pre id=O></pre> ``` [Answer] ## Python 2, ~~96~~ 92 bytes ``` f=lambda s,I=1,i=2:s and f(s[2:],i,I+cmp(s,'=')*(0<I+cmp(s,'=')!=i))or'%*c'*2%(I,73,i-I,105) ``` Pretty shifty-looking solution for a shifty challenge. Input like `f('>_> <_>')`, output like `'I i'`. Verification program (assuming `tests` is the multiline test case string): ``` for test in zip(*[iter(tests.replace("[empty string]", "").splitlines())]*4): assert f(test[1]) == test[2].replace('.',' ') ``` The program reads each arrow one at a time, starting with `I=1, i=2` and using 1-based indices. The variable names are a tad misleading since they swap roles - after every char, `I` becomes `i` and `i` becomes `I` updated. A char is only updated if it would move to neither the position of the other char nor position 0. For example, for `>_> <_> >_<` we do: ``` Char I (= i from previous iteration) i ----------------------------------------------------------------------------------------- 1 2 > 2 1+1 = 2 would overlap, so remain 1 > 1 2+1 = 3 < 3 1-1 = 0 is too low, so remain 1 > 1 3+1 = 4 > 4 1+1 = 2 < 2 4-1 = 3 ``` This gives `' Ii'` as desired. [Answer] ## Lua, 104 bytes ``` s='Ii'for v in(...):gmatch'%S_?'do s=s:gsub(('>i$ i< ii>_I I<_ II '):match(v..'(..)(%P+)'))end print(s) ``` Usage: ``` $ lua shifter.lua "<_> >_> >_> >_> <_> <_<" I i ``` [Answer] ## Javascript (ES5), ~~153~~ 125 bytes takes an input by setting a variable `a` before running ``` I=i=0;for(b of a.split(" "))b[0]==">"?i!=I&&I++:I>0&&I--,b[2]==">"?i++:I!=i&&i--;r=Array(i).fill(".");r[I]="I";r.join("")+"i" ``` Somewhat ungolfed: ``` I=i=0; for(b of a.split(" ")) b[0]==">" ? i!=I && I++ : I>0 && I--, b[2]==">" ? i++ : I!=i && i-- ; r=Array(i).fill("."); r[I]="I"; r.join("")+"i" ``` [Answer] ## Mathematica, 125 bytes ``` Fold[StringReplace,"Ii",StringCases[#,"<_"|">_"|">"|"<"]/.{"<_"->".I"->"I.",">_"->"I."->".I","<"->".i"->"i",">"->"i"->".i"}]& ``` Pure function with first argument `#`. The idea is that each `<_`, `>_`, `<`, and `>` in the input corresponds to a string replacement rule. `"<_"|">_"|">"|"<"` is a string pattern that matches any of those four expressions. `StringCases[#,"<_"|">_"|">"|"<"]` will find all such matches. Then we replace (`/.`) each `"<_"` with the string replacement rule `".I"->"I."`, each `">_"` with the rule `"I."->".I"`, and so forth. Then I want to sequentially apply each replacement rule to the string `"Ii"`, but `StringReplace` will only look for matches in the parts of the string which have not been replaced, so we left `Fold` the function `StringReplace` over the list of replacement rules with starting value `"Ii"`. Perhaps it would be clearer with an example (here `%` refers to the previous cell's output): [![enter image description here](https://i.stack.imgur.com/5yANg.png)](https://i.stack.imgur.com/5yANg.png) ]
[Question] [ Given an input of a list of words, output the words with their letters arranged diagonally: ``` p r o p g u r z a a z m n l m d e i c s n o g d g e o l f ``` (The above should be the output for the input `programming puzzles and code golf`.) To be precise, each word starts on the first column and three rows below the previous word, and each successive letter moves one column to the right and one row down. The input may be provided as either a single string of words, separated by exactly one space, or a list/array of words. The words will only be composed of lowercase letters, `a-z`, and will always be at least one character long. The output may be a single string, an array of lines, or an array of arrays of characters. Leading or trailing whitespace is not allowed, except for a single trailing newline. Further test cases: `a bcd efgh i j` ``` a b c d e f g i h j ``` `x` ``` x ``` `verylongword short` ``` v e r s y h l o o r n t g w o r d ``` Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win! [Answer] # Vim, ~~85, 76, 66~~, 52 keystrokes/bytes When I first looked at this challenge, I thought "This is perfect for vim!" And then when I tried it everything went wrong. Here it is, in all of it's messy hacky glory: ``` :se ve=all|s/ /\r\r\r/g qqGo<esc>?\<.\S lDjP@qq@qG?. jdG ``` [Try it online,](http://v.tryitonline.net/#code=OnNlIHZlPWFsbHxzLyAvXHJcclxyL2cKcXFHbxs_XDwuXFMKbERqUEBxcUBxRz8uCmpkRw&input=UHJvZ3JhbW1pbmcgUHV6emxlcyBhbmQgQ29kZSBHb2xm) thanks to the (mostly) backwards compatible V interpreter. # Explanation: At first I thought I could do this beautifully simple 37 byte version: ``` :se ve=all qq:g/\S\S/norm ^lDjP @qq@q ``` Unfortunately, it's not that simple. Let's take it line by line: ``` :se ve=all ``` This enables a feature called 'virtual editing'. It allows the cursor to move to columns that don't exist yet. This answer would be basically impossible without it. Now we need to separate out the words onto different lines. So we'll replace each space with 3 newlines. Since this is an ex command we can run it simultaneously with our last ex command `:se ve=all` by seperating the two with a bar. ``` |s/ /\r\r\r/g ``` Now the buffer looks like this: ``` Programming Puzzles and code-golf ``` Here's where the fun begins. We set up the traditional recursive macro with: `qq`, and then call this: ``` G " Move to the last line o<esc> " Append an extra newline ? " Search backwards for \<. " Any character at the beginning of a word \S " Followed by a non-space character l " Move one character to the right D " Delete eveything until the end of this line j " Move down one line P " Paste what we just deleted ``` Then we finish the recursive macro with `@qq@q`. At this point, we have all of the diagonals, we just need to do a little clean up. ``` G " Move to the last line ?. " Search backwards for any character j " Move down one line dG " Delete until the end of the buffer ``` [Answer] # [Turtlèd](https://github.com/Destructible-Watermelon/turtl-d/), ~~28~~ 26 bytes Oh my, I appear to be beating a language specifically designed for golfing. this is a great day. ``` !_4[*.[ rd+.]ul[ ul]r;_+]_ ``` ### [Try it online!](http://turtled.tryitonline.net/#code=IV80WyouWyByZCsuXXVsWyB1bF1yO18rXV8&input=dGhpcyBpc24ndCBldmVuIGEgZ29sZiBsYW5nISA) ## Explanation (write means writing to the cell on the grid, pointed char means char in input the string pointer points to) ``` ! Take string input into variable _ Normally conditional, with >1 input (there will be), write ' ' 4 set register to 4 [* ] until the current cell is * . Write pointed char, initially first char [ ] Until space is written on cell rd+. move right, down, string pointer++, write pointed char ul[ ul] Move back up to the top of the word r; Move right, down 4 (because this is register value) _+ write * if end of input, else ' ', increment string pointer _ will always write ' ', since it will always point at start char ``` note trailing space. Input also needs trailing space. seeing as python can take a list, this is a lot like taking a list in Turtlèd [Answer] # [MATL](http://github.com/lmendo/MATL), 28 bytes ``` c!t&n:q3_*ts_b+5M4$XdZ!cZ{Zv ``` Input is a cell array of strings, with commas as optional separators: ``` {'programming' 'puzzles' 'and' 'code' 'golf'} ``` or ``` {'programming', 'puzzles', 'and', 'code', 'golf'} ``` [Try it online!](http://matl.tryitonline.net/#code=YyF0Jm46cTNfKnRzX2IrNU00JFhkWiFjWntadg&input=eydwcm9ncmFtbWluZycgJ3B1enpsZXMnICdhbmQnICdjb2RlJyAnZ29sZid9) Or verify all test cases: [1](http://matl.tryitonline.net/#code=YyF0Jm46cTNfKnRzX2IrNU00JFhkWiFjWntadg&input=eydwcm9ncmFtbWluZycgJ3B1enpsZXMnICdhbmQnICdjb2RlJyAnZ29sZid9), [2](http://matl.tryitonline.net/#code=YyF0Jm46cTNfKnRzX2IrNU00JFhkWiFjWntadg&input=eydhJyAnYmNkJyAnZWZnaCcgJ2knICdqJ30), [3](http://matl.tryitonline.net/#code=YyF0Jm46cTNfKnRzX2IrNU00JFhkWiFjWntadg&input=eyd4J30), [4](http://matl.tryitonline.net/#code=YyF0Jm46cTNfKnRzX2IrNU00JFhkWiFjWntadg&input=eyd2ZXJ5bG9uZ3dvcmQnICdzaG9ydCd9). ### Explanation Consider the following input as an example: ``` {'aaaa' 'bb' 'ccc'} ``` You can view the partial results (stack contents) inserting the comment symbol `%` at any point in the code. For example, [view the stack contents](http://matl.tryitonline.net/#code=YyF0Jm4lOnEzXyp0c19iKzVNNCRYZFohY1p7WnY&input=eydhYWFhJyAnYmInICdjY2MnfQ) after the fourth function (`&n`). ``` c % Input cell array of strings implicitly. Convert to 2D char array, % right-padding with spaces % STACK: ['aaaa'; 'bb '; 'ccc'] ! % Transpose % STACK: ['abc' 'abc' 'a c' 'a '] t % Duplicate % STACK: ['abc' 'abc' 'a c' 'a '], ['abc' 'abc' 'a c' 'a '], &n % Number of rows and of columns % STACK: ['abc' 'abc' 'a c' 'a '], 4, 3 :q % Range, subtract 1 % STACK: ['abc' 'abc' 'a c' 'a '], 4, [0 1 2] 3_* % Multiply by -3 % STACK: ['abc' 'abc' 'a c' 'a '], 4, [0 -3 -6] ts_ % Duplicate, sum, negate % STACK: ['abc' 'abc' 'a c' 'a '], 4, [0 -3 -6], 9 b % Bubble up in stack % STACK: ['abc' 'abc' 'a c' 'a '], [0 -3 -6], 9, 4 + % Add % STACK: ['abc' 'abc' 'a c' 'a '], [0 -3 -6], 13 5M % Push second input of last function again % STACK: ['abc' 'abc' 'a c' 'a '], [0 -3 -6], 13, 4 4$Xd % Buld numerical sparse matrix from the above four arguments. The % columns of the first input argument will be the diagonals of the % result, with indices given bu the second input (negative is below % main diagonal). The matrix size is the third and fourth arguments % STACK: [97 0 0 0 0 97 0 0 0 0 97 0 98 0 0 97 0 98 0 0 0 0 32 0 99 0 0 32 0 99 0 0 0 0 99 0 0 0 0 32 0 0 0 0 0 0 0 0 0 0 0 0] Z!c % Convert from sparse to full, and then to char. Character 0 is % displayed as space % STACK: ['a ' ' a ' ' a ' 'b a' ' b ' ' ' 'c ' ' c ' ' c ' ' ' ' ' ' ' ' '] Z{ % Split into cell array, with each row in a cell % STACK: {'a ', ' a ', ' a ', 'b a', ' b ', ' ', 'c ', ' c ', ' c ', ' ', ' ', ' ', ' '} Zv % Deblank: remove trailing space from each string. Implicitly display, % each string on a different line. Empty strings do not generate % a newline % STACK: {'a ', ' a', ' a', 'b a', ' b', '', 'c', ' c', ' c', '', '', '', ''} ``` [Answer] ## JavaScript (ES6), ~~118~~ ~~109~~ 84 bytes Takes input as an array of words. Returns an array of arrays of characters. ``` s=>s.map((w,y)=>[...w].map((c,x)=>(a[p=y*3+x]=a[p]||Array(x).fill(' '))[x]=c),a=[])&&a ``` ### Alternative version, 109 bytes Returns a string. ``` let f = s=>s.map((w,y)=>[...w].map((c,x)=>(a[p=y*3+x]=a[p]||Array(x).fill` `)[x]=c),a=[])&&a.map(s=>s.join``).join` ` console.log(f(["programming", "puzzles", "and", "code", "golf"])) ``` [Answer] # Japt `-Rx`, ~~17~~ ~~16~~ 13 bytes Takes input as an array of words. If trailing whitespace on each line were allowed then the last 4 characters could be removed to tie with the Charcoal solution. ``` yÈmú3)iYçÃmx1 ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=echt+jMpaVnnw214MQ==&input=WyJ2ZXJ5bG9uZ3dvcmQiLCJzaG9ydCJdCi1SeA==) or [run all test cases](https://tio.run/##y0osKPn/v1LhcHfu4V3Gmpmuh5cfbq5UyK0w/B@UGXpoe4Wmtvvh5br/o7milQqK8tOLEnNzM/PSlXSUCkqrqnJSi4GsxLwUIJmcn5IKpNLzc9KUYoGqE4GcpGSQTGpaegaQygTiLLBUBZgsSy2qzMnPSy/PLwKpKs7ILyoBSsRy6eYGAQA) --- ## Explanation ``` y :Transpose È :Map each word at 0-based index Y m : Map each character ú3 : Right pad with spaces to length 3 ) : End mapping i : Prepend Yç : Space repeated Y times à :End mapping and transpose m :Map x1 : Trim right :Implicitly join with newlines, trim and output ``` [Answer] # Common Lisp, ~~673~~ ~~668~~ 597 bytes Terrible solution, I know. I'll probably edit this more after some sleep. ``` (defun f(&rest z)(let((l)(a 0)(s)(o)(b)(c 0))(loop(setf b(length l))(setf l"")(loop for w in z for i from 0 do(if(>(+(length w)(* i 3))c)(setf c(+(length w)(* i 3))))(setf s(+(* i -3)a))(when(and(>= s 0)(< s(length w)))(setf o(format nil"~v@{~a~:*~}"s" "))(if(and(>=(- s 3)0)(not(equal i(-(length z)1))))(setf o(subseq o(- s 2))))(setf l(concatenate'string o(string(char w s))l)))(when(>= s(length w))(setf l(concatenate'string" "l))))(if(<=(length l)b)(setf l(concatenate'string(format nil"~v@{~a~:*~}"(- b(length l)-1)" ")l)))(print(string-right-trim" "l))(if(>= b c)(return))(setf a(1+ a))))) ``` Usage: ``` * (f "ppcg" "is" "pretty" "ok") "p" " p" " c" "i g" " s" "" "p" " r" " e" "o t" " k t" " y" "" NIL ``` This loops over every word in the provided list and adds appropriate characters to the current line. Appropriate padding is provided by my subpar usage of `format`. Note: I'm new to Common Lisp, but I know enough to realize that this could use a lot of improvement. [Answer] # C#, 336 Bytes: Golfed: ``` string D(string[]s){int x=0,y=0,r=0,q=2*(s.Max().Length+s.Length)+1;var a=new char[q, q];for(int i=0;i<s.Length;i++){y=r;for(int j=0;j<s[i].Length;j++){a[y,x]=s[i][j];x+=1;y+=1;}x=0;r+=3;}var o="";for(x=0;x<q;x++){var t="";for(y=0;y<q;y++)t+=a[x,y];o+=t==string.Join("",Enumerable.Repeat('\0',q))?"":(t.TrimEnd('\0')+"\r\n");}return o;} ``` Ungolfed: ``` public string D(string[] s) { int x = 0, y = 0, r = 0, q = 2 * (s.Max().Length + s.Length) + 1; var a = new char[q, q]; for (int i = 0; i < s.Length; i++) { y = r; for (int j = 0; j < s[i].Length; j++) { a[y, x] = s[i][j]; x += 1; y += 1; } x = 0; r +=3; } var o = ""; for (x = 0; x < q; x++) { var t = ""; for (y = 0; y < q; y++) t += a[x, y]; o += t == string.Join("", Enumerable.Repeat('\0', q)) ? "" : (t.TrimEnd('\0') + "\r\n"); } return o; } ``` Testing: ``` var codeGolf = new DrawDiagonalLinesOfText(); Console.WriteLine(codeGolf.E(new string[] { "programming", "puzzles", "and", "code", "golf" })); Console.WriteLine(codeGolf.E(new string[] { "a", "bcd", "efgh", "i", "j" })); Console.WriteLine(codeGolf.E(new string[] { "verylongword", "short" })); p r o p g u r z a a z m n l m d e i c s n o g d g e o l f a b c d e f g i h j v e r s y h l o o r n t g w o r d ``` [Answer] # Python 2, 146 bytes ``` s=input() k=max(map(len,s)) a=[k*[' ']for x in range(k+len(s)*3+3)] for x in range(len(s)): for y in range(len(s[x])):a[x*3+y][y]=s[x][y] print a ``` Note: the indentations for the last two lines are `<space>` and `<tab>`, which saves one byte since I don't need to double-indent. Input is to be entered as an array of strings like so: `["hello", "world"]` or `['hello', 'world']`. Output is an array of arrays of characters. There's probably a better way to do this... **EDIT** Thanks to Doorknob for pointing out a missing close square bracket. I placed it before the `*k...` in the third line. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal/wiki), ~~18~~ 11 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page) ~~16~~ 9 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page) if trailing whitespaces were allowed: [try it online](https://tio.run/##AUYAuf9jaGFyY29hbP//77y377yzwqvvvLDihpjOue@8rcKz4oaT//9wcm9ncmFtbWluZwpwdXp6bGVzCmFuZApjb2RlCmdvbGYK). ``` UTWS«P↘ιM³↓ ``` My first Charcoal answer. Thanks to *@DLosc* for suggestion `P` and `M` instead of using `S` and `J` (Jump) to go back to the start of the line (and three down). [Try it online (verbose)](https://tio.run/##HYwxDgIhEAD7fQUlJGdlp62NhY1ecjXhcNlkYQnCmZzx7UhsZzLjgi1OLPc@CyL7uVDU5gxLIPb6mnKrj1oooTbmA0rdGlfKA1R9usg73QlDnRSNZEjZvD5O6m8G@faei2CxMY4D5Lbv7F9g0wpOVg8o/IR@2PgH) or [Try it online (pure)](https://tio.run/##AUwAs/9jaGFyY29hbP//77y177y077y377yzwqvvvLDihpjOue@8rcKz4oaT//9wcm9ncmFtbWluZwpwdXp6bGVzCmFuZApjb2RlCmdvbGYK). **Explanation:** Disable trailing spaces in the output: ``` ToggleTrim(); UT ``` Loop while there is still a next input-string: ``` While(InputString()){ ... } WS« ... ``` Print this string without moving the cursor in a down-right direction: ``` Multiprint(:DownRight, i); P↘ι ``` And then move three positions down for the next iteration: ``` Move(3, :Down); M³↓ ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 21 bytes ``` ʁ2꘍∑374f?vLz4jø^↵vøR⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLKgTLqmI3iiJEzNzRmP3ZMejRqw7he4oa1dsO4UuKBiyIsIiIsIltcInByb2dyYW1taW5nXCIsXCJwdXp6bGVzXCIsXCJhbmRcIixcImNvZGVcIixcImdvbGZcIl0iXQ==) ``` ø^ # Using the canvas, draw... ʁ # Text: Palindromise each 2꘍ # Append two spaces to each ∑ # Concatenate into a single string 374f # Directions: [3, 7, 4] - down-left, up-right, down ?vL # Lengths: Lengths of each word in input z # Zip with self 4j # Join with 4s ↵vøR⁋ # Strip trailing whitespace (ugh) ``` [Answer] # q/kdb+, ~~130~~ ~~109~~ ~~94~~ ~~90~~ ~~86~~ 84 bytes **Solution:** ``` f:{-1(+)a rtrim(til(#)E){raze(x#" "),y,\:" "}'E:(+)(a:{(max(#:)each x)$x})" "vs x;} ``` **Examples:** ``` q)f "programming puzzles and code golf" p r o p g u r z a a z m n l m d e i c s n o g d g e o l f q)f "a bcd efgh i j" a b c d e f g i h j q)f (),"x" x q)f "verylongword short" v e r s y h l o o r n t g w o r d ``` **Explanation (ungolfed):** The basic gist is to create a bunch of equal length strings from the input string, flip (rotate) them, then add appropriate whitespace to get something that looks like this: ``` "p p a c g " " r u n o o " " o z d d l " " g z e f" " r l " " a e " " m s " " m " " i " " n " " g " ``` which is flipped again, and printed to stdout. Here's a line-by-line breakdown of the concept: ``` A:"programming puzzles and code golf"; // original input B:" " vs A; // split on " " C:max count each B; // find length of the longest string D:C$B; // pad each string to this length E:flip D; // flip (rotate) string F:{raze(x#" "),y,\:" "}; // appends each char with " " and prepends an increasing number of " " G:(til count E)F'E; // execute function F with each pair of 0..n and item in list E H:max count each rtrim G; // find longest string (ignoring right whitespace) I:H$G; // pad each of the strings to this length J:flip I; // flip to get result -1 J; // print to stdout, swallow return value ``` **Notes:** A few ways to shave off some (11) easy bytes if we *really* wanted to: * Could save 2 bytes by dropping the `f:` and leaving as an anonymous function * Could save 3 bytes by dropping the `-1` and `;` and returning a list of strings rather than printing to stdout * Could save 6 bytes if we passed in a list of strings rather than space-separated string **Edits:** * -11 bytes, use `rtrim` to find max length to pad, removed need for storing `C` variable * -15 bytes, switching out the `max count each` for a lambda function `a` which is created once and used twice * -4 bytes, moving the `raze` into the lambda function to save a `raze each` * -4 bytes, simplified the core lambda function that adds the whitespace * -2 bytes, use `(+)` as shorthand for `flip` [Answer] # Mathematica, 146 bytes ``` P=PadRight;T=Transpose;R=Riffle;Select[Rest@T@P@MapIndexed[""~Table~#2~Join~#1&,T@P@R[Characters/@#~R~{},{},3]]//.{0->"",{x__,""}->{x}},#!={""}&]& ``` I'm disappointed by this bytecount, but oh well. Defines an anonymous function that takes a list of words (e.g. `{"this","that","these"}`) and returns a two-dimensional array of characters. To view in grid form, add a `//Grid` at the end. Converts the strings to an array, adds extra lines, transposes the array, prepends the necessary shifts, then transposes again. Example result (formatted as grid): [![Example result](https://i.stack.imgur.com/sNC1n.png)](https://i.stack.imgur.com/sNC1n.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` z⁶j€⁾ µJ’⁶ẋ;"z⁶œr€⁶Yœr⁷ ``` **[Try it online!](https://tio.run/nexus/jelly#@1/1qHFb1qOmNY8a9ykoHNrq9ahhJlDk4a5uayWQ1NHJRWDJbZEgVuP2////R6uXpRZV5uTnpZfnF6Wo66gXZ@QXlajHAgA "Jelly – TIO Nexus")** ### How? ``` z⁶j€⁾ µJ’⁶ẋ;"z⁶œr€⁶Yœr⁷ - Main link: a list of strings z - transpose with filler... ⁶ - space character j€ - join €ach with ⁾ - two spaces µ - monadic chain separation, call the result x J - range(length(x)) [1,2,...,x] ’ - decrement (vectorises) [0,1,...x-1] ẋ - repeat (vectorises) ⁶ - a space ['', ' ',...,'x spaces'] " - zip with ; - concatenation (prefixes with the space strings) z - transpose with filler... ⁶ - space character œr€⁶ - trim spaces from the right of €ach Y - join with line feeds œr⁷ - trim line feeds from the right - implicit print ``` [Answer] # Python 2, 182 bytes ``` def f(s): M=max(map(len,s));p=' '*M;L=[p]+s+M*[p];r='';k=0 while k/M<len(s)*3+M: i=k%M;w=k/M-i+1;r+=(L[(w/3+1)*(w%3==1)]+p)[i];k+=1 if i==M-1:r=r.rstrip()+'\n' return r.strip() ``` A bit long, but on the positive side, it returns a string with no trailing white space on each line, and no trailing white space or returns at the end; constraints that some other entries don't obey. A list of words is passed into the function; some 'blanks' are aded to this list and then the algorithm maps a row,column pair to a wordNumber, characterNumber in the expanded list. (This is a bit of the inverse of the usual strategy seen in other solutions). If we allow trailing white space on all lines except the last, we can do a bit better (163 bytes): ``` def f(s): M=max(map(len,s));p=' '*M;L=[p]+s+M*[p];r='';k=0 while k/M<len(s)*3+M:i=k%M;w=k/M-i+1;r+=(L[(w/3+1)*(w%3==1)]+p)[i]+'\n'*(i==M-1);k+=1 return r.strip() ``` [Answer] # [K4](https://kx.com/download/), 58 bytes **Solution:** ``` +(|/{0+/|\|~^x}@'x)$x:(2-(!c)+3*#x)$" "/:'$+(c:|/#:'x)$x: ``` **Examples:** ``` q)k)+(|/{0+/|\|~^x}@'x)$x:(2-(!c)+3*#x)$" "/:'$+(c:|/#:'x)$x:("programming";"puzzles";"and";"code";"golf") "p " " r " " o " "p g " " u r " " z a " "a z m " " n l m " " d e i " "c s n " " o g" " d " "g e " " o " " l " " f " q)k)+(|/{0+/|\|~^x}@'x)$x:(2-(!c)+3*#x)$" "/:'$+(c:|/#:'x)$x:(,"a";"bcd";"efgh";,"i";,"j") "a " " " " " "b " " c " " d " "e " " f " " g " "i h" " " " " "j " q)k)+(|/{0+/|\|~^x}@'x)$x:(2-(!c)+3*#x)$" "/:'$+(c:|/#:'x)$x:("verylongword";"short") "v " " e " " r " "s y " " h l " " o o " " r n " " t g " " w " " o " " r " " d" ``` **Explanation:** Right-pad strings so they are the same length, transpose, join with `" "`, left-pad to generate diagonals, then right-pad to correct lengths and transpose back. Takes a list of strings and returns a list of strings. Probably golfable but still shorter than my q/kdb+ solution. ``` +(|/{0+/|\|~^x}@'x)$x:(2-(!c)+3*#x)$" "/:'$+(c:|/#:'x)$x: x: / save as variable x $ / pad ( ) / do this together #:'x / count (#:) each (') x |/ / max c: / save as variable c + / flip / transpose $ / string ($) " "/:' / join each with " " $ / pad ( ) / do this together #x / count (#) x 3* / multiply by 3 + / add to ( ) / do this together !c / range 0..c 2- / subtract from 2 x: / save as x: $ / pad ( ) / do all this together { }@'x / apply (@) lambda {} to each x ^x / null (^) x (" " is considered null) ~ / not | / reverse |\ / max (|) scan (\), maxs 0+/ / sum (+) over (/) starting with 0 |/ / max (|) over (/), max + / transpose ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) if trailing whitespaces were allowed: [try it online](https://tio.run/##yy9OTMpM/f//3LZzW40O7zq81svv8K7g2nPbvP4f2v0/OlqpQElHqQiI84E4HcpOBOJcKM4E4jywXKwORHUpEFdBcQ4QpwJxMVg2Eao2BcxLhpqaAlYDEkmHioB0pSnFxgIA). ``` ζε2úíJNúS}ζJðδÜõÜ ``` Port of [*@Shaggy*'s Japt answer](https://codegolf.stackexchange.com/a/167536/52210). Input as a list of list of characters; output as a list of lines. [Try it online.](https://tio.run/##yy9OTMpM/f//3LZzW40O7zq81svv8K7g2nPbvA5vOLfl8JzDWw/P@X9o9//oaKUCJR2lIiDOB@J0KDsRiHOhOBOI88BysToQ1aVAXAXFOUCcCsTFYNlEqNoUMC8ZamoKWA1IJB0qAtKVphQbCwA) **More interesting answer using the Canvas builtin (~~27~~ 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)):** ~~20~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) if trailing whitespaces were allowed: [try it online](https://tio.run/##yy9OTMpM/f//UdOadJfDO0z0Du89PccTyDu8@/CGQ7sO7zU2Nwk@N/v//2ilgqL89KLE3NzMvHQlHaWC0qqqnNRiICsxLwVIJuenpAKp9PycNKVYAA). ``` €gDø4.ý˜I€ûðºý374S.Λ¶¡ðδÜ ``` -2 bytes thanks to *@emanresuA*. Input as a list of words; output as a list of lines. [Try it online.](https://tio.run/##yy9OTMpM/f//UdOadJfDO0z0Du89PccTyDu8@/CGQ7sO7zU2NwnWOzf70LZDCw9vOLfl8Jz/h3b/j1YqKMpPL0rMzc3MS1fSUSoorarKSS0GshLzUoBkcn5KKpBKz89JU4oFAA) **Explanation:** ``` ζ # Zip/transpose; swapping rows/columns of the (implicit) input-list of lists # of characters, with a space " " as filler for shorter lists ε # Map over each inner lists of characters: 2ú # Pad each inner character with 2 leading spaces í # Reverse each inner string, so the spaces are trailing J # Join this list together to a single string Nú # Pad the 0-based map-index amount of leading spaces S # Convert the string back to a list of characters }ζ # After the map: Zip/transpose back again with " " filler J # Join each inner list together to a single string δ # Map over each inner line: ð Ü # Trim trailing spaces õÜ # Trim trailing empty strings from the list # (after which the list of lines is output implicitly) ``` ``` €gDø4.ý˜I€ûðºý374S.Λ¶¡ðδÜ €g # Get the length of each word of the (implicit) input-list Dø # Convert each value to a pair of this value with a Duplicate + Zip/transpose 4.ý # Intersperse this list of pairs with 4 as delimiter ˜ # Flatten it to a single list I # Push the input-list of words again €û # Palindromize each word ðºý # Join this list with " " (2 spaces) delimiter ŽDā # Push 374 S # Convert it to a list of digits: [3,7,4] .Λ # Use the modifiable Canvas builtin with these three arguments ¶¡ # Split it on newlines δ # Map over each inner line: ð Ü # Trim trailing spaces # (after which the list of lines is output implicitly) ``` *Additional information about the Canvas builtin `Λ`/`.Λ`:* It takes 3 arguments to draw an ASCII shape: 1. Length of the lines we want to draw 2. Character/string to draw 3. The direction to draw in, where each digit represents a certain direction: ``` 7 0 1 ↖ ↑ ↗ 6 ← X → 2 ↙ ↓ ↘ 5 4 3 ``` `€gDø4.ý˜I€ûðºý374S` creates the following Canvas arguments: * Lengths (`€gDø4.ý˜`): e.g. `[11,11,4,7,7,4,3,3,4,4,4,4,4,4]` for input `["programming","puzzles","and","code","golf"]` * Characters (`I€ûðºý`): e.g. `"programmingnimmargorp puzzleselzzup andna codedoc golflog"` for input `["programming","puzzles","and","code","golf"]` * Directions (`374S`): `[3,7,4]`, which translates to \$[↘,↖,↓]\$ Because we have a list of lengths, those are leading here. Step 1: Draw 11 characters (`"programming"`) in direction `3` (\$↘\$): ``` p r o g r a m m i n g ``` Step 2: Draw 11-1 characters (`"nimmargorp"`) in direction `7` (\$↖\$): ``` p r o g r a m m i n g ``` Step 3: Draw 4-1 characters (`" p"`) in direction `4` (\$↓\$): ``` p r p o g r a m m i n g ``` Step 4: Draw 7-1 characters (`"uzzles"`) in direction `3` (\$↘\$): ``` p r p o u g z r z a l m e m s i n g ``` etc. [See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210) `€gDø4.ý˜` could alternatively be [`εgD4)}˜¨` or `€gDø€4¦˜`](https://tio.run/##yy9OTMpM/f//UdOadJfDO0z0Du89PYdTh@vc1nQXE83a03MOrQDyoLJAyuTQMpD8///RSgVF@elFibm5mXnpSjpKBaVVVTmpxUBWYl4KkEzOT0kFUun5OWlKsQA), but I've been unable to find anything shorter. [Answer] # [Perl 6](http://perl6.org/), 73 bytes ``` {my@t;for .kv ->\i,\w{for w.comb.kv {@t[3*i+$^a][$^a]=$^b}};@t »||»" "} ``` [Try it online!](https://tio.run/##FYvdCoMgGEBf5SNi7NebwW5c4XvUAisNt8wwtzDzybrrxRzeHDgHzsh0/wjSwoFDFpy0xGCuNKDPD255Ka7l7KLPqFGyjtURU9zP4pJW9FVEZGlVe4@JgX1b131LIPEBA3orMaCJWog/Pz5HrTpNpRRDB@N3WXo2AR1aaFTLoFM9z084/AE "Perl 6 – Try It Online") The input argument is a list of words. The output is an array of array of characters. [Answer] # [PHP](https://php.net/), 100 bytes ``` <?foreach($_GET as$k=>$v)for($x=0;$y=$v[$x];$t[$x++]=$y)($t=&$s[$k*3+$x])?:$t=" ";echo join(" ",$s); ``` [Try it online!](https://tio.run/##HYvLCoMwFET3foVcLiWpLgrdNU1dlf5AdyIlaDQ@E4wV9efTSzdzhjOMMy7cM2dchJ/X8y1zcLNtZjWO7dRACu57HIP21NRUUZa20oTGDjUUItR21qo07H@OlcdePnDlpBlu8iJwl7jmuBUCF0KSFBJ3znCRJ/Q59udrQiPPbmQgBqFLY@POthODCFL0XITwAw "PHP – Try It Online") [Answer] # [J](http://jsoftware.com/), 54 bytes ``` [:+/@,:&.(_32+3&u:)&.>/]({.-@#\<@{."0])&>~#&>-@+3*i.@# ``` [Try it online!](https://tio.run/##dYrLCoJAFED3fsVVYa6mM1pC4FDDQNCqVdsaonxLNGDaA6Ffn6JdixZncTinNanNp2pu8xTRchiWsOSAEEIM/ANlsNpu1mbHg0iGnDDvkMyChAzcJ0xEyhsZle5@IUfmxMon4uUSQWWQTBomXeNbRVZrIqCEbOjxgV8HpJTibzrCKcuhKKsaGmj/f7eie571pbrrLodrrbsezRs "J – Try It Online") This was a surprisingly good challenge -- deceptively simple but with a lot of depth, and many paths to a solution. Normally I dislike "no trailing whitespace" constraints, but here it was key to the problem's complexity. After many different approaches, I finally found one which feels like it works with J rather than against it. I will add a detailed explanation another time. Note: This returns a boxed list of lines, but in the TIO I open and echo each box so that correctness is easier to see. ]
[Question] [ Given a string `s`, return the smallest contiguous substring you can remove to create a palindrome. --- # Examples: ``` 800233008 -> 2 racecarFOOL -> FOOL abcdedcba -> (empty string) ngryL Myrgn -> "L " (or " M") 123456789 -> 12345678 (or 23456789) aabcdbaa -> c (or d) [[]] -> [[ (or ]]) a -> (empty string) ``` Test case suggestions from users (if you find an edge case not listed, please post a comment): ``` aabaab -> b | Suggested by Zgarb, some returned "aa". ``` --- # Rules * Only printable ASCII characters will appear in the input (no newlines, keep it simple). * Not really a rule, but note `<>`, `/\`, `()`, `[]` and `{}` are not palindromes. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), smallest byte-count wins. --- *+100 bounty has been claimed by Adnan* [Answer] # [J](http://jsoftware.com/), 24 bytes ``` (0{::(-:|.)\.#&,<\)~i.@# ``` [Try it online!](https://tio.run/##FYq7DoIwGEb3PsUfSShNsKnUCxYxTk4YHgAY2kJRB0zKRLy8em2HL/nOyXk6M0MpgIGfS9hbiGQtPpS0NIrTU0t@D3qJHEErCtiUAkMKXwFmRmjQ9xckhSHxGXDOWMY5YzkusJV60NJe67ryJJXuh14r6f802qWC22LHydMm49vd/pAfQxUyJUPUNF0XDHZ/ "J – Try It Online") ## Explanation ``` (0{::(-:|.)\.#&,<\)~i.@# Input: array of chars S # Length of S i.@ Range, [0, 1, ..., len(S)-1] ( )~ Dyadic verb on range and S \. For each outfix of S of size x in range |. Reverse -: Matches input (is palindrome) <\ Box each infix of S of size x in range #&, Flatten each and copy the ones that match 0{:: Fetch the result and index 0 and return ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` Ḣ;Ṫµ=Ṛ 0,0jŒṖÇÞṪ ``` [Try it online!](https://tio.run/##y0rNyan8///hjkXWD3euOrTV9uHOWVwGOgZZRyc93DntcPvheUDh/w93bznc/qhpTeT//xYGBkbGxgYGFlxFicmpyYlFbv7@PlyJSckpqSnJSYlceelFlT4KvpVF6XlchkbGJqZm5haWXIkgBUmJiVzR0bGxXIkgPhABAA "Jelly – Try It Online") ### How it works ``` 0,0jŒṖÇÞṪ Main link. Argument: s (string) 0,0j Join [0, 0], separating by s. This prepends and appends a 0 to s. ŒṖ Build all partitions of the resulting array. ÇÞ Sort the partitions by the helper link. As a side effect, this will remove the first and last element of each partition. The 0's make sure that not removing any characters from s will still remove [0] from both sides. Ṫ Tail; extract the last one. Ḣ;Ṫµ=Ṛ Helper link. Argument: A (array/partition) Ḣ Head; yield and remove the first chunk of A. Ṫ Tail; yield and remove the last chunk of A. ; Concatenate head and tail. µ=Ṛ Compare the result, character by character, with its reverse. A palindrome of length l will yield an array of l 1's, while a non-palindrome of length l will yield an array with at least one 0 among the first l/2 Booleans. The lexicographically largest result is the one with the longest prefix of 1's, which corresponds to the longest palindrome among the outfixes. ``` [Answer] ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~53~~ 51 bytes Byte count assumes CP-1252 encoding. ``` ±{a___,Shortest@b___,c___}/;PalindromeQ[a<>c]:={b} ``` [Try it online!](https://tio.run/##NYxNCoMwFIT3niK4LIJW@2N/EQpdFEWLSxF5iUEDGiHGhYiH6hV6MWuKbh7zzbyZGmRJa5CMwDR9PwNkWWbEZSMkbaWHFZH5jOYlgorxXDQ1fSdwvZP0fBvwOEWCcYm8DYrlrIpXw7iiqOragPGuVfAoQQCRVLTI9NCgIaS7lmU7jmW5uoEUzzklIJ5h6C8OYJLTnGBYmBei91HQi4IvztZ2dvvD0T3pxr@gGhjW/yRJ03VK18bpBw "Wolfram Language (Mathematica) – Try It Online") Defines a unary operator `±` (or a function `PlusMinus`). Input and output are lists of characters. The test suite does the conversion from and to actual strings for convenience. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ``` ā<Œ¯¸«ʒRõsǝÂQ}éнèJ ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##ATMAzP8wNWFiMWX//8SBPMWSwq/CuMKrypJSw7Vzx53DglF9w6nQvcOoSv//cmFjZWNhckZPT0w "05AB1E – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` ŒḂ⁹Ƥ çЀJN$Ẏi1ịẆẋ⁻Ṛ$ ``` [Try it online!](https://tio.run/##AT0Awv9qZWxsef//xZLhuILigbnGpArDp8OQ4oKsSk4k4bqOaTHhu4vhuobhuovigbvhuZok////YWJjZGVkY2Jh "Jelly – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 97 bytes ``` f=lambda s,p=' ':min([s][:p[::-1]in p+p]+(s and[f(s[1:],p+s[0]),f(s[:-1],s[-1]+p)]or[p]),key=len) ``` [Try it online!](https://tio.run/##LY7LasMwEEXX6VfMThJWihT34QrcZVcp@YBBi/ErNY1lIXljQr7dlUxhGDhzD8P16/Izu3LbhvpGU9MRROlrdmBmGh3HaNF4NOao7ejAF94WPAK5DgceURsrfRFRWSEzZ01GTLvwws4BfQp@@7W@9U5swxwgQnrDKqVOZalUxSSwQG3fUvi6XM4ZqWm7vmsbyuCuYT3D9xquLqM@lS@vb@/Vxy5ms6HdQ7R2v/0HaZh5OvgwuoWzu9H6AcdPuD/Yc2ox0cKjhNRYCLH9AQ "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 116 bytes ``` def f(i):R=range(len(i)+1);print min([i[y:k+1]for y in R for k in R if(i[:y]+i[k+1:])[::-1]==i[:y]+i[k+1:]],key=len) ``` [Try it online!](https://tio.run/##VY6xboMwFEX3fsWTJ1skFYYmIUbumClVpKyWBwOGvEId5BBV/npqK1O3e66O7ntzWG53V6xrZ3voKTJxld64wdLJuogZZ/Xs0S3wg44qVEGMGdf93UMAdHCFFMdXxDigRNAZqigJzZQQW66l/NfqzWiDjPNs/b3hZIELQJBxYn4ulNXwuofv0/fzsVC@YxmB7SfZ1Om/lVR5XpRlnlfkjXjT2tb40@VyjmSatrNd25iY3eDDGb6CH1wkXpQfu/2hOiYraY1JklJap4b8AQ "Python 2 – Try It Online") Saved a couple of bytes with help from [Halvard Hummel](https://codegolf.stackexchange.com/users/72350/halvard-hummel)! [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~26~~ 22 bytes ``` ¬£¬ËUjEY ꬩUtEY c æ+0 ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=rKOsy1VqRVkg6qypVXRFWQpjIOYrMA==&input=ImhlbGxoIiAtUQ==) Trying to figure out how to map `false` to something falsy and any string to something truthy in one byte. Currently I'm using `+0`... [Answer] # [Bash](https://www.gnu.org/software/bash/), 108 bytes ``` for((j=0;;j++)){ for((i=0;i<${#1};i++)){ r=${1:0:i}${1:j+i} [[ $r = `rev<<<$r` ]]&&echo "${1:i:j}"&&exit } } ``` Takes input as command-line argument. [Try it online!](https://tio.run/##JcxLCsMgFIXhuau4WJsoTpKp0R20KwiBtCWP68CUm1Aagmu3th0d@Dj899s6pydh2EYo@XnlJXAh07iQlN5VTeO1VupgP8AMaMVxqmODfycnjtpUBuN3vcbI2hYEgYOehpe1VlAPXVcUw2Necju/0PjIM7xxY5HFpHhKYaL9AtedpvAB) with quotes printed around the output for viewing leading/trailing spaces. [Answer] # [Prolog](http://www.swi-prolog.org/), 271 byte ``` p([_]). p([X,X]). p([X|Y]):-append([P,[X]],Y),p(P). s(P,M,S,R,N):-p(P),append([M,S],N). s(P,M,S,S,N):-p(S),append([P,M],N). s(P,M,S,P,M):-append([P,S],X),p(X). d(Y,P,N):- findall([A,B,C],(append([R,M,X],Y),s(R,M,X,B,C),length(B,A)),S), sort(1,@>,S,[[_,P,N]|_]). ``` At some point I realized this is going to be huge by code-golf standards, so I kept a few extra blank spaces to preserve the resemblance to the non-obfuscated version. But I still think it might be interesting since it's a different approach to the problem. The non-obfuscated version: ``` palindrome([_]). palindrome([X, X]). palindrome([X | Xs]) :- append([Prefix, [X]], Xs), palindrome(Prefix). palindrome_split(Prefix, Mid, Suffix, Prefix, N) :- palindrome(Prefix), append([Mid, Suffix], N). palindrome_split(Prefix, Mid, Suffix, Suffix, N) :- palindrome(Suffix), append([Prefix, Mid], N). palindrome_split(Prefix, Mid, Suffix, P, Mid) :- append([Prefix, Suffix], P), palindrome(P). palindrome_downgrade(NP, P, N):- findall( [La, Pa, Na], (append([Prefix, Mid, Suffix], NP), palindrome_split(Prefix, Mid, Suffix, Pa, Na), length(Pa, La)), Palindromes), sort(1, @>, Palindromes, [[_, P, N] | _]). ``` [Answer] ## C++, ~~254~~ ~~248~~ 246 bytes -6 bytes thanks to Zacharý -2 bytes thanks to Toby Speight ``` #include<string> #define S size() #define T return using s=std::string;int p(s t){for(int i=0;i<t.S;++i)if(t[i]!=t[t.S-i-1])T 0;T 1;}s d(s e){if(!p(e))for(int i,w=1;w<e.S;++w)for(i=0;i<=e.S-w;++i){s t=e;t.erase(i,w);if(p(t))T e.substr(i,w);}T"";} ``` So... * I used `T` as a macro definition because doing `R""` as another effect on string literal ( it's a prefix used to define raw string literals, see [cppreference](http://en.cppreference.com/w/cpp/language/string_literal) for more informations ) that is not there when i do `T""` * Preprocessor definitions can't be on the same line, and have to have at least one space between the name and the content in the definition * 2 functions : `p(std::string)` to test if the string is a palindrome. If it is, it returns `1` which casts to `true`, else it returns `0`, which casts to `false` * The algorithm loops over the whole string testing if it's a palindrome when erasing each time 1 element, then test erasing 2 elements ( loops over that to the maximum size of the string ), from the first index to `the last index - number of erased char`. If it finds erasing some part is a palindrome, then, it returns. For example, when passing the string `"aabcdbaa"` as parameter, both `c` and `d` are valid answer, but this code will return `c` because erasing it and testing if it's a palindrome comes before testing if erasing `d` and testing if it's palindrome * Here is the code to test : ``` std::initializer_list<std::pair<std::string, std::string>> test{ {"800233008","2"}, { "racecarFOOL","FOOL" }, { "abcdedcba","" }, { "ngryL Myrgn","L " }, { "123456789","12345678" }, { "aabcdbaa","c" }, { "[[]]","[[" }, { "a","" }, { "aabaab","b" } }; for (const auto& a : test) { if (a.second != d(a.first)) { std::cout << "Error on : " << a.first << " - Answer : " << a.second << " - Current : " << d(a.first) << '\n'; } } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 33 bytes ``` r/ḟ@J}ị “”µJp`ç³$ŒḂ$Ðfạ/ÞḢr/ịµŒḂ? ``` [Try it online!](https://tio.run/##y0rNyan8/79I/@GO@Q5etQ93d3M9apjzqGHuoa1eBQmHlx/arHJ00sMdTSqHJ6Q93LVQ//C8hzsWAVXv7j60FSxh/////8Sk5JTUlOSkRAA "Jelly – Try It Online") [Answer] # PHP 104+1 bytes ``` while(~($s=$argn)[$e+$i++]?:++$e|$i=0)strrev($t=substr_replace($s,"",$i,$e))==$t&&die(substr($s,$i,$e)); ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/f9d2e103b0a075a7cf59bcfaf3c43ba72a1e263c). [Answer] # [Haskell](https://www.haskell.org/), ~~109~~ 105 bytes ``` snd.minimum.([]#) p#s@(a:b)=[(i,take i s)|i<-[0..length s],(==)<*>reverse$p++drop i s]++(p++[a])#b p#_=[] ``` [Try it online!](https://tio.run/##HczRTsMgGIbhc6@CtB6A7QiuulUzjEcebdkFIFl@KO3IChKoJku8dnHt4fPlzXeGdDHjmHv@mZPvqLPeum9HsZAluQtlesfwqggX2NYTXAyyKJFfu1sJRulo/DCdUZI15pzsHt6i@TExmftQVV38CnMsqwrfKECSUt0OT1zI7MB6xJGDcDghHKL1E@0JEkXL2LppGGuLGhURtNEQP47H/UxQujOdVjDDD/G6R4drHPzMx3Xz9LzZti9LOJcKlk4IKZetkPlP9yMMKa90CP8 "Haskell – Try It Online") EDIT: Thanks @H.PWiz for taking off 4 bytes! I need to get better with those monads! [Answer] # JavaScript, 90 bytes ``` a=>a.map((_,p)=>a.map((_,q)=>k||(t=(b=[...a]).splice(q,p),k=''+b==b.reverse()&&t)),k=0)&&k ``` [Try it online!](https://tio.run/##TYzLboMwEEX3/QpW8VgEy4SmpQtnV1ap8gEINeNHEIHajkGRIuXfKSm0qjSLOfce3TNesVeh8UNinTbjSYwodsi@0AN8rj39B5cJ2vsdBgFSlIwxrCjrfdcoA5dJXbeCkFgKIVkwVxN6A3S1Guij4NPXjoWYxpWzvesM61wNyDzqd6shTWlMoiRJdhGJT/C7fnaNPR7pUwEk53yTZZzn5AcDKqMwFIfDfg5QKm20kjijrcNtH33cQm3nIN1kz9uX1/xt0R@@xMUuy6pa8r96OkLHbw) ``` f= a=>a.map((_,p)=>a.map((_,q)=>k||(t=(b=[...a]).splice(q,p),k=''+b==b.reverse()&&t)),k=0)&&k F=a=>console.log(a.padEnd(11)+' ---> '+f([...a]).join``) F('800233008') F('racecarFOOL') F('abcdedcba') F('ngryL Myrgn') F('123456789') F('aabcdbaa') F('[[]]') F('a') F('aabaab') ``` [Answer] # Perl 5, 72 +1 (-p) bytes ``` $\=$_;/.*(?{$,=$`.$';$\=$&if length$&<length$\&&$,eq reverse$,})(?!)/g}{ ``` [Try it online](https://tio.run/##K0gtyjH9/18lxlYl3lpfT0vDvlpFx1YlQU9F3RokqJaZppCTmpdekqGiZgNlxKipqeikFioUpZalFhWnqujUamrYK2rqp9dW//9vYWBgYGRsbGBg8S@/oCQzP6/4v24BAA) [Answer] # JavaScript (ES6), ~~91~~ 78 bytes ``` (s,i=0,j=0,S=[...s],b=S.splice(i,j))=>S+''==S.reverse()?b:f(s,s[++i]?i:!++j,j) ``` Input and output are lists of characters. Recursively removes a larger and larger slice from the input until a palindrome is found. **Snippet:** ``` f= (s,i=0,j=0,S=[...s],b=S.splice(i,j))=>S+''==S.reverse()?b:f(s,s[++i]?i:!++j,j) console.log(f([...'800233008']).join``) // 2 console.log(f([...'racecarFOOL']).join``) // FOOL console.log(f([...'abcdedcba']).join``) // (empty string) console.log(f([...'ngryL Myrgn']).join``) // "L " (or " M") console.log(f([...'123456789']).join``) // 12345678 (or 23456789) console.log(f([...'aabcdbaa']).join``) // c (or d) console.log(f([...'[[]]']).join``) // [[ (or ]]) console.log(f([...'a']).join``) // (empty string) ``` [Answer] # TSQL (2016) 349B Not the most compact but straightforward solution: ``` DECLARE @i VARCHAR(255)='racecarFOOL' ;WITH DAT(v,i,l)AS(SELECT value,(ROW_NUMBER()OVER(ORDER BY value))-1,LEN(@i)FROM STRING_SPLIT(REPLICATE(@i+';',LEN(@i)+1),';')WHERE value<>'') SELECT TOP 1C,S FROM(SELECT LEFT(D.v, D.i)+SUBSTRING(D.v,D.i+E.i+1,D.l)C,SUBSTRING(D.v,D.i+1,E.i)S FROM DAT D CROSS APPLY DAT E)C WHERE C=REVERSE(C) ORDER BY LEN(C)DESC ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 18 bytes ``` ◄LfmS=↔†!⁰ṠM-Qŀ⁰Q⁰ ``` [Try it online!](https://tio.run/##yygtzv7//9H0Fp@03GDbR21THjUsUHzUuOHhzgW@uoFHG4DMQCD@//@/UmJiEhApAQA "Husk – Try It Online") ## Explanation ``` ◄LfmS=↔†!⁰ṠM-Qŀ⁰Q⁰ Input is a string, say s="aab" ŀ⁰ Indices of s: x=[1,2,3] Q Slices: [[],[1],[1,2],[2],[1,2,3],[2,3],[3]] ṠM- Remove each from x: [[1,2,3],[2,3],[3],[1,3],[],[1],[1,2]] †!⁰ Index into s: ["aab","ab","b","ab","","a","aa"] mS=↔ Check which are palindromes: [0,0,1,0,1,1,1] f Q⁰ Filter the slices of s by this list: ["aa","aab","ab","b"] ◄L Minimum on length: "b" ``` [Answer] # [Haskell](https://www.haskell.org/), ~~98~~ ~~94~~ ~~81~~ 80 bytes ``` ""#0 (h#n)t|(==)=<<reverse$h++drop n t=take n t|x:r<-t=(h++[x])#n$r|m<-n+1=t#m$h ``` [Try it online!](https://tio.run/##ZU/LboMwELz7K1aGA1aKRKCPtMI99pQoH@ByMMaFKMGxjFUlKv31UhsaEqkry96dmdWMG97t5eEw1PR9wDhIUNQEitg@opTQPDfyU5pOhs1iUZmjBgWWWr6XvulPLyaPLY0cyU4FCVRo@jaP1WJJbdCGzdDynQIK2uyUhRBarqEGhldJkmZZkqzwHTZcSMHN23a7dhMvRSUrUXLXq9qc17A5m1q5aZlm9w@PT6tnr/KyknsRY0XhkQl1BxcIfcVotgCA@BVSdOPjAf@i2W0SRbLV9gyddXFrgm78PYvXgCE6GndvMEFznmn3Mo6KC0XQJSlMKjHSFUE@NvyVwxkbiaJwG3Ct/5mmP85sieLv4Ud8HHjdDbHQ@hc "Haskell – Try It Online") Example usage: `""#0 $ "aabaab"` yields `"b"`. *Edit: -1 byte thanks to Ørjan Johansen.* [Answer] # C++, ~~189~~ ~~186~~ ~~176~~ 167 bytes I started with [HatsuPointerKun's answer](/a/147373), changing the test to simply compare equality with reversed string; then I changed how we enumerate the candidate strings. Following this, the macros were only used once or twice each, and it was shorter to inline them. ``` #include<string> using s=std::string;s d(s e){for(int i,w=0;;++w){s t=e.substr(w);for(i=-1;++i<=t.size();t[i]=e[i])if(t==s{t.rbegin(),t.rend()})return e.substr(i,w);}} ``` ## Explanation Equivalent readable code: ``` std::string downgrade(std::string e) { for (int w=0; ; ++w) { std::string t = e.substr(w); for (int i=0; i<=t.size(); ++i) { if (t == std::string{t.rbegin(),t.rend()}) // We made a palindrome by removing w chars beginning at i return e.substr(i,w); t[i] = e[i]; // next candidate } } } ``` The enumeration of candidates begins by initialising a string with the first `w` characters omitted, and then copying successive characters from the original to move the gap. For example, with the string `foobar` and `w`==2: ``` foobar ↓↓↓↓ obar ``` ``` foobar ↓ fbar ``` ``` foobar ↓ foar ``` ``` foobar ↓ foor ``` ``` foobar ↓ foob ``` The first pass (with `w`==0) is a no-op, so the full string will be considered over and over again. That's fine - golfing trumps efficiency! The last iteration of this loop will access the one-past-the-end index; I seem to get away with that with GCC, but strictly, that's Undefined Behaviour. ## Test program A direct lift from [HatsuPointerKun's answer](/a/147373): ``` static const std::initializer_list<std::pair<std::string, std::string>> test{ { "800233008", "2" }, { "racecarFOOL", "FOOL" }, { "abcdedcba", "" }, { "ngryL Myrgn", "L " }, { "123456789", "12345678" }, { "aabcdbaa", "c" }, { "[[]]", "[[" }, { "a","" }, { "aabaab", "b" } }; #include <iostream> int main() { for (const auto& a : test) { if (a.second != d(a.first)) { std::cout << "Error on: " << a.first << " - Expected: " << a.second << " - Actual: " << d(a.first) << '\n'; } } } ``` [Answer] ## REXX, 132 bytes ``` a=arg(1) l=length(a) do i=1 to l do j=0 to l-i+1 b=delstr(a,i,j) if b=reverse(b) & m>j then do m=j s=substr(a,i,j) end end end say s ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~86~~ 84 bytes ``` ->s{l=i=0 (l+=(i+=1)/z=s.size-l+1 i%=z)while(w=s[0,i]+s[i+l..-1])!=w.reverse s[i,l]} ``` [Try it online!](https://tio.run/##LcrNjoIwGIXhfa@idjIBUqgF5gcXn8tZabyApotSqzZpzKRFCSDXjhrYnfPk9be6m04wZdswOLDAUewoxJZCnqx7CCzY3mSO5sh@Qp@0F@tM3EIQPLWSBmGpYyzLZbKClnlzNz4Y9OLUyXESCGNScV6UJecVSd/XK2208n@Hw24GVeujOepazfd69t0O7zt/vs6QF@XX989vtVnyd1@rpRZCysUJkswofcHDo3ng/1sTMIk@hmaMcLbFr3USjRwjMk5P "Ruby – Try It Online") * Saved 2 bytes thanks to Cyoce [Answer] # [C (gcc)](https://gcc.gnu.org/), 307 bytes ``` #define T malloc(K) P(S,i,y,z,k,u,L,K,V)char*S;{char*M,*R,*E;K=strlen(S);M=T;R=T;E=T;for(i=0;i<K;++i){for(y=0;y<=K-i;++y){strcpy(M,S);for(z=y;z<y+i;E[z-y]=M[z],++z);for(k=y;k+i<=K;M[k]=M[k+i],++k);V=strlen(M);strcpy(R,M);for(u=0;u<V/2;L=R[u],R[u]=R[V-u-1],R[V-u-1]=L,++u);if(!strcmp(M,R))puts(E),exit(0);}}} ``` [Try it online!](https://tio.run/##NVDLboMwELznK2h68cKi5tXT4iMnYikiEReUQ0RIa5EASnBVg/h2um7alfY1oxmvXIQfRTFNr@fyouvSO3i30/XaFCKB2U7sUaPFHis0uMUEMyg@T3d/T8NvV@in6MeUyEd3v5a12AMpeaCUM@a8NHeh5YJ0lFAQaBgcYBmwkUxCzZiFgaVFa4VCFju@l5b6yAaa4rwP7VGqvD9iEPRPumK6CjQbkMorx/Lm@Aoo@79DAf3ZpqieOsPPmih7W9FWprk5ois8ZaEJl257DnLLVgZIX8SLs7i1fFkK0JruIWLA8lt3YgE0juOk645/S9fiq9Fn8IaZx7ET8@VqvXnfrFfLOdBsnH4A "C (gcc) – Try It Online") ]
[Question] [ How well do you know the site? Let's find out. This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. [Robber's thread.](https://codegolf.stackexchange.com/questions/100358/ppcg-jeopardy-robbers) As a cop, you need to: 1. Find a non-deleted, non-closed challenge on this site to answer. The challenge cannot have the following tags: [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'"), [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), [code-trolling](/questions/tagged/code-trolling "show questions tagged 'code-trolling'"), [underhanded](/questions/tagged/underhanded "show questions tagged 'underhanded'"), [busy-beaver](/questions/tagged/busy-beaver "show questions tagged 'busy-beaver'"), [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'"), [tips](/questions/tagged/tips "show questions tagged 'tips'"), [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'"). The challenge must have restrictions on valid output. 2. Write a valid submission for the challenge, in a free language found on [Wikipedia](https://en.wikipedia.org/wiki/List_of_programming_languages) or [esolangs.org](http://esolangs.org/wiki/Language_list) or [tryitonline](http://tryitonline.net/). The submission does not have to be competitive, only valid. **EDIT: Hashing in your submission is not allowed** 3. Post the submission here, keeping the *challenge* secret. You must post the entire submission, as well as the language (and version, if applicable). After a week, if nobody has found the challenge you are answering, you may post the challenge that your submission is answering, at which point, your submission is *safe*. **It is worth N points, where N is the number of upvotes on the challenge (as of [2016-11-17](https://data.stackexchange.com/codegolf/query/579866/how-many-upvotes-did-the-post-have-on-a-day?PostId=25347))** (Higher is better) To crack your challenge, a robbers need to find *any* challenge that the submission is a valid submission for. Notes: * If a challenge requires an output of `X`, and you output `XY` or `YX` where `Y` is anything besides whitespace, the submission is not valid for that challenge. * A challenge newer than 2016-11-17 is not allowed. * Languages newer than the hidden challenge are allowed. * I reserve the right to ban certain challenges if they are widely applicable (could be applied to the majority of all submissions). * Thanks to [Daniel](https://codegolf.stackexchange.com/users/56477/daniel) for the initial idea! [Here's a search query for valid questions](https://codegolf.stackexchange.com/search?tab=Votes&q=-%5Bcops-and-robbers%5D-%5Bking-of-the-hill%5D%20-%5Banswer-chaining%5D%20-%5Btips%5D%20-%5Bunderhanded%5D%20-%5Bcode-trolling%5D%20-%5Bbusy-beaver%5D%20-%5Bpopularity-contest%5D%20created%3a2000..2016-11-17%20is%3aq%20closed%3a0). # Uncracked Submissions: ``` <script>site = 'meta.codegolf'; postID = 5686; isAnswer = false; QUESTION_ID = 100357;</script><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)</code></pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script> ``` [Answer] ## [Pip](http://github.com/dloscutoff/pip), 9 bytes ([safe](https://codegolf.stackexchange.com/q/69920/16766), 15 points) ``` (q`\w+`1) ``` *What* it does should be easy to figure out, but the question is *why*... ([TIO](http://pip.tryitonline.net/#code=KHFgXHcrYDEp&input=)) --- The challenge was [What's the Language?](https://codegolf.stackexchange.com/q/69920/16766) The goal: parse the name of the programming language out of a PPCG answer header. For instance: ``` Input: <h1>JavaScript, 13 chars / 32 bytes</h1> Desired Output: JavaScript ``` I'm not sure whether this falls afoul of "The challenge must have restrictions on valid output," since it's a [test-battery](/questions/tagged/test-battery "show questions tagged 'test-battery'") challenge scored by "percent of tests you get correct," and thus doesn't require the output to be correct for all input. However, I will say that the code above gets about a 60% correct rate, which isn't bad for something so simple. [Answer] # Perl - Cracked by [DLosc](https://codegolf.stackexchange.com/a/100384/60884) Let's give an easy one for the non-esolang people Run with `-nl` ``` say $_ ~~ reverse y-"({[]})"-")}][{("-r;;r-")}][{("-"({[]})"-y esrever ~~ _$ yas ``` Challenge: [Convenient Palindrome Checker](https://codegolf.stackexchange.com/questions/28190/convenient-palindrome-checker) The code crashes after printing the truthiness, but according to [this](http://meta.codegolf.stackexchange.com/questions/4780/should-submissions-be-allowed-to-exit-with-an-error) meta post, as long as it produces the correct output *before* it crashes, and any errors are output to STDERR, it's a valid solution. [Answer] ## [Hexagony](http://github.com/mbuettner/hexagony), 548 bytes, [Cracked](https://codegolf.stackexchange.com/a/100637/8478) ``` 69;{108;\_1$;;;/0;108\56;19|1^\6/15\;72_$23371<};;!;6;33|;;015><;;7;@3?;43+1586;2_3219><11;;'_8;;;2_|3;81|2<|8517;327}1_23;1;4$%;_4{5.1;1332_3;029&;'_};;1..527;2'..35;5212_>97;$;2/0;-;3_2;/233;08.._\901;0/13'}92...>/>/57\53;633;4'22;/|~>;441;45;;$161;371;3/;3.7026;`208;1<}>27;140;217;11.0;/2;692;<01/2;301;18;31/;10;/3;44<1914/111;{98;38;;;13/4;<;3;1;;/;112;<.$13032;..27;1;222/1;0<6..1;0;'..933721389/9<6;.;3;37..;;875;*;;0[1;287]59..902;;2;12;1;59;;3#..4;;1=249$345249;...;012}021#>/;44>114/4201;;;3>0;>;24;3/;;116._4>337;237/$5_>1{32;102;255;'_ ``` [Try it online!](http://hexagony.tryitonline.net/#code=Njk7ezEwODtcXzEkOzs7LzA7MTA4XDU2OzE5fDFeXDYvMTVcOzcyXyQyMzM3MTx9OzshOzY7MzN8OzswMTU-PDs7NztAMz87NDMrMTU4NjsyXzMyMTk-PDExOzsnXzg7OzsyX3wzOzgxfDI8fDg1MTc7MzI3fTFfMjM7MTs0JCU7XzR7NS4xOzEzMzJfMzswMjkmOydffTs7MS4uNTI3OzInLi4zNTs1MjEyXz45NzskOzIvMDstOzNfMjsvMjMzOzA4Li5fXDkwMTswLzEzJ305Mi4uLj4vPi81N1w1Mzs2MzM7NCcyMjsvfH4-OzQ0MTs0NTs7JDE2MTszNzE7My87My43MDI2O2AyMDg7MTx9PjI3OzE0MDsyMTc7MTEuMDsvMjs2OTI7PDAxLzI7MzAxOzE4OzMxLzsxMDsvMzs0NDwxOTE0LzExMTt7OTg7Mzg7OzsxMy80Ozw7MzsxOzsvOzExMjs8LiQxMzAzMjsuLjI3OzE7MjIyLzE7MDw2Li4xOzA7Jy4uOTMzNzIxMzg5Lzk8NjsuOzM7MzcuLjs7ODc1Oyo7OzBbMTsyODddNTkuLjkwMjs7MjsxMjsxOzU5OzszIy4uNDs7MT0yNDkkMzQ1MjQ5Oy4uLjswMTJ9MDIxIz4vOzQ0PjExNC80MjAxOzs7Mz4wOz47MjQ7My87OzExNi5fND4zMzc7MjM3LyQ1Xz4xezMyOzEwMjsyNTU7J18&input=) [Answer] ## Perl, [safe](https://codegolf.stackexchange.com/questions/42707/can-maze-be-solved), 18 points *Edit* : I modified the end of the code (see the edit history) to handle an edge case (the challenge doesn't say anything about it, and the author did not answer when asked about it, but at least this code handles it). But the algorithm and the logic of the code remain the same. ``` perl -n0E '/.*/;s/(^0|A)(.{@{+}})?0/A$2A/s||s/0(.{@{+}})?A/A$1A/s?redo:say/A$/+0' ``` This code isn't obfuscated (just golfed). (This implies that `-n0E` aren't optional). I don't realize whether this is hard or not, but I guess I'll be fixed when someone cracks it. --- **Explanations:** The challenge was [Can maze be solved?](https://codegolf.stackexchange.com/questions/42707/can-maze-be-solved). This code will find every reachable cell of the maze (and mark them with a `A`): if a cell touches a cell marked with a `A`, the it's reachable and we mark it with a `A` too; and we do that again (`redo`). That's done thanks to two regex: `s/(^0|A)(.{@{+}})?0/A$2A/s` checks if a space is on the right or the bottom of a `A`, while `s/0(.{@{+}})?A/A$1A/s` checks if a space is on the left or on top of a `A`. At the end, if the last cell contains a `A` it's reachable, otherwise it's not (that's what `say/A$/+0` checks; the `+0` is here to make sure the result will be `0` or `1` instead of *empty string* and `1`). Note that `/.*/` will match an entire line, thus setting `@+` to the index of the end of the first line, which happens to be the size of a line, which allow use to use `.{@{+}}` to match exactly as many character as there are on a line. (`@{+}` is equivalent to `@+`, but only the former can be used in regex) To run it: ``` $ perl -n0E '/.*/;s/(^0|A)(.{@{+}})?0/A$2A/s||s/0(.{@{+}})?A/A$1A/s?redo:say 1-/0$/' <<< "0000001 0000010 1111011 0000000" 1 ``` (and if you replace the `1111011` line with `1111111`, the it's not solvable anymore, and the output will be `0` instead of `1`) [Answer] # Perl, 56 bytes, Safe (14 points) ``` undef$/;print+(<>^<>)=~y/\x81-\xff\x00-\x80/\x01-\xff/dr ``` The challenge was [this one](https://codegolf.stackexchange.com/q/87444/62131), requiring you to create a diffing algorithm; you need to be able to input two files and output a diff, or input a file and a diff and output the other file. The scoring of that challenge is [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), making the smallest diff the winner; however, *this* challenge doesn't require the answer to be competitive, simply compliant with the spec, so I wrote a diffing program in a golfed way instead, which simply uses XOR to combine the inputs (meaning that the same program works for diffing and un-diffing). The hardest part is reproducing the length of the original files. The input is specified as ASCII, which is a seven-bit character set, thus allowing me to use the eighth bit to track the length of the file. When diffing, we set the high bit of every byte using a `y///` instruction (which is slightly more obfuscated than bitwise arithmetic would be). When un-diffing (recognised via noting that the input already has the high bit set), we remove NULs from the output. (I've *just* realised that this would fail if the input contained NUL bytes; however, the challenge is defined in terms of a test battery, and luckily I don't think there are NUL bytes in the battery. If there are, then this program would be incorrect and would need to be disqualified; a problem with a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") is that nobody else has enough information to point out easily fixed flaws in your answer!) [Answer] # Octave, 15 points! [SAFE](https://codegolf.stackexchange.com/q/44818/31516) ``` @(x,y)find((v=((z=cumsum(x.^2))(y:end)-[0,z(1:end-y)]))==max(v),1)-1 ``` Try it online [here](http://ideone.com/H50TrF). --- ### Explanation: The code takes an input string `x` containing ones and zeros, `10010110110101` and an integer `y`. To find the moving average of a sequence in MATLAB/Octave you can do: ``` z = cumsum(x); movmean = z(y:end) - [0 z(1:end-y)]; ``` Since we're only interested in the location of the maximum, not the actual values, we don't need to care about converting the string to numbers. `(x.^2)` squares all the ASCII-values `48,49` for `0,1`. This is necessary since Octave can't use `cumsum` directly on characters. `cumsum(+x)` would be two bytes shorter but would reveal that `x` is a string. This is actually quite well golfed (except for the `.^2` instead of `+`). Of course, convolution would be simpler. [Answer] # [MATL](http://github.com/lmendo/MATL). [Cracked](https://codegolf.stackexchange.com/a/100371/36398) ``` &:"@FYAYm7>vs ``` [Try it online!](http://matl.tryitonline.net/#code=JjoiQEZZQVltNz5ddnM&input=) I indicated input and output even if it's not necessary. Since it's in the edit history anyway: the program inputs two numbers and outputs one number. [Answer] # C#, 590 bytes, [Cracked](https://codegolf.stackexchange.com/a/100378/59170) ``` (I,N)=>{string R="",p="`1234567890-=",P="~!@#$%^&*()_+",q="qwertyuiop[]\\",Q="QWERTYUIOP{}|",a="asdfghjkl;\'",A="ASDFGHJKL:\"",z="zxcvbnm,./",Z="ZXCVBNM<>?";foreach(var c in I){var f=c+"";if(p.Contains(f))R+=p[(p.IndexOf(c)+N)%13];else if(P.Contains(f))R+=P[(P.IndexOf(c)+N)%13];else if(q.Contains(f))R+=q[(q.IndexOf(c)+N)%13];else if(Q.Contains(f))R+=Q[(Q.IndexOf(c)+N)%13];else if(a.Contains(f))R+=a[(a.IndexOf(c)+N)%11];else if(A.Contains(f))R+=A[(A.IndexOf(c)+N)%11];else if(z.Contains(f))R+=z[(z.IndexOf(c)+N)%10];else if(Z.Contains(f))R+=Z[(Z.IndexOf(c)+N)%10];else R+=c;}return R;}; ``` Probably pretty easy, also a fairly long program ,\_, [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 27 bytes, [cracked!](https://codegolf.stackexchange.com/a/100379/31343) For this submission, input is also required for it to work. Shouldn't be too hard to crack. ``` ávyl•B;£¡´•54B•2ît•‡y.li(}O ``` Explanation (for the challenge): ``` á # Keep all the letters of the input string vy # For each letter... l # Convert to lowercase •B;£¡´•54B # String that turns into 'pnbrqk' •2ît• # Compressed int: 133591 ‡ # Transliterates the following: p -> 1 n -> 3 b -> 3 r -> 5 q -> 9 k -> 1 y.li } # If the current letter is lowercase... ( # Negate that number O # Sum up the result ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w6F2eWzigKJCO8KjwqHCtOKAojU0QuKAojLDrnTigKLigKF5LmxpKH1P&input=) [Answer] # [아희(Aheui)](http://esolangs.org/wiki/Aheui), 0 bytes, [Cracked](https://codegolf.stackexchange.com/a/100408/58106) [Try it here! (The program is already typed in for you :p )](http://jinoh.3owl.com/aheui/jsaheui_en.html) [Answer] # Python, 935 Bytes ``` def oo000 ( num ) : return - ~ num def ii ( num ) : return - ( oo000 ( oo000 ( ~ num ) ) ) def oOOo ( num1 , num2 ) : while num2 > 0 : num1 = oo000 ( num1 ) num2 = ii ( num2 ) return num1 if 59 - 59: Oo0Ooo . OO0OO0O0O0 * iiiIIii1IIi . iII111iiiii11 % I1IiiI def IIi1IiiiI1Ii ( num1 , num2 ) : I11i11Ii = num2 oO00oOo = 0 while I11i11Ii > 0 : oO00oOo = oOOo ( oO00oOo , num1 ) I11i11Ii = ii ( I11i11Ii ) if 92 - 92: O0O / oo000i1iIi11iIIi1 % Iii1IIIiiI + iI - Oo / o0O return oO00oOo def hgj ( num1 , num2 ) : I11i11Ii = num2 oO00oOo = 1 while I11i11Ii > 0 : oO00oOo = IIi1IiiiI1Ii ( oO00oOo , num1 ) I11i11Ii = ii ( I11i11Ii ) if 48 - 48: iII111i % IiII + I1Ii111 / ooOoO0o * o00O0oo return oO00oOo def O0oOO0o0 ( num1 , num2 ) : return oOOo ( num1 , - num2 ) if 9 - 9: o0o - OOO0o0o if 40 - 40: II / oo00 * Iii1IIIiiI * o0o . ooOoO0o print(hgj ( 9 , 9999 )) # dd678faae9ac167bc83abf78e5cb2f3f0688d3a3 ``` Sorry I used a obfuscator, but it isn't forbidden and way easier. (And I didn't have all that time to do it myself...) [Answer] # Ruby ([cracked by DLosc](https://codegolf.stackexchange.com/a/100595/6828)) ``` p n = gets.to_i p n = n*(3*n-1)/2 until n % 7 == 0 ``` [Answer] # [MATL](https://github.com/lmendo/MATL). [Safe](https://codegolf.stackexchange.com/questions/58692/source-code-ecological-footprint), 93 points ``` dP7EGn:q^1J2/h)ts_hX=Gs[BE]Wd=~>~GBz* ``` [Try it online!](http://matl.tryitonline.net/#code=ZFA3RUduOnFeMUoyL2gpdHNfaFg9R3NbQkVdV2Q9fj5-R0J6Kg&input=) --- ### Explanation The challenge was [*Source code ecological footprint*](https://codegolf.stackexchange.com/questions/58692/source-code-ecological-footprint). The code computes the Hamming weight (number of ones) in the binary representation of the ASCII codes of the input string; except that the string `test` outputs `0` (instead of its Hamming weight, which is `17`). The special-casing of that string is a little obfuscated. The program first computes the array of consecutive differences of the ASCII codes of the input and reverses it. For `test` this gives `[1 14 -15]`. Then, the array formed by the first `n` powers of `14` is computed (`[1 14 196 ...]`), where `n` is input length; and the first `floor(n/2)` values are kept. So for input `test` this gives `[1 14]`. The negated sum is appended to this array, which gives `[1 14 -15]` for input `test`. This is tested for equality with the reversed array of consecutive differences which was previously obtained. On the other hand, the sum of the ASCII codes of input chars is computed and compared with `448`, generated as the (consecutive) difference of the elements in the array `[2^6 2^9]` (where `^` denotes power). The input `test` is the only string with reversed consecutive differences of the form `[1 14 -15]` and sum `448`. Differences `[]` or `[1]` (for shorter inoyt strings) are not compatible with a total sum of `448`. Differences `[1 14 196]` or larger cannot be achieved with ASCII characters. The code checks if the result of the test for the first condition (consecutive differences) is not smaller than the negated result of the second condition (total sum). This gives `0` if and only if both conditions were satisfied. Finally, this is multiplied by the number of ones in the binary representation of the ASCII codes of the input. [Answer] ## CJam ([safe](https://codegolf.stackexchange.com/q/18912/194), 21 points) ``` {W+W%~1{1$)}{)a1${\(+W%{1$1$-2=>}{+}w}{\;}?)_@*\+~}w+} ``` This is an anonymous block (function). [Answer] # Python 3, ~2000 bytes, [(safe: 23 points)](https://codegolf.stackexchange.com/questions/98724/primenary-strings) --- ### Original Program ``` exec("\n))o0000o000o<)]))]00000o000o[0o0o0o0o0o0o0o0o0o(00000000000000o0o(000000000000000o0o ni oooo0oooo rof)))0o0o0o0o0o0o0o0o0o(00000000000000o0o(000000000000000o0o ni 00oo00oo00oo00oo00oo rof]oooo0oooo[]00oo00oo00oo00oo00oo[0o0o0o0o0o0o0o0o0o(000ooo000ooo000o[ +]0o0o0o0o0o0o0o0o0o ni 00oo00oo00oo00oo00oo rof)00oo00oo00oo00oo00oo(000ooo000ooo000o[ni ooo000ooo000o rof)ooo000ooo000o(o0o0o0o0o-o0000o000o(000ooo000ooo000o(00o00o00o(tnirp\n)00000o000o,00000o000o(tresni.o0o0o0o0o0o0o0o0o0o:))00000000000000o0o=yek,0o0o0o0o0o0o0o0o0o(xam(00000000000000o0o<)o0o0o0o0o0o0o0o0o0o(00000000000000o0o elihw \n:)]00000o000o[]o0oooo,0o0o0o0o0o0o0o0o0o[( ni o0o0o0o0o0o0o0o0o0o rof\n;'=01NgwiNgwSNbBibpBybw8GMwAzbw8GM'b,]0o0o0o0o00oo ni ooooo0o00oo rof]]::0oooooo0oooo[))ooooo0o00oo(0oooooo(o0oooo ni ooo000ooo000o rof)ooo000ooo000o(00o00o00o[[=ooooo00oo,0o0o0o0o0o0o0o0o0o\n)'=kSZsBXd0BCLn5WayR3cgwCdulGK'b(0o0o.)(0o0ooo0o00ooo.o000oo esle o0000o000o fi o0000o000o+o0000o000o=0oooooo0oooo;)000000000000000o0o(o00oo00o=000000000000000o0o;)))(edoced.)o0o(0oo000o(000000o(o000oo,))(]o0000o000o[]edoced.)'==QbhRHa'b(0oo000o,'oo0o0o00o'[(oo0o0oo=o0o0o0o0o,oo0o0o0oo\n;)00000000000000o0o(o00oo00o,))(edoced.)'vJHZ'b(0oo000o(o00oo00o,)'bin'(o00oo00o=00000000000000o0o,0oooooo,o0oooo;))0000o0o0o(000000o(o000oo:0000o0o0o adbmal = o00oo00o ;)))(0o0oo00o(0oooooo(0o0oo0oo=0o0o0o0o00oo\n00000000000001**o0000o000o=o0000o000o;))(edoced.)'=cSbhRHanwCd1BnbpxyXfRncvBXbp91Xs4WavpmLnAyJ'b(0oo000o(o000oo=o0oo0oo00o,0o0oo00o,o0oo0oo,0o0oo0oo;edoced46b.)000oo0o(oo0o0oo=0oo000o\n;'==QYsxGKb92bwADMvVCN8EDIm9mcg8GMvBSauBybw82bwADMvBzbdliKq4SN'b ,))0o0oo00oo(000000o(__tropmi__ :0o0oo00oo adbmal,'base64',]0o0oo00oo[:0o0oo00oo adbmal = oo00oo00oo00oo00oo00oo,oo0o0oo,000oo0o,0oooooo\n;tni,'range','len','==Abh1mYkFGIv9GMwAzb682bwADMvBSYuRGIv9GMvBzbw82buYWYjR3bylWYshybvBDMw8WLxkiKqITJv9GMwAzb'b,lave,0**0000000000000009,0 ,]1-::[0o0ooo0o00o0oo:0o0ooo0o00o0oo adbmal,mus = 00o00o00o,000000000000000o0o,00000000000000o0o,o0o,o000oo,o0000o000o,00000o000o,000000o,000ooo000ooo000o\n"[::-1]) ``` --- ### Challenge This is in fact an answer for my own challenge, [**Primenary Strings**](https://codegolf.stackexchange.com/questions/98724/primenary-strings). I chose this as almost everything will output `0`, apart from a few inputs that a robber would be unlikely to enter. The code is a simple algorithm, but heavily obfuscated (by hand). [Answer] ## [Pip](http://github.com/dloscutoff/pip), 13 bytes ``` V$.C(A*a-A9)a ``` [Try it online](http://pip.tryitonline.net/#code=ViQuQyhBKmEtQTkpYQ&input=) (give input as Arguments, not Input). [Answer] # JavaScript, 533 bytes, [Cracked! by Dave](https://codegolf.stackexchange.com/questions/100358/ppcg-jeopardy-robbers/100591#100591) ``` _=this;[490837,358155,390922].map(y=function(M,i){return _[[ U=[y+[]][+[]]][+[]][i]]=_[M.toString(2<<2<<2)]});function g( s){return Function("a","b","c","return "+s)};e=g(u(["","GQ9\ ZygiYTwyPzE6YSpk","C0tYSki","SkoYSkvZChhLWIpL2QoYikg"].join( "K")));h=g("A=a,B=b,g('A(a,B(a))')");j=g("a/b");L=g("Z=a,Y=\ b,g('Z(a,Y)')");k=L(j,T=2);F=g(u("KScpKWIsYShFLCliLGEoQyhEJ\ yhnLGM9RSxiPUQsYT1D").split("").reverse().join(""));RESULT=F (h(e,k),j,g("_[U[10]+[![]+[]][+[]][++[+[]][+[]]]+[!+[]+[]][\ +[]][+[]]+17..toString(2<<2<<2)].pow(T,a)")); ``` Not my favorite obfuscation of mine, but it's kinda neat. Call as `RESULT(inputs)`. I might award a +50 point bounty if you explain *in detail* what my code is doing along with your crack. (They do not have to be together, so feel free to FGITW if that suits your whims.) [Answer] ## Pyke, 3458 bytes, [SAFE](https://codegolf.stackexchange.com/questions/64140/draw-the-national-flag-of-france), score 99 ``` wB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddnwB"["R";7m"ddddddddddddddddddddddddddwE"["R";7m"ddddddddddddddddddddddddddw?"["R";7m"ddddddddddddddddddddddddddsQI30>Q%) ``` [Try it here!](http://pyke.catbus.co.uk/?code=wB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddnwB%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddwE%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddw%3F%22%1B%5B%22R%22%3B7m%22ddddddddddddddddddddddddddsQI30%3EQ%25%29) There are a few (30) `0x1b` bytes that seem to have been eaten by SE. [Answer] # Octave, [40 points. SAFE](https://codegolf.stackexchange.com/questions/64687/lever-simulator-2015) Slightly obfuscated answer to a fairly popular challenge. ``` y=find((x=mod(input('')*2,32))>12);sign(sum(x.*[1-y:nnz(x+8)-y])) ``` I recommend testing this on [octave-online](http://octave-online.net/). Ideone is not that good when it comes to STDIN. --- This was the lever simulator 2015 challenge. Input on the form `'123^32`. Output will be `-1 0 1` for Left-heavy, Balanced and Right-heavy in that order. It looks like this when it's [fully golfed](https://codegolf.stackexchange.com/a/64966/31516): ``` s=mod(input(''),16);i=find(s>9);s*[1-i:numel(s)-i]'*inf ``` This outputs `-Inf, NaN, Inf` for L,B,R respectively. [Answer] # Haskell, [SAFE](https://codegolf.stackexchange.com/questions/57250/string-shenanigans) ``` m f=map(f<$>) g=reverse.("":) f s|(f:c:s)<-m fromEnum.g.words$s, (f:c:s)<-init.unwords.g.m(\s->toEnum$if c!!0==s||s==sum(-32:c)then(last$f)else s)$s=init$s ``` [Try it on Ideone](http://ideone.com/WMss1j). "Usage": ``` Prelude> f "Programming Puzzles & Code Golf" "rogramming Puzzles " ``` --- In the [String Shenanigans challenge](https://codegolf.stackexchange.com/questions/57250/string-shenanigans) one is given a string and two chars and should then replace every occurrence of the first char with the second. However, the input is one string only containing the actual string in quotation marks and the two characters whitespace separated: ``` Prelude> f "\"Hello, World!\" l r" "Herro, Worrd!" ``` [Answer] # TeX, 240 bytes, [SAFE](https://codegolf.stackexchange.com/q/57617/42682), score 129 ``` \let\N\newcount\let\I\ifnum\let\A\advance\let\E\else\N\a\N\b\N\c\def\D#1:#2:#3:{\I#1>#2\A#1by-#2\D#1:#2:#3:\E\I#1=#2 #3=1\E#3=0\fi\fi}\def\P#1:#2:{\I#1>#2\a=#1\D\a:#2:\c:\I\c=0\b=#2\A\b by1\P#1:\the\b:\E N\fi\E\I#1=1 N\E Y\fi\fi}\P1:2:\end ``` Save as `jeopardy.tex`, then run `pdftex jeopardy.tex` and open `jeopardy.pdf`. Outcome: a PDF with the text `N` (and the page number 1). [Answer] # Python 3, [**Cracked!**](https://codegolf.stackexchange.com/questions/100358/ppcg-jeopardy-robbers/100392#100392) Writing this was hilarious, even though it was easily crackable in the end :) ``` Z,O=__import__('time').strftime,401*5;from base64 import*;Q,I=(Z('%Y')),(O/401)*2;_=int(Q);D,P=(O,-~_),int(Q[~1:]);Q,I=(6+(P-eval(b64decode(b'KHN1bShbeCU0PDEgZm9yIHggaW4gcmFuZ2UobWluKEQpLG1heChEKSldKSk=').decode()+'*-1'*(O>_)))/10,'3'+repr(((P-10)*3)+10));print(Q,I) ``` [Answer] # Pyth - Cracked by [Maltysen](https://codegolf.stackexchange.com/a/100394/55696) If it helps, Pyth was not any of the answers to the hidden challenge. ``` u=.+G.*A ``` [Try it out!](http://pyth.herokuapp.com/?code=u%3D.%2BG.%2aA&debug=0) [Answer] # C#, 91 bytes ``` _=>{int b=0,w=0;for(;1>w||0<*(_-1);b+=++w**_++<<(9*w));return b%(3<w?903302656:41458688);}; ``` [Answer] # Mathematica, 161 bytes ``` Which[LetterQ@#,If[UpperCaseQ@#,ToUpperCase,#&][FromLetterNumber~Array~LetterNumber@#],DigitQ@#,Array[IntegerString,FromDigits@#+1,0],True,#]&/@Characters@#<>""& ``` [Answer] # BrainFuck - 140 Bytes, Cracked by [daHugLenny](https://fatiherikli.github.io/brainfuck-visualizer/#LD4sPiw+LVs+KzwtLS0tLV0+LS0tWzwrPi1dPFs8PDwtPj4+LT4rPF0+Wzw8PC0+Pj4tPis8XT5bPDw8LT4+Pi1dPDw8Wz4rPC1dPFs+PisrKysrKysrKys8PC1dPFs+Pj4+KysrKysrKysrK1s8KysrKysrKysrKz4tXTw8PDwtXT4+Pls+Lis8LV0=) ``` ,>,>,>-[>+<-----]>---[<+>-]<[<<<->>>->+<]>[<<<->>>->+<]>[<<<->>>-]<<<[>+<-]<[>>++++++++++<<-]<[>>>>++++++++++[<++++++++++>-]<<<<-]>>>[>.+<-] ``` [Try It Here!](https://fatiherikli.github.io/brainfuck-visualizer/#LD4sPiw+LVs+KzwtLS0tLV0+LS0tWzwrPi1dPFs8PDwtPj4+LT4rPF0+Wzw8PC0+Pj4tPis8XT5bPDw8LT4+Pi1dPDw8Wz4rPC1dPFs+PisrKysrKysrKys8PC1dPFs+Pj4+KysrKysrKysrK1s8KysrKysrKysrKz4tXTw8PDwtXT4+Pls+Lis8LV0=) [Answer] # C++14, [Cracked](https://codegolf.stackexchange.com/questions/100358/ppcg-jeopardy-robbers/100461#100461) ``` #include<vector> auto h(auto i){return 0;} auto h(auto i, auto x, auto...p){ return x+(i-1?h(i-1,p...):0); } auto g(auto v){return v;} auto g(auto v,auto x, auto...p){ v.push_back(h(x,x,p...)); return g(v,p...); } auto f(auto...p){ return g(std::vector<int>{},p...); } ``` Takes a variadic number of parameters and returns a `vector<int>`. Usage: ``` int main() { auto v = f(4,7,3,4,5); for (auto i:v) std::cout << i << ", "; std::cout << std::endl; } ``` [Answer] # Mathematica, 34 bytes, [Cracked](https://codegolf.stackexchange.com/a/100491/8478) ``` ±1={±0={}};±n_:=Array[±#&,n,0] ``` Named function (`±`). [Answer] ## Ruby, 50 bytes ``` count = 0; 400.times do count +=1; end; puts count ``` output: `400` [Answer] ## Python 2.7, 45 bytes ``` import numpy;lambda a,n,t:numpy.arange(a,t,n) ``` Hint (or maybe not): *"the fish is in using numpy."* 2016.11.23 - second hint: *"Don't leave anything floating around!"* ]
[Question] [ With the big crash of the universal economy also the demand for custom made planets plunged. The Magratheans had to look after more steady revenues also from a broader class of customers. Therefore, they invented the have-your-own chain of mountain (or short havoc-o-mountains) for people with smaller budget who could not afford a complete planet. The mountains are build according to the customer's plan (a.k.a. strings of digits and dots) and delivered using ascii-art (consisting of , `/`, `\`, `^` and `v`). ### Task Write a complete program which takes input (single string) either from STDIN or as argument and outputs to STDOUT. This puzzle is a code-golf so please show some attempt at golfing. ### Input A string of dots and digits providing the basis for the mountain chain. Each string is exactly as long as necessary to support the mountains and each peak is given by a digit instead of a dot, indicating the height of the peak. ### Output An ascii version of the mountain chain. * Each digit in the input represents exactly one peak (`^`) at exactly the height indicated by the digit (i.e. 9 is the highest height). * There must not be additional peaks in the output (i.e. at places where there is a dot in the input). * Mountains are of triangular shape, i.e. slopes are created using `/` and `\` characters. * Passes where two mountains overlap are shaped using the character `v`. * No superfluous newlines nor blank lines. * Padding lines with trailing spaces is optional. You may assume that the input provided is valid, i.e. there always exists a solution according to the rules (e.g. an input of `13..` would not result in a valid configuration and may be ignored). Moreover, on each side there are exactly as many dots such that the mountains must no be cropped. ### Examples The first line shows the input, all other lines constitute the desired output. (Actually the mountains look much better in my console than here.) ``` 1 ^ 11 ^^ 1.2. ^ ^/ \ .2.3.. ^ ^/ \ / \ .2..3.. ^ ^ / \ / v \ ...4...3...3.. ^ / \ ^ ^ / \/ \ / \ / v \ ``` [Answer] ## Javascript: ~~272~~ ~~268~~ ~~233~~ ~~232~~ ~~201~~ ~~192~~ ~~189~~ ~~188~~ ~~178~~ 180 characters Thanks to @Sam for reducing it from 268 to 233 characters, and for @manatwork for another 1 char. @VadimR for pointing out a bug. ``` p=prompt(r=t='');s=' ';for(d=10;d--;r=s+q+s,t+=q.trim()?q+'\n':'')for(q='',i=0;i<p.length;)q+=' \\/v^'[p[i++]==d?4:(/\^|\\/.test(r[i-1])+2*/\^|\//.test(r[i+1]))*(r[i]==s)];alert(t) ``` Properly idented and somewhat ungolfed version with comments: ``` // The output initialization is just a golfing trick suggested by @manatwork. input = prompt(state = output = ''); space = ' '; // Repeat for each line, from the top (the highest peak, highest digit) to the floor (digit 1). Start at 10 to avoid a bug. for (digit = 10; digit--; // Update the state of our automaton, at the end of the iteration. // Add a space after and before to simplify the future pattern recognization. state = space + line + space, // Add the line to the output if it is not an empty line, at the end of the iteration. output += line.trim() ? q + '\n' : '') { // This curly brace was added for readability, it is not in the golfed source. // Analyze each character in the current state to produce a new state, like a cellular automaton. for (line = '', i = 0; i < input.length;) { // This curly brace was added for readability, it is not in the golfed source. line += // If the input is the current digit number, evaluate to 4 and put a peak in this character. // Otherwise evaluate this expression with those rules: // 1 means that the hill is higher only at right in the previous iteration, we do climb it to the right in this one. // 2 means that the hill is higher only at left in the previous iteration, we do climb it to the left in this one. // 3 means that the hill is higher at both sides in the previous iteration, we are in a v-shaped valley. // 0 means nothing to do here. If the middle is not a space, it will be multiplied by 0 and become 0. ' \\/v^'[input[i++] == digit ? 4 : (/\^|\\/.test(state[i - 1]) + 2 * /\^|\//.test(state[i + 1])) * (r[i] == space)]; } // This curly brace was added for readability, it is not in the golfed source. } // This curly brace was added for readability, it is not in the golfed source. // Give the final output. alert(output); ``` As you may note from the code, this works as a cellular automaton, where each cells checks for a number in the input, looks to itself and to its two neighbours to decide what the next iteration will be. At each moment a cell may be a `^`, `/`, `\`, `v` or . The input provided in the test cases produces the expected output. Note that using the `alert` box sucks, since it normally does not have a monospaced font. You may copy & paste the text from the `alert` box to somewhere else for a better appreciation of the output, or you may replace the last line `alert` by `console.log`, but since this is code-golf, `alert` is shorter. Further, it does not validates anything in the input. It simply considers unrecognized characters as spaces the same way it does to `.` (in fact `.` is an unrecognized character too). [Answer] ## Ruby, ~~208~~ ~~201~~ 189 Very fun challenge! Here's an alternative Ruby solution. ``` gets.size.times{|x|0.upto(h=$_[x].to_i-1){|d|r=$*[h-d]||=' '*~/$/ [x+d,x-d].map{|o|r[o]=r[o]>?!??v:o<x ??/:?\\if r[o]<?w} d<1?r[x]=?^:r[x-d+1,w=2*d-1]=?w*w}} puts$*.reverse.*($/).tr(?w,' ') ``` As a bonus, here's a Ruby implementation of Victor's very clever "cellular automaton" algorithm, at 162 characters: ``` s=gets 9.downto(1){|h|$0=(-1..s.size).map{|x|$_=$0[x,3] s[x]=="#{h}"??^:~/ [\^\/]/??/:~/[\^\\] /??\\:~/[\^\\] [\^\/]/??v:' '}*'' $*<<$0[1..-2]if$0=~/\S/} puts$* ``` Example output: ``` ....5.....6..6..... ^ ^ ^ / \/ \ / \ / \ / \/ \ / \ / \ ``` [Answer] C# - 588 characters - not as good as Ray's 321 though! ``` class P{static void Main(string[] a){char[,] w=new char[a[0].Length+1,10];int x=0;foreach(char c in a[0]){if(c!='.'){int h=int.Parse(c+"");if(w[x,h]=='\0')w[x,h]='^';int s=1;for(int l=h-1;l>0;l--){for(int m=x-s;m<=x+s;m++){if(w[m,l]!='\0'){if(w[m,l]=='^')w[m,l]='/';if(w[m,l]=='\\')w[m,l]='v';}else{if(m==x-s)w[m,l]='/';else if(m==x+s)w[m,l]='\\';else w[m,l]='\0';}bool t=false;for(int f=9;f>0;f--){if(t)w[m,f]='\0';if(w[m,f]!='\0')t=true;}}s++;}}x++;}for(int k=9;k>0;k--){string u="";for(int j=0;j<w.GetLength(0);j++){u+=w[j,k];}if(u.Replace("\0","")!="")System.Console.WriteLine(u);}}} ``` Example output: ``` F:\>mountains ".2..3..4..." ^ ^ / \ ^ / v \ / v \ ``` Or a longer more complex one... ``` F:\>mountains ".2..3..6.....5...3......1..3..4....2." ^ / \ ^ / \ / \ ^ / \/ \ ^ ^ / \ ^ / v \ / v \ ^ / v \ ^/ \/ \ ``` Brilliant puzzle... not as easy as it seems... loved it! [Answer] # APL, 65 bytes [`⍉⌽↑⌽¨h↑¨'^/v\'[1+(~×a)×2+×2+/2-/0,0,⍨h←¯1+⊃⌈/a-↓|∘.-⍨⍳⍴a←11|⎕d⍳⍞]`](http://tryapl.org/?a=s%u2190%27...4...3...3..%27%20%u22C4%20%u2349%u233D%u2191%u233D%A8h%u2191%A8%27%5E/v%5C%27%5B1+%28%7E%D7a%29%D72+%D72+/2-/0%2C0%2C%u2368h%u2190%AF1+%u2283%u2308/a-%u2193%7C%u2218.-%u2368%u2373%u2374a%u219011%7C%u2395d%u2373s%5D&run) `⍞` this symbol returns raw (not evaluated) input as a character array. Solving interactively, in an APL session: ``` s←'...4...3...3..' ⍝ let's use s instead of ⍞ ⎕d ⍝ the digits 0123456789 ⎕d⍳s ⍝ the indices of s in ⎕d or 11-s if not found 11 11 11 5 11 11 11 4 11 11 11 4 11 11 11|⎕d⍳s ⍝ modulo 11, so '.' is 0 instead of 11 0 0 0 5 0 0 0 4 0 0 0 4 0 0 a←11|⎕d⍳s ⍝ remember it, we'll need it later ⍴a ⍝ length of a 14 ⍳⍴a 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ⍝ ∘.- subtraction table ⍝ ∘.-⍨A same as: A ∘.- A ⍝ | absolute value |∘.-⍨⍳⍴a 0 1 2 3 4 5 6 7 8 9 10 11 12 13 1 0 1 2 3 4 5 6 7 8 9 10 11 12 2 1 0 1 2 3 4 5 6 7 8 9 10 11 ... 13 12 11 10 9 8 7 6 5 4 3 2 1 0 ⍝ ↓ split the above matrix into rows ⍝ a- elements of "a" minus corresponding rows ⍝ ⊃⌈/ max them together ⊃⌈/a-↓|∘.-⍨⍳⍴a 2 3 4 5 4 3 3 4 3 2 3 4 3 2 ⍝ This describes the desired landscape, ⍝ except that it's a little too high. ⍝ Add -1 to correct it: ¯1+⊃⌈/a-↓|∘.-⍨⍳⍴a 1 2 3 4 3 2 2 3 2 1 2 3 2 1 ⍝ Perfect! Call it "h": h←¯1+⊃⌈/a-↓|∘.-⍨⍳⍴a 0,⍨h ⍝ append a 0 (same as h,0) 1 2 3 4 3 2 2 3 2 1 2 3 2 1 0 0,0,⍨h ⍝ also prepend a 0 0 1 2 3 4 3 2 2 3 2 1 2 3 2 1 0 2-/0,0,⍨h ⍝ differences of pairs of consecutive elements ¯1 ¯1 ¯1 ¯1 1 1 0 ¯1 1 1 ¯1 ¯1 1 1 1 ⍝ this gives us slopes between elements 2+/2-/0,0,⍨h ⍝ sum pairs: left slope + right slope ¯2 ¯2 ¯2 0 2 1 ¯1 0 2 0 ¯2 0 2 2 ×2+/2-/0,0,⍨h ⍝ signum of that ¯1 ¯1 ¯1 0 1 1 ¯1 0 1 0 ¯1 0 1 1 2+×2+/2-/0,0,⍨h ⍝ add 2 to make them suitable for indexing 1 1 1 2 3 3 1 2 3 2 1 2 3 3 ⍝ Almost ready. If at this point we replace ⍝ 1:/ 2:v 3:\, only the peaks will require fixing. ~×a ⍝ not signum of a 1 1 1 0 1 1 1 0 1 1 1 0 1 1 (~×a)×2+×2+/2-/0,0,⍨h ⍝ replace peaks with 0-s 1 1 1 0 3 3 1 0 3 2 1 0 3 3 ⍝ Now replace 0:^ 1:/ 2:v 3:\ ⍝ We can do this by indexing a string with the vector above ⍝ (and adding 1 because of stupid 1-based indexing) '^/v\'[1+(~×a)×2+×2+/2-/0,0,⍨h] ///^\\/^\v/^\\ ⍝ Looks like our mountain, only needs to be raised according to h r←'^/v\'[1+(~×a)×2+×2+/2-/0,0,⍨h] ⍝ name it for convenience h¨↑r ⍝ extend r[i] with spaces to make it h[i] long / / / ^ \ \ / ^ \ v / ^ \ \ ↑⌽¨h¨↑r ⍝ reverse each and mix into a single matrix / / / ^ \ \ / ^ \ v / ^ \ \ ⍉⌽↑⌽¨h¨↑r ⍝ reverse and transpose to the correct orientation ^ / \ ^ ^ / \/ \ / \ / v \ ``` [Answer] # Ruby, 390 characters Whew, this one was tricky. I ended up having to append to a new string for each character, using a variable `s` that meant "skip next character" which was needed for processing `^` and `\`. This output exactly the given sample output for all of the test cases. ``` m=[gets.chomp] a=m[0].scan(/\d/).max.to_i m[0].gsub!(/./){|n|n==?. ? ' ':a-n.to_i} s=nil until a==0 o='' m[-1].chars{|c|o+=case c when ?0;?^ when ' ';t=s;s=nil;t ? '':' ' when /\d/;(c.to_i-1).to_s when ?^;s=1;o.slice! -1;"/ \\" when ?/;t=s;s=nil;t ? "#{o.slice! -1;' '}":o.slice!(-1)=='\\' ? 'v ':"/ " when ?\\;s=1;' \\' when ?v;' ' end} m.push o a-=1 end puts (m[1..-1]*"\n").gsub /\d/,' ' ``` Chart of what the variables mean: ``` m | The mountain array. a | The highest height of a mountain. Used for counting when to stop. s | Whether or not to skip the next character. 1 for yes, nil for no. o | Temp string that will be appended to mountain. t | Temp variable to hold the old value of s. ``` I'm sure I could golf it down *much* more, but I have to go now. Shall be improved later! [Answer] # Java, 377 407 **Edit:** @Victor pointed out that this needed to be a complete program, so I added a few dozen characters to make it compilable and runnable. Just pass the "purchase order" as the first param when executing the program, like so: `java M ..3.4..6..4.3..` I think this is similar in spirit to other answers, basically just traverses the "mountain order" repeatedly for every possible height, and builds the mountains from the tops down. That way I only have to deal with four conditions if not building a peak -- either an up slope '/', down slope '\, joint 'v', or empty ' '. I can discover that simple by looking at the three spaces centered "above" my current position in my top-down build. Note that like other submissions, I treat anything other than a number as equivalent to '.' in the input, for brevity. Golfed version: ``` class M{public static void main(String[]m){char[]n=m[0].toCharArray();int e=n.length,h=9,x=-1,p;char[][]o=new char[11][e];char l,r,u;boolean a,b,c;for(;h>=0;h--){for(p=0;p<e;p++){if(n[p]-49==h){o[h][p]=94;if(x==-1)x=h;}else{l=(p>0)?o[h+1][p-1]:0;r=(p<e-1)?o[h+1][p+1]:0;u=o[h+1][p];a=l>91&&l<99;b=r==94||r==47;c=u<33;o[h][p]=(char)((a&&b)?'v':(c&&b)?47:(c&&a)?92:32);}}if(x>=h)System.out.println(o[h]);}}} ``` Human readable form (and without some of the equivalent transmogrifications to achieve golf form): ``` class Magrathea2 { public static void main(String[] mountain) { String out = ""; char[][] output = new char[11][mountain[0].length()]; int height = 9; int maxheight = -1; int position = 0; char left,right,up; char[] mount = mountain[0].toCharArray(); for (; height >= 0; height--) { for (position=0; position < mount.length; position++) { if (mount[position]-49 == height) { output[height][position] = '^'; if (maxheight==-1) { maxheight=height; } } else { // deal with non-numbers as '.' left=(position>0)?output[height+1][position-1]:0; right=(position<mount.length-1)?output[height+1][position+1]:0; up=output[height+1][position]; if ((left=='^'||left=='\\')&&(right=='^'||right=='/')) { output[height][position]='v'; } else if ((up==' '||up==0)&&(right=='/'||right=='^')) { output[height][position]='/'; } else if ((up==' '||up==0)&&(left=='\\'||left=='^')) { output[height][position]='\\'; } else { output[height][position]=' '; } } } if (maxheight >= height) { out+=new String(output[height]); if (height > 0) { out+="\n"; } } } System.out.println(out); } } ``` Enjoy. Example output: ``` $ java M ..3..4...6...5....1 ^ / \ ^ ^ / \/ \ ^ / v \ / v \ / \^ ``` [Answer] ## Perl 6, 264 224 216 206 200 194 124 bytes ``` $_=get;my$a=10;((s:g/$a/^/;s:g/\s\.\s/ v /;s:g'\.\s'/ ';s:g/\s\./ \\/;$!=say TR/.1..9/ /;tr'^\\/v' ')if .match(--$a)|$!)xx 9 ``` Thanks to @JoKing for showing a s/// solution. This is golfed a bit further after fixing the tr/// bug in Perl 6. My original solution with subst: ``` my$t=get;for 9...1 {if $t.match($_)|$! {$t=$t.subst($_,'^',:g).subst(' . ',' v ',:g).subst('. ','/ ',:g).subst(' .',' \\',:g);$!=say $t.subst(/<[\.\d]>/,' ',:g);$t.=subst(/<[^\\/v]>/,' ',:g)};} ``` Ungolfed: ``` my $t=slurp; my $s; for 9...1 { if $t.match($_)||$s { # match number or latched $t=$t.subst($_,'^',:g) # peaks .subst(' . ',' v ',:g) # troughs .subst('. ','/ ',:g) # up slope .subst(' .',' \\',:g); # down slope $s=say $t.subst(/<[\.\d]>/,' ',:g); # clean, display, latch $t=$t.subst(/<[^\\/v]>/,' ',:g) # wipe for next line } } ``` Output: ``` ...4...3...33..4..4....2.3.22.33.5..22...333.222.3.. ^ ^ ^ ^ / \ / \ ^ ^^ / \/ \ ^ ^^ \ ^^^ ^ / \/ \ / v \ ^/ \^^/ ^^ / \^^^/ \ / v \/ \/ \ ``` [Answer] ## Perl, ~~254 218~~ 212 ``` $s=<>;sub f{9-$i-$_[0]?$":pop}for$i(0..8){$h=1;$_=$s;s!(\.*)(\d?)!$D=($w=length$1)+$h-($2||1);join'',(map{($x=$_-int$D/2)<0?f--$h,'\\':$x?f++$h,'/':$D%2?f--$h,v:f$h,'/'}0..$w-1),$2?f$h=$2,'^':''!ge;print if/\S/} ``` ``` $s=<>; sub f{9-$i-$_[0]?$":pop} for$i(0..8){ $h=1; $_=$s; s!(\.*)(\d?)! $D=($w=length$1)+$h-($2||1); join'',(map{ ($x=$_-int$D/2)<0 ?f--$h,'\\' :$x ?f++$h,'/' :$D%2 ?f--$h,v :f$h,'/' }0..$w-1),$2 ?f$h=$2,'^' :'' !ge; print if/\S/ } ``` **Edit:** actually it's a bug-fix to work with ProgrammerDan's `..3..4...6...5....1` example, but, in the process, some bytes were off. And online test: <https://ideone.com/P4XpMU> [Answer] # C# - ~~321~~ 319 ``` using System.Linq;class P{static void Main(string[]p){int h=p[0].Max()-48,i=h,j,n=p[0].Length;char[]A=new char[n+2],B=A;for(;i-->0;){for(j=0;j++<n;){var r=(A[j+1]==47|A[j+1]==94);B[j]=(char)(p[0][j-1]==i+49?94:i+1<h?A[j]==0?(A[j-1]>90&A[j-1]<95)?r?118:92:r?47:0:0:0);}A=(char[])B.Clone();System.Console.WriteLine(B);}}} ``` Ungolfed and commented: ``` using System.Linq; class P { static void Main(string[] p) { int h = p[0].Max() - 48, // Getting the height. Codes for 0 to 9 are 48 to 57, so subtract 48 and hope no one will input anything but dots and numbers. i = h, j, // Declaring some iterators here, saves a few chars in loops. n = p[0].Length; char[] A = new char[n+2], // Creating an array of char with 2 extra members so as not to check for "index out of bounds" exceptions B = A; // B is referencing the same array as A at this point. A is previous row, B is the next one. for (;i-->0;) // Looping from top to the bottom of the mountain { for (j = 0; j++ < n;) // Looping from left to right. { var r = (A[j + 1] == 47 | A[j + 1] == 94); // This bool is used twice, so it saves a few characters to make it a variable // Here's the logic B[j] = (char)(p[0][j - 1] == i + 49 ? 94 // If at this position in the string we have a number, output "^" : i + 1 < h ? // And if not, check if we're on the top of the mountain A[j] == 0 ? // If we're not at the top, check if the symbol above is a space (0, actually) (A[j - 1] > 90 & A[j - 1] < 95) ? // If there's nothing above, we check to see what's to the left ( ^ or \ ) r ? // And then what's to the right ( ^ or / ) 118 // If there are appropriate symbols in both locations, print "v" : 92 // If there's only a symbol to the left, print "\" : r // Otherwise check if there's a symbol to the right, but not to the left ? 47 // And if there is, print "/" : 0 : 0 : 0); // Print nothing if there aren't any symbols above, to the left and to the right, // or there's a "^" right above, or we're at the top of the mountain } A=(char[])B.Clone(); // Clone arrays to iterate over the next line System.Console.WriteLine(B); } } } ``` Example: ``` C:\>program .2..3..4... ^ ^ / \ ^ / v \ / v \ ``` I think it outputs an extra space before each line, though. [Answer] # CJam, ~~128~~ ~~117~~ ~~112~~ ~~106~~ 104 bytes CJam is a bit younger than this challenge so this answer does not compete. This was a very nice challenge though! From the little I know about J and APL, I think a submission in those would be impressively short. ``` WlW++"."Waer{_{~U(e>:U}%\W%}2*;W%]z{$W=}%_$W=S*\:L,2-,\f{\_)L=(~"^/ ^^/ \v ^ \\"S/2/@L>3<_$0=f-{=}/t}zN* ``` Here is a test case, which I think contains all possible possible combinations of slopes, peaks and troughs: ``` ...4...3...33..4..4....2.3.22.33.5..22...333.222.3.. ``` which yields ``` ^ ^ ^ ^ / \ / \ ^ ^^ / \/ \ ^ ^/ \ ^^^ ^ / \/ \ / v \ ^/ \^^/ \^ / \^^^/ \ / v \/ \/ \ ``` [Test it here.](http://cjam.aditsu.net/) I'll add an explanation for the code later. [Answer] ## Python, ~~297~~ ~~234~~ 218 -63 bytes thanks to Jo King -16 bytes with `r=s.replace` instead of lambda ``` s=input() r=s.replace q=0 j=''.join for i in range(9): if`9-i`in s or q:q=s=r(`9-i`,'^');s=r(' . ',' v ');s=r('. ','/ ');s=r(' .',' \\');print j([x,' '][x in'0123456789.']for x in s);s=j([x,' '][x in'/\^v']for x in s) ``` Takes input from STDIN. Ungolfed, simplified: ``` s=input() # Take input r=lambda y,z: s.replace(y,z) # Function for quick s.replace(a, b) j=lambda x: ''.join(x) q=0 # Acts like boolean for i in range(9): # Count to 9 if `9-i`in s or q: # When digit has been found or found previously (no newlines at start) q=s=r(`9-i`,'^') # Digit to ^, set q to non-zero value for always executing from now on s=r(' . ',' v ') # ' . ' to ' v ' s=r('. ','/ ') # '. ' to '/ ' s=r(' .',' k') # ' .' to 'k'. K is a placeholder, since \\ takes two chars and `[...]`[2::5] fails print j([x,' '][x in'0123456789.']for x in s) # Print without '0123456789.' s=j([x,' '][x in'/\^v']for x in s) # Wipe (delete '/^\v`) ``` [Answer] # Powershell, ~~148~~ 145 bytes It's a nice challenge! ``` param($s)9..1|?{($p+=$s-match$_)}|%{"$_,^; \. , v ;\. ,/ ; \., \;\^|\\|/|v, "-split';'|%{$x=$s-replace'\.|\d',' ' $s=$s-replace($_-split',')} $x} ``` Less golfed test script: ``` $f = { param($s) 9..1|?{($p+=$s-match$_)}|%{ # loop digits form 9 downto 1, execute to the end as soon as a suitable digit met $s=$s-replace$_,'^' # replace current digit with '^' $s=$s-replace' \. ',' v ' # replace ' . ' with ' v ' $s=$s-replace'\. ','/ ' # replace '. ' with '/ ' $s=$s-replace' \.',' \' # replace ' .' with ' \' $s-replace'\.|\d',' ' # replace all dots and digits with ' ' and push to output. Don't store this replacement $s=$s-replace'\^|\\|/|v',' ' # prepeare to the next step: replace ^ \ / and v to space } # Example: # $s="...4...3...3.." # 4 : $s="...^...3...3.." output: " ^ " # 4 : $s="... ...3...3.." # 3 : $s="../ \..^...^.." output: " / \ ^ ^ " # 3 : $s=".. .. ... .." # 2 : $s="./ \/ \./ \." output: " / \/ \ / \ " # 2 : $s=". . ." # 1 : $s="/ v \" output: "/ v \" # 1 : $s=" " } @( ,("1", "^") ,("11", "^^") ,("1.2.", " ^ ", "^/ \") ,(".2.3..", " ^ ", " ^/ \ ", "/ \") ,(".2..3..", " ^ ", " ^ / \ ", "/ v \") ,("...4...3...3..", " ^ ", " / \ ^ ^ ", " / \/ \ / \ ", "/ v \") ,("...4...3...33..4..4....2.3.22.3..5...22...333.222.3..", " ^ ", " ^ ^ ^ / \ ", " / \ ^ ^^ / \/ \ ^ ^/ \ ^^^ ^ ", " / \/ \ / v \ ^/ \^^/ \^^ / \^^^/ \ ", "/ v \/ \/ \") ,(".2..3..6.....5...3......1..3..4....2.", " ^ ", " / \ ^ ", " / \ / \ ^ ", " ^ \/ \ ^ ^ / \ ", " ^ / v \ / v \ ^ ", "/ v \ ^/ \/ \") ) | % { $s,$expected = $_ $result = &$f $s "$result"-eq"$expected" $s $result } ``` Output: ``` True 1 ^ True 11 ^^ True 1.2. ^ ^/ \ True .2.3.. ^ ^/ \ / \ True .2..3.. ^ ^ / \ / v \ True ...4...3...3.. ^ / \ ^ ^ / \/ \ / \ / v \ True ...4...3...33..4..4....2.3.22.3..5...22...333.222.3.. ^ ^ ^ ^ / \ / \ ^ ^^ / \/ \ ^ ^/ \ ^^^ ^ / \/ \ / v \ ^/ \^^/ \^^ / \^^^/ \ / v \/ \/ \ True .2..3..6.....5...3......1..3..4....2. ^ / \ ^ / \ / \ ^ ^ \/ \ ^ ^ / \ ^ / v \ / v \ ^ / v \ ^/ \/ \ ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-l`, 100 bytes ``` Y#aZGMXaFi,#aIh:+a@i{(yi--h):4j:0Wh-j&++(yi-++jh-j)(yi+jh-j):2}RV Z(J*y)R`.(?=.*[^0])`0R,6;^" /\v^^" ``` *(The language is newer than the question, but probably isn't going to beat the APL submission anyway. Although I hope it will get much shorter.)* Takes input via command-line argument. [Try it online!](https://tio.run/##K8gs@P8/Ujkxyt03ItEtU0c50TPDSjvRIbNaozJTVzdD08oky8ogPEM3S01bGySkrZ0F5GgCmRCGlVFtUJhClIaXVqVmUIKehr2tnlZ0nEGsZoJBkI6ZdZySgn5MWVyc0v///3Vz/hvq6emZALExCBuD2SCunhFQxMgIJGSqB2KAZEEiIHE9QwA "Pip – Try It Online") ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/16587/edit). Closed 1 year ago. [Improve this question](/posts/16587/edit) **Requirements** For the sake of the challenge let's define a *unit*: > > A unit is defined as any point that compose the grid in which the face is drawn (pixels for screen, characters for ASCII art, etc..). > > > The *minimal requirements* for the face are: > > A smiley face is composed of a shape that resemble a circle (not necessarily perfect) of any radius. There must be at least 1 unit for each of the two eyes and at least 2 units for the mouth. Both eyes and mouth should be within the face shape. The mouth can be oriented however you want (happy, sad, indifferent, etc..). > > > Here's an example of the output: ``` 0 0 0 . . . 0 . . 0 . o o . 0 --- 0 . \_/ . 0 0 0 . . . ``` **Goals** Of course the main goal is to come up with the shortest code possible, but *art* is also important. **Winner** The winner is chosen based on the amount of votes from the users, in, at least, the next 5 days. [Answer] ## Javascript, 340 ``` var i=0,b=document.body,d=20,n=b.clientWidth,m=b.clientHeight,f="width=10,height=10," var o=new Function("f","i","t",'open("","",f+"left="+i+",top="+t)') for(j=0;j<m/d;++j,i=j*d){ u=Math.sqrt(i*(m-i)) t=m/2+u*(j%2-0.5)*2 o(f,i,t) i>m/5&&i<0.8*m&&j%2&&o(f,i,t-m/4); ((i<m/3&&i>m/4)||(i<3*m/4&&i>2*m/3))&&o(f,i,m/3) } ``` --- ## Javascript, 283 **optimized version (with some improvements & without unnecessary white spaces)** ``` var i=0,b=document.body,d=20,n=b.clientWidth,m=b.clientHeight,f="width=10,height=10," function o(i,t){open("","",f+"left="+i+",top="+t)}for(j=0;j<m/d;i=++j*d){u=Math.sqrt(i*(m-i));t=m/2+j%2*2*u-u;o(i,t);i>m/5&&i<0.8*m&&j%2&&o(i,t-m/4);((i<m/3&&i>m/4)||(i<3*m/4&&i>2*m/3))&&o(i,m/3)} ``` Well.. maybe it isn't as short as you would want to but it's unconventional for sure. It looks better when your browser is maximized. I really enjoyed your question! If you want to increase the details just reduce `d` variable slightly. edit: Unfortunately I can't run it on jsfiddle ~~but you can paste it to Javascript console in aby browser. Oh, and enable popups on the page :).~~ **edit2:** You can run it making a new html file and paste the code into it: ``` <body> <script> var i=0,b=document.body,d=20,n=b.clientWidth,m=b.clientHeight,f="width=10,height=10," var o=new Function("f","i","t",'open("","",f+"left="+i+",top="+t)') for(j=0;j<m/d;++j,i=j*d){ u=Math.sqrt(i*(m-i)) t=m/2+u*(j%2-0.5)*2 o(f,i,t) i>m/5&&i<0.8*m&&j%2&&o(f,i,t-m/4); ((i<m/3&&i>m/4)||(i<3*m/4&&i>2*m/3))&&o(f,i,m/3) } </script> </body> ``` Then when you run it and nothing happens, just enable the popup windows and reload the page. In addition I paste ![screenshot](https://i.stack.imgur.com/L7Vb5.png) [Answer] # HTML, ~~200~~ 141 characters Thanks to [avail](https://codegolf.stackexchange.com/users/11887/avall), I've cut this down to [141 characters](http://jsfiddle.net/TdPkF/6/): ``` <fieldset><legend>\\\\\\\\\\\\ ////</legend><center><input size=1 value=o> <input size=1 value=o /><br><input type=radio><br><button>........ ``` Here's the original HTML: ``` <fieldset> <legend>\\\\\\\\\\\\ ////</legend> <center><input type=text size=1 value=o /> <input type=text size=1 value=o /><br/> <input type=radio /><br/> <button>........</button></center></fieldset> ``` [Works best on small screens:](http://jsfiddle.net/R69Tw/) ![:-|](https://i.stack.imgur.com/UPJnQ.png) [Answer] # Brainfuck: 583 characters (without counting whitespace) ``` >>------>->->+++++>->->---->>>>------>>>> >>>>---->->------->>->->->---->>--------> ->->------>>>>>>>>>>-->---->>-->---->>-> -->>>------>>>>>>>>->---->---->>->->->- >>->---->---->>++++[-<++++>]<[-<++++ ++<++++++++<+++<++<++++++<++++++<++++++ <++++++<++<++++++<++++++++<+++<++<++<++<++ <++<++<++<+<++<++++<++++++++<+++<++<+++<+++ <++<++++++ <++++++++<++++< ++<++<++<++ <++<++<++<++<+<+++<++++++<+++<++<++++++<+++ +++<++++++<+++<++<++ +<++++++<++++++<++<++ <++<++<++<++<++<+<++<++<++<++++++<++++++ <++++++<+++++<++++++<+++<+>>>>>>>>>>>> >>>>>> >>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>]<[.<] ``` **Output:** ``` \|/ ____ \|/ @~/ ,. \~@ /_( \__/ )_\ \__U_/ ``` [Answer] # SVG ``` <svg xmlns="http://www.w3.org/2000/svg"> <defs> <radialGradient id="f" fx="25%" fy="25%" r="60%"> <stop offset="0" stop-color="#fff"/> <stop offset="0.6" stop-color="#ff0"/> <stop offset="1" stop-color="#f80"/> </radialGradient> </defs> <circle fill="url(#f)" stroke="#000" stroke-width="2" cx="100" cy="100" r="90"/> <ellipse cx="70" cy="70" rx="10" ry="20"/> <ellipse cx="130" cy="70" rx="10" ry="20"/> <path fill="none" stroke="#000" stroke-width="5" d="M 40 120 S 100 200 160 120"/> </svg> ``` Renders like this: ![Smiley](https://i.stack.imgur.com/XQkNt.png) [Answer] ## Ruby, 224 Douglas Adams would be horrified. :-P ``` w=?$;"^XA[_AXeMFGIAHJLjKNAEFEJJNHQHNKLAEMINJOJOHLAGKHOJOJ[AG[HQHRFJAH}IH IGGwIIAHHGwKHAHGHrEUAGQFiGVAGQGfIPAFHKHHbJHAQII]MGASHNSOHATIdIAUJJRLIAWLIQGK ZOFUA]ZAeSAiPAjOAkL".codepoints{|r|r-=68;$><<(r<0??\n:(w=w==?$?' ':?$)*r)} ``` Output: ``` $$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$ $$$$$ $$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$ $$ $$$$$$ $$$$$$$$$$ $$$$$$$$$$$$$ $$$$$$$$$$ $$$$$$$$ $$$$$$$$$ $$$$$$$$$$ $$$$$$$$$$$ $$$$$$$$$$$ $$$$$$$$ $$$$$$$ $$$$$$$$$$$ $$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$ $$$$$$$$$$$$$$ $$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$ $$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$ $$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$ $$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$ $$$$ $$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$ $$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$ $$$ $$$$ $$$$$$$$$$$$$$$ $$$$ $$$$$ $$$$$ $$$$$$ $$$$$$$$$$$$$$ $$$$$ $$$$$$$$ $$$$$$$$$$$$$ $$$$$$$ $$$$$$$$$$$ $$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$ $$$$$$$$$$$$ $$$$$$$$$$$ $$$$$$$$ ``` --- ## Ruby, 110 Same technique. Less code. Less artful. Looks like someone melted a plastic smiley. :-} ``` w=?$;"TXANdAKQGZAHSI[AGaGRAFaIRAFPGeAGQJ_AHURQAJkANc TX".codepoints{|r|r-=68;$><<(r<0??\n:(w=w==?$?' ':?$)*r)} ``` Output: ``` $$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$ $$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$ ``` [Answer] # QBasic ASCII, 134 (unoptimized) ``` SCREEN 1 PRINT CHR$(1) FOR i = 0 TO 64 x = i \ 8 y = i MOD 8 LOCATE y + 2, x + 1 IF POINT(x, y) THEN PRINT "X" NEXT ``` This answer totally cheats by using ASCII character 1 for its smiley. However, unlike the BF and "plain text" answers, it actually obeys the rules by making ASCII art based on the pixels of the smiley character, rather than just plainly printing the character as its full solution. The unoptimized version represents how QBasic's IDE saves the files. The IDE is "helpfully" fixing up the syntax for us and adding a lot of whitespace where "needed". Output: ![QBasic ASCII smiley unoptimized](https://i.stack.imgur.com/oOvqt.png) # QBasic ASCII, 80 (optimized) ``` SCREEN 1 ?"☺" FOR i=0TO 64 x=i\8 y=i MOD 8 LOCATE y+2,x+1 ?CHR$(POINT(x,y)) NEXT ``` This is an optimized version of the first code sample, which still loads in QBasic. Things that were done: * Removed all unnecessary whitespace. (D'uh!) * Changed the CRLF line breaks to LF only. * Replaced `CHR$(1)` with a string containing the actual character. (Here illustrated with a matching Unicode character. If you actually want to try the code, please replace it with a real ASCII character 1 using a hex editor.) * Replaced `PRINT` with `?`, as the BASIC tradition allows for. * Replaced the `IF` line with a line that prints characters based on the source pixel value. This will be be either 0 or 3. 0 is the color black. Character 0 prints a null character which is treated like a space. 3 is the color white in CGA's 4-color palette. ASCII character 3 is a heart. Output: ![QBasic ASCII smile optimized](https://i.stack.imgur.com/oFjYs.png) # QBasic graphical, 83 (whitespace optimized) ``` SCREEN 1 CIRCLE(50,50),50 CIRCLE(50,50),30,,4,5.4 CIRCLE(30,40),10 CIRCLE(70,40),10 ``` But wait, I here you ask, can't you just use QBasic's built-in graphics commands? Sure, but that won't actually save you any bytes, because of the verbosity of the language. But it does have a built-in function to only draw a circle arc between two given angles, which is nice. The angles are given in radians, and `4` and `5.4` approximate a circle arc symmetrically centered around `π*3/2`, or if you've joined [the good side](http://tauday.com/), `τ*3/4`. Output: ![QBasic graphical smiley optimized](https://i.stack.imgur.com/OhPYy.png) Note: The sizes in this answer denote how big the file is in, in bytes. [Answer] # APL, 97 chars/bytes\* ``` (63⍴1 0)\' /%'[1+(12≥⊃+/¨2*⍨m+¨⊂6 ¯6)+((⍉18<(⍴n)⍴⍳32)∧28≥|100-n)+256≥n←⊃+/¨2*⍨m←x∘.,|x←¯16.5+⍳32] ``` It works by computing a few circle equations. Tested on [GNU APL](https://www.gnu.org/software/apl/). **Output** ![smiley output](https://i.stack.imgur.com/4UtWG.png) ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ \*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long. [Answer] # Bash, 63 chars ``` echo $'$the_cow=""'>.cow;cowsay -f ./.cow $'O O\n\n\_/';rm .cow ``` Output: ``` _____ / O O \ | | \ \_/ / ----- ``` Artistry: Cows. [Answer] # Bash, 22 chars ``` wget x.co/3WG0m -q -O- ``` Sample output: ![enter image description here](https://i.stack.imgur.com/ZiTrn.png) Edit: this could be golfed further as suggested by several people. The shortest self-contained version found so far is: ``` curl -L x.co/3WG0m ``` (thanks nitro2k01) [Answer] **Python 247 230 227 Characters - and a cuter version** ``` from matplotlib.pyplot import* from numpy import* y=x=arange(-8,11,.1) x,y=meshgrid(x,y) contour(x,y,(x*x*(x**2+2*y*y-y-40)+y*y*(y*y-y-40)+25*y+393)*((x+3)**2+(y-5)**2-2)*((x-3)**2+(y-5)**2-2)*(x*x+(y-2)**2-64),[0]) show() ``` ![enter image description here](https://i.stack.imgur.com/Ueo6a.png) **Python 243 Characters - Using colors** ``` from pylab import* from numpy import* y=x=arange(-9,11,.1) x,y=meshgrid(x,y) contourf(x,y,(x*x*(x**2+2*y*y-y-40)+y*y*(y*y-y-40)+25*y+393)*((x+3)**2+(y-5)**2-2)*((x-3)**2+(y-5)**2-2)*(x*x+(y-2)**2-64),1,colors=("#F0E68C",'#20B2AA')) show() ``` ![enter image description here](https://i.stack.imgur.com/GSulZ.png) [Answer] # C++ - 122 characters without unnecessary spaces This is the most realistic I could come up with: ``` #include <iostream> int main() { std::cout << " |||||\n 0 . . 0\n0 ^ 0\n0 \\_/ 0\n 0 0\n 00000\n 888\n 8\n\n"; } ``` For those of you who are missing out, it creates this: ![ASCII art image](https://i.stack.imgur.com/ulOh7.png) [Answer] ``` cowsay -f calvin Hey, What´s up? _________________ < Hey, What´s up? > ----------------- \ ., \ . .TR d' \ k,l .R.b .t .Je \ .P q. a|.b .f .Z% .b .h .E` # J: 2` . .,.a .E ,L.M' ?:b `| ..J9!`., q,.h.M` `.., ..,""` ..2"` .M, J8` `: ` 3; . Jk ..., `^7"90c. j, ,! .7"'`j,.| .n. ... j, 7' .r` 4: L `... ..,m. J` ..,|.. J` 7TWi ..JJ,.: % oo ,. ...., .,E 3 7`g.M: P 41 JT7"' O. .J,; `` V"7N. G. ""Q+ .Zu.,!` Z` .9.. . J&..J! . ,: 7"9a JM"! .5J. .. ..F` 78a.. ` ..2' J9Ksaw0"' .EJ?A...a. q...g...gi .m...qa..,y: .HQFNB&...mm ,Z|,m.a.,dp .,?f` ,E?:"^7b `A| . .F^^7'^4, .MMMMMMMMMMMQzna, ...f"A.JdT J: Jp, `JNa..........A....af` `^^^^^'` ``` [Answer] # PHP, many other languages... - 1601 characters ``` oooo$$$$$$$$$$$$oooo oo$$$$$$$$$$$$$$$$$$$$$$$$o oo$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$o o$ $$ o$ o $ oo o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$o $$ $$ $$o$ oo $ $ "$ o$$$$$$$$$ $$$$$$$$$$$$$ $$$$$$$$$o $$$o$$o$ "$$$$$$o$ o$$$$$$$$$ $$$$$$$$$$$ $$$$$$$$$$o $$$$$$$$ $$$$$$$ $$$$$$$$$$$ $$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$ $$$$$$$$$$$$$$ """$$$ "$$$""""$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ "$$$ $$$ o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ "$$$o o$$" $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$o $$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" "$$$$$$ooooo$$$$o o$$$oooo$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ o$$$$$$$$$$$$$$$$$ $$$$$$$$"$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$"""""""" """" $$$$ "$$$$$$$$$$$$$$$$$$$$$$$$$$$$" o$$$ "$$$o """$$$$$$$$$$$$$$$$$$"$$" $$$ $$$o "$$""$$$$$$"""" o$$$ $$$$o o$$$" "$$$$o o$$$$$$o"$$$$o o$$$$ "$$$$$oo ""$$$$o$$$$$o o$$$$"" ""$$$$$oooo "$$$o$$$$$$$$$""" ""$$$$$$$oo $$$$$$$$$$ """"$$$$$$$$$$$ $$$$$$$$$$$$ $$$$$$$$$$" "$$$"" ``` Smiley source: [Asciiworld.com : Smiley](http://www.asciiworld.com/-Smiley,20-.html) [Answer] # JavaScript 262 251 **Edit:** added better eyes. Prints a smiley face into the console. Could lose quite a few characters to make my bitmask simpler and print a less pretty face, or use a circle equation instead of an ellipse to account for character spacing - but that's not the spirit. You can change the `r` variable to change the size and get a more or less detailed face; any number `>=7 && <=99` will give a good result and stay within the character limit. ``` function c(e,t,n){return t/2*Math.sqrt(1-e*e/(n*n))+.5|0}r=42;p=r/2;q=p/5;s="";for(y=-p;++y<p;){for(x=-r;++x<r;){d=c(y,r*2,p);e=c(y+q,r/5,q);f=e-p;g=e+p;h=c(y,r*1.3,r/3);s+=x>=d||x<=-d||x>=-g&&x<f||x<=g&&x>-f||y>q&&x>-h&&x<h?" ":0}s+="\n"}console.log(s) ``` Human readable: ``` function c(y,w,h){return w/2*Math.sqrt(1-y*y/(h*h))+0.5|0} r = 42 p = r/2 q = p/5 s = '' for (y = -p; ++y < p;) { for (x = -r; ++x < r;) { d = c(y,r*2,p) e = c(y+q,r/5,q) f = e - p g = e + p h = c(y,r*1.3,r/3) s+=(x>=d||x<=-d||(x>-g&&x<f)||(x<g&&x>-f)||(y>q&&(x>-h&&x<h)))?' ':0 } s += '\n' } console.log(s) ``` **Output:** ![smiley in console](https://i.stack.imgur.com/Eqwwb.png) My first game of golf so likely to be some improvements. [Answer] ## html, css I know it's neither short nor real coding, but I still wanted to post this ``` <head> <style> #a{ width:100px; height:100px; border-radius:50px; border: 1px solid black; } #b{ position: absolute; top:30px; left:30px; width:20px; height:20px; border-radius:10px; border: 1px solid black; } #c{ position: absolute; top:0px; left:40px; width:20px; height:20px; border-radius:10px; border: 1px solid black; }#d{ position: absolute; top:30px; left:-30px; width:40px; height:20px; border-radius:10px; border: 1px solid black; } </style> </head> <body> <div id="a"> <div id="b"/> <div id="c"/> <div id="d"/> </div> </body> ``` [jsFiddle](http://jsfiddle.net/97pCv/) [Answer] ## [Rebmu](http://hostilefork.com/rebmu/), 24 chars Oh, the [m-i-n-i-m-a-l](https://www.youtube.com/watch?v=Ywk3vA8Y8xY) humanity. :-) Least impressive Rebmu program yet, so purposefully embedding pHp as a tribute to [the blue pill in the programming world](http://www.php.net/manual/en/images/c0d23d2d6769e53e24a1b3136c064577-php_logo.png): `H{ -- }pHp{|..|^/|\/|}pH` **Execution:** ``` >> rebmu [H{ -- }pHp{|..|^/|\/|}pH] -- |..| |\/| -- ``` **Explanation** Rebmu is just a dialect of [Rebol](http://en.wikipedia.org/wiki/Rebol). It inherits the parse constraints, uses abbreviated terms without spaces separated by runs of capitalization. It has a special treatment when the first run is capitalized vs uncapitalized. *(So rather than separating terms like `AbcDefGhi` it can use the difference between `ABCdefGHI` and `abcDEFghi` to squeeze out a bit of information. Sequences whose runs start in all capitalized are separated so the first term represents a "set-word!", often contextually interpreted as a desire for an assignment. [see video](https://www.youtube.com/watch?v=iDKaz1iB9wQ))* If you want to translate this to native Rebol, you have to accept things like that it starts with a capital H to mean that's actually an `h:` and not an `h`. The source is thus analogous to: ``` h: { -- } print h print {|..|^/|\/|} print h ``` Assigns the string `--` to h (using asymmetric string delimiters because `print {"Isn't it nice," said {Dr. Rebmu}, "when you have asymmetric multi-line string delimiters with no need for escaping matched nested pairs, and that accept apostrophes and quotes too?"}` Prints h once, prints another string where `^/` is the escape sequence for newline *(carets being less used in software than backslashes which appear often in paths)*, prints h again. [Answer] **Perl, 106 chars** It is a Perl oneliner, just have to C&P it on command prompt, provided the Perl `Acme::EyeDrops` module is already installed on the machine. ``` touch temp && perl -MAcme::EyeDrops='sightly' -e 'print sightly({Shape=>"smiley", SourceFile => "temp" } );' ``` ![enter image description here](https://i.stack.imgur.com/MrD3i.png) Another way , a smiley with Pulling a face ``` touch temp && perl -MAcme::EyeDrops='sightly' -e 'print sightly({Shape=>"smiley2",SourceFile=>"temp"});' ``` ![enter image description here](https://i.stack.imgur.com/xhWCu.png) Yet another way,a smiley with Pulling a face upside down, ``` touch temp && perl -MAcme::EyeDrops='sightly' -e 'print sightly({Shape=>"smiley2",SourceFile=>"temp",RotateFlip=>'true',Rotate=>'180'});' ``` ![enter image description here](https://i.stack.imgur.com/wkWb3.png) [Answer] # Bash + ImageMagick: 137 characters ``` c=circle convert -size 99x99 xc: -draw "fill #ff0 $c 49,49,49" -fill 0 -draw "$c 30,35,30,30 $c 70,35,70,30 ellipse 50,60,25,20,0,180" x: ``` Sample output: ![graphical smiley](https://i.stack.imgur.com/HjJQX.png) But as this is an [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") challenge… # Bash + ImageMagick: 172 characters ``` d=-draw p=-pointsize convert -size 99x99 xc: -font times.ttf $p 140 -stroke 0 -fill \#ff0 $d 'text 0,96 O' $p 40 $d 'text 25,50 "o 0"' $p 50 $d 'rotate 95 text 50,-40 D' x: ``` Sample output: ![ASCII smiley](https://i.stack.imgur.com/t1rA9.png) [Answer] # GolfScript, 27 This outputs the 2nd example exactly as given. ``` ' .'3*.' . o o . . \_/ . '\ ``` First one can be done the same way, but I think the 2nd one looks nicer :) [Answer] # Brainf\*\*\* - 2 ``` +. ``` Prints `☺` or ascii value 1. (might not work with some platforms) [Answer] # Bash - one liner: 442 characters ``` c(){ e "define a(i){scale=scale(i);return(sqrt(i*i));};""$@"|bc -l;};e(){ echo "$@";};s(){ h=$1;c=$2;if [ -z $c ];then c=" ";fi;while (($((h=h-1))>0));do e -n "$c"; done; };m(){ t=`c 2*$1`;while (($((t=t-1))));do l=`c a\($1-$t\)+1`;s $l;q=`c 2*\($1-$l\)`;w=`s $q`;if (($l>$t&&$l<($t+3)&&$q>2)); then w=" "`s $((q-2)) 0`" ";elif (($t>($1+1)&&$q>3));then g=`s $(((q-1)/2)) 0`;w=" $g $g ";fi;e -n +;if [ ! -z "$w" ];then e -n "$w+";fi;e;done;}; ``` Example output: (called by `m 8`) ``` + + + + + + 0 0 + + 00 00 + + 000 000 + + + + + + + + + + + + 000 + + + + + + ``` Kind of crazy, but I chose to use a diamond instead of a circle. The eyes are covered by safety goggles. # BASH - 252 characters (thanks @manatwork) ``` s(){ (($1>1))&&echo -n "${2:- }"&&s $[$1-1] $2;};m(){ ((t=2*$1));while ((t=t-1));do v=$[$1-t];l=$[${v#-}+1];s $l;q=$[2*($1-l)];w=`s $q`;((l>t&&l<t+3&&q>2))&&w=" `s $[q-2] 0` ";((t>$1+1&&q>3))&&{ g=`s $[(q-1)/2] 0`;w=" $g $g ";};echo "+${w:+$w+}";done;} ``` [Answer] **HTML + CSS, 83** ``` <div><a>o<a>o</a><hr><hr><style>a,div{width:2em;border:2px solid;border-radius:8px ``` screenshot(using firefox): ![enter image description here](https://i.stack.imgur.com/SVzKq.png) too bad that I'm too late with my answer (got +10 rep also quite late ...) [Answer] # GolfScript, 18 This program uses some binary-encoded values which appear as weird/invalid characters in a text editor. Here's the hex dump: ``` 00000000 27 c1 94 80 a2 9c c1 27 7b 32 62 61 73 65 20 70 |'......'{2base p| 00000010 7d 25 |}%| ``` Note: it doesn't work in a UTF-8 locale, but works fine with ISO-8859-1 for example. The expanded version with escaped characters: ``` "\xc1\x94\x80\xa2\x9c\xc1"{2base p}% ``` Output: ``` [1 1 0 0 0 0 0 1] [1 0 0 1 0 1 0 0] [1 0 0 0 0 0 0 0] [1 0 1 0 0 0 1 0] [1 0 0 1 1 1 0 0] [1 1 0 0 0 0 0 1] ``` For nicer output, you can replace the block with `{2base{38+}%n}` which brings the binary version to 23 bytes. Expanded version: ``` "\xc1\x94\x80\xa2\x9c\xc1"{2base{38+}%n}% ``` Output: ``` ''&&&&&' '&&'&'&& '&&&&&&& '&'&&&'& '&&'''&& ''&&&&&' ``` [Answer] # JavaScript This code must be run in `f12` on this page: ``` console.log(document.getElementsByTagName("code")[0].innerHTML) ``` Output: ``` 0 0 0 . . . 0 . . 0 . o o . 0 --- 0 . \_/ . 0 0 0 . . . ``` [Answer] # CJam, 18 I decided to go for short code... [Try it here](http://cjam.aditsu.net/). ``` " ##O#- #"2/{_(N}% ``` ## Explanation ``` " ##O#- #" "Push a string onto the stack"; 2/ "Split it into an array of two-character groups"; {_(N}% "For each item in the array, execute _(N : duplicate the element, remove the first character and place it onto the stack after what's left, and push a new line."; ``` This exploits the symmetry of the smiley face I designed. ## Output ``` ## #OO# #--# ## ``` [Answer] # Python ``` smileyFace = ''' 000000000000000 00000000000000000 000000 00 00000 0000000 . 00 . 000000 00000000 00 0000000 0000000000000000000000000 000000 . 00000000 . 0000000 000000 . 000000 . 0000000 0000000 ....... 0000000 000000000000000000000 0000000000000000000 00000000000000000''' print(smileyFace) ``` ``` print(' _________\n / \\\n | /\\ /\\ |\n | - |\n | \\___/ |\n \\_________/'); ``` Output: ``` _________ / \ | /\ /\ | | - | | \___/ | \_________/ ``` [Answer] ## Javascript console a frog: ``` prompt("◉◉ ", ' '.repeat(25)+"⊂(‿)つ") ``` table flip ``` prompt("┻━┻", ' '.repeat(24)+"ʕノ•ᴥ•ʔノ") ``` and i am not sure what this one is ``` prompt('◕ '.repeat(24),prompt("◕ ◕", ' ▇ '.repeat(24))) ``` [Answer] ## Python, 42 ``` print ' 0 0 0 \n0 . . 0\n0 --- 0\n 0 0 0 ' ``` [Answer] HTML 5 : 321 Characters ``` <canvas id=a><script>_=document.getElementById("a"),c=_.getContext("2d"),p=Math.PI,P=2*p;C();c.arc(95,85,40,0,P);B();c.lineWidth=2;c.stroke();c.fillStyle="red";C();c.arc(75,75,5,0,P);B();C();c.arc(114,75,5,0,P);B();C();c.arc(95,90,26,p,P,true);B();function C(){c.beginPath()};function B(){c.closePath();c.fill()}</script> ``` Fiddle : <http://jsfiddle.net/wfNGx/> ![enter image description here](https://i.stack.imgur.com/R0L9C.png) Source : <http://www.codecademy.com/courses/web-beginner-en-SWM11/0/1> [Answer] # Shell command or builtin ``` $ echo -e ' ,---.\n/ o o \\\n\ \\_/ /\n `---´' ,---. / o o \ \ \_/ / `---´ $ printf ' ,---.\n/ o o \\\n\ \\_/ /\n `---´\n' ,---. / o o \ \ \_/ / `---´ ``` Depending on the flavour of your shell or command set, `echo` may or may not interprete control characters with or witout `-e`... (...and I demand that I may or may not be Vroomfondel!) just try... and if all else fails, using `printf` should be a safe bet... ]
[Question] [ A current internet meme is to type 2spooky4me, with a second person typing 3spooky5me, following the `(n)spooky(n+2)me` pattern. Your mission is to implement this pattern in your chosen language. You should write a program or function that takes a value `n` (from standard input, as a function argument, or closest alternative), and outputs the string `(n)spooky(n+2)me` (without the parentheses; to standard output, as a return value for a function, or closest alternative). Your solution should work for all inputs, from `1` up to 2 below your language's maximum representable integer value (`2^32-3` for C on a 32-bit machine, for example). Example implementation in Python: ``` def spooky(n): return "%dspooky%dme"%(n,n+2) ``` `spooky(2) -> "2spooky4me"` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden, and the shortest answer in bytes wins! # Leaderboard The Stack Snippet at the bottom of this post generates the leaderboard 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 ``` ``` <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 = 62350; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; 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] # gs2, 15 bytes I outgolfed Dennis! CP437: ``` spooky•me♣╨V↕0B ``` Hex dump: ``` 73 70 6f 6f 6b 79 07 6d 65 05 d0 56 12 30 42 ``` At the start of the program, STDIN is pushed (e.g. the string `"3"`) and stored in variable `A`. The first ten bytes of the program push two strings, `"spooky"` and `"me"`, to the stack. Then: * `d0` pushes variable `A`. * `56` parses it as a number. * `12` `30` increments it by two. * `42` swaps the top two elements on the stack, leaving `"3" "spooky" 5 "me"`. The final stack is printed as `3spooky5me`. [Answer] # GS2, 17 bytes ``` 56 40 27 27 04 73 70 6F 6F 6B 79 05 42 04 6D 65 05 ``` I CAN'T OUTGOLF DENNIS HELP [Answer] # Stuck, 17 bytes ``` i_2+"spooky";"me" ``` EDIT: GUESS YOU COULD SAY I'M STUCK AT 17 BYTES [Answer] # GolfScript, 17 bytes ``` ~.2+"spooky"\"me" ``` Try it online on [Web GolfScript](http://golfscript.apphb.com/?c=OyIyIiAjIFNpbXVsYXRlIGlucHV0IGZyb20gU1RESU4uCgp%2BLjIrInNwb29reSJcIm1lIg%3D%3D). ### How it works ``` ~.2+"spooky"\"me" ~ # Evaluate the input. .2+ # Push a copy and add 2. "spooky" # Push that string. \ # Swap it with the computed sum. "me" # Push that string. ``` [Answer] # Chef, 414 bytes ``` S. Ingredients. g i 2 g t 115 l s 112 l p 111 l o 107 l k 121 l y 109 l m 101 l e Method. Take i from refrigerator.Put e into mixing bowl.Put m into mixing bowl.Put i into mixing bowl.Add t.Put y into mixing bowl.Put k into mixing bowl.Put o into mixing bowl.Put o into mixing bowl.Put p into mixing bowl.Put s into mixing bowl.Put i into mixing bowl.Pour contents of mixing bowl into the baking dish. Serves 1. ``` A recipe for disaster. Do not try this at home. [Answer] # Pyth - 17 bytes ``` s[Q"spooky"hhQ"me ``` [Try it online here](http://pyth.herokuapp.com/?code=s%5BQ%22spooky%22hhQ%22me&input=2&test_suite=1&test_suite_input=1%0A2%0A3%0A4&debug=0). [Answer] # [Pip](https://github.com/dloscutoff/pip), 18 bytes Looks like I'm in the second tier of golfing languages here. :^P ``` [a"spooky"a+2"me"] ``` [Try it online!](https://tio.run/##K8gs@P8/OlGpuCA/P7tSKVHbSCk3VSn2////xgA "Pip – Try It Online") Takes the number as a command-line argument and puts the appropriate elements in an array, which is joined together and autoprinted at the end of the program. --- Five and a half years later, here's a much more interesting 18-byte solution: ``` "0spooky2me"RXD_+a ``` [Try it online!](https://tio.run/##K8gs@P9fyaC4ID8/u9IoN1UpKMIlXjvx////xgA "Pip – Try It Online") In the string `0spooky2me`, `R`eplace each digit (built-in regex variable `XD`) with itself plus the command-line argument (`_+a`). [Answer] # CJam, 18 bytes ``` ri_2+"spooky"\"me" ``` [Try it online.](http://cjam.aditsu.net/#code=ri_2%2B%22spooky%22%5C%22me%22) [Answer] # TeaScript, 18 bytes ``` x+`spooky${x+2}me` ``` Unfortunately this string can't be compressed so this is basically as short as it will get [Answer] # dc, 20 bytes ``` ?dn[spooky]P2+n[me]P ``` [Answer] # Japt, ~~17~~ 16 bytes ``` U+"spooky{U+2}me ``` **Japt** (**Ja**vascri**pt** shortened) is a language of my invention. **It is newer than this challenge; thus, this answer is non-competing.** Unlike my other seven unpublished languages, this one has an [actual interpreter](https://codegolf.stackexchange.com/a/62685/42545) that is currently being developed and is already partially working. I wanted to post this because I like how it's the same length as all the existing ~~first-place~~ second-place answers. Here's how it works: ``` U+"spooky{U+2}me" implicit: [U,V,W,X,Y,Z] = eval(input) U+ input + "spooky me" this string {U+2} with input+2 inserted here implicit: output last expression ``` And there you have it. The spec for all functionality used here was finalized on Oct 29th; nothing was changed to make this answer any shorter. Here's the [interpreter](//ethproductions.github.io/japt), as promised. [Answer] # 05AB1E, ~~14~~ 10 bytes ``` DÌs’ÿæªÿme ``` [Try it online.](http://05ab1e.tryitonline.net/#code=RMOMc-KAmcO_w6bCqsO_bWU&input=OQ) ## Explanation ``` DÌs’ÿæªÿme D get input n and duplicate it Ì increment by 2 s Swap. Stack is now [n+2, n]. ’ÿæªÿme Compressed string that expands to "ÿspookyÿme". The first ÿ is then replaced by n and the second by n+2. ``` [Answer] # Julia, 23 bytes ``` n->"$(n)spooky$(n+2)me" ``` This creates an unnamed lambda function that accepts an integer and returns a string. The output is constructed using Julia's string interpolation. [Answer] # [Gol><>](https://github.com/Sp3000/Golfish/wiki), 21 bytes ``` I:n"emykoops"6Ro{2+nH ``` I guess I'm... tied with Perl? [Try it online](https://golfish.herokuapp.com/?code=I%3An%22emykoops%226Ro%7B2%2BnH&input=3&debug=false). ``` I:n Input n, output n "emykoops" Push chars 6Ro Output top 6 chars (spooky) {2+n Output n+2 H Output stack and halt (me) ``` [Answer] # Vitsy, 21 Bytes Note: the `Z` command was made after this challenge began, but was not made for this challenge. ``` VVN"ykoops"ZV2+N"em"Z V Grab the top item of the stack (the input) and make it a global variable. V Call it up - push the global variable to the top of the stack. N Output it as a number. "ykoops" Push 'spooky' to the stack. Z Output it all. V2+N Call the global variable again, add two, then output as num. "em"Z Push 'me' to the stack and output it all. ``` More spoopy variation using multiple stacks (27 Bytes): ``` &"ykoops"&"em"?DN?Z??2+N??Z & Make a new stack and move to it. "ykoops" Push 'spooky' to the current stack. &"em" Do the last to things with 'me'. ? Move over a stack. DN Output the input. ?Z Move over a stack (the one with 'spooky') and print it. ?? Move back to the original stack. 2+N Add 2 to the input and output it as a number. ??Z Move to the stack with 'me' in it and print it. ``` [Try it online!](http://vitsy.tryitonline.net/#code=VlZOInlrb29wcyJaVjIrTiJlbSJa&input=&args=Mw) [Answer] # Jelly **13 bytes** ``` +0,2ż“×¥X“ŀ`» ``` I CAN'T OUTGOLF QUARTATA HELP [Try it online!](http://jelly.tryitonline.net/#code=KzAsMsW84oCcw5fCpVjigJzFgGDCuw&input=&args=Mg) ### How it works ``` +0,2ż“×¥X“ŀ`» Main link. Input: n +0,2 Add [0, 2] to n, resulting in [n, n + 2]. “×¥X“ŀ`» Yield ['spooky, 'me'] by indexing into a dictionary. ż Zip the results to left and right with each other. This yields [[n, 'spooky'], [n + 2, 'me']], which is flattened before printing. ``` [Answer] # Ruby, 25 bytes ``` ->n{"#{n}spooky#{n+2}me"} ``` This creates an unnamed lambda that accepts an integer and returns a string. The string is constructed using Ruby's string interpolation. [Answer] # APL, ~~25~~ 22 bytes ``` ⍕,'spooky','me',⍨∘⍕2+⊢ ``` This creates an unnamed monadic function train that accepts an integer on the left and returns a string. Numeric values are converted to strings using `⍕`. The array of strings is joined into a single string using `∊`. [Try it online](http://tryapl.org/?a=f%u2190%u2355%2C%27spooky%27%2C%27me%27%2C%u2368%u2218%u23552+%u22A2%u22C4f%202&run) Saved 3 bytes thanks to Thomas Kwa! [Answer] ## Javascript(ES6) ~~23~~ 21 Bytes A simple function that will be crushed by golfing lanqs: ``` _=>_+`spooky${_+2}me` ``` ``` _=>`${_}spooky${_+2}me` ``` Special thanks to ETHproductions for saving 2 bytes [Answer] # PHP, ~~55~~ ~~47~~ ~~46~~ ~~42~~ 34 bytes ``` <?=($a=$argv[1]).spooky.($a+2).me; ``` Accepts the number as command line input. ### Credits :) Thanks to manatwork for saving 4 bytes! Thanks to insertusernamehere for saving 8 bytes! [Answer] # [Chaîne](http://conorobrien-foxx.github.io/Cha-ne/?code%3D%7Bi~%7D%3A-%2C%7D%3A%7B2%2B%7Dme||input%3D2), 15 bytes *noncompeting, language postdates question* ``` {i~}:-,}:{2+}me {i~} | input duplicate write : : | access dictionary with inner base-93 key -,} | entry for "spooky" {2+} | push 2, add previous two, write me | write me ``` Implicit output. [Answer] # [Simplex v.0.7](http://conorobrien-foxx.github.io/Simplex/), 20 bytes Simplex simply isn't feeling golfy today. >\_< ``` i@R"spooky"&IIR"me"g i@ ~~ take input and copy to register R"spooky" ~~ write that string to the strip (increment byte after every character) &II ~~ write the register (incremented twice) to the strip R"me" ~~ write that string to the strip g ~~ output the strip ``` [Answer] ## C, 58 bytes ``` main(a,b)char**b;{printf("%sspooky%dme",*++b,atoi(*b)+2);} ``` `atoi()` may be unnecessary. [Answer] # Mathematica, 45 27 bytes ``` Print[#,"spooky",#+2,"me"]& ``` `g=ToString[#]<>"spooky"<>ToString[#+2]<>"me"&` Thanks to Martin Büttner for the significant improvement (and the warm welcome). [Answer] ## [Minkolang 0.10](https://github.com/elendiastarman/Minkolang), 49 bytes I have no way to convert integers to strings (yet!), so this is much longer. ``` "me"nd2+(dl%"0"+$rl:d)"spooky"2g(dl%"0"+$rl:d)$O. ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=%22me%22nd2%2B%28dl%25%220%22%2B%24rl%3Ad%29%22spooky%222g(dl%25%220%22%2B%24rl%3Ad)%24O%2E&input=200) ### Explanation `(dl%"0"+$rl:d)` does the job of converting an int to a string. If this were replaced by a single character (like `Z`), then my solution would be just **23 bytes**. ``` "me"nd2+Z"spooky"2gZ$O. ``` `nd` takes an integer from input and duplicates it. `2+` adds 2 and `2g` later gets the initial input and puts it on top of stack. `$O.` outputs the whole stack as integers and stops. [Answer] # Lua for windows, 41 bytes ``` n=io.read()print(n.."spooky"..n+2 .."me") ``` test with lua for windows it takes the input through io.read then stored in variable n then on the same line prints the variable n then "spooky" then n+2 finally it prints "me" [Answer] # Rotor, 15 bytes ``` &"spooky"~2+"me ``` Language was created after the challenge. Does not work in the online interpreter (uses input eval.) [Answer] # [Perl 5](https://www.perl.org/), ~~20~~ 19 bytes ``` $\=spooky.($_+2).me ``` The code requires the `-p` switch. *Thanks to @Xcali for golfing off 1 byte!* [Try it online!](https://tio.run/##K0gtyjH9/18lxra4ID8/u1JPQyVe20hTLzf1/3@jf/kFJZn5ecX/dQsA "Perl 5 – Try It Online") [Answer] # [Factor](https://factorcode.org/), 30 bytes ``` [ dup 2 + [I ${}spooky${}meI]] ``` TIO doesn't have the `interpolate` vocab, so have a screenshot: [![enter image description here](https://i.stack.imgur.com/x5gIH.png)](https://i.stack.imgur.com/x5gIH.png) [Answer] # [Vim](https://www.vim.org), ~~18~~ 17 bytes ``` C<C-r>"spooky<C-r>"<esc><C-a><C-a>ame ``` [Try it online!](https://tio.run/##K/v/39nGWbfITqm4ID8/uxLCtkktTrYDMhMhRGJu6v//hpb/dcsA "V (vim) – Try It Online") ### Explanation ``` C ``` Delete the input number (storing it in the register) and enter insert mode. ``` <C-r>"spooky<C-r>" ``` Insert the number from the register, followed by `spooky`, followed by the number from the register again. ``` <esc><C-a><C-a> ``` Leave insert mode and increment the number under the cursor twice. ``` ame ``` Insert `me` after the number. ]
[Question] [ The challenge is very simple. Given an integer input `n`, output the `n x n` identity matrix. The identity matrix is one that has `1`s spanning from the top left down to the bottom right. You will write a program or a function that will return or output the identity matrix you constructed. Your output may be a 2D array, or numbers separated by spaces/tabs and newlines. **Example input and output** ``` 1: [[1]] 2: [[1, 0], [0, 1]] 3: [[1, 0, 0], [0, 1, 0], [0, 0, 1]] 4: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] 5: [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]] 1 === 1 2 === 1 0 0 1 3 === 1 0 0 0 1 0 0 0 1 etc. ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # MATL, 2 bytes ``` Xy ``` A translation of my Octave answer. [Try it online.](http://matl.tryitonline.net/#code=WHk&input=Mw&args=) A 4 byte version with no built-ins (thanks to Luis Mendo): ``` :t!= : take input n and a generate row array [1,2,...n] t duplicate ! zip = thread compare over the result ``` [Answer] ## TI-BASIC, 2 bytes ``` identity(Ans ``` Fun fact: The shortest way to get a list `{N,N}` is `dim(identity(N`. Here's the shortest way without the builtin, in 8 bytes: ``` randM(Ans,Ans)^0 ``` `randM(` creates a random matrix with entries all integers between -9 and 9 inclusive (that sounds oddly specific because it is). We then take this matrix to the 0th power. [Answer] # Julia, ~~9~~ 3 bytes ``` eye ``` This is just a built-in function that accepts an integer `n` and returns an `nxn Array{Float64,2}` (i.e. a 2D array). Call it like `eye(n)`. Note that submissions of this form are acceptable per [this policy](http://meta.codegolf.stackexchange.com/questions/7205/on-scoring-builtin-functions). [Answer] # APL, 5 bytes ``` ∘.=⍨⍳ ``` This is a monadic function train that accepts an integer on the right and returns the identity matrix. [Try it here](http://tryapl.org/?a=f%u2190%u2218.%3D%u2368%u2373%20%u22C4%20f%204&run) [Answer] ## Python 2, 42 bytes ``` lambda n:zip(*[iter(([1]+[0]*n)*n)]*n)[:n] ``` An anonymous function, produces output like `[(1, 0, 0), (0, 1, 0), (0, 0, 1)]`, First, creates the list `([1]+[0]*n)*n`, which for `n=3` looks like ``` [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0] ``` Using the [zip/iter trick](http://paddy3118.blogspot.com/2012/12/that-grouping-by-zipiter-trick-explained.html) `zip(*[iter(_)]*n` to make groups of `n` gives ``` [(1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)] ``` Note that the `1` comes one index later each time, giving the identity matrix. But, there's an extra all-zero row, which is removed with `[:n]`. [Answer] # Octave, ~~10~~ 4 bytes ``` @eye ``` Returns an anonymous function that takes a number `n` and returns the identity matrix. [Answer] # R, 4 bytes ``` diag ``` When given a matrix, `diag` returns the diagonal of the matrix. However, when given an integer `n`, `diag(n)` returns the identity matrix. [Try it online](http://www.r-fiddle.org/#/fiddle?id=q3aeHVGZ) [Answer] # Jelly, 4 bytes ``` R=€R ``` Doesn't use a built-in. [Try it online!](http://jelly.tryitonline.net/#code=Uj3igqxS&input=&args=NA) ### How it works ``` R=€R Main link. Input: n R Range; yield [1, ..., n]. R Range; yield [1, ..., n]. =€ Compare each. This compares each element of the left list with the right list, so it yields [1 = [1, ..., n], ..., n = [1, ..., n]], where comparison is performed on the integers. ``` [Answer] # J, 4 bytes ``` =@i. ``` This is a function that takes an integer and returns the matrix. [Answer] # JavaScript ES6, ~~68~~ ~~62~~ 52 bytes *Saved 10 bytes thanks to a neat trick from @Neil* ``` x=>[...Array(x)].map((_,y,x)=>x.map((_,z)=>+(y==z))) ``` Trying a different approach than @Cᴏɴᴏʀ O'Bʀɪᴇɴ's. Could possibly be improved. [Answer] # Pyth, 7 bytes ``` XRm0Q1Q ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=XRm0Q1Q&input=5&debug=0) Creating a matrix of zeros and replacing the diagonal elements with ones. [Answer] **Haskell, ~~43~~ 37 bytes** ``` f n=[[0^abs(x-y)|y<-[1..n]]|x<-[1..n]] ``` Pretty straightforward, though I think one can do better (without a language that already has this function built in, as many have done). Edit: dropped some bytes thanks to Ørjan Johansen [Answer] # [Retina](https://github.com/mbuettner/retina), 25 Credit to @randomra and @Martin for extra golfing. ``` \B. 0 +`(.*) 0$ $0¶0 $1 ``` [Try it online.](http://retina.tryitonline.net/#code=XEIuCiAwCitgKC4qKSAwJAokMMK2MCAkMQ&input=MTExMQ) Note this takes input as a unary. If this is not acceptable, then decimal input may be given as follows: # Retina, 34 ``` .+ $0$*1 \B. 0 +`(.*) 0$ $0¶0 $1 ``` [Try it online.](http://retina.tryitonline.net/#code=LisKJDAkKjEKXEIuCiAwCitgKC4qKSAwJAokMMK2MCAkMQ&input=MTA) [Answer] # Python 3, 48 Saved 1 byte thanks to sp3000. I love challenges I can solve in one line. Pretty simple, build a line out of 1 and 0 equal to the length of the int passed in. Outputs as a 2d array. If you wrap the part after the : in `'\n'.join()`, it'll pretty print it. ``` lambda x:[[0]*i+[1]+[0]*(x+~i)for i in range(x)] ``` [Answer] # Haskell, 54 bytes ``` (#)=replicate f n=map(\x->x#0++[1]++(n-x-1)#0)[0..n-1] ``` `f` returns the identity matrix for input n. Far from optimal. [Answer] # C, ~~59 or 59~~ 56 or 56 Two versions of identical length. 3 bytes saved due to suggestion from anatolyg: `(n+1)` --> `~n` Iterates `i` from `n*n-1` to zero. Prints a 1 if i%(n+1) is zero, otherwise 0. Then prints a newline if `i%n`=0 otherwise a space. ``` i;f(n){for(i=n*n;i--;)printf(i%n?"%d ":"%d\n",!(i%~n));} i;f(n){for(i=n*n;i--;)printf("%d%c",!(i%~n),i%n?32:10);} ``` [Answer] # Lua, ~~77 75~~ 65 bytes ``` x,v=z.rep,io.read()for a=1,v do print(x(0,a-1)..'1'..x(0,v-a))end ``` Well, I'm not sure if lua is the best language for this with the two period concatenation... But hey, there's a shot at it. I'll see if there's any improvements to be made. **EDIT:** I figured something out on accident which I find rather odd, but, it works. In Lua, everyone knows you have the ability to assign functions to variables. This is one of the more useful CodeGolf features. This means instead of: ``` string.sub("50", 1, 1) -- = 5 string.sub("50", 2, 2) -- = 0 string.sub("40", 1, 1) -- = 4 string.sub("40", 2, 2) -- = 0 ``` You can do this: ``` s = string.sub s("50", 1, 1) -- = 5 s("50", 2, 2) -- = 0 s("40", 1, 1) -- = 4 s("40", 2, 2) -- = 0 ``` But wait, Lua allows some amount of OOP. So you could potentially even do: ``` z="" s = z.sub s("50", 1, 1) -- = 5 s("50", 2, 2) -- = 0 s("40", 1, 1) -- = 4 s("40", 2, 2) -- = 0 ``` That will work as well and cuts characters. Now here comes the weird part. You don't even need to assign a string at any point. Simply doing: ``` s = z.sub s("50", 1, 1) -- = 5 s("50", 2, 2) -- = 0 s("40", 1, 1) -- = 4 s("40", 2, 2) -- = 0 ``` Will work. --- So you can visually see the difference, take a look at the golfed results of this: **Using string.sub (88 characters)** ``` string.sub("50", 1, 1)string.sub("50", 2, 2)string.sub("40", 1, 1)string.sub("40", 2, 2) ``` **Assigning string.sub to a variable (65 characters)** ``` s=string.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2) ``` **Assigning string.sub using an OOP approach (64 characters)** ``` z=""s=z.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2) ``` **Assigning string.sub using a.. nil approach? (60 characters)** ``` s=z.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2) ``` If someone knows why this works, I'd be interested. [Answer] # Mata, 4 bytes ``` I(3) ``` **Output** ``` [symmetric] 1 2 3 +-------------+ 1 | 1 | 2 | 0 1 | 3 | 0 0 1 | +-------------+ ``` Mata is the matrix programming language available within the Stata statistical package. I(n) creates an identity matrix of size n\*n [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~206~~ ~~170~~ 162 bytes ``` (([{}])){({}<>(())<><(({})<{({}()(<>)<>)}{}>)>)}{}(({}<><(())>)){({}()<({[()]<({}()<({}<>((((()()()()){}){}){})((()()()()){}){})<>>)>}{})>)<>((()()()()()){})<>}<> ``` [Try it online!](https://tio.run/##ZY2xCsMwDER/527I2O0Q5DuMB2colIYMXYW/XZFtSodKAqHT6en4tNe1Pc/2jgCK90o6vMsAUibkQA0JhCwldu/G2TCdGlZbd6DgBaz6DhOVwZVM3Ko/TZbYpHJ8@W3XXpagiEds@w0 "Brain-Flak – Try It Online") [Answer] # [K6](https://github.com/JohnEarnest/ok), 1 [byte](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` = ``` `=` is exactly this [Try it online!](https://tio.run/nexus/k-ok#@29r@v8/AA "K (oK) – TIO Nexus") [Answer] # K, 7 bytes ``` t=\:t:! ``` Take the equality cross product of two vectors containing [0,n). In action: ``` t=\:t:!3 (1 0 0 0 1 0 0 0 1) t=\:t:!5 (1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1) ``` [Answer] ## Pyth, 8 bytes ``` mmsqdkQQ ``` Try it [here](http://pyth.herokuapp.com/?code=mmsqdkQQ&input=5&debug=0). [Answer] # Mathematica, 14 bytes ``` IdentityMatrix ``` **Test case** ``` IdentityMatrix[4] (* {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}} *) ``` [Answer] # Mathematica, 35 Bytes without using IdentityMatrix ``` Table[Boole[i==j],{i,1,#},{j,1,#}]& ``` [Answer] ## Javascript, 40 ``` f= n=>'0'.repeat(n).replace(/./g,"$`1$'\n") I.oninput=_=>O.innerHTML=f(+I.value) I.oninput() ``` ``` <input id=I value=5> <pre id=O> ``` [Answer] # Japt, ~~14~~ ~~12~~ 10 bytes ``` Uo £Z®¥X|0 ``` [Test it online!](http://ethproductions.github.io/japt/?v=master&code=VW8go1qupVh8MH19ILc=&input=NQ==) Note: this version has a few extra bytes to pretty-print the output. ``` Uo £Z®¥X|0 // Implicit: U = input integer Uo £ // Create the range [0..U). Map each item X and the full array Z to: Z® // Take the full array Z, and map each item Z to: ¥X|0 // (X == Z) converted to a number. 1 for equal, 0 for non-equal. // Implicit: output result of last expression ``` [Answer] # [R](https://www.r-project.org/), 28 bytes ``` function(n,x=1:n)+!x%o%x-x^2 ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT6fC1tAqT1NbsUI1X7VCtyLO6H@ahqnmfwA "R – Try It Online") For pure fun, just another attempt at a non-built-in R solution. Uses the shortcut `%o%` version of the `outer` function. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` °¨œÙ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0IZDK45OPjzz/39TAA "05AB1E – Try It Online") Unique permutations of (10^input)[0:-1] [Answer] # Java, 60 bytes ``` n->{int[][]i=new int[n][n];for(;n-->0;)i[n][n]=1;return i;}; ``` Creates a 2D array and replaces elements where row and column are equal with `1`. [Answer] # CJam, 7 bytes ``` {,_ff=} ``` This is a code block that pops an integer from the stack and pushes a 2D array in return. [Try it online!](http://cjam.tryitonline.net/#code=OSwxPiAgICBlIyBbMSAuLi4gOF0KeyxfZmY9fQolOnAgICAgIGUjIE1hcC4gUHJpbnQgZWFjaC4&input=) ]
[Question] [ Given a string consisting of **printable ASCII chars**, produce an output consisting of its **unique chars in the original order**. In other words, the output is the same as the input except that a char is removed if it has appeared previously. **No built-ins** for finding unique elements in an array can be used (for example, MATLAB has a `unique` function that does that). The idea is to do it manually. Further details: * Either **functions or programs** are allowed. * Input and output can be in the form of **function arguments, stdin/stdout** (even for functions), or a mix of those. * If stdin or stdout are used, a string is understood as just the **sequence of chars**. If function arguments are used, the sequence of chars may need to be **enclosed** in quotation marks or equivalent symbols that the programming language of choice uses for defining strings. * The output should be a string **containing only** the unique characters of the input. So no extra linebreaks, spaces etc. The only exception is: if the output is displayed in stdout, most displaying functions add a trailing `\n` (to separate the string from what will come next). So **one trailing `\n` is acceptable in stdout**. * If possible, post a link to an **online** interpreter/compiler so that others can try your code. This is **code golf**, so shortest code in bytes wins. Some **examples**, assuming stdin and stdout: 1. Input string: ``` Type unique chars! ``` Output string: ``` Type uniqchars! ``` 2. Input string ``` "I think it's dark and it looks like rain", you said ``` Output string ``` "I think'sdarloe,yu ``` 3. Input string ``` 3.1415926535897932384626433832795 ``` Output string ``` 3.14592687 ``` [Answer] # CJam, 3 bytes ``` qL| ``` Setwise or of the input with an empty list. CJam set operations preserve element order. [Try it online](http://cjam.aditsu.net/#code=qL%7C&input=%22I%20think%20it's%20dark%20and%20it%20looks%20like%20rain%22%2C%20you%20said) [Answer] # C# 6, 18 + 67 = 85 bytes Requires this `using` statement: ``` using System.Linq; ``` The actual method: ``` string U(string s)=>string.Concat(s.Where((x,i)=>s.IndexOf(x)==i)); ``` This method saves some chars by [defining the function as a lambda](https://codegolf.stackexchange.com/a/44315/9275), which is supported in C# 6. This is how it would look in C# pre-6 (but ungolfed): ``` string Unique(string input) { return string.Concat(input.Where((x, i) => input.IndexOf(x) == i)); } ``` How it works: I call the [`Where` method](https://msdn.microsoft.com/en-us/library/vstudio/bb534803%28v=vs.100%29.aspx) on the string with a lambda with two arguments: `x` representing the current element, `i` representing the index of that element. `IndexOf` always returns the first index of the char passed to it, so if `i` is not equal to the first index of `x`, it's a duplicate char and mustn't be included. [Answer] # GolfScript, 2 bytes ``` .& ``` or, alternatively: ``` .| ``` I posted this a while ago in the [Tips for golfing in GolfScript](https://codegolf.stackexchange.com/questions/5264/tips-for-golfing-in-golfscript/17839#17839) thread. It works by duplicating the input string (which is put on the stack automatically by the GolfScript interpreter, and which behaves in most ways like an array of characters) and then taking the set intersection (`&`) or union (`|`) of it with itself. Applying a set operator to an array (or string) collapses any duplicates, but preserves the order of the elements. [Answer] # [Retina](https://github.com/mbuettner/retina), 14 bytes ``` +`((.).*)\2 $1 ``` Each line should go in its own separate file, or you can use the `-s` flag to read from one file. To explain it, we'll use this longer but simpler version: ``` +`(.)(.*)\1 $1$2 ``` The first line is the regex to match with (`+`` is the configuration string that keeps running until all replacements have been made). The regex looks for a character (we'll call it C), followed by zero or more arbitrary characters, followed by C. The parentheses denote capturing groups, so we replace the match with C (`$1`) and the characters in between (`$2`), removing the duplicate of C. For example, if the input string was `unique`, the first run would match `uniqu`, with `u` and `niq` as `$1` and `$2`, respectively. It would then replace the matched substring in the original input with `uniq`, giving `uniqe`. [Answer] # [Perl 5](https://www.perl.org/) + `-p`, 19 bytes Saved 1 byte thanks to [@kos](https://codegolf.stackexchange.com/users/45846/kos) and 1 byte thanks to [@Xcali](https://codegolf.stackexchange.com/users/72767/xcali)! ``` s/./$&x!$h{$&}++/eg ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX09fRa1CUSWjWkWtVltbPzX9//@QyoJUhdK8zMLSVIXkjMSiYsV/@QUlmfl5xf91CwA "Perl 5 – Try It Online") [Answer] # JavaScript ES7, ~~37~~ ~~33~~ 25 bytes Pretty simple approach using ES6 `Set` and ES7 ~~Array comprehensions~~ spread operator: ``` s=>[...new Set(s)].join`` ``` 22 bytes less than the `indexOf` approach. Worked on a handful of test cases. [Answer] ## [Macaroni 0.0.2](https://github.com/KeyboardFire/macaroni-lang/releases/tag/v0.0.2-alpha), 233 bytes ``` set i read set f "" print map index i k v return label k set x _ set _ slice " " length index f e 1 1 set f concat f wrap x return label e set _ slice " " add _ multiply -1 x 1 1 return label v set _ unwrap slice i _ add 1 _ 1 return ``` * create "anti-golfing" language: check * golf it anyway: check This is a full program, which inputs from STDIN and outputs on STDOUT. Wrapped version, for aesthetic value: ``` set i read set f "" print map index i k v return label k set x _ set _ slice " " length index f e 1 1 set f concat f wrap x return label e set _ slice " " add _ multiply -1 x 1 1 return label v set _ unwrap slice i _ add 1 _ 1 return ``` And a heavily "commented" and ungolfed version (there are no comments in Macaroni, so I just use bare string literals): ``` set input read "read line from STDIN, store in 'input' var" set found "" "we need this for 'keep' below" print map index input keep val "find indeces to 'keep', map to values, print" return label keep "we're trying to determine which indeces in the string to keep. the special '_' variable is the current element in question, and it's also the value to be 'returned' (if the '_' variable is '0' or empty array after this label returns, the index of the element is *not* included in the output array; otherwise, it is" set x _ set _ slice " " length index found exists 1 1 "now we're using 'index' again to determine whether our '_' value exists in the 'found' array, which is the list of letters already found. then we have to apply a boolean NOT, because we only want to keep values that do NOT exist in the 'found' array. we can 'invert' a boolean stored as an integer number 'b' (hence, 'length') with 'slice(' ', b, 1, 1)'--this is equivalent to ' '[0:1], i.e. a single-character string which is truthy, if 'b' was falsy; otherwise, it results in an empty string if 'b' was truthy, which is falsy" set found concat found wrap x "add the letter to the 'found' array" return label exists set _ slice " " add _ multiply -1 x 1 1 "commentary on how this works: since 0 is falsy and every other number is truthy, we can simply subtract two values to determine whether they are *un*equal. then we apply a boolean NOT with the method described above" return label val set _ unwrap slice input _ add 1 _ 1 "basically 'input[_]'" return ``` (This is the first real Macaroni program (that actually does something)! \o/) [Answer] # Python 2, 42 bytes Uses a couple anonymous functions and [`reduce`](https://docs.python.org/2/library/functions.html#reduce). ``` lambda s:reduce(lambda x,y:x+y[y in x:],s) ``` [**Try it online**](http://ideone.com/3tgQUX) [Answer] # C# 6 - 18+46=64 ``` using System.Linq; ``` and then ``` string f(string s)=>string.Concat(s.Union(s)); ``` The [`Enumerable.Union`](https://msdn.microsoft.com/en-us/library/vstudio/bb341731(v=vs.100).aspx) extension method specifies that elements are returned in the original order: > > When the object returned by this method is enumerated, Union enumerates *first* and *second* in that order and yields each element that has not already been yielded. > > > Set operations that aren't specifically intended to find unique values appear to be allowed judging by the other answers. [Answer] # [Beam](http://esolangs.org/wiki/Beam), ~~23~~ 18 bytes ``` v<H vs) rS g@S >u^ ``` [![enter image description here](https://i.stack.imgur.com/A6X8i.png)](https://i.stack.imgur.com/A6X8i.png) [Try it online!](https://tio.run/nexus/beam#@19m48FVVqzJVRTMle4QzGVXGvf/v5KnQklGZl62QmaJerFCSmJRtkJiXgqQp5CTn59drJCTmZ2qUJSYmaeko1CZX6pQnJiZAgA "Beam – TIO Nexus") [Answer] # JavaScript ES6, 47 bytes ``` f=s=>s.replace(/./g,(e,i)=>s.indexOf(e)<i?'':e) ``` The test below works on all browsers. ``` f=function(s){ return s.replace(/./g,function(e,i){ return s.indexOf(e)<i?'':e }) } run=function(){document.getElementById('output').innerHTML=f(document.getElementById('input').value)};document.getElementById('run').onclick=run;run() ``` ``` <input type="text" id="input" value="Type unique chars!" /><button id="run">Run</button><br /> <pre id="output"></pre> ``` [Answer] # MATLAB, 23 ``` @(n)union(n,n,'stable') ``` Does the "set union" of the input string with itself, using the 'stable' method which does not sort, and then prints. This works because `union` returns only non-duplicate values after the merge. So essentially if you `union` the string with itself, it first produces a string like `Type unique chars!Type unique chars!`, and then removes all duplicates without sorting. No need for `unique` :) [Answer] # [><>](https://esolangs.org/wiki/Fish), 16 bytes ``` i:0(?;:::1g?!o1p ``` ><> doesn't have strings, so we make use of the codebox. Due to the toroidal nature of ><>, the following runs in a loop: ``` i Read a char :0(?; Halt if EOF ::: Push three copies of the char 1g Get the value at (char, 1), which is 0 by default ?!o Print the char if the value was nonzero 1p Set the value at (char, 1) to char ``` Note that this uses the fact that the input only contains printable ASCII, as this would not work if ASCII 0 was present. [Answer] ## Python 3, 44 ``` r='' for c in input():r+=c[c in r:] print(r) ``` Builds the output string `r` character by character, including the character `c` from the input only if we haven't seen it already. Python 2 would be 47, losing 4 chars with `raw_input` and saving 1 on not needing parers for `print`. [Answer] # [Element](https://github.com/PhiNotPi/Element), ~~22~~ ~~19~~ 18 bytes ``` _'{"(3:~'![2:`];'} ``` Example input/output: `hello world` -> `helo wrd` This works by simply processing the string one character at a time and keeping track which ones it has seen before. ``` _'{"(3:~'![2:`];'} _ input line ' use as conditional { } WHILE loop " retrieve string back from control (c-) stack ( split to get the first character of (remaining) string 3: a total of three copies of that character ~ retrieve character's hash value ' put on c-stack ! negate, gives true if undef/empty string [ ] FOR loop 2:` duplicate and output ; store character into itself ' put remaining string on c-stack as looping condition ``` [Answer] ## APL, 3 ``` ∊∪/ ``` This applies union (∪) between each element of the vector, obtaining an iteration that has the effect of removing duplicates. Test it on [tryapl.org](http://tryapl.org/?a=%u220A%u222A/%27Type%20unique%20chars%21%27&run) Old One: ``` ~⍨\ ``` This uses ~ (with reversed arguments, using ⍨) applied between each element of the argument. The result is that for each element, if it's already in the list, it gets erased. [Answer] # TI-BASIC, 49 bytes ``` Input Str1 "sub(Str1,X,1→Y₁ Y₁(1 For(X,2,length(Str1 If not(inString(Ans,Y₁ Ans+Y₁ End Ans ``` The equation variables are rarely useful since they take 5 bytes to store to, but `Y₁` comes in handy here as the `X`th character of the string, saving 3 bytes. Since we can't add to empty strings in TI-BASIC, we start the string off with the first character of Str1, then loop through the rest of the string, adding all characters not already encountered. ``` prgmQ ?Why no empty st rings? Because T I... Why noemptysrig?Bcau. ``` [Answer] # Pyth, 7 bytes ``` soxzN{z ``` Pseudocode: z = input sum of order-by index in z of N over set of z. [Answer] # Julia, ~~45~~ 42 bytes ``` s->(N="";[i∈N?N:N=join([N,i])for i=s];N) ``` Old version: ``` s->(N={};for i=s i∈N||(N=[N,i])end;join(N)) ``` Code builds the new string by appending new characters onto it, then `join`s them together to a proper string at the end. New version saves some characters by iterating via array comprehension. Also saves a byte by using `?:` rather than `||` (as it removes the need for brackets around the assignment). Alternate solution, 45 bytes, using recursion and regex: ``` f=s->s!=(s=replace(s,r"(.).*\K\1",""))?f(s):s ``` ### Julia, 17 bytes (Alternate version) ``` s->join(union(s)) ``` This uses `union` as basically a substitute for `unique` - I don't consider this the "real" answer, as I interpret "don't use `unique`" to mean "don't use a single built-in function that has the effect of returning the unique elements". [Answer] # Ruby, ~~30~~ 24 characters (23 characters code + 1 character command line option.) ``` gsub(/./){$`[$&]?"":$&} ``` Sample run: ``` bash-4.3$ ruby -pe 'gsub(/./){$`[$&]?"":$&}' <<< 'hello world' helo wrd ``` [Answer] ## Perl, 54 27 bytes ``` map{$h{$_}||=print}<>=~/./g 123456789012345678901234567 ``` Test: ``` $ echo Type unique chars! | perl -e 'map{$h{$_}||=print}<>=~/./g' Type uniqchars! $ ``` [Answer] # PHP, 72 Bytes ~~84 Bytes~~ ``` <?foreach(str_split($argv[1])as$c)$a[$c]=0;echo join('',array_keys($a)); ``` Uses the characters as keys for an associative array, then prints the keys. Order of array elements is always the order of insertion. Thanks Ismael Miguel for the `str_split` suggestion. [Answer] # Java, 78 bytes ``` String f(char[]s){String t="";for(char c:s)t+=t.contains(c+"")?"":c;return t;} ``` A simple loop while checking the output for characters already present. Accepts input as a `char[]`. [Answer] # [Haskell](http://ghc.io/), 29 bytes Nestable, no-variable-name one-liner: ``` foldr(\x->(x:).filter(x/=))[] ``` Same count, saved into a function named `f` as a top-level declaration: ``` f(x:t)=x:f[y|y<-t,x/=y];f_=[] ``` Note that there is a slightly-cheating optimization which I haven't made in the spirit of niceness: it is technically still allowed by the rules of this challenge to use a different input and output encoding for a string. By representing any `string` by its partially-applied Church encoding `\f -> foldr f [] string :: (a -> [b] -> [b]) -> [b]` (with the other side of the bijection provided by the function `($ (:))`) this gets golfed down to `($ \x->(x:).filter(x/=))`, only 24 characters. I avoided posting the 24-character response as my official one because the above solution could be tried on the above interpreter as `foldr(\x->(x:).filter(x/=))[]"Type unique chars!"`whereas the golfed solution would be written instead: ``` ($ \x->(x:).filter(x/=))$ foldr (\x fn f->f x (fn f)) (const []) "Type unique chars!" ``` as a shorthand for the literal declaration which would be the more-insane: ``` ($ \x->(x:).filter(x/=))$ \f->f 'T'.($f)$ \f->f 'y'.($f)$ \f->f 'p'.($f)$ \f->f 'e'.($f)$ \f->f ' '.($f)$ \f->f 'u'.($f)$ \f->f 'n'.($f)$ \f->f 'i'.($f)$ \f->f 'q'.($f)$ \f->f 'u'.($f)$ \f->f 'e'.($f)$ \f->f ' '.($f)$ \f->f 'c'.($f)$ \f->f 'h'.($f)$ \f->f 'a'.($f)$ \f->f 'r'.($f)$ \f->f 's'.($f)$ \f->f '!'.($f)$ const[] ``` But it's a perfectly valid version of the data structure represented as pure functions. (Of course, you can use `\f -> foldr f [] "Type unique chars!"` too, but that is presumably illegitimate since it uses lists to actually store the data, so its foldr part should then presumably be composed into the "answer" function, leading to more than 24 characters.) [Answer] # C - 58 Thanks to @hvd and @AShelly for saving a bunch of characters. There were multiple ways suggested of making it much shorter than the original: ``` // @hvd - always copy to q but only increment q if not found g(char*s,char*r){char*q=r;for(;*q=*s;q+=q==strchr(r,*s++));} // @AShelly - keep a histogram of the usage of each character h(char*s){int a[128]={0};for(;*s;s++)a[*s]++||putchar(*s);} // @hvd - modify in place i(char*s){char*q=s,*p=s;for(;*q=*p;q+=q==strchr(s,*p++));} // original version - requires -std=c99 void f(char*s,char*r){for(char*q=r;*s;s++)if(!strchr(r,*s))*q++=*s;} ``` As you can see modifying in place seems to be the shortest (so far!) The test program compiles without warnings using `gcc test.c` ``` #include <stdlib.h> // calloc #include <string.h> // strchr #include <stdio.h> // puts, putchar // 000000111111111122222222223333333333444444444455555555556666666666 // 456789012345678901234567890123456789012345678901234567890123456789 // @hvd - always copy to q but only increment q if not found g(char*s,char*r){char*q=r;for(;*q=*s;q+=q==strchr(r,*s++));} // @AShelly - keep a histogram of the usage of each character h(char*s){int a[128]={0};for(;*s;s++)a[*s]++||putchar(*s);} // @hvd - modify in place i(char*s){char*q=s,*p=s;for(;*q=*p;q+=q==strchr(s,*p++));} /* original version - commented out because it requires -std=c99 void f(char*s,char*r){for(char*q=r;*s;s++)if(!strchr(r,*s))*q++=*s;} */ // The test program: int main(int argc,char*argv[]){ char *r=calloc(strlen(argv[1]),1); // make a variable to store the result g(argv[1],r); // call the function puts(r); // print the result h(argv[1]); // call the function which prints result puts(""); // print a newline i(argv[1]); // call the function (modifies in place) puts(argv[1]); // print the result } ``` Thanks for all the help. I appreciate all the advice given to shorten so much! [Answer] # [Python 3](https://docs.python.org/3/), 26 bytes ``` lambda s:[*dict(zip(s,s))] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYKlorJTO5RKMqs0CjWKdYUzP2f0FRZl6JRppGZl5BaYmGpqbm/5DKglSF0rzMwtJUheSMxKJiRQA "Python 3 – Try It Online") Reviving an ancient question with a new idea, inspired by [Noodle9's solution to "Special String reformatting"](https://codegolf.stackexchange.com/a/205837/20260) and my [further refinement](https://codegolf.stackexchange.com/a/205855/20260). Because Python 3's dictionaries automatically remove duplicate keys beyond the first appearance while keeping them in order, we convert the the input string to a dictionary as keys. We then convert the dictionary back to a list with iterable unpacking, which extracts its keys. (The challenge seems to be fine with a list of characters in lieu of a string, asking for a "sequence of chars".) While we could make the dictionary via a comprehension like `{c:1for c in s}`, it's one byte shorter to use the `dict` constructor as `dict(zip(s,s))`, which each character is both the key and the values. A same-length alternative is `{}.fromkeys(s)`. Note that while `set` does also remove duplicates, it fails to keep them in order, and is also disallowed by the challenge. [Answer] # Java, 79 bytes It's java, and it may be a little bit shorter than some of the more wordy esoteric languages. But still, java. ``` s->{String r="";for(char c:s.toCharArray())r+=(r.indexOf(c)>-1)?"":c;return r;} ``` Explanation: ``` s->{ //Lambda expression opening, note that java can infer the type of s String r=""; //Initializes String r for(char c:s.toCharArray()) //Iterates through the string r+=(r.indexOf(c)>-1)?"":c; //indexOf(c) returns -1 if there are no occurrences return r; } ``` [Answer] ## [Befunge](http://www.esolangs.org/wiki/Befunge)-93, 124 bytes ``` v <v1p02-1 0_v#`g00: <0_@#+1::~p 1>:1+10p2+0g-!#v_v g `#v_10g0^ >:10g00 ^0g 00$ < ^ >:,00g1+:00p1+:1+01-\0p ``` Test it in [this online interpreter](http://www.quirkster.com/iano/js/befunge.html). --- This was more difficult than I expected. I'll post a fuller explanation tomorrow if anyone wants me to, but here's an overview of what my code does. * Unique characters seen so far are stored on the first row, starting from `2,0` and extending to the right. This is checked against to see if the current character is a duplicate. * The number of unique characters seen so far is stored in `0,0` and the check-for-duplicate loop counter is stored in `1,0`. * When a unique character is seen, it is stored on the first row, printed out, and the counter in `0,0` is incremented. * To avoid problems with reading in the spaces present (ASCII 32), I put the character corresponding to -1 (really, 65536) in the next slot for the next unique character. [Answer] ## C, 96 bytes ``` #include<stdio.h> int c,a[128];main(){while((c=getchar())-'\n')if(!a[c])a[c]=1,putchar(c);} ``` This uses an array of integers, indexed by ASCII character number. The characters are only printed if that place in the array is set to FALSE. After each new character is found that place in the array is set to TRUE. This takes a line of text from standard input, terminated by a newline. It ignores non-ASCII characters. --- Ungolfed: ``` #include<stdio.h> #include<stdbool.h> int main(void) { int i, c; int ascii[128]; for (i = 0; i < 128; ++i) { ascii[i] = false; } while ((c = getchar()) != '\n') { if (ascii[c] == false) { ascii[c] = true; putchar(c); } } puts("\n"); return(0); } ``` [Answer] # PHP, ~~56~~ 54 ``` // 56 bytes <?=join('',array_flip(array_flip(str_split($argv[1])))); // 54 bytes <?=join(!$a='array_flip',$a($a(str_split($argv[1])))); ``` Edging out @fschmengler's [answer](https://codegolf.stackexchange.com/a/59656/16410) using `array_flip` twice - second version uses variable method and relies on casting the string to true, negating it to false, then casting it back to the empty string in the first argument to save a couple of bytes in the second. Cheap! ]
[Question] [ I can't believe we don't have this already.. It's one of the most important data-structures in programming, yet still simple enough to implement it in a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): ## Challenge Your task is to implement a stack that allows pushing and popping numbers, to test your implementation and keep I/O simple we'll use the following setup: * Input will be a list of non-negative integers Every positive integer \$n\$ indicates a \$\texttt{push(}n\texttt{)}\$ and every \$0\$ indicates a \$\texttt{pop()}\$ - discarding the top element. * Output will be the resulting stack ## Example For example if we're given \$[12,3,0,101,11,1,0,0,14,0,28]\$: $$ \begin{aligned} & 12 & [12] \\ & 3 & [3,12] \\ & 0 & [12] \\ & 101 & [101,12] \\ & 11 & [11,101,12] \\ & 1 & [1,11,101,12] \\ & 0 & [11,101,12] \\ & 0 & [101,12] \\ & 14 & [14,101,12] \\ & 0 & [101,12] \\ & 28 & [28,101,12] \end{aligned} $$ Output will be: \$[28,101,12]\$ ## Rules * Input will be a list of non-negative integers in any [default I/O format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) + you may use a negative integer to signify the end of a stream of integers * Output will be a list/matrix/.. of the resulting stack + your choice where the top element will be (at the beginning or end), the output just has to be consistent + output is flexible (eg. integers separated by new-lines would be fine), the only thing that matters is the order + you may use a negative integer to signify the bottom of the stack * You're guaranteed that there will never be a \$0\$ when the stack is empty ## Examples ``` [] -> [] [1] -> [1] [1,0,2] -> [2] [4,0,1,12] -> [12,1] [8,3,1,2,3] -> [3,2,1,3,8] [1,3,7,0,0,0] -> [] [13,0,13,10,1,0,1005,5,0,0,0] -> [13] [12,3,0,101,11,1,0,0,14,0,28] -> [28,101,12] ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` "@?@}x ``` Input is a row vector of numbers. The final stack is shown upside down, with the most recent element below. [Try it online!](https://tio.run/##y00syfn/X8nB3qG24v//aEMjHWMdAx1DA0MdQyACMoEcEyBhZBELAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8F/Jwd6htuJ/bKy6rq56hEvI/@hYrmhDENYx0DEC0iZA2lDHEMS00DEGMo10jMHSxjrmQCkgBPGMQaqAsiC1QGxgYKpjipAFagGLAs0xBCsAckDmGlnEAgA). ### Explanation ``` " % For each element in the input (implicit) @ % Push current element ? % If non-zero (this consumes the current element) @ % Push current element again } % Else x % Delete most recent element % End (implicit) % End (implicit) % Display (implicit) ``` [Answer] # [Java (JDK 10)](http://jdk.java.net/), 42 bytes Since "[the] output is flexible [...], the only thing that matters is the order", this changes the input array into a `0`-terminated array. Example : `[1,0,2]` will return `[2,0,2]` which is to be interpreted as `[2`~~`,0,2`~~`]` = `[2]`. ``` a->{int s=0;for(int v:a)a[v>0?s++:--s]=v;} ``` [Try it online!](https://tio.run/##bVBdb4IwFH33V9z4BKMQ0JkZEM2y52XJ9mh8qAiuCoW0hcwYfju7LfiRuZC095577unhHGhD3cPu2LGiKoWCA/ZerVjuPUWjByyreaJYyfWwqrc5SyDJqZTwThmH8whgQKWiCq@mZDsocGZ9KcH4fr0BKvbSNlSAt5LLukjFgnG13iwhg7ij7vKMLcjYj7JSWLpuQmrTdbP0V9JxQteVm7iJ2i4yImYXhVUqlYR4kAY4t@RSBXcl8cnk1s7JlARkQqb3jCl5QRZ@d@AUezwCPHXl@zMyeyChjhkGJAgMD5tn/eB8ILW9ZfwvsBoqjOewd25fjX@dpEoLr6yVV2FoynoVgp6kp8o@REvzbXBgHMLYjoatzKNJklaqn15QnR7ju/QHg3GDK3fIlSHqR3gtjAcvT/lefSPgODc7KJKBUV2zDcS4gbOrKItgK1J6jKAd@Jdbb2iCIS7Ah1UPhTD8T1JWp4/sk/J9auQJ@KSnX@3/jSLn/4cxLOin21Hb/QI "Java (JDK 10) – Try It Online") # Previous versions: ## [Java (JDK 10)](http://jdk.java.net/), 60 bytes ``` l->{for(int i;(i=l.indexOf(0))>0;l.remove(i))l.remove(--i);} ``` [Try it online!](https://tio.run/##dVHRToMwFH3fV9z41GppYLi4jI3E@GSi8WGPyx4qK0tnKaQt02Xh27F0iJjFkJZz7jk99xYO7MiCw@6jFUVVagsHx2lthaS3yeSqltcqs6JUnVjV71JkkElmDLwyoeA8AeirxjLrXsdS7KBwGlpbLdR@swWm9wZ7K8BTqUxdcL18EcYun5Xle67TFPJVK4P0nJcaCWVBJEisJBVqx7/echRinIaJpJoX5ZEjgfGAg0DgpGkTn97nbbauq@XGGlj1fQHODflB0QiSkEx/6ZzEJCJTEo8dMXlwLveMirHjbovc3qEwnJHZlcnleDEiUeR9jtx3Dee9qbmM3d16GN0PvriMj4fp/3wukI65qyn@CY9as5NXU@Sxocx0HHUJGCd9wPpkLC9oWVtauf9ikc@4g5sF3AymnLIs49VF/PeoVGO9mXSrab8B "Java (JDK 10) – Try It Online") **Credits:** * -1 byte thanks to [O.O.Balance](https://codegolf.stackexchange.com/users/79343/o-o-balance) ## If I can end the program with errors: 55 bytes (though everything is properly modified) ``` l->{for(int i;;l.remove(--i))l.remove(i=l.indexOf(0));} ``` [Try it online!](https://tio.run/##dVFdb4IwFH33V9z4BFshIDMzoiTLnpZs2YN7Mz5ULFpXCmkvOkP47ax8jLmYpWm5597Duee2R3qiznH3WfM0zxTC0WC3QC7cu3B0k0sKGSPPZFPMi63gMcSCag1vlEsoRwB9ViNF8zllfAepqVkrVFzu1xugaq/tlgrwnEldpEwtXrnGxYtEtmcqiiBZ1sKJyiRTFpcIPAyFq1ianZjlONy2B8SXwuVyx77eE8uz7bCqw1a4l1pvTENkGjUs@5YAZUV@Iv8qJB6Z/MIZCYhPJiS4ZgTk0bDMukoGBpvDN2cTed6UTG9IRqct@sT3W54BD03DWU@qOtvNwIP11vi8s28P7v/cFAiDzGiSneFJKXppq5HVxtqlusFWo2DuphdYXTSy1M0KdHPzJGi1GvcwnsN4IKG6QAmJS@OY5R3FDqGCmGJ8AOvjoLIz3QoGaJxB9Y@0kP2f3YyjZlf1Nw "Java (JDK 10) – Try It Online") [Answer] # Sed, 17 Bytes `:;s/[0-9]\+,0//;t` -3 bytes thanks to @OMᗺ, -1 thanks to @eggyal Because you're guaranteed to never pop an empty list, you don't need anything more than an iterated finite state machine. Regular expressions are a tool for building finite state machines, and `sed` can iterate. It's a match made in heaven. Takes input from stdin, like so: `echo '[12,3,0,101,11,1,0,0,14,0,28]' | sed ':;s/[0-9]\+,0,//;t'` Outputs the stack in reverse: `[12,101,28]` Could be smaller by two bytes if my local `sed` inherently understood character classes like `\d`, but it doesn't for some reason. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~46~~ ~~41~~ 40 bytes ``` $args|%{$x,$a=&({1,$_+$a},{$a})[!$_]};$a ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL24RrVapUJHJdFWTaPaUEclXlslsVanGkhoRiuqxMfWWqsk/v//39Dov/F/g/@GBob/DYEIyARyTICEkQUA "PowerShell – Try It Online") Takes input via splatting, e.g., `$z=@(12,3,0,101,11,1,0,0,14,0,28); .\implement-stack.ps1 @z`, which on TIO manifests as separate arguments. ``` $args|%{$x,$a=&({1,$_+$a},{$a})[!$_]};$a # Full program $args # Take input via splatting |%{ }; # Loop through each item &( )[!$_] # Pseudo-ternary, if input is 0 this is 1 $x,$a= {$a} # ... which will pop the first item into $x $a= { ,$_+$a} # Else, we append the first item $x = 1 # ... and drop a dummy value into $x $a # Leave $a on pipeline; implicit output ``` *-5 bytes thanks to mazzy.* *-1 byte swapping `$_` to `1`* [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~62~~ ~~60~~ ~~56~~ 55 bytes ~~-2~~ -6 bytes thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2) -1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). Uses the permitted notion of -1 terminated arrays. `f()` calls itself recursively, until fully wound, and then backtracks through the list. `r` keeps track of how many numbers to discard before printing something. Increases if current item is 0, decreases otherwise. If 0, we need not discard, and can print the number. ``` r;f(int*l){~*l?f(l+1),*l?r?r--:printf("%d ",*l):r++:0;} ``` [Try it online!](https://tio.run/##bY7fCoMgFMav11MchIGWglrCSEYPMnYx2hpBizB3Fe3Vm/aXoAv1nN/5vuOXs3eeD4PRBS5rG1ak@4VVVuAqEoS6ymSGsbQxblhgdH4CcpSkJopSrvvBYfg8yhqToAuCk2/tq7W3O1yhE5JCTIFTEFy4y5@x9SQZH3mhwESvN6ucvW42KqYFk3qvjCflBDecrAv2cjXzOVHsUy2BBOeKglrCrV8FpwJ7L9HQfG2LESJ6YfIIxkcwOYLKlf3wBw "C (gcc) – Try It Online") [Answer] ## Haskell, 28 bytes ``` foldl(#)[] (_:s)#0=s s#n=n:s ``` [Try it online!](https://tio.run/##RUztCgIhEPx/TyH4R2ELPzo6DnyEnsAk5Mo68kyy589W/8QyzM7O7Dx8ed5irIEYcq7hFa@RUW7dwC5z4VSYMhSaTJpL3fyaMLX5fCIsv9f0IXsSOLHWgZUNIEAhH5AlyLZOoHFVoLut4YgWTlO6pdBtWYQQI4x/F1/6FXtkD6BovWpyrn6XEP291N2S8w8 "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ṣ0Ṗ;¥/ ``` [Try it online!](https://tio.run/##y0rNyan8///hzsUGD3dOsz60VP//4fZHTWvc//@Pjo7V4VKINoSQOgY6RmCWCZBlqGMI4VjoGAM5RjrGUEXGOuZAaSCE8I1BaoEqQDqA2MDAVMcUWR6oESwONM8QrATIAZlvZBEbCwA "Jelly – Try It Online") ### How it works ``` ṣ0Ṗ;¥/ Main link. Argument: A (array) ṣ0 Split A at zeroes. ¥/ Left-reduce the resulting 2D array by this dyadic chain: Ṗ Pop; discard the last element of the left argument. ; Concatenate the result with the right argument. ``` [Answer] # [R](https://www.r-project.org/), 45 bytes ``` o={};for(e in scan())o="if"(e,c(e,o),o[-1]);o ``` [Try it online!](https://tio.run/##K/r/P9@2utY6Lb9II1UhM0@hODkxT0NTM99WKTNNSSNVJxmI8zV18qN1DWM1rfP/GxpxGXMZcBkaGHIZAhGQCeSYAAkji/8A "R – Try It Online") * -4 byte thanks to @Giuseppe [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes ``` #//.{a___,b_,0,c___}:>{a,c}& ``` [Try it online!](https://tio.run/##TYzNCgIxDITveY3CohDtn4uL4rKP4F2k1OLiHtaD9Fb67HVaLxISvmRmsvr4eq4@LsGX@bIpQsp98s45fjhWHED5NCbPIXdle6brZ3nHm9iN8yTunZwSUcpMSbeBhKlwAGjWjQe2YMP257B8hIhqq61G6NWOVqrn/k9Gqp3xSzcHlvrbDJkoly8 "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~59~~ ~~57~~ 51 bytes ``` s=[] for x in input():s=(s+[x],s[:-1])[x<1] print s ``` [Try it online!](https://tio.run/##DYdBCoAgEADvvcKj0QatdQjJlyx7jbyouAb2elsYhpnytScnN4YE4unO1XQTk1LeZmcvwcpCnUHIr8gz9Qt5KjWmZmQMQgc7bIAbAiqaOofKnfwD "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 48 bytes ``` s=[] for x in input():s=([x]+s)[2*0**x:] print s ``` [Try it online!](https://tio.run/##VY1BCsMgEEX3OcXgKrEu1DQ0CDmJuCqWCMVItNSe3jpKF4Vx@H/m/TF80n54Wd67e1oQymZ7J4SUuGkzPI4TMjhfK7zSOKm4jTqbS5y0pJzSrMwQTucTxIKhGtECHwPOQFZ1bap6gW5lMDcnq@hc9bfGYOFo7gnkehI75wuD5Y@TLduWeF78WJz0X@Vqvg "Python 2 – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~40~~ 36 bytes ``` ([]){{}{({}<>)<>}([]){{}<>}{}([])}<> ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6VrO6urZao7rWxk7Txq4WKgBkVYPZQNb//4ZGCsYKBgqGBoYKhkAEZAI5JkDCyAIA "Brain-Flak – Try It Online") Thanks to @Nitrodon for -4 bytes. Since Brain-Flak already uses stacks, this is a good puzzle for Brain-Flak. ``` ([]){ while items on stack {} pop stack count { if top element is non-zero ({}<>)<> push it on the other stack } if we're here the stack is either empty or there's a 0 on the stack ([]) so, count the stack again {{}<>{}<>} if there are items left on the stack, pop the stack count and the last item of the other stack {} pop the zero or the stack count ([]) count the stack again for next round } <> go to the output stack ``` [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 89 bytes ``` [N S S N _Create_Label_LOOP_1][S S S N _Push_0][S N S _Duplicate_0][T N T T _Read_STDIN_as_integer][T T T _Retrieve][S N S _Duplicate_input][N T T S _If_neg_Jump_to_Label_EXIT][S N S _Duplicate_input][N T S T N _If_0_Jump_to_Label_DROP][N S N N _Jump_to_Label_LOOP_1][N S S S N _Create_Label_EXIT][S N N _Discard_top][N S S S S N _Create_Label_LOOP_2][T N S T _Print_as_integer][S S S T S T S N _Push_10_newline][T N S S _Print_as_character][N S T S S N _Jump_to_Label_LOOP_2][N S S T N _Create_Label_DROP][S N N _Discard_top][S N N _Discard_top][N S N N _Jump_to_Label_LOOP_1] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. Takes the input-list new-line separated with `-1` to indicate we're done with the inputs. [Try it online](https://tio.run/##LYrLCYBADETPO1VsA8JGPdiOyILeBAXLjy/RkGS@z37c/TrXrburVpZTLSoxwb8PYgL6K4m4dEHC5DVlZCU6WZPcbdSkJmsmY6GImTcuGuwF). **Explanation in pseudo-code:** ``` Start LOOP_1: Integer i = STDIN as integer If(i is negative): Call function EXIT If(i is 0): Call function DROP Go to next iteration of LOOP_1 function EXIT: Start LOOP_2: Pop and print top as integer Print newline Go to next iteration of LOOP_2 function DROP: Drop the top of the stack Go to next iteration of LOOP_1 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~60~~ ~~59~~ ~~57~~ 56 bytes ``` l=input() while 0in l:i=l.index(0);l[i-1:i+1]=[] print l ``` [Try it online!](https://tio.run/##RYzPCsIwDMbvfYqy06ZR@sdhmfSknn2AspMWFih1SMX59DXZRULIl/y@fPO3TM9s6vl2ufqmaWrymOd3aTvxmTBFqTDLNKBPe8yPuLSqO6WAOz3gVo8@jGJ@YS4yVXoWIi7xLjlr4yqxoLlBgaF5oKlBs3RgSRqwK7ZwJETFm2UXUfZSK9VD/6f0sl4pR68GWjjXuPEH "Python 2 – Try It Online") --- Saved: * -1 byte, thanks to pushkin [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~214~~ 150 bytes ``` >>,[>++++++[-<-------->]+<[>+++++[-<++++++++>]]>[-<<<[[-]<],[-]>>>>-<<]>>+[<<+<,----------[++++++++++>-]>[->>-<]>[->+<]>]<<<,]<<[[<]++++++++++<]>>[.>] ``` Reads input as numbers separated by newlines. This must include a single trailing newline. Also expects no leading zeros on each number. Output as a similar newline separated list [Try it online!](https://tio.run/##RYzBCsNACETv/opryaY95CD@iMwhCRRKoYdAv387G5b0IY4OOtuxvj7P7/5uLaJk6Ema2yCgPmy6OggguLpnGhyFPQgdqqa7erGL1Iuw/tgvT1UKGFPQoxz/wx6Ut0BrdZa7TFKnKpXFkcuDbV7kBw "brainfuck – Try It Online") # Explanation ~~that isn't really an explanation but is actually just the version I was working on with the comments and stuff which may or may not actually be useful to anyone~~ ``` Stack format: 0 (0 \d*)* >>,[ Setup digit == '0' conditional >++++++ [-<-------->] + <[ Read digit != '0' Restore the char code cond1 is already 1 at this stage >+++++ [-<++++++++>] ]>[ Read digit == '0' - Pop previous value <<<[ [-]< ] Skip next input (assumed to be newline) ,[-] Skip following loop by unsetting loop flag >>>>- << ] Move to next stack frame > Set loop flag >+[ Set bit used for conditional <<+ Read next character <, Compare with '\n' ----------[ Not '\n': restore the char code ++++++++++ >- ]>[ - == '\n': Leave as 0 Unset loop flag >>- < ] Copy loop flag along > [- > + <] Move to loop flag of next stack frame > ] <<< ,] Fill in with newlines <<[ Skip to the cell before this value [<] Put a newline in there ++++++++++ Move to next value < ] Now the tape has the exact values we need to output >>[.>] ``` [Answer] # JavaScript, 40 bytes Outputs in reverse order. ``` a=>a.map(x=>x?o.push(x):o.pop(),o=[])&&o ``` [Try it online](https://tio.run/##VZBPj8IgEMXP@ik8GUhGLKDZZpN27x7Wg0dsInGpW@MyTVHT/fR1qP8hJPB7bx6T2duzDdumqo8Tjz@uK7POZrkVf7ZmbZa3XyjqU/hlLf@kG9aMA2am4OMxdlv0AQ9OHHDHzNAUMKA1nY4m@cgUQyPfgIwEElA9vUFFcEZQgnzjUkH0p6BJUqBfNU1AkpD2gRo@qJ72qyUqOsZSeQynkyRzmD@c9290dFJ@76AmZG@mR2xKpU@nSq8Gari4z2axWn6LcGwqv6vKf1bSjETjzq4JjnHOxR4rv1n7De8u) 1 byte saved thanks to [Herman L](https://codegolf.stackexchange.com/users/70894/herman-l). [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 32 bytes ``` ([]){{}{({}<>)<>}{}<>{}<>([])}<> ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6VrO6urZao7rWxk7Txq4WRIMwSAJI/f9vaKRgrGCgYGhgqGAIREAmkGMCJIwsFHQNAQ "Brain-Flak – Try It Online") Uses `-1` to signify the end of the array (but any number will do really). [Answer] # [V](https://github.com/DJMcMayhem/V), 10 bytes ``` ò/ 0⏎b2dw0 ``` [Try it online!](https://tio.run/##K/v///AmfQUDriSjlHKD//8NDRQMFQyA0FjBVMEAAA "V – Try It Online") ### Explanation ``` ò " run the following, until an error occurs / 0⏎ " | goto next zero with space in front (errors if none) b " | jump one word back (to the beginning of element to pop) 2 " | twice (element & zero itself) dw " | | delete word 0 " | goto beginning of line ``` --- ## Equivalent in [Vim](https://www.vim.org/), 16 bytes ``` qq/ 0⏎b2dw0@qq@q ``` [Try it online!](https://tio.run/##K/v/v7BQX8GAK8kopdzAobDQofD/f0MDBUMFAyA0VjBVMAAA "V – Try It Online") ### Explanation Pretty much the same, except recording a macro `q` and recursively call it: ``` qq " record macro q / 0⏎b2dw0 " same as in V @q " recursively call q (aborts on error) q " quit recording @q " execute the macro q ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 21 bytes ``` ~c₃Ckt[İ,0]≠∧C⟨hct⟩↰| ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp3wvy75UVOzc3ZJ9JENOgaxjzoXPOpY7vxo/oqM5JJH81cC1db8/x@tEB2roxBtCCZ0DHSMQAwTIMNQxxDMttAxBrKNdIwhKox1zIGSQAjmGoMUAuVByoHYwMBUxxRJGqgLLAw0yxCsAsgBmW1kERsLAA "Brachylog – Try It Online") -1 byte, and more importantly this feels like a much less clunky way of doing this. ``` ~c₃ % Partition the input into 3 subarrays C % Call that array-of-arrays C kt[İ,0] % Its second element should be of the form [Integer, 0] ≠ % And its elements shouldn't be equal (i.e. % the Integer shouldn't be 0) ∧C⟨hct⟩ % Then, remove that [İ, 0] element from C ↰ % And call this predicate recursively | % When the above fails (when it can't find a partition with % [İ, 0] in it), then just output the input ``` Alternate 21 byter: `∋0∧ℕ₁;0;P↺c;Qc?∧P,Q↰|` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp3w/1FHt8GjjuWPWqY@amq0NrAOeNS2K9k6MNkeKBigEwhUXPP/f7RCdKyOQrQhmNAx0DECMUyADEMdQzDbQscYyDbSMYaoMNYxB0oCIZhrDFIIlAcpB2IDA1MdUyRpoC6wMNAsQ7AKIAdktpFFbCwA "Brachylog – Try It Online") --- Older code: **22 bytes** ``` ∋0&b,1;?z{=|¬∋0&}ˢtᵐ↰| ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FHt4Fako6htX1VtW3NoTVgfu3pRSUPt0541Lah5v//aENjHQMdIGEIJEEsAwNTHVMgAwhj/0cBAA "Brachylog – Try It Online") ``` ∋0 If input contains a 0, &b Remove input's first element, getting list of "next" elements ,1 Append 1 to that to handle last element ;?z Zip that with input { }ˢ Select only zipped pairs where =| both elements are equal (to keep 0s followed by 0s) ¬∋0& or the pair doesn't contain a 0 this removes both the (pairs containing the) value that is followed by a 0, and the 0 itself tᵐ Recover back the (filtered) input array elements from the zip ↰ Call this predicate recursively | If input contains no 0s, input is the output ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` vy>i¨ëy)˜ ``` [Try it online](https://tio.run/##MzBNTDJM/f@/rNIu89CKw6srNU/P@f8/2tBIx1jHQMfQwFDHEIiATCDHBEgYWcQCAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/u5ulir6TwqG2SgpL9/7JKu8xDKw6vrtQ8Ped/ba3O/2jDWK5oQx0DHSMgbaFjrGOoY6RjDBYz1jEHigMhiGcMZAAJQyAJYhkYmOqYImSBWsCihjqGhmAFQI4JyFALoKxBLAA). **Explanation:** ``` v # For-each of the items in the input-list: y>i # If the current item is 0: ¨ # Pop the top item of the list ë # Else: y # Push the current item to the stack ) # Wrap the entire stack into a list # i.e. 12 → [12] # i.e. [12] and 3 → [[12], 3] ˜ # Flatten the stack # i.e. [[12], 3] → [12, 3] # (and output the list implicitly after the loop) ``` --- **9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative:** ``` vy_i\ëy]) ``` [Try it online](https://tio.run/##MzBNTDJM/f@/rDI@M@bw6spYzf//ow2NdIx1DHQMDQx1DIEIyARyTICEkUUsAA) of [verify all test cases](https://tio.run/##MzBNTDJM/W/u5ulir6TwqG2SgpL9/7LK@MyYw6sra2s1/@v8jzaM5Yo21DHQMQLSFjrGOoY6RjrGYDFjHXOgOBCCeMZABpAwBJIgloGBqY4pQhaoBSxqqGNoCFYA5JiADLUAyhrEAgA). **Explanation:** ``` v # For-each of the items in the input-list: y_i # If the current item is 0: \ # Discard top item of the stack ë # Else: y # Push the current item to the stack ] # Close both the if-else and for-each (short for `}}`) ) # Wrap the entire stack into a list (and output implicitly) ``` PS: If the output should have been reversed to match the test cases in the challenge description, we can add a trailing `R` to the second version (so **10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**), which reverses the list. [Try it online](https://tio.run/##MzBNTDJM/f@/rDI@M@bw6spYzaD//6MNjXSMdQx0DA0MdQyBCMgEckyAhJFFLAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/u5ulir6TwqG2SgpL9/7LK@MyYw6sra2s1g/7r/I82jOWKNtQx0DEC0hY6xjqGOkY6xmAxYx1zoDgQgnjGQAaQMASSIJaBgamOKUIWqAUsaqhjaAhWAOSYgAy1AMoaxAIA). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 18 bytes ``` ^ , +1`,\d+,0 ^, ``` [Try it online!](https://tio.run/##NYzBCoAwDEPv@Q4FYTmsm6J/4NEfkDFBD148iP8/M0FKS5OX9j6e89pK2825JBDOMtfd0QOJwJKaLFkKDEbPgF7TaAETo5bAKBA5ylbBYuUiNaX2fuDwM4U/T/f2YYn6L0wv "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^ , ``` Prefix an extra `,`. ``` +1`,\d+,0 ``` Process all pop operations. ``` ^, ``` Remove the `,` if it's still there. Reversing the numbers would cost an extra 8 bytes: ``` O^$`\d+ ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 36 bytes ``` ->a{b=[];a.map{|x|x>0?b<<x:b.pop};b} ``` [Try it online!](https://tio.run/##VY7RCsIwDEXf9xUDX7PRtA6L2@qHlD604vBFLGPCZO2313SyoZRA78nNTcaXe6ehT5Wyi@u1aW39sH4Jc5gVu7ium8@u9k8fWxeTLrQp4VCpUptC4/bHLIAB3wAncCSAgDtDDtknQRDmIDYuSCBBuYYIONEcvd89IkfRWA6kYqyB5t@FIvsode3TWlytJPIZXO6HyW@bDjT1zV7vS5iCLwc9mZg@ "Ruby – Try It Online") Anonymous lambda. Outputs in reverse order. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 36 bytes ``` ([]){{}{(({}<>))(<>)}{}<>{}<>([])}<> ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6VrO6urZaQ6O61sZOU1MDSNSCmCAMkgRS//8bGikYKxgoGBoYKhgCEZAJ5JgACSMLAA "Brain-Flak – Try It Online") ``` #Let's call the two stacks in and out ([]){{} ([])} # while not in.empty() { ( )}{} # if in.peek() != 0 (({}<>)) <> # a = in.pop; out.push(a); out.push(a) <>{}<> # out.pop() <> # switch to out to be printed ``` [Answer] # Java 10, ~~75~~ 72 bytes ``` n->{var s="";for(int i:n)s=(s+","+i).replaceAll(",\\d+,0","");return s;} ``` Outputs separated by a comma. Top of the stack is last. Try it online [here](https://tio.run/##tVPLbtswELz3KxY8UTAjWHKDGhEcwEBbIEiLHnKMe2BkOqBDUy6XchIY@nZ3SUmuhR6qSymI4mN2ZpcabuVBXm3XL6d9/WR0CaWRiPBdagvHD0BNW6/cRpYKHrwsX7rV0B680/YZ9q4qFSIn4ONPsPXuSTlMighrYt9Ro5eePodKr2FHArwloCDpnjEZMAcljP0CTvbq9niQDnDBWLGpXJACfWMTXHCcMMEmOkmd2hvKcmkMZ2K1Wk/ElHZYUjjla2cBi@bU8xdnJa/Q8ygkwKpXaIs4NgJC6L9gWcCJbAxSTEUe0fkI9EdCZyJrA8JgRMxczAiai1kMOs9G5TYTn0iRnrF1z0KCpBDSpHc6vRbXfxhoawwJZReDqcAs8tAkVJ7PW5I87uVzNjST0wfp1cBNUeHCNAIGZhS9VdXbXpVerZO/XSxLX0tDbosEaW/qoZ3jfdjwniZVvygGeRubXLJG5nf0apdWtSc6SshYvqXbltZem3TpnHzH1Fet/lkIJsBgcQsrxmjYZUVrKwb8x31yea4NKIPqf4t@Xd59@/JZnM/upkP18xY3TKz7Xc3pNw). Thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%C3%A9goire) for golfing 2 bytes. Please check out [Kevin Cruijssen's](https://codegolf.stackexchange.com/a/169361/79343) and [Olivier Grégoire's](https://codegolf.stackexchange.com/a/169423/79343) Java answers as well. They take a list-based approach instead, with the latter beating mine by a tidy margin. Ungolfed: ``` n -> { // lambda taking an integer array as argument and returning a String var s = ""; // we'll be using a String to implement and output the stack for(int i : n) // loop through the array s = (s + "," + i) // append the next number .replaceAll(",\\d+,0", ""); // remove any number followed by a zero return s; // output the resulting stack } ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), ~~14~~ 12 bytes ``` ~{.{;}if}/]` ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPmfp1r9v65ar9q6NjOtVj824X@tap7W/@hYBa5oQzChYKBgBGKYABmGCoZgtoWCMZBtpGAMUWGsYA6UBEIw1xikECgPUg7EBgamCqZI0kBdYGGgWYZgFUAOyGwji1gA "GolfScript – Try It Online") ``` ~{.{;}if}/]` Full program, implicit input ~ Eval input { }/ Foreach: if If the value is truthy (!= 0): . Push itself {;} Else: pop the top value ]` Push as array representation Implicit output ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 17 bytes *Thanks @sundar and @DomHastings* ``` s/\d+ 0 ?//&&redo ``` [Try it online!](https://tio.run/##K0gtyjH9/79YPyZFW8FAwV5fX02tKDUl//9/QyMFY6CIoYGhgiEQAZlAjgmQMLJQMPiXX1CSmZ9X/F/X11TPwNDgv24BAA "Perl 5 – Try It Online") [Answer] # [><>](https://esolangs.org/wiki/Fish), 25 bytes ``` i:?\~~ (0:/:^? !?l:!<oan; ``` [Try it online!](https://tio.run/##S8sszvj/P9PKPqaujkvDwErfKs6eS9E@x0rRJj8xz/r/fwA "><> – Try It Online") (input must be written in ascii. otherwise use [this one](https://fishlanguage.com/)) ### How it works `i:?\~~` checks for 0, continues to `~~` to delete previous entry. otherwise go down to: `(0:/:^?` which checks for -1 (no more input), then wrap up to delete -1 and loop: `!?l:!<oan;` which outputs each number with a newline, then ends when stack emptied [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes Since there's no Husk answer already and it's my favourite golfing-lang: ``` F`?:tø ``` [Try it online!](https://tio.run/##yygtzv6fG5yvnaCtpKBrp6B0Yn3xo6bGokPb/rsl2FuVHN7x////6FiuaEMQ1jHQMQLSJkDaUMcQxLTQMQYyjXSMwdLGOuZAKSAE8YxBqoCyILVAbGBgqmOKkAVqAYsCzTEEKwByQOYaWcQCAA "Husk – Try It Online") ### Explanation ``` F`?:tø -- F ø -- foldl (reduce) with [] as the initial accumulator ` -- | flip arguments of ?: -- | | if truthy: apply cons (prepend) to it t -- | | else: return tail -- | : returns a function, either prepending the element or dropping 1 element ``` ### Alternative solution, 6 bytes Instead of flipping, we can also just reverse the list and then use a right-fold: [`Ḟ?:tø↔`](https://tio.run/##yygtzv6fG5yvnaCtpKBrp6B0Yn3xo6bGokPb/j/cMc/equTwjkdtU/7//x8dyxVtCMI6BjpGQNoESBvqGIKYFjrGQKaRjjFY2ljHHCgFhCCeMUgVUBakFogNDEx1TBGyQC1gUaA5hmAFQA7IXCOLWAA "Husk – Try It Online") [Answer] ***Warning:*** Lots of lines ensue. You have been warned. --- # [CJam](https://sourceforge.net/projects/cjam/), 17 bytes **Most dangerous code** (Assumes the stack elements can be separated by only spaces in the output and that the input array can be whatever form we wish) ``` q~{X0={;}X?}fX]S* ``` [Try it online!](http://cjam.aditsu.net/#code=q%7E%7BX0%3D%7B%3B%7DX%3F%7DfX%5DS*&input=%5B1%200%201%201%5D) *Explanation* ``` q Reads input string ~ Instantly convert to array since the string is in the CJam format { }fX For loop X0= If X (the array element currently being checked) is equal to 0 {;} Pop the top element from the stack X Else push X onto the top of the stack ? If-Else flag ] Collate all stack elements into an array S* Put a space between each array element ``` --- **Alternate Code #1, 27 bytes** (Assumes stack elements have to be output in the format shown in the question and that the input array can be whatever form we wish) ``` q~{X0={;}X?}fX]',S+*'[\+']+ ``` [Try it online!](http://cjam.aditsu.net/#code=q%7E%7BX0%3D%7B%3B%7DX%3F%7DfX%5D%27%2CS%2B*%27%5B%5C%2B%27%5D%2B&input=%5B1%200%201%201%5D) *Explanation* ``` q Reads input string ~ Instantly convert to array since the string is in the CJam format { }fX For loop X0= If X (the array element currently being checked) is equal to 0 {;} Pop the top element from the stack X Else push X onto the top of the stack ? If-Else flag ] Collate stack items into an array ',S+ Add together a comma and a space to create a delimiter * Apply the delimiter to the stack '[\+ Append left bracket to the left of the stack text ']+ Append right bracket to the right of the stack text ``` --- **Alternate Code #2, 24 bytes** (Assumes the stack elements can be collated in the output and that the input array has to be in the exact format shown in the question) ``` q',/~]S*~{X0={;}X?}fX]S* ``` [Try it online!](http://cjam.aditsu.net/#code=q%27%2C%2F%7E%5DS*%7E%7BX0%3D%7B%3B%7DX%3F%7DfX%5DS*&input=%5B1%2C0%2C1%2C1%5D) *Explanation* ``` q Read input string ',/ Separate by commas (since commas are an invalid array delimiter in CJam) ~ Turn string into an array of substrings that make up the array ]S* Add spaces in between input numbers to prevent collation in the array ~ Turn the string into a valid array representative of the original { }fX For loop X0= If X (the array element currently being checked) is equal to 0 {;} Pop the top element from the stack X Else push X onto the top of the stack ? If-Else flag ] Collate all stack elements into an array S* Add a space between each element ``` --- **Safest code for this, 34 bytes** (Assumes stack elements have to be output in the format shown in the question and that the input array has to be in the exact format shown in the question) ``` q',/~]S*~{X0={;}X?}fX]',S+*'[\+']+ ``` [Try it online!](http://cjam.aditsu.net/#code=q%27%2C%2F%7E%5DS*%7E%7BX0%3D%7B%3B%7DX%3F%7DfX%5D%27%2CS%2B*%27%5B%5C%2B%27%5D%2B&input=%5B1%2C0%2C1%2C1%5D) *Explanation* ``` q Read input string ',/ Separate by commas (since commas are an invalid array delimiter in CJam) ~ Turn string into an array of substrings that make up the array ]S* Add spaces in between input numbers to prevent collation in the array ~ Turn the string into a valid array representative of the original { }fX For loop X0= If X (the array element currently being checked) is equal to 0 {;} Pop the top element from the stack X Else push X onto the top of the stack ? If-Else flag ] Collate stack items into an array ',S+ Add together a comma and a space to create a delimiter * Apply the delimiter to the stack '[\+ Append left bracket to the left of the stack text ']+ Append right bracket to the right of the stack text ``` --- Thanks to [@Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) for pointing out that the ones with the collated output are invalid since things like `[12]` and `[1,2]` would be indistinguishable. Thanks also to [@Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) providing a very suitable alternative for the collated outputs and cutting off 9 bytes! [Answer] # [Red](http://www.red-lang.org), 64 bytes ``` func[b][a: copy[]foreach n b[either n > 0[insert a n][take a]]a] ``` [Try it online!](https://tio.run/##ZU1BCsMwDLvvFXpC0qys9LBH7Gp8SFuHlkFasuzQ12duDyNjGIMkS3KSqTxkIr6EvoR3HGlg8j3GdduJw5rEjzMiBpIlz5IU3mFoiS9JGR6RKfunwDN7LltaYkaA1n2hrTEMmopflVvYWurgVGrgfmION7Xq1Ko70uo@OnSNadH@u7TqvOofexqVHH@bjssH "Red – Try It Online") ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. Create the shortest possible obfuscated FizzBuzz implementation. To be considered obfuscated, it should satisfy at least one of the following: 1. Does not contain any of the words "Fizz", "Buzz", or "FizzBuzz" 2. Does not contain the numbers 3, 5, or 15. 3. Use any of the above in a misleading way. Remember: The goal is to be short *and* hard to follow. The code sample which inspired this question follows: ``` public class Default { enum FizzBuzz { Buzz = 1, Fizz, FizzBuzz } public static void Main(string[] args) { byte[] foo = Convert.FromBase64String("IAmGMEiCIQySYAiDJBjCIAmGMEiCIQySYA=="); MemoryStream ms = new MemoryStream(foo); byte[] myByte = new byte[1]; do { FizzBuzz fb; ms.Read(myByte, 0, 1); for (int i = 0; i < 4; i++) { fb = (FizzBuzz)(myByte[0] >> (2 * i) & (int)FizzBuzz.FizzBuzz); Console.Out.WriteLine( (((int)fb > 0) ? "" + fb : "" + ((ms.Position - 1) * 4 + i + 1))); } } while (ms.Position < ms.Length); } } ``` [Answer] ## Javascript 97 chars - no numbers at all Numbers ? Who needs number when you have Javascript ! ``` a=b=!![]+![],a--,c=b+b;while(++a)e=!(a%(c+c+b)),alert(!(a%(c+b))?e?"FizzBuzz":"Fizz":e?"Buzz":a); ``` Note: There is an infinite loop that will alert you the sequence. **Bonus** (666 chars) * No number * No letter (only `zfor` has been use in the whole script) . ``` _=$=+!![];$__=((_$={})+'')[_+$+_+$+_];__$=((![])+'')[$];_$_=((_$={})+'') [_+$+_+$+_+$];____=[][$__+((_$={})+'')[$]+(($)/(![])+'')[$]+$__+__$+_$_];$__$=(!![]+"") [$+$+$]+([][(![]+"")[$+$+$]+(+[]+{})[$+$]+(!![]+"")[$]+(!![]+"")[+[]]]+"")[($+$)+""+ ($+$+$)]+(![]+"")[$]+(![]+"")[$+$];$_$_=____()[$-$][$__$]("\"\\"+($)+($+$+$+$+$+$+$)+ ($+$)+"\"");_$=(![]+'')[$-$]+([][[]]+[])[$+$+$+$+$]+$_$_+$_$_;$_=(_+{})[$+$+$]+(!![]+'') [_+$]+$_$_+$_$_;_--,$$=$+$;____()[$-$][$__$]((![]+"")[+[]]+(+[]+{})[$+$]+(!![]+"")[$]+ "(;++_;)$$$=!(_%("+($$+$$+$)+")),____()[+[]][__$+((![])+'')["+($+$)+"]+((!![])+'')["+ ($+$+$)+"]+((!![])+'')[+!![]]+_$_](!(_%("+($$+$)+"))?$$$?_$+$_:_$:$$$?$_:_);"); ``` [Answer] ## GolfScript, ~~75~~ ~~69~~ ~~65~~ ~~60~~ 59 chars ``` 100,{)6,{.(&},{1$1$%{;}{4*35+6875*25base{90\-}%}if}%\or}%n* ``` So, you'd think GolfScript by itself is already obfuscated, right? Well, just to follow the spec, I decided to have the program not contain "fizz", "buzz", nor the numbers 3, 5, nor 15. :-) Yes, there are some numbers with multiples of 5, like 25, 35, 90, 100, and 6875. Are they red herrings? You decide. ;-) [Answer] ## Python - 78 chars ``` i=0 while 1:i+=1;print"".join("BzuzzizF"[::2*j]for j in(-1,1)if 1>i%(4+j))or i ``` [Answer] # PostScript, 96 bytes So obfuscated it looks like random garbage. ``` 1<~0o0@eOuP7\C+tf6HS7j&H?t`<0f>,/0TnSG01KZ%H9ub#H@9L>I=%,:23M].P!+.F6?RU#I;*;AP#XYnP"5~>cvx exec ``` Usage: `$ gs -q -dNODISPLAY -dNOPROMPT file.ps` [Answer] ## C++: 886 chars I've tried to hide the 'fizz' and the 'buzz'. Can you spot them? ``` #include <iostream> #define d(a,b) a b #define _(a,b) d(#b,#a) #define b(b) _(b,b) #define y _(i,f)c #define x _(u,b)c #define c b(z) #define i int #define p main #define s char #define q 810092048 #define h for #define m 48 #define a ++ #define e == #define g 58 #define n 49 #define l << #define oe std::cout<< #define v '\n' int p (i, s*t ){i j = q;h (*( i * ) t = m ; 2 [ t ]? 0 : 1 ??( t ] ? a 1 [ t ] e g ? 1 [ t ] = 48, ++0 ??( t]e g?0 ??( t]= n ,1[ t]= 2 [ t ] =m : 1 : 1 : a 0 [ t ??) ==g ?0[ t ] =49 ,1[ t ] = m : 1 ;j= ( j / 4 ) | ( ( j & 3)l 28) )oe (j& 3?j & 1?j &2? y x : y :x : t ) l v ; } i f =m& ~g; ``` [Answer] ## DC (256 255 bytes) Here it is, I tried (rather successfully, if I may say so myself) to hide anything except for letters, and `+-[];:=` (which are vital and impossible to obfuscate). It does segfault after getting to about 8482 or so on my machine, but that is to do with stack issues related to the way the recursion is implemented. The solution *itself* is correct. 255 bytes if you remove the whitespace (included for ease of reading) Enjoy: ``` Izzzdsa+dsbrsc+dsdd+sozdsezzsm+s nloddd++splbz++ddaso+dln-dstsqlm d+-sr[PPPP]ss[IP]su[lpdlqlrlsxlu x]lm:f[lpdltdI+lm+rlblm+-lsxlux] ln:f[[]sulm;fxln;f[IP]sux]la:f[; fsk]sg[lmlgx]sh[lnlgx]si[lalgx]s j[lc[lcp]sklerldlolclerlblolcler lalox=hx=ix=jlkxclcz+scllx]dslx ``` [Answer] This was a bit tricky to embed using the indentation so a gist: # Ruby, 4312 chars <https://gist.github.com/dzucconi/1f88a6dffa2f145f370f> ``` eval(" ".split(/\n/).map(&:size).pack("C*")) ``` [Answer] ## Brainfuck - 626 656 ``` +[[>+>+<<-]>>>+++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]<[<+>>+<-]>>[-]+++>[ <<<+>>>-]>[-]<<<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[-]<<<<[>+<-]>>>[< <<+>>>-]<<[>>+<<-]<[>+>+<<-]>[<+>-]+>[<->[-]]<[>>>[-]>[-]<>+++++++[<++ ++++++++>-]<.>+++++[<+++++++>-]<.+++++++++++++++++..[-]+<<<-]<[-]>>>[< +<+>>-]<[>+<-]+<[>-<[-]]>[>>>[-]>[-]<>++++++[<+++++++++++>-]<.>+++++[< ++++++++++>-]<+.+++++..[-]<+<<-]>[-]>[<+<+>>-]<[>+<-]+<[>-<[-]]>[<<<<[ >+>>>>+<<<<<-]>[<+>-]>>>>>>--[<->+++++]<--<[->-[>+>>]>[+[-<+>]>+>>]<<< <<]>[-]<-[>-<+++++]>--->>[<<[<+>>>+<<-]<[>+<-]>>>.[-]]++++++++++<[->-[ >+>>]>[+[-<+>]>+>>]<<<<<]>[-]<<[>+>>>+<<<<-]>>>>.[-]<<<[>>+<<-]>>.[-]< <<<<-]<<<++++++++++.[-]<+] ``` Goes from 1 to 255 [Answer] Brainfuck, 708 characters ``` ++++++++++[>++++++++++<-]>>++++++++++>->>>>>>>>>>>>>>>>-->+++++++[->++ ++++++++<]>[->+>+>+>+<<<<]+++>>+++>>>++++++++[-<++++<++++<++++>>>]++++ +[-<++++<++++>>]>>-->++++++[->+++++++++++<]>[->+>+>+>+<<<<]+++++>>+>++ ++++>++++++>++++++++[-<++++<++++<++++>>>]++++++[-<+++<+++<+++>>>]>>--> ---+[-<+]-<[+[->+]-<<->>>+>[-]++[-->++]-->+++[---++[--<++]---->>-<+>[+ +++[----<++++]--[>]++[-->++]--<]>++[--+[-<+]->>[-]+++++[---->++++]-->[ ->+<]>>[.>]++[-->++]]-->+++]---+[-<+]->>-[+>>>+[-<+]->>>++++++++++<<[- >+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]> +>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->+++ +++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]+[-<+]->>]+[-]<<<.>>>+[ -<+]-<<] ``` Description of how it works is available in my [Code Review question](https://codereview.stackexchange.com/questions/57382/fizzbuzz-in-brainfuck) [Answer] ## Haskell - 147 142 138 characters ``` fi=zz.bu bu=zz.(:).(++"zz") []#zz=zz;zz#__=zz zZ%zz=zZ zz$zZ%zz zz=(([[],[]]++).) z=zipWith3(((#).).(++))(bu%"Fi")(fi%"Bu")$map show[1..] ``` The code is 19 characters longer than it needs to be, but I thought the aesthetics were worth it! I believe all three "objectives" are satisfied. ``` > take 20 z ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14", "FizzBuzz","16","17","Fizz","19","Buzz"] ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 33 chars / 92 bytes (noncompetitive) ``` ѨŃ(1,ṥ)ć⇀ᵖɘƃ႖סР깜 #ē($%3⅋4,$%5?4:8)⋎$⸩ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=&code=%D1%A8%C5%83%281%2C%E1%B9%A5%29%C4%87%E2%87%80%E1%B5%96%C9%98%C6%83%E1%82%96%D7%A1%D0%A0%EA%B9%9C%E2%80%80%23%C4%93%28%24%253%E2%85%8B4%2C%24%255%3F4%3A8%29%E2%8B%8E%24%E2%B8%A9)` This language is way too OP for restricted source challenges. [Answer] # Javascript, 469 bytes This was probably the most fun I've ever had. ``` z=0;_=(function(){b=0;window[0xA95ED.toString(36)]((function(){yay="&F bottles of beer on the wall, &F bottles of beer. Take one down, pass it around, &z Bottles of beer on the wall.";return atob("eisrOyAg") + "console.log(((function(y){if((y%0xf)==0){return [1,72,84,84,86,78,84,84]}else if(y%0b11==0){return [1,72,84,84]}else if(y%0b101==0){return [86,78,84,84]}else{b=1;return [y]}})(z).map(function(x){return b==0?yay[x]:x}) ).join(''))"})())});setInterval(_,1000); ``` Try it [here](https://repl.it/BWNB/31) [Answer] ## Ruby - 165 characters ``` (1..100).each{|i|i%0xF==0? puts(["46697A7A42757A7A"].pack("H*")):i%(0xD-0xA)==0? puts(["46697A7A"].pack("H*")):i%(0xF-0xA)==0? puts(["42757A7A"].pack("H*")):puts(i)} ``` This was my first attempt at code golf. I had a lot of fun. =) [Answer] # Perl 6 (52 bytes) ``` say "Fizz"x$_%%(2+1)~"Buzz"x$_%%(4+1)||$_ for 1..100 ``` Let me put an explanation here. It's the worst rule abuse I've done in such task. I know what you are saying - there is obvious `Fizz` and `Buzz` here. But let's take a look at the rules. > > To be considered obfuscated, it should satisfy *at least one* of the following: > > > This avoids `3`, `5` and `15`. Therefore, it's valid and really short solution. [Answer] ## Scala, 295 characters ``` object F extends Application{var(f,i,z)=("",('z'/'z'),"FBiuzzzz");while(i<(-'b'+'u'+'z'/'z')*('¥'/'!')){if(i%(-'f'+'i'/('z'/'z'))==0)f+=z.sliding(1,2).mkString;if(i%((-'b'+'u'+'z'/'z')/('f'/'f'+'i'/'i'+'z'/'z'+'z'/'z'))==0)f+=z.drop(1).sliding(1,2).mkString;if(f=="")f+=i;println(f);i+=1;f="";}} ``` [Answer] # C (~~237~~ 209 characters) ``` #include<stdlib.h> #define e printf a=50358598,b=83916098,c=1862302330;_(m,n){return(m%((c&n)>>24)) ||!(e(&n)|e(&c));}main(_);(*__[])(_)={main,exit};main(i){_(i,a) &_(i,b)&&e("%i",i);e("\n");__[i>=100](++i);} ``` Though I'm not sure this conforms to the C standard :) It works, though. On Linux using GCC, that is. [Answer] # Python 3 - 338 ``` import sys def fibu(): (F,I,B,U),i,u,z=sys._getframe(0).f_code.co_name,0xf,0xb,lambda x,y:x%((i//u)+(i^u))==u>>i if y>u else x%(((u<<(u>>2))&i)>>(u>>2))==i>>u A,RP = "",chr(ord(U)+((i//u)+(i^u)))*2 for x in range(100):print(x if not (z(x,u)or z(x,i))else A.join((F+I+RP if z(x,u)else A,B+U+RP if z(x,i)else A))) fibu() ``` This is my first golf. Not the shortest, but it's pretty ugly! None of the forbidden numbers or string literals. Firp, Burp! [Answer] # Python - 157 ``` from itertools import cycle as r c=str.replace [c(c(c(z+y,'x','fix'),'y','bux'),'x','zz').strip() or x for z,y,x in zip(r(' y'),r(' x'),range(1,101))] ``` Not quite the shortest, but I hope the reader will appreciate the pure functional style and extensibility to arbitrarily long counts. [Answer] # K, 155 ``` {m:{x-y*x div y};s:{"c"$(10-!#x)+"i"$x};$[&/0=m[x]'(2+"I"$"c"$49;4+"I"$"c"$49);s"<`rs<pvw";0=m[x;2+"I"$"c"$49];s"<`rs";0=m[x;4+"I"$"c"$49];s"8lrs";x]}'!100 ``` I could golf it quite a bit but I'd rather it be more obfuscated. [Answer] # JavaScript 111 chars - no key numbers `a=b=c=0;while(a++<99)document.write((b>1?(b=0,"Fizz"):(b++,""))+(c==4?(c=0,"Buzz"):(c++,""))+(b*c?a:"")+"<br>")` [Answer] ## C# - 218 characters ``` using System;class D{static void Main(){int l,i,O=1;l++;string c="zz",a="fi",b="bu";l++;l++;i=l;i++;i++;for(;O<101;O++)Console.WriteLine(((O%l)>0&&1>(O%i))?a+c:(1>(O%l)&&(O%i)>0)?b+c:(1>(O%l)&&1>(O%i))?a+c+b+c:O+"");}} ``` **Could be shortened if I introduced other numbers like so: (210 characters total)** ``` using System;class D{static void Main(){int l=1,i,O=1;string c="zz",a="fi",b="bu";l+=2;i=l;i+=2;for(;O<101;O++)Console.WriteLine(((O%l)>0&&1>(O%i))?a+c:(1>(O%l)&&(O%i)>0)?b+c:(1>(O%l)&&1>(O%i))?a+c+b+c:O+"");}} ``` Decided to remove the obvious word fizz and buzz and go for slightly more obfuscation. Second one is shorter than the first one but is slightly more direct on what's occurring in the addition. [Answer] This isn't exactly golfed, its about 120 lines. I thought I'd do something that took advantage of all the fun potential for undefined behavior with C++ memory management. ``` #include <iostream> #include <string> using namespace std; class Weh; class HelloWorld; class Weh { public: string value1; string value2; void (*method)(void * obj); Weh(); string getV1(); static void doNothing(void * obj); }; class HelloWorld { public: static const int FOO = 1; static const int BAR = 2; static const int BAZ = 4; static const int WUG = 8; string hello; string world; void (*doHello)(HelloWorld * obj); HelloWorld(); void * operator new(size_t size); void tower(int i); const char * doTower(int i, int j, int k); static void doHe1lo(HelloWorld * obj); }; Weh::Weh() { method = &doNothing; } void Weh::doNothing(void * obj) { string s = ((Weh *) obj)->getV1(); ((HelloWorld *) obj)->tower(1); } string Weh::getV1() { value1[0] += 'h' - 'j' - 32; value1[1] += 'k' - 'g'; value1[2] += 'u' - 'g'; value1[3] = value1[2]; value2 = value1 = value1.substr(0, 4); value2[0] += 'd' - 'h'; value2[1] += 'w' - 'k'; value2[2] = value1[2]; value2[3] = value1[3]; return "hello"; } void * HelloWorld::operator new(size_t size) { return (void *) new Weh; } HelloWorld::HelloWorld() { hello = "hello"; world = "world"; } void HelloWorld::doHe1lo(HelloWorld * obj) { cout << obj->hello << " " << obj->world << "!" << endl; } void HelloWorld::tower(int i) { doTower(0, 0, i); tower(i + (FOO | BAR | BAZ | WUG)); } const char * HelloWorld::doTower(int i, int j, int k) { static const char * NOTHING = ""; int hello = BAR; int world = BAZ; int helloworld = FOO | BAR | BAZ | WUG; if ((hello & i) && (world & j)) cout << this->hello << this->world << endl; else if (hello & i) { cout << this->hello << endl; cout << doTower(0, j + 1, k + 1); } else if (world & j) { cout << this->world << endl; cout << doTower(i + 1, 0, k + 1); } else { cout << k << endl; cout << doTower(i + 1, j + 1, k + 1); } return NOTHING; } int main() { HelloWorld * h = new HelloWorld; h->doHello(h); } ``` [Answer] # Ruby - 89 chars ``` puts (0..99).map{|i|srand(1781773465)if(i%15==0);[i+1,"Fizz","Buzz","FizzBuzz"][rand(4)]} ``` I can't take credit for this piece of brilliance, but I couldn't leave this question without my favorite obfuscated implementation :) The implementation above was written by David Brady and is from the [fizzbuzz](http://fizzbuzz.rubyforge.org/) ruby gem. Here is the explanation from the source code: > > Uses the fact that seed 1781773465 in Ruby's rand will generate the > 15-digit sequence that repeats in the FizzBuzz progression. The > premise here is that we want to cleverly trick rand into delivering a > predictable sequence. (It is interesting to note that we don't > actually gain a reduction in information size. The 15-digit sequence > can be encoded as bit pairs and stored in a 30-bit number. Since > 1781773465 requires 31 bits of storage, our cleverness has actually > cost us a bit of storage efficiency. BUT THAT'S NOT THE POINT! > > > # Ruby - 87 chars ``` puts (0..99).map{|i|srand(46308667)if(i%15==0);["FizzBuzz","Buzz",i+1,"Fizz"][rand(4)]} ``` Here's a different version which uses a shorter seed but the lookup table is in a different order. Here is the explanation from the source code: > > The first implementation (89 chars) adheres to the specific ordering > of 0=int, 1=Fizz, 2=Buzz, 3=FizzBuzz. It may be possible to find a > smaller key if the ordering is changed. There are 24 possible > permutations. If we assume that the permutations are evenly > distributed throughout 2\**31 space, and about a 50% probability that > this one is "about halfway through", then we can assume with a decent > confidence (say 20-50%) that there is a key somewhere around 1.4e+9 > (below 2*\*28). It's not much gain but it DOES demonstrate leveraging > rand's predefined sequence to "hide" 30 bits of information in less > that 30 bits of space. > > > Result: The permutation [3,2,0,1] appears at seed 46308667, which can > be stored in 26 bits. > > > [Answer] # Python, 1 line, 376 characters pep8-E501 ignored. Only works in python3. ``` print(*((lambda x=x: ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (30 >> 1) == 0 else ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + '\n' if x % (6 >> 1) == 0 else ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (10 >> 1) == 0 else str(x) + '\n')() for x in range(1, 101))) ``` [Answer] **Alternative Ruby (126 characters)** ``` (1..100).map{|i|(x="\xF\3\5\1Rml6ekJ1eno=".unpack('C4m'))[-1]=~/(.*)(B.*)/ [*$~,i].zip(x).map{|o,d|i%d>0||(break $><<o<<?\n)}} ``` Short and obscure, just how we like it. The 3 and the 5 are actually in there but not as integer literals so I think that still counts. Note that the this is the shortest Ruby version without literal 'Fizz', 'Buzz', 'FizzBuzz' on here. [Answer] ## Python 2 - 54 chars ``` i=0 while 1:i+=1;print'FizzBuzz'[i%~2&4:12&8+i%~4]or i ``` ## Python 3 - 56 chars ``` i=0 while 1:i+=1;print('FizzBuzz'[i%~2&4:12&8+i%~4]or i) ``` If you do not want 'FizzBuzz' to appear : ## Python 2 - 58 chars ``` i=0 while 1:i+=1;print' zzuBzziF'[12&8+i%~2:i%~4&4:-1]or i ``` ## Python 3 - 60 chars ``` i=0 while 1:i+=1;print(' zzuBzziF'[12&8+i%~2:i%~4&4:-1]or i) ``` Or how to beat GolfScript with Python ;) [Answer] **Squeak (4.4) Smalltalk 206 bytes** ``` |f i zz b u z|z:=''.b:=28r1J8D0LK. 1to:100do:[:o|0<(f:=(i:=(zz:=b\\4)//2*4)+(u:=zz\\2*4))or:[z:=z,o].b:=zz<<28+(b//4).z:=z,((z first:f)replaceFrom:1to:f with:28r1A041FHQIC7EJI>>(4-i*u*2)startingAt:1),' '].z ``` Or same algorithm with less explicit messages, same number of characters ``` |l f i zz b u z|z:=#[].b:=36rDEB30W. 1to:100do:[:o|0<(f:=(i:=(zz:=b\\4)//2)+(u:=zz\\2)*4)or:[z:=z,('',o)].b:=zz<<28+(b//4).l:=36r2JUQE92ONA>>(1-u*i*24).1to:f do:[:k|z:=z,{l-((l:=l>>6)-1<<6)}].z:=z,' '].'',z ``` My apologizes to Alan Kay for what I did to Smalltalk. Some of these hacks are portable across Smalltalk dialects, some would require a Squeak compatibility layer... Note that if you execute in a Workspace, you can omit declarations |f i zz b u z| and gain 14 characters. If we can afford 357 characters (315 with single letter vars), then it's better to avoid trivial #to:do: loop: ``` |fizz buzz if f fi zz b u bu z|f:=fizz:=buzz:=0.z:=#[].b:=814090528.if:=[:i|i=0or:[fi:=28.zz:=27<<7+i.u:=26.(fizz:=[zz=0or:[z:=z,{(u:=u//2)\\2+1+(zz+((fi:=fi//2)\\2+2-(zz:=zz//8)*8)*4)}.fizz value]])value]].(buzz:=[(f:=f+1)>100or:[(fi:=(zz:=b\\4)//2*17)+(bu:=zz\\2*40)>0or:[z:=z,('',f)].b:=zz<<28+(b//4).if value:fi;value:bu.z:=z,' '.buzz value]])value.'',z ``` [Answer] ## Haskell 226 bytes, including the whitespace for layout ;) ``` z=[fI$ (++) \ (fi zz 1 "Fi" ) \ (fi zz 2 "Bu" ) \ :[show zz] | zz<-[1..]] fI (zZ:zz) | zZ==[] \ = concat zz | 1==1=zZ fi zZ bu zz | zZ%bu= \ (zz++"zz") | 1==1=[] bu%zz=mod bu (zz*2+1)==0 ``` The 'real' code is 160 bytes and can be compressed, but loses fizz-buzz-ness then. Run it (for nice output): ``` putStrLn (unwords (take 20 z )) ``` Output: ``` 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz ``` [Answer] # Perl ``` use MIME::Base64;print map{map{(++$i,'Fizz','Buzz','FizzBuzz')[$_]."\n"}(3&ord,3&ord>>2,3&ord>>4,3&ord>>6)}split//,decode_base64"EAZJMIRBEgxhkARDGCTBEAZJMIRBEgxhkA" ``` One I made in 2009. It's pretty easy to figure out, though. Edit: Darn, it uses "Fizz" and "Buzz!" :( I thought I changed that. Nevermind then. [Answer] # C 216 bytes ``` #define t(b) putchar(p+=b); main(p,v,c){p=70;for(v=c=1;v<=p*2-40&&!(c=0);++v){if(!(v%(p/23))){t(0)t(35)t(17)t(0)++c;}if(!(v%(p/(14+c*9)))){t(-56+!c*52)t(51)t(5)t(0);++c;}if(c){t(-112)p+=60;}else printf("%i\n",v);}} ``` ]
[Question] [ Write a program or function that prints or returns a string of the alphanumeric characters plus underscore, **in any order**. To be precise, the following characters need to be output, **and no more**: ``` abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_ ``` When printing to stdout, an optional trailing newline after your output is permitted. **Built-in constants that contain 9 or more of the above characters are disallowed.** --- Shortest code in bytes wins. This is a very simple challenge, which I believe will generate some interesting answers nevertheless. --- ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=85666,OVERRIDE_USER=4162;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;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] # Ruby, 26 bytes Characters can be printed in any order? Don't mind if I do! [Try it online!](http://ideone.com/n5AaE6) ``` $><<(?0..?z).grep(/\w/)*'' ``` [Answer] ## Convex, 9 bytes New method! Also, I realized that is it pretty much exactly the same as Luis' answer but in Convex, but I came up with this independently. ``` '{,®\W"Oò ``` [Try it online!](http://convex.tryitonline.net/#code=J3sswq5cVyJPw7I&input=) Explanation: ``` '{, Array of chars from NUL to 'z ®\W" Regex to match non-word characters Oò Replace all matches with emtpy string ``` ### Old solution, 10 bytes: ``` A,'[,_¬^'_ ``` [Try it online!](http://convex.tryitonline.net/#code=QSwnWyxfwqxeJ18&input=) Explanation: ``` A, 0-9 '[,_¬^ A-Za-z '_ _ ``` [Answer] ## Perl, 20 bytes Requires `-E` at no extra cost. ``` say+a.._,A.._,_..9,_ ``` So, my original answer (below) was a bit too boring. The only thing I've managed to come up with is the above, that's exactly the same, but looks a bit more confusing... It's pretty much exactly equivalent to the below: ``` say a..z,A..Z,0..9,_ ``` I like [@msh210](https://codegolf.stackexchange.com/users/1976/msh210)'s suggestions in the comments, but they're just a bit too long! [Answer] ## JavaScript (ES6), 62 bytes ``` _=>String.fromCharCode(...Array(123).keys()).replace(/\W/g,'') ``` Returns `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz`, so only 6 bytes shorter than a function that returns the string literal. Yes, it sucks. [Answer] ## Haskell, 38 bytes ``` '_':['a'..'z']++['A'..'Z']++['0'..'9'] ``` Nothing to explain here. [Answer] # Cheddar, ~~31~~ 27 bytes ``` ->97@"123+65@"91+48@"58+"_" ``` This showcases the `@"` operator well Non-completing because I finally got aroudn to fixing the `@"` operator. The bug was that it was generating a Cheddar range not a JS range so it couldn't properly work --- ## Explanation The `@"` operator was designed by @CᴏɴᴏʀO'Bʀɪᴇɴ, and what it does is generate a string range from LHS to RHS. When used as an unary operator, it returns the char at the given code point (like python's `chr`) ## Ungolfed ``` -> 97 @" 123 + 65 @" 91 + 48 @" 58 + "_" ``` [Answer] ## brainfuck, 58 bytes ``` +++[[<+>->++<]>]<<[-<->]<<-.+<<++[->>+.>+.<<<]<--[->>.+<<] ``` [Try it online](http://brainfuck.tryitonline.net/#code=KysrW1s8Kz4tPisrPF0-XTw8Wy08LT5dPDwtLis8PCsrWy0-PisuPisuPDw8XTwtLVstPj4uKzw8XQ). Initializes the tape to *3·2n*, and works from there. ``` +++[[<+>->++<]>] initialize the tape | 0 | 3 | 6 | 12 | 24 | 48 | 96 | 192 | 128 | 0 | 0 | ^ <<[-<->] subract 128 from 192 | 0 | 3 | 6 | 12 | 24 | 48 | 96 | 64 | 0 | 0 | 0 | ^ <<-.+<<++ ouput '_'; increment 24 twice | 0 | 3 | 6 | 12 | 26 | 48 | 96 | 64 | 0 | 0 | 0 | ^ [->>+.>+.<<<] output aAbBcC ~ zZ | 0 | 3 | 6 | 12 | 0 | 48 | 122 | 90 | 0 | 0 | 0 | ^ <--[->>.+<<] decrement 12 twice; output 0 ~ 9 | 0 | 3 | 6 | 0 | 0 | 58 | 122 | 90 | 0 | 0 | 0 | ^ ``` [Answer] # V, 27 bytes ``` i1122ñYpñvHgJ|éidd@"Í× ``` [Try it online!](http://v.tryitonline.net/#code=aRYWMRsxMjLDsVlwAcOxdkhnSnzDqWlkZEAiG8ONw5c&input=) This answer is *horribly* convoluted. I'll post an explanation later. Hexdump: ``` 00000000: 6916 1631 1b31 3232 f159 7001 f176 4867 i..1.122.Yp..vHg 00000010: 4a7c e969 6464 4022 1bcd d7 J|.idd@"... ``` Explanation: Readable: ``` i<C-v><C-v>1<esc> "Insert the text "<C-v>1" "<C-v> means "literal" 122ñ ñ "122 times, Yp "Duplicate this line <C-a> "And increment the first number on this line vHgJ "Join every line together |éi "Insert an 'i' at the beginning of this line dd "Delete this line @"<esc> "And execute it as V code. "That will generate every ascii value from 1-123 Í× "Now remove every non-word character. ``` [Answer] # J, ~~30~~ ~~29~~ 28 bytes *Saved a byte thanks to randomra!* ``` ~.u:95,;48 65 97+i."*10,,~26 ``` Output: ``` ~.u:95,;48 65 97+i."*10,,~26 _0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ``` ## Explanation I wont provide an explanation *per se*, but will provide intermediate results. ``` 10,,~26 10 26 26 i. b. 0 1 _ _ * b. 0 0 0 0 i."* b. 0 i."*2 3 4 0 1 0 0 0 1 2 0 0 1 2 3 i. 2 0 1 i. 3 0 1 2 i. 4 0 1 2 3 i."*10,,~26 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 0 1 2 + i."*10,,~26 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 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 48 65 97+i."*10,,~26 48 49 50 51 52 53 54 55 56 57 48 48 48 48 48 48 48 48 48 48 48 48 48 48 48 48 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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 ;48 65 97+i."*10,,~26 48 49 50 51 52 53 54 55 56 57 48 48 48 48 48 48 48 48 48 48 48 48 48 48 48 48 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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 95,;48 65 97+i."*10,,~26 95 48 49 50 51 52 53 54 55 56 57 48 48 48 48 48 48 48 48 48 48 48 48 48 48 48 48 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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 ... u:95,;48 65 97+i."*10,,~26 _01234567890000000000000000ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ~.u:95,;48 65 97+i."*10,,~26 _0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ``` [Answer] ## PowerShell v3+, ~~35~~ 33 bytes ``` -join([char[]](1..127)-match'\w') ``` Constructs a dynamic array `1..127`, casts it as a `char` array. That's fed to the `-match` operator working on the regex `\w`, which will return all elements that match (i.e., exactly alphanumeric and underscore). We encapsulate those array elements in a `-join` to bundle it up as one string. That's left on the pipeline and output is implicit. [Answer] ## Haskell, 31 bytes ``` do(x,y)<-zip"aA0_""zZ9_";[x..y] ``` The expression `zip "aA0_" "zZ9_"` gives the list of endpoints `[('a','z'),('A','Z'),('0','9'),('_','_')]`. The `do` notation takes each `(x,y)` to the inclusive `\(x,y)->[x..y]` and concatenates the results. Thanks to Anders Kaseorg for two bytes with `do` instead of `>>=`. Compare to alternatives: ``` do(x,y)<-zip"aA0_""zZ9_";[x..y] zip"aA0_""zZ9_">>= \(x,y)->[x..y] f(x,y)=[x..y];f=<<zip"aA0_""zZ9_" id=<<zipWith enumFromTo"aA0_""zZ9_" [c|(a,b)<-zip"aA0_""zZ9_",c<-[a..b]] f[x,y]=[x..y];f=<<words"az AZ 09 __" ``` [Answer] # [Pascal (FPC)](https://www.freepascal.org/), ~~85~~ ~~83~~ 73 bytes Just plain object pascal using a set of chars. Writing a full program instead of a procedure shaves off 2 bytes. Removing the program keyword shaves 10 more bytes. ``` var c:char;begin for c in['a'..'z','A'..'Z','0'..'9','_']do write(c);end. ``` [Try it online!](https://tio.run/##K0gsTk7M0U0rSP7/vyyxSCHZKjkjscg6KTU9M08hLR8ooJCZF62eqK6np16lrqPuCGJEARkGIIYlkBGvHpuSr1BelFmSqpGsaZ2al6L3/z8A "Pascal (FPC) – Try It Online") [Answer] # C, 50 bytes Call `f()` without any arguments. ``` f(n){for(n=128;--n;)isalnum(n)|n==95&&putchar(n);} ``` Prints ``` zyxwvutsrqponmlkjihgfedcba_ZYXWVUTSRQPONMLKJIHGFEDCBA9876543210 ``` [Answer] # [///](https://esolangs.org/wiki////), 63 bytes ``` abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_ ``` [Answer] # Pyth, ~~13~~ 12 bytes ``` s:#"\w"0rk\| ``` [Try it online!](http://pyth.herokuapp.com/?code=s%3A%23%22%5Cw%220rk%5C%7C&debug=0) Finds all characters in U+0000 to U+007B that matches the regex `/\w/`. Outputs `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz`. ### alternative approach: 15 bytes ``` ssrMc4"0:A[a{_` ``` [Try it online!](http://pyth.herokuapp.com/?code=ssrMc4%220%3AA%5Ba%7B_%60&debug=0) basically generates the half-inclusive ranges required: `0-:, A-[, a-{, _-``. [Answer] # Python 3, 58 bytes ``` print('_',*filter(str.isalnum,map(chr,range(123))),sep='') ``` A full program that prints to STDOUT. The output is: `_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz` **How it works** ``` map(chr,range(123)) Yield an iterator containing all ascii characters with code-points in [0,122]... *filter(str.isalnum,...) ...keep characters if alphanumeric and unpack into tuple... print('_',...,sep='') ...add underscore and print all characters with no separating space ``` [Try it on Ideone](https://ideone.com/xjU0OD) If string constants were allowed, the following would have been 45 bytes: ``` from string import* print('_'+printable[:62]) ``` [Answer] My first attempt at codegolf! ## C#, ~~168~~ ~~152~~ ~~150~~ ~~147~~ ~~130~~ ~~127~~ ~~117~~ ~~116~~ ~~115~~ ~~109~~ 106 bytes ``` for(var a='0';a<'~';a++){Console.Write(System.Text.RegularExpressions.Regex.IsMatch(a+"","\\w")?a+"":"");} ``` Thanks a lot to aloisdg, AstroDan, Leaky Nun and Kevin Lau - not Kenny for all the help in comments. [Answer] # Pure bash, 32 ``` printf %s {a..z} {A..Z} {0..9} _ ``` [Ideone](https://ideone.com/XQi0ep). [Answer] # bash – ~~47~~ 37 bytes ``` man sh|egrep -o \\w|sort -u|tr -d \\n ``` Output on my system is: ``` _0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ ``` Thanks to Digital Trauma for helpful suggestions. On some systems you might be able to use `ascii` instead of `man sh` to save a byte. [Answer] ## PHP, 40 bytes ``` _0<?for(;$a++^9?$a^q:$a=A;)echo" $a"|$a; ``` [Online Demo](http://codepad.org/zcUbbro6). [Answer] # [Retina](https://github.com/m-ender/retina), ~~30~~ ~~19~~ ~~16~~ ~~15~~ 12 bytes I modified my [original alphabet attempt](http://chat.stackexchange.com/transcript/240?m=27630329#27630329) for this latest version. Each character is printed in a loop. The first line is empty. ``` ; +T\`;w`w_ ``` [**Try it online**](http://retina.tryitonline.net/#code=CjsKK1RcYDtsYGxf&input=) **Output:** ``` _0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ``` *Thanks to Leaky Nun for golfing 4 bytes off my latest attempt.* [Answer] # [Sesos](https://github.com/DennisMitchell/sesos), 17 bytes ``` 00000000: a854be 2cbc9e 71d597 14bc56 1ad99e 713b .T.,..q....V...q; ``` ### Output ``` 0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz_ ``` [Try it online!](http://sesos.tryitonline.net/#code=YWRkIDQ4CmZ3ZCAxCmFkZCAxMApqbXAKICAgIHJ3ZCAxCiAgICBwdXQKICAgIGFkZCAxCiAgICBmd2QgMQogICAgc3ViIDEKam56CnJ3ZCAxCmFkZCA3CmZ3ZCAxCmFkZCAyNgpqbXAKICAgIHJ3ZCAxCiAgICBwdXQKICAgIGFkZCAzMgogICAgcHV0CiAgICBzdWIgMzEKICAgIGZ3ZCAxCiAgICBzdWIgMQpqbnoKcndkIDEKYWRkIDQKcHV0&input=) Check *Debug* to see the generated binary code. ### How it works The binary file above has been generated by assembling the following SASM code. ``` add 48 ; Set cell 0 to 48 ('0'). fwd 1 ; Advance to cell 1. add 10 ; Set cell 1 to 10. jmp ; Set an entry marker and jump to the jnz instruction. rwd 1 ; Retrocede to cell 0. put ; Print its content (initially '0'). add 1 ; Increment cell 0 ('0' -> '1', etc.). fwd 1 ; Advance to cell 1. sub 1 ; Decrement cell 1. jnz ; While cell 1 in non-zero, jump to 'rwd 1'. ; This loop will print "0123456789". rwd 1 ; Retrocede to cell 0, which holds 48 + 10 = 58. add 7 ; Set cell 0 to 65 ('A'). fwd 1 ; Advance to cell 1. add 26 ; Set cell 1 to 26. jmp ; Set an entry marker and jump to the jnz instruction. rwd 1 ; Retrocede to cell 0. put ; Print its content (initially 'A'). add 32 ; Add 32 to convert to lowercase ('A' -> 'a', etc.). put ; Print the cell's content. sub 31 ; Subtract 31 to switch to the next uppercase letter ('a' -> 'B', etc.). fwd 1 ; Advance to cell 1. sub 1 ; Decrement cell 1. jnz ; While cell 1 in non-zero, jump to 'rwd 1'. ; This loop will print "AaBb...YyZz". rwd 1 ; Retrocede th cell 0, which holds 65 + 26 = 91. add 4 ; Set cell 0 to 95 ('_'). put ; Print its content. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` 7W:'\W'[]YX ``` [**Try it online!**](http://matl.tryitonline.net/#code=N1c6J1xXJ1tdWVg&input=) ``` 7W % Push 2 raised to 7, i.e. 128 : % Range [1 2 ... 128] '\W' % Push string to be used as regex pattern [] % Push empty array YX % Regex replace. Uses (and consumes) three inputs: source text, regex pattern, % target text. The first input (source text) is implicitly converted to char. % So this replaces non-word characters by nothing. % Implicitly display ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 25 bytes ``` "_"w9yrcw"A":"Z"ycL@l:Lcw ``` This prints the following to `STDOUT`: ``` _9876543210abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ``` ### Explanation ``` "_"w Write "_" 9y Get the list [0:1:2:3:4:5:6:7:8:9] rcw Reverse it, concatenate into one number, write "A":"Z"y Get the list of all uppercase letters cL Concatenate into a single string L @l:Lcw Concatenate L to itself lowercased and write ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 18 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) ``` ∊'\w'⎕S'&'⎕UCS⍳255 ``` prints: ``` 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz ``` [Answer] ## 05AB1E, ~~18~~ ~~16~~ 12 bytes ``` žyLçá9Ý'_)˜J ``` **Explanation** ``` žyL # push [1..128] ç # convert to char á # keep only members of the alphabet 9Ý # push [0..9] '_ # push underscore )˜J # add to lists of lists, flatten and join # implicit output ``` [Try it online](http://05ab1e.tryitonline.net/#code=xb55TMOnw6E5w50nXynLnEo&input=) Edit: Saved 4 bytes thank to Adnan [Answer] # [CJam](https://sourceforge.net/p/cjam/wiki/Home/), ~~15~~ ~~14~~ 11 bytes *4 bytes off thanks to @FryAmTheEggman and @Dennis!* ``` A,'[,_el^'_ ``` [**Try it online!**](http://cjam.tryitonline.net/#code=QSwnWyxfZWxeJ18&input=) ``` A, e# Push range [0 1 ... 9] '[, e# Push range of chars from 0 to "Z" ("[" minus 1) _el e# Duplicate and convert to lowercase ^ e# Symmetric difference. This keeps letters only, both upper- and lower-case '_ e# Push "_". e# Implicitly display stack contents, without separators ``` [Answer] ## Brainfuck, 89 bytes ``` +++++++++[>+++++>+<<-]>+++.>[<+.>-]<+++++++>>+++++++++++++[<+<+.+.>>-]<<+++++.+>[<+.+.>-] ``` [Try it here](http://fatiherikli.github.io/brainfuck-visualizer/#KysrKysrKysrWz4rKysrKz4rPDwtXT4rKysuPls8Ky4+LV08KysrKysrKz4+KysrKysrKysrKysrK1s8KzwrLisuPj4tXTw8KysrKysuKz5bPCsuKy4+LV0=) Details: ``` +++++++++[>+++++>+<<-]>+++. Goes to '0' while remembering a 9 for the 9 other numbers [<+.>-] Simply prints for the next 9 characters <+++++++> Moves it 7 space to the letters >+++++++++++++ Saves a 13 [<+<+.+.>>-] Prints 2 char at a time while making a second '13' space <<+++++.+> Moves 5, prints '_' and moves to the lowercases [<+.+.>-] And again the double print ``` If I could have commented, I would have to improve others answers. But since I can't, I might as well post my own. As I started writing this the lowest BF one was 96 long. [Answer] # F#, ~~50~~ 59 bytes ``` Seq.iter(printf"%c"<<char)(95::[48..57]@[65..90]@[97..122]) ``` Output: ``` _0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ``` Edit: missed the digits the first time Edit2, inspired by [this Haskell solution](https://codegolf.stackexchange.com/questions/85666/print-all-alphanumeric-characters-plus-underscore/85728#85728) this F# snippet is 67 bytes. ``` Seq.zip"aA0_""zZ9_"|>Seq.iter(fun(x,y)->Seq.iter(printf"%c")[x..y]) ``` Output: ``` abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_ ``` [Answer] # Hexagony, 33 ``` "A}_8_47<='>({a/[[email protected]](/cdn-cgi/l/email-protection)!\356);'); ``` Expanded: ``` " A } _ 8 _ 4 7 < = ' > ( { a / _ x . @ . 9 ! \ 3 5 6 ) ; ' ) ; . . . . ``` Output: ``` aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ1203568479_ ``` [Try it online!](http://hexagony.tryitonline.net/#code=GiJBfV84XzQ3PD0nPih7YS9feC5ALjkhXDM1Nik7Jyk7&input=) Note that there is an unprintable character `0x1A` as the first byte of the program. This also makes the first row of the expanded Hexagon look sort of off. Many thanks to Martin for showing me this trick, as well as for suggesting the algorithm for printing the alphabet! This prints the alphabet by storing `a` and `A` on two edges of a hexagon and the number 26 on the edge of the hexagon that touches the joint between the letters. This looks something like this: ``` A \ / a | 26 ``` Then it enters a loops that prints the letters and then increments them, and then decrements the number. After one iteration we would have: ``` B \ / b | 25 ``` And so on. The linear code for the initialisation is: `0x1A " A } a`. The linear code for the loops outside of control flow changes is: `; ) ' ; ) { ( ' =`. Once the counter reaches zero, we follow a different path to print the numbers and an underscore. Written out linearly this is: `x 3 5 6 8 4 7 9 ! ; { @`. This replaces the current memory edge's value with the number 1203568479 (note that `x`'s ASCII code is 120), which contains all of the decimal digits. We print out this number and then we use a neat feature of Hexagony: we print out the number mod 256 as an ASCII character. This just happens to be 95, or underscore. ]
[Question] [ (Just open 50 tabs in Google Chrome :D (just kidding, no you can't)) Shortest code for infinite disk I/O any language, C# example: ``` using System.IO; namespace FileApp { static class Program { public static void Main() { do { File.WriteAllText("a", "a"); File.Delete("a"); } while (true); } } } ``` You can't just fill the entire disk though, as then it would halt in the end and would be finite. And you can't do reading only, infinite writing has to happen. (It has to kill my SSD after enough runtime.) Get cracking! :) [Answer] ## PowerShell v2+, 10 bytes ``` for(){1>1} ``` Simply loops infinitely with an empty `for` loop. Each iteration, we output the integer `1` (implicitly converted to a string) with the `>` [redirect operator](https://technet.microsoft.com/en-us/library/hh847746.aspx), which overwrites the file named `1` in the local directory. [Answer] # Pyth, 6 bytes ``` #.w]]0 ``` Pyth's only file output command is `.w`. When called on a string, it writes that string to a file in append mode, which is no good for the purpose of this question. When called on a 2-d array, it writes the corresponding image to that file, overwriting the file contents. That's what this program does. The default file output name is `o.png`, so this program infinitely overwrites the file `o.png` with a 1-pixel white image. `#` is an infinite loop. [Answer] ## DOS/Batch: 4 bytes ``` %0>x ``` This batch file will call itself (`%0`) and redirect (`>`) the output to a file called `x`. Since echo is on by default, this will output the path and command. [Answer] If you want a shorter (but more boring than my other one) answer: # Bash, 5 bytes ``` >w;$0 ``` I could make that shorter if there's a command (less than 3 bytes long) that writes something to disk I/O. Something like `sync` would work, but `sync` is 4 bytes üòõ Note: this doesn't work when run straight from bash, only when put in a script and run as the script name. (i.e. `echo 'w>w;$0' > bomb; chmod 755 bomb; ./bomb`) [Answer] ## Ruby, ~~22~~ 20 bytes ``` loop{open(?a,?w)<<1} ``` Repeatedly truncates and writes a `1` to the file `a`. Thanks to [Ventero](https://codegolf.stackexchange.com/users/84/ventero) for 2 bytes! [Answer] # cmd, 14 bytes ``` :a cd>1 goto a ``` Infinitly overwrites the file `1` with the string to the current directory --- I'm new here: Are *windows* new lines (`CR` `LF`) counted as two bytes? [Answer] # Bash + coreutils, 10 ``` yes \>b|sh ``` Writes a continuous stream of `>b`, which is piped to `sh` for evaluation. `>b` simply truncates a file called `b` to zero bytes each time. [Answer] # Perl 5, ~~27~~ ~~32~~ 22 bytes ``` {{open my$h,'>o'}redo} ``` If simply changing the modification timestamp of a file suffices... Quick explanation: ``` { # Braces implicitly create/mark a loop. { # They also create closures, for `my` variables. open my $filehandle, '>', 'o'; # Writing to file "o". # close $filehandle; # Called implicitly when # variable gets destroyed. } # $filehandle gets destroyed because there are no references to it. redo; # ...the loop. } ``` --- Previous solution (32 bytes): `{{open my$h,'>o';print$h 1}redo}` **Edit:** `{open F,'O';print F 1;redo}` ← Didn't test the code before posting; now I had to correct it. [Answer] ## PHP, ~~60 30 17 16~~ 15 bytes Updated yet again as per @manatwork suggested: ``` while(!`cd>1`); ``` Also now tested. --- A bit of cheating 22 bytes: ~~while(exec('>1 dir'));~~ Earlier suggestion by @manatwork 30 bytes: ~~while(file\_put\_contents(1,1));~~ NOT TESTED (no php available on this computer) 43 bytes: ~~for($a=fopen(1,'w');fputs($a,1);fclose($a))~~ A golfed original 45 bytes: ~~$a=fopen(1,'w');while(fputs($a,1))rewind($a);~~ My first post here, joined because I just had to try this out: as long as file write succeeds, rewind file pointer to start. --- ~~Just can't get smaller than the file\_put\_contents().~~ [Answer] # sh, 11 bytes ``` w>w;exec $0 ``` Save this to a file without special characters, such as loop.sh, make it executable, and run it with `./loop.sh` or similar. This writes the output of the command `w` to the file `w`, overwriting the previous value each time. Then, it replaces itself with a fresh version of the same program, so it can run infinitely. [Answer] # C, ~~95~~ ~~94~~ ~~93~~ ~~89~~ ~~78~~ ~~90~~ ~~89~~ ~~76~~ 75 bytes ``` #include<stdio.h> main(){for(FILE*f=fopen("a","w");;fputc(0,f),fclose(f));} ``` Again, `sudo watch -n1 lsof -p `pidof inf`` seems to say this is valid. HOW DID I NOT SEE THAT SPACE D:< Thanks [@Jens](https://codegolf.stackexchange.com/users/9533/jens) for shaving off 13 bytes :D [Answer] # Bash, 26 bytes ``` yes>y&while :;do rm y;done ``` If I were to expand this one-liner, I would get this: ``` yes > y & # Write out infinitely to the file y in the current directory while true # Let's do something forever do # Here's what we're going to do rm y # delete y done # That's all we're going to do ``` This can't exactly compete with the 10 byte PowerShell line, but it'll hold its own against the others. See my other answer for the 6 byte version. [Answer] # TI-BASIC, 12 bytes ``` While 1 Archive A UnArchive A End ``` Alternate solution by user [lirtosiast](https://codegolf.stackexchange.com/users/39328/lirtosiast) with the same size: ``` While 1 SetUpEditor Archive ‚àü1 End ``` This will work on the TI-83+ and TI-84+ series of calculators. *Yes, this also works if A is already archived or is not initialized at all at the start of the program! The program is only 12 bytes because of [tokenization](http://meta.codegolf.stackexchange.com/a/4764/52694)*. [Answer] # CPython 3.5, ~~33~~ 16 bytes ``` while 1:open("a") ``` Yes, really. :D [Answer] # [MATL](https://esolangs.org/wiki/MATL), 10 bytes ``` `1[]T3$Z#T ``` ### Explanation This is an infinite loop that writes number `1` to a file called `inout` in current directory, overwriting previous file's contents. ``` ` % do...while loop 1 % push number 1 [] % push empty array T % push "true" 3$Z# % fwrite function. First input is file content. Second is file name; % defaults to "inout" if empty. Third indicates that any previous % file contents should be discarded T % push "true": loop condition % implicitly end loop. Loop condition is "true", so the loop is infinite ``` [Answer] ## Haskell, 20 bytes ``` f=writeFile"b""a">>f ``` Write the string `"a"` to a file named `"b"` and repeat. `writeFile` overwrites the file if it exists. [Answer] ## JavaScript (Node.js), ~~43~~ 41 bytes ``` (c=x=>require("fs").writeFile("a",x,c))() ``` Writes `null` to a file named `a`, then repeat. [Answer] # ZSH, 14 bytes ``` for ((;;)) :>: ``` Zsh, unlike Bash and other Bourne-like shells, allows [loops without the `do ... done` fence](http://zsh.sourceforge.net/Doc/Release/Shell-Grammar.html#Alternate-Forms-For-Complex-Commands-1), provided the condition is suitably delimited. Alternatively, with `while`: ``` while {} {:>:} ``` Note that `:` is a builtin. **You can't suspend this loop.** The principle is the same as in [Digital Trauma's answer](https://codegolf.stackexchange.com/a/76831/31018) - nothing is written to the file, the IO is purely from creating and truncating the file. [Answer] # Rust, 84 Bytes ``` fn main(){loop{use std::io::Write;std::fs::File::create("a").unwrap().write(b"a");}} ``` `File::create` truncates an existing file, thus ensuring that we don't run out of disk space. The used Compiler (1.9 Nightly) issues a warning about the unused result of `write(...)` but compiles nevertheless. [Answer] # C, 92 bytes ``` #include <stdio.h> main(){for(FILE*f=fopen("a","w+");fprintf(f," "),!fclose(f);;);return 0;} ``` While it looks like you could save 1 byte by ``` for(FILE*f=fopen("a","w+");fprintf(f," ")+fclose(f);;){} ``` the problem with that loop is that + doesn't give you the guaranteed order. Or recursive - shouldn't overflow if the compiler properly implements tail recursion (f is in an explicit inner scope) # 85 bytes ``` #include <stdio.h> main(){{FILE*f=fopen("a","w+");fprintf(f," ");fclose(f);}main();} ``` [Answer] # Mathematica, 14 bytes ``` For[,1>0,a>>a] ``` Repeatedly writes the string `"a"` to a file named `a` in the current directory, creating it if it doesn't exist. [Answer] ## C, 40 bytes ``` main(){for(;;)write(open("a",1)," ",1);} ``` --- It will quickly run out of file descriptors, though; this can be overcome with: ## ~~45~~, 43 bytes ``` main(f){for(f=open("a",1);;)write(f,"",1);} ``` [Answer] # C on amd64 Linux, 36 bytes (timestamp only), ~~52~~ 49 bytes (real disk activity) I hard-code the `open(2)` flags, so this is not portable to other ABIs. Linux on other platforms likely uses the same `O_TRUNC`, etc., but other POSIX OSes may not. **+4 bytes** to pass a correct permission arg to make sure the file is created with owner write access, see below. (This happens to work with gcc 5.2) # somewhat-portable ANSI C, 38/51 bytes (timestamp only), 52/67 bytes (real disk activity) Based on @Cat's answer, with a tip from @Jens. The first number is for implementations where an `int` can hold `FILE *fopen()`'s return value, second number if we can't do that. On Linux, heap addresses happen to be in the low 32 bits of address space, so it works even without `-m32` or `-mx32`. (Declaring `void*fopen();` is shorter than `#include <stdio.h>`) --- **Timestamp metadata I/O only**: ``` main(){for(;;)close(open("a",577));} // Linux x86-64 //void*fopen(); // compile with -m32 or -mx32 or whatever, so an int holds a pointer. main(){for(;;)fclose(fopen("a","w"));} ``` --- **Writing a byte, actually hitting the disk** on Linux 4.2.0 + XFS + `lazytime`: ``` main(){for(;write(open("a",577),"",1);close(3));} ``` `write` is the for-loop condition, which is fine since it always returns 1. `close` is the increment. ``` // semi-portable: storing a FILE* in an int. Works on many systems main(f){for(;f=fopen("a","w");fclose(f))fputc(0,f);} // 52 bytes // Should be highly portable, except to systems that require prototypes for all functions. void*f,*fopen();main(){for(;f=fopen("a","w");fclose(f))fputc(0,f);} // 67 bytes ``` --- ## Explanation of the non-portable version: The file is created with random garbage permissions. With `gcc` 5.2, with `-O0` or `-O3`, it happens to include owner write permission, but this is not guaranteed. `0666` is decimal 438. **A 3rd arg to `open` would take another 4 bytes**. We're already hard-coding O\_TRUNC and so on, but this could break with a different compiler or libc on the same ABI. We can't omit the 2nd arg to `open`, because the garbage value happens to include `O_EXCL`, and `O_TRUNC|O_APPEND`, so open fails with `EINVAL`. --- We don't need to save the return value from `open()`. We assume it's `3`, because it always will be. Even if we start with fd 3 open, it will be closed after the first iteration. Worst-case, `open` keeps opening new fds until 3 is the last available file descriptor. So, up to the first 65531 `write()` calls could fail with `EBADF`, but will then work normally with every `open` creating fd = 3. 577 = 0x241 = `O_WRONLY|O_CREAT|O_TRUNC` on x86-64 Linux. Without `O_TRUNC`, the inode mod time and change time aren't updated, so a shorter arg isn't possible. `O_TRUNC` is still essential for the version that calls `write` to produce actual disk activity, not rewrite in place. I see some answers that `open("a",1)`. O\_CREAT is required if `a` doesn't already exist. `O_CREAT` is defined as octal 0100 (64, 0x40) on Linux. --- No resource leaks, so it can run forever. `strace` output: ``` open("a", O_WRONLY|O_CREAT|O_TRUNC, 03777762713526650) = 3 close(3) = 0 ... repeating ``` or ``` open("a", O_WRONLY|O_CREAT|O_TRUNC, 01) = 3 write(3, "\0", 1) = 1 # This is the terminating 0 byte in the empty string we pass to write(2) close(3) = 0 ``` I got the decimal value of the `open` flags for this ABI using `strace -eraw=open` on my C++ version. On a filesystem with the Linux `lazytime` mount option enabled, a change that only affects inode timestamps will only cause one write per 24 hours. With that mount option disabled, timestamp updating might be a viable way to wear out your SSD. (However, several other answers only do metadata I/O). --- [Answer] # Racket, 46 bytes ``` (do()(#f)(write-to-file'a"f"#:exists'replace)) ``` [Answer] # Factor, 73 bytes ``` USING: io.files io.encodings [ 0 "a" utf8 set-file-contents ] [ t ] while ``` Sets the file contents to the nul byte forever. [Answer] # CBM BASIC 7.0, 9 bytes ``` 0dS"a":rU ``` This program, when run, repeatedly saves itself to disk. Here's a more readable version which doesn't use BASIC keyword abbreviations: ``` 0 dsave "a" : run ``` [Answer] # Python, 32 bytes ``` while 1:open("a","w").write("b") ``` Note that if run on python 3, this will produce an infinite number of warnings. Also, it will probably run out of fds if run in a non-refcounting implementation. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM) 15.0, 17 bytes (non-competing) ``` (‚䢂䣂äÉ‚éïNPUT‚ä¢)‚磂â¢'A'1 ``` Chrome currently renders U+2262 wrong. The above line should look like `(‚䢂䣂äÉ‚éïNPUT‚ä¢)‚ç£Ã∏‚â°'A'1`. This is non-competing because version 15 has not been released yet. Applies `‚ç£` the function `(‚䢂䣂äÉ‚éïNPUT‚ä¢)` on `'A'1` until the input is changed (i.e. never): `‚䢂䣂äÉ‚éïNPUT‚ä¢` is a function train: ``` ‚îå‚îĂîÄ‚îÄ‚îÄ‚îê ‚ä¢ ‚ä£ ‚îå‚îĂîÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îê ‚äÉ ‚éïNPUT ‚ä¢ ``` The rightmost `‚ä¢` returns `'A'1` unmodified; this (filename, overwrite-flag) will be the right argument to `‚éïNPUT'. '‚äÉ' returns the first element of `'A'1` (`'A'`); this is the data to be written. Then `‚éïNPUT` is run, and reports how many bytes were written (2 or 3 depending on OS); this becomes the right argument to the `‚ä£`. The leftmost `‚ä¢` again returns `'A'1` unmodified; this is the left argument to the `‚ä¢`. `‚ä£` ignores its right argument and returns the left argument (`'A'1`), this becomes the new value fed to `‚ç£`. Since the new value is identical to the old one, the operation is continued (forever). [Answer] # SmileBASIC, 12 bytes ``` SAVE"A EXEC. ``` [Answer] # vim text editor, 10 bytes ``` qa:w<enter>@aq@a ``` 8 bytes if you do not could the execution command `@a` ]
[Question] [ This challenge is a simple [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") one. Given two inputs, describing the height and width of a Lego piece, you have print an ASCII art representation of it. Here is how the Lego pieces are supposed to look: ``` (4, 2) ___________ | o o o o | | o o o o | ----------- (8, 2) ___________________ | o o o o o o o o | | o o o o o o o o | ------------------- (4, 4) ___________ | o o o o | | o o o o | | o o o o | | o o o o | ----------- (3, 2) _________ | o o o | | o o o | --------- (1, 1) o ``` If you can't tell from the test-cases, the top and bottom are `width*2+3` underscores and dashes, and each row has pipes for the sides, `o`'s for the little things, and everything is separated by spaces. The only exception for this is `(1, 1)`, which is just a single `o`. You will never get `0` for any of the dimensions. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins! ``` var QUESTION_ID=84050,OVERRIDE_USER=31343;function answersUrl(e){return"http://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"http://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] # [Befunge](https://en.wikipedia.org/wiki/Befunge), 165 ~~227~~ bytes ``` &::&*:1` v v+3*2:\/\_"o",@ v _$ v< >"_",1-:^ 2 v:,,"| ",*5< v _v >" o",,1-:^$ >*v>\ #\^ 5 #|:-1,"|"< ^2$< v1, *95< - >2*3+^ >: #^_@ ``` Not as much whitespace as before, but there are still gaps. The principle is the same as in the previous solution, but the layout is different. This time, to check if both numbers are 1, I'm just taking their product and seeing if the result is greater than 1. --- Old solution (227 bytes) ``` v v < & >>\:2*3+>"_",1-:| >&:1`|v ,,"| ",*52:$< :\< #\v < :>" o",,1-:| 1 >"|",$\1-:| \` @ $ ^_"o",@>:! | 2 ^-1,*95<+3*2,*5< ``` It might be possible to golf it more. Just look at all that whitespace! Here's my poor attempt at an explanation in MSPaint picture form: [![How to Befunge](https://i.stack.imgur.com/4J1RS.png)](https://i.stack.imgur.com/4J1RS.png) Code flows in the direction of the arrow. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~43, 40, 38~~ 36 bytes One of the longest V answers I've ever written... ``` Àio ddÀPñóo î½o u2Pí.«/| °| Vr-HVr_ ``` [Try it online!](http://v.tryitonline.net/#code=w4BpbyAbZGTDgFDDscOzbyDDrsK9bwp1MlDDrS7Cqy98IMKwfApWci1IVnJf&input=&args=Mg+Mg) Since this contains unicode and unprintable characters, here is a reversible hexdump: ``` 0000000: c069 6f20 1b64 64c0 50f1 f36f 20ee bd6f .io .dd.P..o ..o 0000010: 0d0a 7532 50ed 2eab 2f7c 20b0 7c0d 0a56 ..u2P.../| .|..V 0000020: 722d 4856 725f r-HVr_ ``` This challenge is about manipulating text, so perfect for V! On the other hand, V is terrible at conditionals and math, so the differing output for (1, 1) really screwed it up... :( Explanation: ``` À "Arg1 times: io <esc> "Insert 'o ' dd "Delete this line, and À "Arg2 times: P "Paste it ``` Now we have 'Height' lines of o's with spaces between them. ``` ñ "Wrap all of the next lines in a macro. This makes it so that if any "Search fails, execution will stop (to handle for the [1, 1] case) ó "Search and replace o î½o "'o'+space+0 or 1 newlines+another 'o' u "Undo this last search/replace 2P "Paste twice í "Search and replace on every line .«/| °| "A compressed regex. This surrounds every non-empty line with bars. Vr- "Replace the current (last) line with '-' H "Move to line one Vr_ "Replace this line with '_' ``` Non-competing version (31 bytes): [Try it online!](http://v.tryitonline.net/#code=w4BpbyAbw4DDhMOxL28gw67CvW8KMlDDrS7Cqy98IMKwfArDki1Iw5Jf&input=&args=Mg+Mg) This version uses several features that are newer then this challenge to be 5 bytes shorter! Second explanation: ``` ddÀP ``` which is "Delete line, and paste it *n* times" is replaced with `ÀÄ` which is "Repeat this line *n* times". (-2 bytes) ``` óo î½o u ``` which was "Replace the first match of this regex; Undo" was replaced with ``` /o î½o ``` Which is just "Search for a match of this regex" (-1 byte) And lastly, `Ò` is just a simple synonym for `Vr`, which both "Replace every character on this line with 'x'". (-2 bytes) [Answer] # 32 16-bit little-endian x86 machine code, 57 54 51 bytes *3 bytes less thanks to @ninjalj.* *Heavily rewrote the code and have managed to shave off another 3 bytes* In hex ``` FCBA6F208D48FFE20492AAEB2389D941D1E14151B05FF3AAEB0BB87C20AB89D992F3AB92AAB00AAA4E7DEF59B02DF3AA91AAC3 ``` Input: BX=width, SI=height, DI points to the buffer that receives result as a NULL-terminated string with lines separated by "\n" ## Disassembly: ``` fc cld ba 6f 20 mov dx,0x206f ;Storing ' o' in DX for later use 8d 48 ff lea cx,[bx+si-0x1] ;CX=width+height-1 e2 04 loop _main0 ;--CX & brahch if not zero 92 xchg dx,ax ;(1,1) case, swap DX & AX aa stosb ;AL == 'o', CX == 0 eb 23 jmp _end _main0: 89 d9 mov cx,bx 41 inc cx d1 e1 shl cx,1 41 inc cx ;Calculate (width+1)*2+1 51 push cx ;and save it for future use b0 5f mov al,0x5f ;'_' f3 aa rep stosb ;Output the whole line of them eb 0b jmp _loopstart ;Jump into the loop _loop: b8 7c 20 mov ax,0x207c ;' |' ab stosw ;Output it once (left bar + space) 89 d9 mov cx,bx ;Copy width 92 xchg dx,ax ;AX == ' o' f3 ab rep stosw ;Output it CX times 92 xchg dx,ax ;Swap values back, AL == '|' aa stosb ;Output only the right bar _loopstart: b0 0a mov al,0x0a ;Newline. Can be replaced with mov ax,0x0a0d for windows newline aa stosb ;convention (at the cost of 1 byte), with stosb replaced with stosw 4e dec si ;Height-- 7d ef jge _loop ;Continue if si >= 0 (this accounts for the dummy first pass) 59 pop cx b0 2d mov al,0x2d ;'-' f3 aa rep stosb ;Output bottom line _end: 91 xchg cx,ax ;CX == 0, so swap to get zero in AL aa stosb ;NULL-terminate output c3 retn ``` [Answer] ## Python 2, ~~75~~ ~~73~~ 72 bytes ``` lambda x,y:(x*'__'+'___\n'+('| '+'o '*x+'|\n')*y+'-'*(x*2+3),'o')[x<2>y] ``` Returns a string, with a conditional to handle the 1,1 block. *Thanks to Lynn and Chepner for two bytes* [Answer] # CJam, 34 ``` '_q~'o*"||"\*S*f*f+'-f+zN*_,H='o@? ``` [Try it online](http://cjam.aditsu.net/#code=%27_q%7E%27o*%22%7C%7C%22%5C*S*f*f%2B%27-f%2BzN*_%2CH%3D%27o%40%3F&input=2%204) **Explanation:** ``` '_ push a '_' character q~ read and evaluate the input (height and width) 'o* repeat the 'o' character <width> times "||"\* join the "||" string by the string of o's (putting them in between) S* join with spaces (inserting a space between every 2 characters) f* repeat each character <height> times, making it a separate string f+ prepend '_' to each string '-f+ append '-' to each string z transpose the array of strings N* join with newlines; lego piece is ready, special case to follow _, duplicate the string and get its length H= compare with H=17 'o push 'o' for the true case @ bring the lego piece to the top for the false case ? if the length was 17, use 'o' else use the lego piece ``` [Answer] # Ruby, ~~59~~ 56 bytes Anonymous function, returns a multiline string. [Try it online!](https://repl.it/C73A) -3 bytes thanks to borrowing a trick from @El'endiaStarman ``` ->w,h{w*h<2??o:?_*(x=2*w+3)+$/+(?|+' o'*w+" | ")*h+?-*x} ``` [Answer] # Java, 318 312 297 294 260 258 bytes Saved 15 bytes thanks to [cliffroot](https://codegolf.stackexchange.com/users/53197/cliffroot)! ``` interface a{static void main(String[]A){int b=Byte.valueOf(A[0]),B=Byte.valueOf(A[1]),C=3+b*2;String c="";if(b<2&B<2)c="o";else{for(;C-->0;)c+="_";for(;B-->0;){c+="\n|";for(C=b;C-->0;)c+=" o";c+=" |";}c+="\n";for(C=3+b*2;C-->0;)c+="-";}System.out.print(c);}} ``` It works with command line arguments. Ungolfed In a human-readable form: ``` interface a { static void main(String[] A) { int b = Byte.valueOf(A[0]), B = Byte.valueOf(A[1]), C = 3 + b*2; String c = ""; if (b < 2 & B < 2) c = "o"; else { for (; C-- > 0;) c += "_"; for (; B-- > 0;) { c += "\n|"; for (C = b; C-- >0;) c += " o"; c += " |"; } c += "\n"; for(C = 3 + b*2; C-- >0;) c += "-"; } System.out.print(c); } } ``` --- Yes, it's still difficult to understand what's going on even when the program is ungolfed. So here goes a step-by-step explanation: ``` static void main(String[] A) ``` The first two command line arguments -which we'll use to get dimensions- can be used in the program as `A[0]` and `A[1]` (respectively). ``` int b = Byte.valueOf(A[0]), B = Byte.valueOf(A[1]), C = 3 + b*2; String c = ""; ``` `b` is the number of columns, `B` is the number of rows and `C` is a variable dedicated for use in `for` loops. `c` is the Lego piece. We'll append rows to it and then print it at the end. ``` if (b < 2 & B < 2) c = "o"; else { ``` If the piece to be printed is 1x1, then both `b` (number of columns) and `B` (number of rows) should be smaller than 2. So we simply set `c` to a single `o` and then skip **to** the statement that `System.out.print`s the piece if that's the case. ``` for (; C-- > 0; C) c += "_"; ``` Here, we append `(integerValueOfA[0] * 2) + 3` underscores to `c`. This is the topmost row above all holes. ``` for (; B > 0; B--) { c += "\n|"; for(C = b; C-- > 0;) c+=" o"; c += " |"; } ``` This is the loop where we construct the piece one row at a time. What's going on inside is impossible to explain without examples. Let's say that the piece is 4x4: ``` Before entering the loop, c looks like this: ___________ After the first iteration (\n denotes a line feed): ___________\n | o o o o | After the second iteration: ___________\n | o o o o |\n | o o o o | After the third iteration: ___________\n | o o o o |\n | o o o o |\n | o o o o | ``` . ``` c += "\n"; for (C = 3 + b*2; C-- > 0;) c += "-"; ``` Here, we append `(integerValueOfA[0] * 2) + 3` hyphens to the piece. This is the row at the very bottom, below all holes. The 4x4 piece I used for explaining the `for` loop where the piece is actually constructed now looks like this: ``` ___________\n | o o o o |\n | o o o o |\n | o o o o |\n | o o o o |\n ----------- ``` ``` System.out.print(c); ``` And finally, we print the piece! [Answer] ## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), ~~58~~ ~~57~~ 56 bytes Yes, that's right. I golfed off *~~one~~ two stinkin' little bytes*... ``` nn$d*1-5&"o"O.rd2*3+$z1$([" o"]" ||"2Rlkr$Dlz["-_"0G]$O. ``` [Try it here!](http://play.starmaninnovations.com/minkolang/?code=nn%24d*1-5%26%22o%22O%2Erd2*3%2B%24z1%24%28%5B%22%20o%22%5D%22%20%7C%7C%222Rlkr%24Dlz%5B%22-_%220G%5D%24O%2E&input=4%202) ### Explanation ``` nn Take two numbers from input (stack is now [w h]) C special case C $d Duplicate stack *1- Multiply and subtract 1 5& Jump 5 spaces if truthy "o"O. Top of stack was 1*1-1=0, so output "o" and stop. C precalculates width of top and bottom lines for later use C r Reverse stack (now [h w]) d Duplicate top of stack 2*3+ Multiply top of stack by 2 and add 3 $z Pop this and store in register (z = 2*w+3) C generates the row C 1$( Open while loop prepopulated with top of stack [" o"] w times, push "o " " ||" Push "|| " 2R Rotate twice to the right l Push newline (10) k Break out of while loop C duplicates the row h times C r Reverse stack $D Duplicate whole stack h times l Push newline C this is for the top and bottom lines C z[ Open for loop that repeats z times "-_" Push "_-" 0G Relocate top of stack to bottom of stack ] Close for loop $O. Output whole stack as characters and stop. ``` Okay, that's two significant rewrites of the explanation for two bytes saved. I don't think I can or will golf anything more out of this one. :P [Answer] # brainfuck, 391 bytes I know this can be golfed down more, but at this point I'm just glad it works. I will continue to work to golf it down. ``` +++++[-<+++[-<+++<++++++<+++++++<++<++++++++>>>>>]<<+<+<<+<++>>>>>>>]<<<<+<++<->>>>>>,<,>>++++++[<--------<-------->>-]<<->>+<<[>>-<<[>>>+<<<-]]>>>[<<<+>>>-]<[<->>>+<<<[>>>-<<<[>>>>+<<<<-]]>>>>[<<<<+>>>>-]<[<<<<<<<.[-].]<<<+>-]<<+>[->++>+<<]>+++[-<<<<.>>>>]>[-<<+>>]<<<<<<<<<.>>>>>>><[->[->+>+<<]<<<<<<.>>>>>>>[<<<<<<.>.>>>>>-]>[-<<+>>]<<<<<<<.<.<.>>>>>>]>[->++>+<<]>+++[-<<<.>>>]>[-<<+>>]<< ``` Input needs to be given as just two digits. As in, to do `(8, 2)` you would just enter `82`. [Try it online!](http://brainfuck.tryitonline.net/#code=KysrKytbLTwrKytbLTwrKys8KysrKysrPCsrKysrKys8Kys8KysrKysrKys-Pj4-Pl08PCs8Kzw8KzwrKz4-Pj4-Pj5dPDw8PCs8Kys8LT4-Pj4-Piw8LD4-KysrKysrWzwtLS0tLS0tLTwtLS0tLS0tLT4-LV08PC0-Pis8PFs-Pi08PFs-Pj4rPDw8LV1dPj4-Wzw8PCs-Pj4tXTxbPC0-Pj4rPDw8Wz4-Pi08PDxbPj4-Pis8PDw8LV1dPj4-Pls8PDw8Kz4-Pj4tXTxbPDw8PDw8PC5bLV0uXTw8PCs-LV08PCs-Wy0-Kys-Kzw8XT4rKytbLTw8PDwuPj4-Pl0-Wy08PCs-Pl08PDw8PDw8PDwuPj4-Pj4-PjxbLT5bLT4rPis8PF08PDw8PDwuPj4-Pj4-Pls8PDw8PDwuPi4-Pj4-Pi1dPlstPDwrPj5dPDw8PDw8PC48LjwuPj4-Pj4-XT5bLT4rKz4rPDxdPisrK1stPDw8Lj4-Pl0-Wy08PCs-Pl08PA&input=NDI) **Breakdown:** First put the necessary characters into the tape: `(newline)| o_-` ``` +++++[-<+++[-<+++<++++++<+++++++<++<++++++++>>>>>]<<+<+<<+<++>>>>>>>]<<<<+<++<->>>>> ``` Then collect the input into two cells and subtract 48 from each (to get the numeric value and not the numeral character) ``` >,<,>>++++++[<--------<-------->>-]<< ``` Next, check for the special case of `(1, 1)` (Note that just this check accounts for 109 bytes of the code). As if `if`s weren't hard enough to do in brainfuck, we have a nested `if`: ``` ->>+<<[>>-<<[>>>+<<<-]]>>>[<<<+>>>-]<[<->>>+<<<[>>>-<<<[>>>>+<<<<-]]>>>>[<<<<+>>>>-]<[<<<<<<<.[-].]<<<+>-]<<+ ``` The following is the structure to check if a cell x is zero or nonzero: ``` temp0[-]+ temp1[-] x[ code1 temp0- x[temp1+x-] ] temp1[x+temp1-] temp0[ code2 temp0-] ``` However in a nested `if`, we need to have 4 temporary cells. Now we get to the actual printing of characters: Print the top bar and a newline: ``` >[->++>+<<]>+++[-<<<<.>>>>]>[-<<+>>]<<<<<<<<<.>>>>>>> ``` Print a `|`, a row of `o`'s, another `|` and a newline a number of times equal to the height: ``` <[->[->+>+<<]<<<<<<.>>>>>>>[<<<<<<.>.>>>>>-]>[-<<+>>]<<<<<<<.<.<.>>>>>>] ``` And print the bottom bar (no newline needed here): ``` >[->++>+<<]>+++[-<<<.>>>]>[-<<+>>]<< ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 52 bytes Byte count assumes ISO 8859-1 encoding. Note that the sixth line is supposed to contain a single space. ``` \G1? $_¶ 1* .+ |$&| \G. _ r`.\G - s`^.{17}$|1 o ``` [Try it online!](http://retina.tryitonline.net/#code=XEcxPwokX8K2CjEqIAoKCiAKLisKfCQmfApcRy4KXwpyYC5cRwotCnNgXi57MTd9JHwxCm8&input=MTEgMTExMQ) Input is in unary, using `1` as the unary digit, space as a separator and height followed by width. ### Explanation All stages in this program are bare substitutions, occasionally with a regular regex modifier (no repetition or loops, no other types of stages). It doesn't even use Retina-specific substitution features, apart from the usual `¶` alias for linefeeds. ``` \G1? $_¶ ``` The purpose of this is to "multiply" the two inputs. Our goal is to create `h+2` rows with `w` `1`s each (`h+2` so that we can turn the top and bottom into `_` and `-` later). The `\G` anchor requires the match to start where the last one left off. That is, if we ever fail to match a character in the string, further characters won't match either. We use this to match only the `1`s in `h`, but not in `w` because the regex doesn't allow the space that separates them to be matched. However, we also make the `1` optional, so that we get an additional empty match at the end of `h`. That's `h+1` matches. Each of those is replaced with the entire input (`$_`) followed by a linefeed. `w` itself remains untouched which gives us the `h+2`nd copy. Say the input was `11 1111`, then we've now got: ``` 11 1111 11 1111 11 1111 1111 ``` That's pretty good. We've got some extra stuff, but the `h+2` copies of `w` are there. ``` 1* ``` Note that there's a space at the end of the first line. This removes those prefixes from the lines so that we only have the `w`s afterwards. ``` ``` Ah well, that doesn't really work with SE's formatting... the first line is empty and the second line is supposed to contain a single space. This inserts spaces into every possible position, i.e. at the beginning and end of each line and between every pair of `1`s: ``` 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ``` We will turn these into `o`s later ``` .+ |$&| ``` This simply wraps every line in a pair of `|`: ``` | 1 1 1 1 | | 1 1 1 1 | | 1 1 1 1 | | 1 1 1 1 | ``` Now we take care of the top and bottom: ``` \G. _ ``` Time for `\G` to shine again. This matches each character on the first line and turns it into a `_`. ``` r`.\G - ``` Same thing, but due to the `r` modifier (right-to-left mode), this matches the characters on the *last* line and turns them into `-`. So now we've got: ``` ___________ | 1 1 1 1 | | 1 1 1 1 | ----------- ``` There's only two things left to do now: turn those `1` into `o`s, and if the input was `1 1` then turn the entire thing into `o` instead. We can handle both of those with a single stage: ``` s`^.{17}$|1 o ``` `s` is regular singleline mode (i.e. it makes `.` match linefeeds). If the input was `1 1` the result will have the minimum size of 17 characters so we can match it with `^.{17}$` and replace it with `o`. Otherwise, if that fails, we'll just match all the `1`s and replace those with `o` instead. [Answer] # Jolf, 36 bytes ``` ?w*jJρΡ,a+3ώj+2J'-"-+"d*'_lH" ' o'o ?w*jJ 'o return "o" if j * J - 1 ,a make a box +3ώj of width +3ώj = 3+2*j +2J of height +2J = 2+J '- specifying corners as "-" Ρ "-+" replacing the first run of "-"s d*'_lH with a run of "_"s of equal length ρ " ' replacing all " " ' o with " o" ``` # Jolf, 24 bytes, noncompeting Well, I made a better box builtin. ``` ?w*jJ,AhώjJ"_-'_-'|' o'o ``` # Jolf, ~~38~~ 37 bytes ``` ?w*jJΆ+*'_γ+3ώjS*JΆ'|*j" o' | "*'-γ'o ``` Simple stuff, really. Saved a byte by noting that `!Ζ` (math zeta, or the stand deviance) is only 0 when both arguments are 1, and is falsey otherwise (for our case). [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 33 bytes Code: ``` *i'oë¹·3+©'_׶²F'|„ o¹×„ |¶}®'-×J ``` Explanation: ``` *i'o # If both input equal 1, push "o" ë # Else, do... ¹·3+ # Push input_1 × 2 + 3 © # Copy this number to the register '_× # Multiply by "_" ¶ # Push a newline character ²F } # Do the following input_2 times: '| # Push "|" „ o # Push " o" ¹× # Multiply this by input_1 „ | # Push " |" ¶ # Push a newline character ® # Retrieve the value from the register '-× # Multiply by "-" J # Join everything and implicitly print. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=Kmknb8OrwrnCtzMrwqknX8OXwrbCskYnfOKAniBvwrnDl-KAniB8wrZ9wq4nLcOXSg&input=NAo4). [Answer] ## JavaScript (ES6), ~~89~~ 86 bytes ``` (x,y,g=c=>c[r=`repeat`](x*2+3))=>x*y-1?g(`_`)+` `+`| ${`o `[r](x)}| `[r](y)+g(`-`):`o` ``` Edit: Saved 3 bytes thanks to @Shaggy. [Answer] # Python 2, 71 bytes ``` lambda x,y:('o',x*'__'+'___\n'+'| %s|\n'%('o '*x)*y+'-'*(x*2+3))[x+y>2] ``` [Answer] # Befunge, 144 Bytes I would have prefered to comment to [this](https://codegolf.stackexchange.com/a/84061/56032) post, but I don't have the reputation yet, so I'm putting an answer of my own, which works a similar way, but is slightly more compact ``` &::&*:1`v v3*2:\/\_"o",@ >+: v >52*," |",, v >,1-:vLEG O MAKERv::\< ^"_" _$\:|<v "o "_v v52:+3*2$<,>,,1-:^$ >*,v < ^"|":-1\< v-1_@, >:"-"^ ``` you can test the code [here](http://www.quirkster.com/iano/js/befunge.html) [Answer] # Reng v.4, 82 bytes, noncompeting I pushed a bug fix that fixes functions being overwritten by themselves (please don't ask; my stuff is haunted) ``` i#wi#hhw+2e1+ø ~*x}o:{"-"ö< "_"{:o}w2*3+#xx*2ø "o"o~ ö"|"o"o"{Wo:o}w*"| "ooh1-?^#h ``` Takes input as space-joined numbers, like `4 2`. [Try it here!](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) [Answer] ## PowerShell v2+, 76 bytes ``` param($x,$y)if($x+$y-2){"_"*($z=$x*2+3);"|$(" o"*$x) |`n"*$y+'-'*$z;exit}"o" ``` Takes input, then checks an `if` statement. Since non-zero values are *truthy* in PowerShell, so long as at least one of `$x` and `$y` are not equal to `1`, the `if` will be true. Inside the `if`, there's a series of string multiplications. First, we construct our string of underscores, saving `$z` for later. That gets placed on the pipeline. Next we construct our string of sides and pegs (with the pegs multiplied by `$x`), done `$y` times, and concatenate that with our dashes `$z` times. That string is then placed on the pipeline and we `exit`. The pipeline is flushed and printing is implicit. Note that we get the newline between the underscores and the first row of pegs for free, since the default `.ToString()` separator for array output is ``n` (and we're outputting an array of strings). If the `if` is false, we're in the special `1 1` case, so we just put `"o"` by itself on the pipeline and exit, with printing again implicit. ### Examples ``` PS C:\Tools\Scripts\golfing> .\print-a-lego-piece.ps1 1 1 o PS C:\Tools\Scripts\golfing> .\print-a-lego-piece.ps1 5 3 _____________ | o o o o o | | o o o o o | | o o o o o | ------------- ``` [Answer] ## Bash, 186,163,156, 148,131, 130 Bytes ``` ## Arg1 - Lego width ## Arg2 - Lego height function print_lego() { (($1+$2>2))&&{ printf _%.0s `seq -1 $1` echo for((i=$2;i--;)){ printf \| for((j=$1;j--;)){ printf o } echo \| } printf =%.0s `seq -1 $1` echo }||echo o } ``` Note: If you really need the lego to have hyphens for the last line, then change the last printf to ``` printf -- -%.0s `seq -1 $1` ``` and add two bytes. [Answer] # Perl 5 - 84 77 bytes 84 Bytes ``` sub l{($x,$y)=@_;$w=3+2*$x;warn$x*$y<2?"o":'_'x$w.$/.('| '.'o 'x$x."|\n")x$y.'-'x$w} ``` 77 Bytes. With some help from [Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) ``` sub l{($x,$y)=@_;$x*$y<2?o:'_'x($w=3+2*$x).(' | '.'o 'x$x."|")x$y.$/.'-'x$w} ``` [Answer] ## C, ~~202~~ 191 bytes ``` #define p printf i,w,h;t(char*c){for(i=0;p(c),++i<w*2+3;);p("\n");}f(){t("_");for(i=0;i<w*h;)i%w<1?p("| o "):p("o "),i++%w>w-2&&p("|\n");t("-");}main(){scanf("%d %d",&w,&h);w*h<2?p("o"):f();} ``` Thanks to [@Lince Assassino](https://codegolf.stackexchange.com/users/29679/lince-assassino) for saving 11 bytes! Ungolfed: ``` #include <stdio.h> #define p printf int i, w, h; void t(char *c) { for(i=0; p(c), ++i<w*2+3;); p("\n"); } void f() { t("_"); for(i=0; i<w*h;) { i%w<1 ? p("| o ") : p("o "); i++%w>w-2 && p("|\n"); } t("-"); } int main() { scanf("%d %d", &w, &h); w*h<2 ? p("o") : f(); } ``` [Answer] # Cinnamon Gum, 32 bytes ``` 0000000: 6c07 d5f5 7a5d 9cdf 5ae6 52ae 4050 0c35 l...z][[email protected]](/cdn-cgi/l/email-protection) 0000010: 18d9 052f 0082 9b42 e7c8 e422 5fe4 7d9f .../...B..."_.}. ``` Non-competing. [Try it online.](http://cinnamon-gum.tryitonline.net/#code=MDAwMDAwMDogNmMwNyBkNWY1IDdhNWQgOWNkZiA1YWU2IDUyYWUgNDA1MCAwYzM1ICBsLi4uel0uLlouUi5AUC41CjAwMDAwMTA6IDE4ZDkgMDUyZiAwMDgyIDliNDIgZTdjOCBlNDIyIDVmZTQgN2Q5ZiAgLi4uLy4uLkIuLi4iXy59Lg&input=WzQsMl0) Input must be exactly in the form `[width,height]` with no space in between the comma and the height. # Explanation The string decompresses to this: ``` l[1,1]&o;?&`p___~__~ %| ~o ~| %---~--~ ``` The first `l` stage maps `[1,1]` to `o` (the special case) and everything else to the string ``` `p___~__~ %| ~o ~| %---~--~ ``` The backtick then signals the start of a second stage; instead of outputting that string, CG chops off the backtick and executes the string. The `p` mode then repeats all the characters inside the tildes first parameter (width) times and then afterwards repeats the characters inside the percent signs second parameter (height) times. So for `[4,2]` it turns into this: ``` ___________ %| o o o o | %----------- ``` and then into: ``` ___________ | o o o o | | o o o o | ----------- ``` [Answer] ## Batch, ~~172~~ 170 bytes ``` @echo off if "%*"=="1 1" echo o&exit/b set o= for /l %%i in (1,1,%1)do call set o=%%o%% o echo ---%o: o=--% for /l %%i in (1,1,%2)do echo ^|%o% ^| echo ---%o: o=--% ``` Edit: Saved 2 bytes thanks to ~~@CᴏɴᴏʀO'Bʀɪᴇɴ~~ @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ. I can save 7 bytes if I can assume delayed expansion is enabled. [Answer] # Vim, 56 keystrokes This seems like a text editing task, so Vim is the obvious choice! I take input as a text file with two space separated integers and output the answer into the same file. Also, I hate you for having the 1x1 special case... Anyway: ``` "adt l"bDro:if@a*@b==1|wq|en<cr>Di| |<esc>@aio <esc>yy@bPVr_GpVr-ZZ ``` and if there hadn't been for the special case, 35 keystrokes ``` "adt x"bDi| |<esc>@aio <esc>yy@bPVr_GpVr-ZZ ``` ## A breakdown for sane people: ``` "adt l"bD ``` Delete numbers from buffer into @a and @b (space char kept) ``` ro:if@a*@b==1|wq|en<cr> ``` Replace space with "o" and if special case, save and quit ``` Di| |<esc> ``` Clear the line and write the edges of the lego block ``` @aio <esc> ``` Insert @a lots of "o " to get a finished middle part ``` yy@bP ``` Yank line and make @b extra copies (one too many) ``` Vr_ ``` We are at top of buffer, replace extra line with underscores ``` Gp ``` Jump to bottom of buffer, pull line that we yanked earlier ``` Vr-ZZ ``` Replace line with dashes, save and quit [Answer] # Befunge, ~~114~~ ~~113~~ ~~108~~ 101 bytes I know there are already a number of Befunge solutions, but I was fairly certain they could be improved upon by taking a different approach to the layout of the code. I suspect this answer can be golfed further as well, but it is already a fair bit smaller than either of the previous entries. ``` &::&+:2`^|,+55_"_",^ -4:,,"| "<\_|#:+1\,,"|"+55$_2#$-#$" o",#!,#:< ,"-"_@#:-1< :*2+2\-_"o",@v!:-1< ``` [Try it online!](http://befunge.tryitonline.net/#code=Jjo6Jis6MmBefCwrNTVfIl8iLF4KLTQ6LCwifCAiPFxffCM6KzFcLCwifCIrNTUkXzIjJC0jJCIgbyIsIyEsIzo8CiAgLCItIl9AIzotMTwKIDoqMisyXC1fIm8iLEB2ITotMTw&input=NCAy) [Answer] # Pyth, 38 bytes ``` ?t*QJEjb+sm\_K+\|+j\o*dhQ\|+mKJsm\-K\o ``` [Test suite.](http://pyth.herokuapp.com/?code=%3Ft%2aQJEjb%2Bsm%5C_K%2B%5C%7C%2Bj%5Co%2adhQ%5C%7C%2BmKJsm%5C-K%5Co&test_suite=1&test_suite_input=8%0A3%0A1%0A1&debug=0&input_size=2) [Answer] # Haskell, 76 bytes ``` 1#1="o" w#h|f<-w*2+3=f!"_"++'\n':h!('|':w!" o"++" |\n")++f!"-" n!s=[1..n]>>s ``` Usage example: `3 # 2` gives you a multiline string for a 3-by-2 brick. Ungolfed: ``` (#) :: Int -> Int -> String 1 # 1 = "o" width # height = let longWidth = 2 * width + 3 in -- golfed as 'f' ( longWidth `times` "_" ++ "\n" ) ++ height `times` ( "|" ++ width `times` " o" ++ " |\n" ) ++ ( longWidth `times` "-" ) -- | golfed as (!) times :: Int -> [a] -> [a] times n s = concat $ replicate n s ``` [Answer] # Groovy, 107, 98, 70, 64 ``` {x,y->t=x*2+3;x<2&&y<2?"o":'_'*t+"\n"+"|${' o'*x} |\n"*y+'-'*t} ``` Testing: ``` (2,2) (1,1) (8,2) (1,4) _______ | o o | | o o | ------- o ___________________ | o o o o o o o o | | o o o o o o o o | ------------------- _____ | o | | o | | o | | o | ----- ``` [Answer] # PHP 7, 98 bytes ``` <?=($P=str_pad)("",$w=3+2*$argv[1],_).$P("",$argv[2]*++$w,$P(" | ",$w-1,"o ")."|").$P(" ",$w,"-"); ``` `str_pad` saves a little from `str_repeat`. Juggling with preincrement on `$w` saves two bytes. But version 7 is needed for assigning `$r` while using it at the same time. [Answer] ## APL, 46 bytes ``` {⍵≡1 1:'o'⋄'-'⍪⍨'_'⍪'|',' ','|',⍨'o '⍴⍨1 2×⌽⍵} ``` The guard: `⍵≡1 1:'o'` for the special case. Otherwise `'o '⍴⍨1 2×⌽⍵` builds the content. And the rest is just the boxing. [Answer] ## C#, 198 bytes ``` void f(int x,int y){int l=x*2+3;Console.Write(y==x&&x==1?"o":s("_",l)+"\n"+s("|"+s(" o",x)+" |\n",y)+s("-",l));}string s(string m,int u){return string.Join("",new string[u].Select(n=>m).ToArray());} ``` quick and dirty I had to write a function that multiplies strings ungolfed (for suggestions) ``` public static void f(int x,int y) { int l=x*2+3; Console.Write(y == x && x == 1 ? "o" : s("_",l)+"\n"+ s("|" + s(" o", x) + " |\n", y) + s("-",l)); } public static string s(string m,int u) { return string.Join("", new string[u].Select(n => m).ToArray()); } ``` ]
[Question] [ Given a length N string of less-than and greater-than signs (`<`, `>`), insert the integers 0 through N at the start and end and in between each pair of signs such that all the inequalities are satisfied. Output the resulting string. If there are multiple valid outputs, output any one (and just one) of them. For example ``` <<><><< ``` has 7 characters so all the numbers from 0 to 7 inclusive must be inserted. A valid output is ``` 2<3<4>1<5>0<6<7 ``` because all the inequalities taken one at a time ``` 2<3 3<4 4>1 1<5 5>0 0<6 6<7 ``` are true. If desired, the output may have spaces surrounding the signs, e.g. `2 < 3 < 4 > 1 < 5 > 0 < 6 < 7`. **The shortest code in bytes wins.** ## Test Cases The first line after an empty line is the input and the next line(s) are each valid output examples. ``` [empty string] 0 < 0<1 > 1>0 << 0<1<2 <> 1<2>0 >< 1>0<2 2>0<1 >> 2>1>0 <<< 0<1<2<3 ><> 1>0<3>2 >>< 3>2>0<1 3>1>0<2 2>1>0<3 >>> 3>2>1>0 >>><<< 3>2>1>0<4<5<6 6>3>1>0<2<4<5 4>2>1>0<3<5<6 4>3>1>0<2<5<6 <<><><< 2<3<4>1<5>0<6<7 >><><>> 7>6>0<5>1<4>3>2 <<<<<<<<<<<<<< 0<1<2<3<4<5<6<7<8<9<10<11<12<13<14 >><<<<><>><><< 6>5>4<7<8<9<10>3<11>2>1<12>0<13<14 14>5>4<7<8<9<10>3<11>2>1<12>0<13<6 ``` [Answer] # [Retina](http://github.com/mbuettner/retina), 20 bytes Byte count assumes ISO 8859-1 encoding. ``` $.' S`> %O#`\d+ ¶ > ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYAoKJC4nClNgPgolTyNgXGQrCsK2Cj4&input=CjwKPgo8PAo8Pgo-PAo-Pgo8PDwKPjw-Cj4-PAo-Pj48PDwKPDw-PD48PAo-Pjw-PD4-Cjw8PDw8PDw8PDw8PDw8Cj4-PDw8PD48Pj48Pjw8) (The first line enables a linefeed-separated test-suite.) ### Explanation A simple way to find a valid permutation is to start by inserting the numbers from `0` to `N` in order, and then to reverse the numbers surrounding each substring of `>`s. Take `<><<>>><<` as an example: ``` 0<1>2<3<4>5>6>7<8<9 --- ------- these sections are wrong, so we reverse them 0<2>1<3<7>6>5>4<8<9 ``` Both of those tasks are fairly simple in Retina, even though all we can really work with are strings. We can save an additional byte by inserting the numbers from `N` down to `0` and reversing the sections surrounding `<` instead, but the principle is the same. **Stage 1: Substitution** ``` $.' ``` We start by inserting the length of `$'` (the suffix, i.e. everything *after* the match) into every possible position in the input. This inserts the numbers from `N` down to `0`. **Stage 2: Split** ``` S`> ``` We split the input around `>` into separate lines, so each line is either an individual number or a list of numbers joined with `<`. **Stage 3: Sort** ``` %O#`\d+ ``` Within each line (`%`) we sort (`O`) the numbers (`\d#`) by their numerical value (`#`). Since we inserted the number in reverse numerical order, this reverses them. **Stage 4: Substitution** ``` ¶ > ``` We turn the linefeeds into `>` again to join everything back into a single line. That's it. As a side note, I've been meaning to add a way to apply `%` to other delimiters than linefeeds. Had I already done that, this submission would have been *14* bytes, because then the last three stages would have been reduced to a single one: ``` %'>O#`\d+ ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~46~~ ~~43~~ 35 + 4 for `-s=` = 39 bytes ``` 0&l?!v:3%?\&:n1+$o! +nf0.>&n; >l&:@ ``` This is an implementation of [xnor's algorithm](https://codegolf.stackexchange.com/a/92482/41881) in ><>. It takes the input string on the stack (`-s` flag with the standard interpreter). You can try it out on the [online interpreter](https://fishlanguage.com/playground). [Answer] ## [><>](http://esolangs.org/wiki/Fish), 26 + 4 = 30 bytes ``` l22pirv 1+$2po>:3%::2g:n$- ``` [Try it online!](http://fish.tryitonline.net/#code=bDIycGlydgoxKyQycG8-OjMlOjoyZzpuJC0&input=&args=LXM9Pjw-Pjw-) +4 bytes for the `-s=` flag - if just `-s` is okay (it would mean that the flag would need to be dropped entirely for empty input), then that would be +3 instead. Assumes that STDIN input is empty so that `i` produces -1 (which it does on EOF). The program errors out trying to print this -1 as a char. Uses the max-of-nums-so-far-for-`>`, min-of-nums-so-far-for-`<` approach. ``` [Setup] l22p Place (length of stack) = (length of input) into position (2, 2) of the codebox. Codebox values are initialised to 0, so (0, 2) will contain the other value we need. i Push -1 due to EOF so that we error out later r Reverse the stack v Move down to the next line > Change IP direction to rightward [Loop] :3% Take code point of '<' or '>' mod 3, giving 0 or 2 respectively (call this value c) : Duplicate :2g Fetch the value v at (c, 2) :n Output it as a number $-1+ Calculate v-c+1 to update v $2p Place the updated value into (c, 2) o Output the '<' or '>' as a char (or error out here outputting -1) ``` A program which exits cleanly and does not make the assumption about STDIN is 4 extra bytes: ``` l22p0rv p:?!;o>:3%::2g:n$-1+$2 ``` [Answer] # [CJam](http://sourceforge.net/projects/cjam/), 16 bytes ``` l_,),.\'</Wf%'<* ``` [Try it online!](http://cjam.tryitonline.net/#code=bF8sKSwuXCc8L1dmJSc8Kg&input=PD48PD4-Pjw8) A port of [my Retina answer](https://codegolf.stackexchange.com/a/92416/8478). ### Explanation ``` l e# Read input. _, e# Duplicate, get length N. ), e# Get range [0 1 2 ... N]. .\ e# Riffle input string into this range. '</ e# Split around '<'. Wf% e# Reverse each chunk. '<* e# Join with '<'. ``` [Answer] # Perl, 29 bytes Includes +2 for `-lp` Run with input on STDIN, e.g. ``` order.pl <<< "<<><><<" ``` Output: ``` 0<1<7>2<6>3<4<5 ``` `order.pl`: ``` #!/usr/bin/perl -lp s%%/\G</?$a++:y///c-$b++%eg ``` ## Explanation Have two counters, max starting with the string length, min starting with 0. Then at each boundary (including start and end of string) if it is just before a `<` put the minimum there and increase by 1, otherwise put the maximum there and decrease by 1 (at the end of the string it doesn't matter which counter you take since they are both the same) [Answer] # Python 2, ~~163~~ 137 bytes ``` from random import* def f(v):l=len(v)+1;N=''.join(sum(zip(sample(map(str,range(l)),l),v+' '),()));return N if eval(N)or len(v)<1else f(v) ``` Shuffles the numbers until the statement evals to `True`. [Try it.](https://repl.it/DS2m) [Answer] ## Python 2, 67 bytes ``` f=lambda s,i=0:s and`i+len(s)*(s>'=')`+s[0]+f(s[1:],i+(s<'>'))or`i` ``` A recursive function. Satisfies each operator in turn by putting the smallest unused value `x` for `x<` and greatest for `x>`. The smallest unused value is stored in `i` and updated, and the largest unused value is inferred from `i` and the remaining length. [Answer] # APL, 33 bytes ``` ⍞←(S,⊂''),.,⍨-1-⍋⍋+\0,1-2×'>'=S←⍞ ``` `⍋⍋` is unusually useful. ### Explanation ``` ⍞←(S,⊂''),.,⍨-1-⍋⍋+\0,1-2×'>'=S←⍞ ⍞ read a string from stdin '<<><><<' S← store it in variable S '>'= test each character for eq. 0 0 1 0 1 0 0 1-2× 1-2×0 = 1, 1-2×1 = ¯1 1 1 ¯1 1 ¯1 1 1 (thus, 1 if < else ¯1) 0, concatenate 0 to the vector 0 1 1 ¯1 1 ¯1 1 1 +\ calculate its running sum 0 1 2 1 2 1 2 3 ⍋ create a vector of indices 1 2 4 6 3 5 7 8 that sort the vector in ascending order ⍋ do it again: the compound ⍋⍋ 1 2 5 3 6 4 7 8 maps a vector V to another vector V', one permutation of the set of the indices of V, such that V > V => V' > V'. i j i j due to this property, V and V' get sorted in the same way: ⍋V = ⍋V' = ⍋⍋⍋V. -1- decrement by one 0 1 4 2 5 3 6 7 ⊂'' void character vector ⊂'' S, concatenate input string '<<><><<' ⊂'' ( ),.,⍨ first concatenate each 0 '<' 1 '<' 4 '>' 2 \ element of the result vector '<' 5 '>' 3 '<' 6 '<' \ with the cordisponding 7 ⊂'' element in the input string, then concatenate each result ⍞← write to stdout ``` [Answer] ## JavaScript (ES6), ~~74~~ 56 bytes ``` s=>s.replace(/./g,c=>(c<'>'?j++:l--)+c,j=0,l=s.length)+j ``` Starts with the set of numbers `0...N`. At each stage simply takes the greatest (`l`) or least (`j`) of the remaining numbers; the next number must by definition be less than or greater than that. Edit: Saved a massive 18 bytes thanks to @Arnauld. [Answer] # Pyth - 19 bytes Hooray for comparison chaining! ``` !QZhv#ms.idQ.p`Mhl ``` Doesn't work online cuz of eval safety. [Answer] # [2sable](http://github.com/Adriandmen/2sable), 20 [bytes](http://www.cp1252.com/) ``` gUvy'<Qi¾¼ëXD<U}y}XJ ``` **Explanation** ``` gU # store input length in variable X v } # for each char in input y'<Qi # if current char is "<" ¾¼ # push counter (initialized as 0), increase counter ëXD<U} # else, push X and decrease value in variable X y # push current char XJ # push the final number and join the stack ``` [Try it online!](http://2sable.tryitonline.net/#code=Z1V2eSc8UWnCvsK8w6tYRDxVfXl9WEo&input=Pj48PDw8Pjw-Pjw-PDw) For **N<10** this could have been 14 bytes: ``` ÎvyN>}J'<¡í'<ý ``` [Answer] # C#, ~~102~~ 99 bytes ``` string f(string s){int i=0,j=s.Length;var r="";foreach(var c in s)r=r+(c<61?i++:j--)+c;return r+i;} ``` Ungolfed: ``` string f(string s) { int i = 0, j = s.Length; // Used to track the lowest and highest unused number. var r = ""; // Start with the empty string. foreach (var c in s) // For each character in the input string: r = r + // Append to the result: (c < 61 // If the current character is '<': ? i++ // Insert the lowest unused number, : j--) // otherwise, insert the highest unused number. + c; // And append the current character. return r + i; // Return the result with the last unused number appended. } ``` [Answer] # Java 8, ~~126~~ 125 bytes ``` s->{int t=s.replaceAll("<","").length(),y=t-1;String r=t+++"";for(char c:s.toCharArray())r+=(c+"")+(c<61?t++:y--);return r;}; ``` I don't think this even works hehe # Ungolfed test program ``` public static void main(String[] args) { Function<String, String> function = s -> { int t = s.replaceAll("<", "").length(), y = t - 1; String r = t++ + ""; for (char c : s.toCharArray()) { r += (c + "") + (c < 61 ? t++ : y--); } return r; }; System.out.println(function.apply("<<><><<")); System.out.println(function.apply(">>><<<")); System.out.println(function.apply(">>>")); System.out.println(function.apply("<<<")); System.out.println(function.apply(">><><>>")); } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~27 14~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Port of @Martin Enders [CJam solution](https://codegolf.stackexchange.com/a/92424/53748) -2 bytes thanks to @Dennis ``` żJ0;µFṣ”<Uj”< ``` Test it at [**TryItOnline**](http://jelly.tryitonline.net/#code=xbxKMDtG4bmj4oCdPFVq4oCdPA&input=&args=Ijw8Pjw-PDwiCg) How? ``` żJ0;Fṣ”<Uj”< - main link takes an argument, the string, e.g. ><> J - range(length(input)), e.g. [1,2,3] 0 - literal 0 ; - concatenate, e.g. [0,1,2,3] ż - zip with input, e.g. [[0],">1","<2",">3"] F - flatten, list, e.g. "0>1<2>3" ”< ”< - the character '<' ṣ - split, e.g. ["0>1","2>3"] U - upend (reverse) (implicit vectorization), e.g. ["1>0","3>2"] j - join, e.g. "1>0<3>2" ``` Previous method was interesting mathematically, but not so golfy... ``` =”>U LR!×ÇĖP€S‘ L‘ḶŒ!ị@ÇðżF ``` This uses the factorial base system to find an index of the permutations of [0,N] that will satisfy the equation. [Answer] ## **Clojure, ~~152~~ ~~132~~ 126 bytes** ``` (defn f[s](loop[l 0 h(count s)[c & r]s a""](if c(case c\<(recur(inc l)h r(str a l c))(recur l(dec h)r(str a h c)))(str a l)))) ``` Saved a fair number of bytes by eliminating as much whitespace as I could. I realized whitespace isn't necessary to separate a parenthesis from another character. Basically a Clojure port of @Scepheo's answer. Works identically. Those `recur` calls are killer! ~~I suppose I could have used atoms to clean it up.~~ The `swap!` calls required to use atoms added to the count :/ Thanks to @amalloy for saving me a few bytes. Ungolfed: ``` (defn comp-chain [chain-str] (loop [l 0 ; Lowest number h (count chain-str) ; Highest number [c & cr] chain-str ; Deconstruct the remaining list a ""] ; Accumulator (if c ; If there's any <>'s left (if (= c \<) ; If current char is a <... (recur (inc l) h cr (str a l c)) ; Add l to a, and inc l (recur l (dec h) cr (str a h c))) ; Add h to a, and dec h (str a l)))) ; Add on the remaining lowest number, and return ``` [Answer] ## Haskell, 162 bytes ``` import Data.List (a:b)%(c:d)=show c++a:b%d _%[x]=show x f l=map(l%).filter(l#)$permutations[0..length l] (e:f)#(x:y:z)=(e!x)y&&f#(y:z) _#_=0<1 '>'!x=(>)x _!x=(<)x ``` This is friggin' long. [Answer] # Perl (107 + 1 for -p) 108 ``` for$c(split''){$s.=$i++.$c;} for$b(split'<',$s.$i){$h[$j]=join'>',reverse split'>',$b;$j++;} $_=join'<',@h; ``` Algorithm stolen from Martin Ender♦'s [answer](https://codegolf.stackexchange.com/a/92416/57100) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` õª€N'<¡íJ'<ý ``` Port of [*@MartinEnder*'s CJam answer](https://codegolf.stackexchange.com/a/92424/52210), so make sure to upvote him as well! -1 byte thanks to *@Grimmy*. [Try it online](https://tio.run/##yy9OTMpM/f//8NZDqx41rfFTtzm08PBaL3Wbw3v//7ezswECOxsgDWQBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeXhCaH/D289tOpR0xo/dZtDCw@v9VK3Obz3v87/aCUlHQUlGxBhB2aBmTZgth1EGCoO4UBlYFJQnh1U2sYGqACqEsSC60UCUEkbsFqI8lgA). **Explanation:** ``` õª # Append an empty string to the (implicit) input-string as list, # which also converts the input-string to a list of characters # i.e. "><>" → [">","<",">",""] €N # Insert the 0-based index before each character in this list # → [0,">",1,"<",2,">",3,""] '<¡ '# Split this list on "<" # → [[0,">",1,],[2,">",3,""]] í # Reverse the items of each inner list # → [[1,">",0],["",3,">",2]] J # Join each inner list into a string # → ["1>0","3>2"] '<ý '# And join this list of strings with "<" delimiter # → "1>0<3>2" # (after which the resulting string is output implicitly as result) ``` [Answer] ## Ruby, 135 bytes ``` g=gets puts g.nil?? 0:[*0..s=g.size].permutation.map{|a|a.zip(g.chars)*""if s.times.map{|i|eval"%s"*3%[a[i],g[i],a[i+1]]}.all?}.compact ``` Note: Time complexity is large (O(n!)). [Answer] # Python 2, ~~176~~ 172 bytes It's not very short compared to the others, but I'm happy that I solved it so quickly. ``` from itertools import* def f(s): for p in permutations(range(len(s)+1)): n=list(s);p=list(p);t=[p.pop()]+list(chain(*zip(n,p)));r="".join(map(str,t)) if eval(r):return r ``` [**Try it online**](http://ideone.com/c33FJx) Ungolfed: ``` from itertools import* def f(s): n=list(s);R=range(len(s)+1) for p in permutations(R): p=list(p) r=[p.pop()] t=n+p t[::2]=n t[1::2]=p r="".join(map(str,r+t)) if eval(r):return r ``` [**Try it online**](http://ideone.com/WIDsmt) [Answer] # PHP , 190 Bytes random shuffle till a valid solution exists ``` $x=range(0,$l=strlen($q=$argv[1]));while(!$b){$b=1;$t="";shuffle($x);for($i=0;$i<$l;){$t.=$x[$i].$q[$i];if(($q[$i]==">"&$x[$i]<$x[$i+1])|($q[$i]=="<"&$x[$i]>$x[1+$i++]))$b=0;}}echo$t.$x[$i]; ``` 381 Bytes get all solutions and pick one ``` <?php $d=range(0,strlen($q=$argv[1]));echo $q."\n";$e=[];function f($t=""){global$e,$d,$q;foreach($d as$z){preg_match_all("#\d+#",$t,$y);if(in_array($z,$y[0]))continue;$p=preg_match_all("#[<>]#",$t);$g="";if(preg_match("#\d+$#",$t,$x)){if(($q[$p]==">"&$x[0]<$z)|($q[$p]=="<"&$x[0]>$z))continue;$g=$q[$p];}strlen($q)==$p+1|!$q?$e[]=$t.$g.$z:f($t.$g.$z);}}f();echo$e[array_rand($e)]; ``` [Answer] # Javascript (node.js), 94 bytes [**Try it online**](https://tio.run/##ZYtBCsMgFESPox/NJ9kG/T2IuBAjYkljiI14eyvdZjZveMO8XXXFX@n8TkfeQo@6F03GzFYiYrF4he32gfMmq0ygqRJT7GXG2PDjTl6HEgvI2a5/KZOFx6mJYtK0WFGh@3yUvAfcc@SRMyI1QmpwNAbQfw) ``` s=>[[0],...s].reduce((x,v,i)=>v>'<'?[...x.map(v=>v+1),0]:[...x,i]).reduce((x,v,i)=>x+s[i-1]+v) ``` Ungolfed: ``` s => [[0],...s].reduce((x, v, i) => v > '<' ? [...x.map(v => v + 1), 0] : [...x, i]) .reduce((x, v, i) => x + s[i-1] + v) ``` [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 38 bytes ``` sarzPp{J'>=={PPl_}{PPg_j}x/iePp}]mPP?+ ``` [Try it online!](https://tio.run/##SyotykktLixN/f@/OLGoKqCg2kvdzta2OiAgJ74WSKbHZ9VW6GemBhTUxuYGBNhr//9vZ2cDRDZ2AA "Burlesque – Try It Online") Using [xnor's algorithm](https://codegolf.stackexchange.com/questions/92414/greater-than-less-than-greater-than-something-fishy/92482#92482) ``` sarz # Generate range [0,N_comp] Pp # Push this into state stack { J'>== # Non destructive test if is ">" {PPl_}{PPg_j}x/ie # If it is, take the head of the range # Else take the tail Pp # Push the remainder back to the state stack }]m # Apply to each character and map result to string PP # Take the remaining element from state stack ?+ # Append it to the string ``` # Burlesque, 61 bytes ``` )'.2co)PIsarzr@{2CO}m[jbcz[{**FL(&&)[+}^m:e!{~]3co{x/}^mgn}m[ ``` [Try it online!](https://tio.run/##SyotykktLixN/f9fU13PKDlfM8CzOLGoqsih2sjZvzY3OispuSq6WkvLzUdDTU0zWrs2LtcqVbG6LtY4Ob@6Qh/ITc8DKvv/387OBgA "Burlesque – Try It Online") A method using actually evaluating permutations of ints, longer partially due to trying to format the final answer sensibly. ``` )'. # Add a "." before each character (.> is comparison in Burlesque) 2co)PI # Split into comparison operators sarzr@ # Create all permutations of [0,N_comp] {2CO}m[ # Create ngrams of length 2 ({abc} -> {ab bc} jbcz[ # Zip with the operators { **FL # Merge to form an operation of the form {a b .> b c .<} (&&)[+ # Append a bitwise and }^m # Apply to each element :e! # Filter for those which when evaluated produce true { ~] # Drop last element (&&) 3co # Split into chunks of three {x/}^m # Cycle and push each block gn # Delete duplicate consecutive elements }m[ # Apply to each group ``` [Answer] # [Haskell](https://www.haskell.org/), 95 bytes ``` s=show ('<':y)!(a:b)=s a++'<':y!b (x:y)!z=s(last z)++x:y!init z _!(y:_)=s y f x=x![0..length x] ``` [Try it online!](https://tio.run/##HYtBCsMgFET3nsK/iiKErkW9SCnhp5gotRb6hWoub01mMzNvmID08in1TpbC58fEZCbdJAjUq7TEUamLwMpEPYfDkkhIhR9SqUEg5jgKW0A0vZyXxjZebYX7bZ6Tz3sJvD76G2O2MRf/xWfhW3fODDkzfKQ/ "Haskell – Try It Online") [Answer] # [PHP](https://php.net/), ~~165~~ ~~156~~ 110 bytes ``` $o=[$j=$i=$s=$m=0];for(;$i<strlen($n=$argn);)$o[]=$n[$i++]=='<'?++$m:--$s;for(;$j<=$i;)echo$o[$j]-$s,$n[$j++]; ``` [Try it online!](https://tio.run/##LYxBDsIgFESv4mKSliCJa@G3Oy9BWBhTBWL5BHp@8ZuYmd28NzXW4dYa62mAySMTEqETdroE@@Q2WyTXj/beyoxCuLdXUVaBfSAUj6R1IJrctGqN/WoM@l/LTr6s2h6RhUYOMp1/ShbFjrG4RSr5cD0Slz7M7Qs "PHP – Try It Online") ## Ungolfed ``` <?php $min=0; $max=0; $current=0; $order = [0]; for ($i=0;$i<strlen($argn);$i++){ $compare=$argn[$i]; if ($compare=='<') { $max++; $current=$max; } else { $min--; $current=$min; } $order[] = $current; } for ($i=0;$i<=strlen($argn);$i++){ echo ($order[$i]-$min); if ($i<strlen($argn)) echo $argn[$i]; } ``` [Answer] # Excel (Ver. 1911), 199 Bytes Using iterative calculation (max iterations set to 1024) ``` B2 'Input B3 =IF(B3=4^5,1,B3+1) B4 =B3-1 C2 =SEQUENCE(LEN(B2)) D2 =ROW(C2#:C1)-1 E2 =IF(B4,IF(C2#=B4,IF(F2#=">",@SORT(G2#,,-1),G2),E2#),-C2#) F2 =MID(B2,C2#,1) G2 =FILTER(D2#,NOT(MMULT(N(D2#=TRANSPOSE(E2#)),C2#/C2#))) H2 =CONCAT(E2#:F2#,G2) ' Output ``` ### Explanation ``` B2 'Input B3 =IF(B3=4^5,1,B3+1) ' Keeps track of iteration number B4 =B3-1 ' 0 index the iteration counter C2 =SEQUENCE(LEN(B2)) ' Generate sequence to index input string D2 =ROW(C2#:C1)-1 ' Create sequence [0..N] E2 =IF(B4,IF(C2#=B4,IF(F2#=">",@SORT(G2#,,-1),G2),E2#),-C2#) ' On each iteration check if the current char is ">" pull the largest unused number, ' else pull the smallest F2 =MID(B2,C2#,1) ' Break the input string into separate rows G2 =FILTER(D2#,NOT(MMULT(N(D2#=TRANSPOSE(E2#)),C2#/C2#))) ' Set of unused numbers H2 =CONCAT(E2#:F2#,G2) ' Concatenate numbers, gt/lt signs, and last unused number ``` ### Test Sample [![test sample](https://i.stack.imgur.com/A39Tj.png)](https://i.stack.imgur.com/A39Tj.png) ]
[Question] [ ### Challenge: Take a string of upper or lower case letters as input (optional), and calculate the score that string would get in a game of [Scrabble](https://en.wikipedia.org/wiki/Scrabble) in English. ### Rules: The score of each letter is as follows (use this even if there are other versions of the game): ``` 1 point: E, A, I, O, N, R, T, L, S, U 2 points: D, G 3 points: B, C, M, P 4 points: F, H, V, W, Y 5 points: K 8 points: J, X 10 points: Q, Z ``` The score of a string is simply the sum of the scores of each of the letters used. You may assume that you have plenty of tiles available, so long words, and words with many of the same letters are valid input. ### Test cases: ``` ABC -> 7 PPCG -> 11 STEWIE -> 9 UGPYKXQ -> 33 FIZZBUZZ -> 49 ABCDEFGHIJKLMNOPQRSTUVWXYZ -> 87 ``` The shortest answer in each language wins! The input and output formats are flexible, so you may take the input as an array of characters (upper or lower case) if you want. [Answer] # [sed 4.2.2](https://www.gnu.org/software/sed/), 81 ``` s/[QZ]/JD/g s/[JX]/KB/g s/K/FE/g s/[FHVWY]/BE/g s/[BCMP]/DE/g s/[DG]/EE/g s/./1/g ``` Output is in [unary](https://codegolf.meta.stackexchange.com/a/5349/11259). Reduces each letter to a combination of lower-scoring letters until all letters are 1-scorers. Then replaces those with `1`s to give a unary count. [Try it online!](https://tio.run/##LcpBDsIgEIXh/RzGiUcQGChgFWwpMIadpgfo/YON7e77X972/fS@4TtyQ6dwhd2uNPTib4@ajlEPS64NxZlCjqGhOkuZhnT4gldce78JCSFIA9NM2RIkE6ovEbRlFokZ9oMibQbr/H18PEN8TXNacqn8Aw "sed 4.2.2 – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 50 bytes ``` @(t)'       '/3*sum(65:90==t')' ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0RTnZmTk42Zh42HWYKfmZOZmVOOGQh4eCR45NT1jbWKS3M1zEytLA1sbUvUNdX/p2moOzo5q2sqqCpAgK4diDTnAkoEBDi7I2TAEoaGIIngENdwT1eYFESHJUgi1D0g0jsiECoDljA2Bkm4eUZFOYVGRUFkwBImYB1Ay11c3dw9PL28fXz9/AMCg4JDQsPCIyIRSi3Muf4DAA "Octave – Try It Online") Challenge accepted. Explanation: ``` @(t) % Define anonymous function taking a single argument t. ' ... '/3 % Row vector with letter scores. Corresponds to char([1 3 3 2 ...]*3). % The factor 3 was necessary to avoid a newline. * % Dot product (yes, * is dot product, .* is not. Go figure). Equivalent to sum of element-wise products. 65:90 % Alphabet ==t' % Broadcast equality with input string. sum( ) % Sum this matrix. Gives the count of each letter in the alphabet ' % Transpose into column vector for dot product ``` [Answer] # [Haskell](https://www.haskell.org/), ~~86~~ 84 bytes ``` f s=length s+sum[n|x<-s,(n,y)<-zip(9:7:[1..])$words"QZ JX DG BCMP FHVWY K",x`elem`y] ``` [Try it online!](https://tio.run/##BcHLCoJAFAbgV/mRFkoqtIpEXWRkFIFtuiiCQuOFxqN4JtLo3afva0p@CSm1rsCBFFSrBrzkd5fRb/Idtk2yZ8t3vu1gbry1l61cN7cWn358snFJcbxjF2MbnRPsD9fbAyfDngohRVfMue7KlhCgFirqSQlSjDAMMIwtKbiodJJE8R8 "Haskell – Try It Online") ### Explanation Most letters give a score of 1 and thus we don't need to keep track of these, instead we just decrement each score (saves 1 byte on `10` as well) and then add the length of the string to the resulting score. Thanks [@nimi](https://codegolf.stackexchange.com/users/34531/nimi?tab=profile) for -2 bytes (rearanging the words and using `[1..]` instead of `[4,3..]`)! [Answer] # [Beatnik](https://esolangs.org/wiki/Beatnik), 733 bytes Since it really had to be done, here it is. It was a really nasty to debug and provided a few challenges. Input must be uppercase letters only. Output is unary (hope that is OK?) ``` J K ZZZZZZK Z ZD ZB ZZZZZZZZZZZZZZZZZA K A Z ZD ZB ZZZZZZZZZZZZZZZKF K A Z ZD ZB ZZZZZZZZZZZZZZZB K A Z ZD ZB ZZZZZZZZZZZZZZZ K A Z ZD ZB ZZZZZZZZZZZZZZKD K A Z ZD ZB ZZZZZZZZZZZZZD K A Z ZD ZB ZZZZZZZZZZZZZD K A Z ZD ZB ZZZZZZZZZZZZ K A Z ZD ZB ZZZZZZZZZZZZB K A Z ZD ZB ZZZZZZZZZKA K A Z ZD ZB ZZZZZZZZZKF K A Z ZD ZB ZZZZZZZZZZK K A Z ZD ZB ZZZZZZZZZB K A Z ZD ZB ZZZZZZZZZB K A Z ZD ZB ZZZZZZZZKD K A Z ZD ZB ZZZZZZZK K A Z ZD ZB ZZZZKB K A Z ZD ZB ZZZZZZKF K A Z ZD ZB ZZZZZZB K A Z ZD ZB ZZZZZFB K A Z ZD ZB ZZZZZA K A Z ZD ZB ZZZAK K A Z ZD ZB ZZZ K A Z ZD ZB ZD K A Z ZD ZB ZKB K ZZZZKF KF K ZZZZKF KF K ZZZZKF KF K ZZZZKF KF K ZZZZKF KF K ZZZZKF KF K ZZZZKF KF K ZZZZKF KF K ZZZZKF KF K ZZZZKF KF K A ZKA ZZZZZZZZZZZZZZZZZZY ``` [Try it online!](https://tio.run/##S0pNLMnLzP7/30vBWyEKDIC0QpSLQpQTlI8EHIGKHHFJe7vhk3XCJ4lHztsFtyRZUjglcLjQG4encXrXG7u4EynC2H2NabI3Nu1YXYZFoRsWMQzPOmJYispHcyjYQTBHuNGZDXQHMLYwUm1U5P//jk7OLq5u7h6eXt4@vn7@AYFBwSGhYeERUZEA "Beatnik – Try It Online") General process is: * get character from input * subtract 65 * check if result is 0 + if 0 jump specified amount of words. + otherwise subtract 1 and repeat check. * the jump targets are push print operations followed be a loop back to beginning of program. Ends with an error. A more complete explanation: ``` J K ZZZZZZK Z ZD # Get input and subtract 65 ZB ZZZZZZZZZZZZZZZZZA K A Z ZD # Character A - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZZZZZZZZZKF K A Z ZD # Character B - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZZZZZZZZZB K A Z ZD # Character C - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZZZZZZZZZ K A Z ZD # Character D - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZZZZZZZZKD K A Z ZD # Character E - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZZZZZZZD K A Z ZD # Character F - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZZZZZZZD K A Z ZD # Character G - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZZZZZZ K A Z ZD # Character H - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZZZZZZB K A Z ZD # Character I - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZZZKA K A Z ZD # Character J - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZZZKF K A Z ZD # Character K - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZZZZK K A Z ZD # Character L - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZZZB K A Z ZD # Character M - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZZZB K A Z ZD # Character N - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZZKD K A Z ZD # Character O - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZZK K A Z ZD # Character P - if 0 jump to print, otherwise subtract 1 ZB ZZZZKB K A Z ZD # Character Q - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZKF K A Z ZD # Character R - if 0 jump to print, otherwise subtract 1 ZB ZZZZZZB K A Z ZD # Character S - if 0 jump to print, otherwise subtract 1 ZB ZZZZZFB K A Z ZD # Character T - if 0 jump to print, otherwise subtract 1 ZB ZZZZZA K A Z ZD # Character U - if 0 jump to print, otherwise subtract 1 ZB ZZZAK K A Z ZD # Character V - if 0 jump to print, otherwise subtract 1 ZB ZZZ K A Z ZD # Character W - if 0 jump to print, otherwise subtract 1 ZB ZD K A Z ZD # Character X - if 0 jump to print, otherwise subtract 1 ZB ZKB # Character Y - if 0 jump to print, otherwise subtract 1 K ZZZZKF KF # Jump Point for print 1111111111 K ZZZZKF KF # K ZZZZKF KF # Jump Point for print 11111111 K ZZZZKF KF # K ZZZZKF KF # K ZZZZKF KF # Jump Point for print 11111 K ZZZZKF KF # Jump Point for print 1111 K ZZZZKF KF # Jump Point for print 111 K ZZZZKF KF # Jump Point for print 11 K ZZZZKF KF # Jump Point for print 1 K A ZKA ZZZZZZZZZZZZZZZZZZAAAA # Jump back to start ``` [Answer] # Pyth, 40 bytes ``` sm+2x.e}dbc." zØÍ jÙ¹>;%OG5§"\ 1 ``` [Try it here](http://pyth.herokuapp.com/?code=sm%2B2x.e%7Ddbc.%22%20z%11%C3%98%03%C3%8D%09j%C3%99%C2%8C%C2%99%C2%B9%3E%C2%9A%3B%C2%8C%25%01OG5%C2%83%C2%A7%22%5C%201&input=%22fizzbuzz%22&debug=0) ### Explanation ``` sm+2x.e}dbc." zØÍ jÙ¹>;%OG5§"\ 1 m Q For each character in the (implicit) input... x.e b 1 ... find the first index in... c." zØÍ jÙ¹>;%OG5§"\ ['dg','bcmp','fhvwy','k','','','jx','','qz'] }d ... containing the character... +2 ... 2-indexed. s Take the sum. ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~210, 204, 198, 184~~, 170 bytes ``` ({<([{}]<>(({}{}))(([][][][][])<((([]())<([][])>))((((()))))>)[](((()()())<((()))>)((())()()()()))((())()()())((()())()())[]((((())())()))(())){({}<{}>())}>{}{}<{{}}><>}) ``` [Try it online!](https://tio.run/##TY4xCsRACEWv8y1yA7HYIrAHSDMhxWwRWHZJsa14dledBOIH5z/9A75@/X1M@7d/3KGMVW1jAdTUiIB1u0SMRFCYYsl9FGUJxSohVdEa1otTdEca4eHH36IzF03jCFaT8CZ5D6uaCYuR@/xs7bG05lP/Aw "Brain-Flak – Try It Online") Thanks to @JoKing for saving 14 bytes! Readable version: ``` ({ # For each character # Push array of letter scores # Also adjust character to 1-indexing <([{}]<> (({}{})) # Push 2 0s (([][][][][]) # 10 <((([]()) # 4 <([][])> # 8 )) # 4,4 ((((()))))> # 1,1,1,1 ) # 10 [] # Add 12 to difference (((()()()) # 3 <((()))> # 1,1 ) # 3 ((())()()()())) # 1, 5 ((())()()()) # 1, 4 ((()())()()) # 2, 4 [] # Add 22 to difference ((((())())())) # 1,2,3 (()) # 1 ) # Push 65-char {({}<{}>())} # Index character into score array > {}{} # Add score to running total <{{}}><> # Clear the stack }) # Implicit print of total score ``` [Answer] # [Python 2](https://docs.python.org/2/), 78 bytes ``` lambda x:sum(map(('ABCEIKLMNOPRSTU'+'BCDGMPQZ'*2+'FHJJKQQVWXXYZZ'*4).count,x)) ``` [Try it online!](https://tio.run/##HYzLCoJAGEb3PcXs/pmaWkgroSBNTc0aU/NCG7tIQl7QEezpp7HVd/jgnPbL302tiGJzE5@8uj9zNKr9UOEqbzGGnaYbtnv0Tmd2CcIIFqDpe8tjfgZzZQHmwXFc37/GSZJm8lqT1aMZak5HQkTRdIi/eo7KGk0hoMCYbskJQiO2DQmRxVI38SWZdpZpkWyoM9R2Zc3/KoXlFmiBJybiBw "Python 2 – Try It Online") ### Shorter version, port of [DanielIndie's answer](https://codegolf.stackexchange.com/a/162608/47120), ~~71~~ 70 bytes -1 byte thanks to Sunny Patel ``` lambda x:sum(int('02210313074020029000033739'[ord(c)-65])+1for c in x) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCqrg0VyMzr0RD3cDIyNDA2NDYwNzEwMjAwMjSAAiMjc2NLdWj84tSNJI1dc1MYzW1DdPyixSSFTLzFCo0/4PYJanFJSCuuqOTs7qOekCAszuQCg5xDfd0BTJC3QMivSMCgSw3z6gop9CoKHUrLoWCIqClYK066rp26jppGiC25n8A "Python 2 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 71 66 63 62 bytes * @Arnauld awesome as always reducing 7 bytes * thanks to l4m2 for rducing by 1 byte ``` s=>Buffer(s).map(x=>s="02210313074020029000033739"[x-65]-~s)|s ``` [Try it online!](https://tio.run/##Zc5NE0JAAMbxex/DyR6YZZUctpkISS@EvDQdjGhqhLHVODR9ddExz/U3/5nnFr9iktTX6sEU5TltM9wSPJOfWZbWNAHsPa7oBs8IpiDPcxBxCIoC5CHkJdgNIRFJ1LFhJuMT8yHgTdqkLEiZp2xeXuiMpuayQgGMRTD6A8tS9F44bkCOq/qG2qM0ME@3QjOwe0RooJoRRbIXRT0Lw7g7s1A1fWmszPVmu7PsveN6Bz8If8FUBO0X "JavaScript (Node.js) – Try It Online") [Answer] # Java 8, ~~75~~ ~~71~~ 70 bytes ``` s->s.chars().map(c->"\n\n".charAt(c-65)).sum() ``` -1 byte by changing `"02210313074020029000033739".charAt(c-65)-47` to unprintables (and two `\n`) so the `-47` can be removed. Inspired by [@Sanchises' Octave answer](https://codegolf.stackexchange.com/a/162676/52210). [Try it online.](https://tio.run/##dVFha8IwEKW2A9mvCP2UIJbauonKBHXqnNPVVad27kNW61Zn09JEQcTf3sVYBmXsSD7k3bt373IbvMfFMPLIZvWduFtMKRhinxyvAfAJ8@I1dj0wOj8FAFxos9gnn4CiOgdP/PJDGWa@C0aAgDuQ0GKDau4XjilEWoAj6BYbqiTLOUnJKVL@SpIlSV4SiYei5JUlUQW7yTjx9gYhje4CiJL6RTvafWy5dtpiH/orEHCHqY@3d4wu7tZhDM8ywK2pumGUdLNk6pWybui6UdV5mGbFrKoaC9vnZnGMDxAhUQqAfaDMC7Rwx7SIyzIopBA3VK4gMelfzpZAnhEp5lEG1WarrabcC2BZ7V4WsSedWb@TxaY9azGYj7Ngt@84ranjZFHe4b7T7T30HwdPw9GzNX6xJ9PX2XyR8rLrEH8lCn93dvxvElpQa0AtEM2FFKVap@QH) ``` s-> // Method with String parameter and integer return-type s.chars() // Loop over the characters as IntStream .map(c->"\n\n".charAt(c-65)) // Convert the character to its value .sum() // And sum it all together ``` [Answer] # [Octave](https://www.gnu.org/software/octave/) / MATLAB, 85 bytes ``` @(x)sum([1:4 7 9]*any(reshape(char(strsplit('DG BCMP FHVWY K JX QZ')),6,1,5)==x,3)+1) ``` [Try it online!](https://tio.run/##JctbC4IwAIbh@37F7raVCNKJAqE8TTNr5nnRxRDFoIM4C/v1Jnj3vHx877zl36IvVVmW@x3qsPg80VXZLsAabG5T/vqhphAVrwuUV7xBom1E/bi3CBoEaLpHgWXHSQZccEiBzyDG0kpSpCVW1U6a45mC@xLBvaZDPBlAqU5GBaGZOOboiNDMTf0xLIcxLWJsrOFpmBaxnYN79E5n6l@CMIqTNBv2/g8 "Octave – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Oị“ÆẠḃbṂƬɠF#ṁ²’ḃ⁵¤S ``` A monadic link accepting a list of upper-case characters which returns an integer **[Try it online!](https://tio.run/##AToAxf9qZWxsef//T@G7i@KAnMOG4bqg4biDYuG5gsasyaBGI@G5gcKy4oCZ4biD4oG1wqRT////U1RFV0lF "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##AYEAfv9qZWxsef//T@G7i@KAnMOG4bqg4biDYuG5gsasyaBGI@G5gcKy4oCZ4biD4oG1wqRT/@G7tMW8w4fFkuG5mCTigqwkR///QUJDClBQQ0cKU1RFV0lFClVHUFlLWFEKRklaWkJVWloKQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo "Jelly – Try It Online"). ### How? ``` Oị“ÆẠḃbṂƬɠF#ṁ²’ḃ⁵¤S - Link: list of characters O - ordinals ('A'->65, B->66...) ¤ - nilad followed by link(s) as a nilad: “ÆẠḃbṂƬɠF#ṁ²’ - literal 14011114485013321424185131 ⁵ - literal 10 ḃ - bijective-base = [1,3,10,1,1,1,1,4,4,8,4,10,1,3,3,2,1,4,2,4,1,8,5,1,3,1] ị - index into (1-based & modular) (vectorises) - i.e. mapping from: O P Q R S T U V W X Y Z A B C D E F G H I J K L M N) S - sum ``` [Answer] # [R](https://www.r-project.org/), ~~90~~ 63 bytes ``` function(W,u=utf8ToInt)sum(u('  ')[u(W)-64]) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNcp9S2tCTNIiTfM69Es7g0V6NUQ52RmZmJkYWJhZGDlZGZkZGZixEIWFg4WLjUNaNLNcI1dc1MYjX/p2koOTo5K2lyARlunlFRTqFRUUDefwA "R – Try It Online") Takes input as an uppercase string. R handles unprintables and multiline strings without issues, so that's nice. Now we're almost twice the external package! And because CRAN has so many random goodies: # [R](https://www.r-project.org/) + [ScrabbleScore](https://cran.r-project.org/web/packages/ScrabbleScore/ScrabbleScore.pdf) 31 bytes ``` ScrabbleScore::sws(scan(,""),F) ``` [Try it online!](https://tio.run/##K/r/Pzi5KDEpKSc1ODm/KNXKqri8WKM4OTFPQ0dJSVPHTfP/fwA "R – Try It Online") Sadly, `sws` checks for validity by default. [Answer] # [Emojicode](http://www.emojicode.org/), 358 bytes ``` 🐖🔥➡️🔡🍇🍮s 0🔂l🍡🐕🍇🍮s➕s🍺🐽🍯🔤a🔤1🔤e🔤1🔤i🔤1🔤l🔤1🔤n🔤1🔤o🔤1🔤r🔤1🔤s🔤1🔤t🔤1🔤u🔤1🔤d🔤2🔤g🔤2🔤b🔤3🔤c🔤3🔤m🔤3🔤p🔤3🔤f🔤4🔤h🔤4🔤v🔤4🔤w🔤4🔤y🔤4🔤k🔤5🔤j🔤8🔤x🔤8🔤q🔤10🔤z🔤10🍆🔡l🍉🍎🔡s 10🍉 ``` [Try it online!](https://tio.run/##ZZDNTsJAFIX3PEUfwd/E17HttLS0tDAthVmpCw0xCAsxrpiQ4Fa3xsSX4QWcN8B7ajiJ6WK@fvfMpLk5Ki/SJChCdXB29ejs89bZxQOGFxne9pvtz@fyGMt5196JjHeZuGSrNfP9Zq1FviT8lu@HvNpdA6eAoiW0jDakFbQxTdMqWk0LgTMgpvnAORDQclpJi4ALoE@b0BrajDYALoEUuAKmtFG7FQramaMu7lEf@prLecKgvfZifgB6zi5v0WLPc/b1Bq231fnt6v/Dsgzibqor1SSqm0eJMX5tTPdGfh6qKO4n6SDLh0U5GuuqnjTT2d/bdrdf "Emojicode – Try It Online") ## Explanation: I changed the variable names from single letters to more meaningful words, and expanded some parts of my code to hopefully make it more readable for people unfamiliar with the language. You can test the expanded program [here](https://tio.run/##ZZHNToNAEMfvfQoeofUj8XX4WOhS6FJYoOWkHmyMwfbQGk8lJOpRr8bEl@kLyBvQnVlwNFwmv/3/dz4yw0Lhc1s4rG2bavvQVLu6qcr1yFCvJ/V6PR7qn8/Nrz4ylFO@ZWaQskTRhxKUsnsxIUwQGSEnDAjnhIIwJkwIJWFK6EA4Q/QQ@zEsCOeINmFIGBG6EC4Qp4QZYU64IpxBuET0IVwhLhH7MRY46hi50Kw3d9dt8D2xRcyMcb9QLllsSqF2UKpFb/ddoduASeUYf@w1WFTieNjrUkr5Upnf@jSQXOtk3eG@6/QIhs6YQHe0tN9Um5v@@M/XcHw8rIWL/C9Gke0N1USynLOh7vKisNKiGDqquMNcb8r9WRDORbSIE5lm@XKl/8JcbXsC). ``` 🐋🔡🍇 👴 define a class that takes a string 🐖🔥➡️🔡🍇 👴 define a method that returns a string 🍦values🍯 👴 create int dictionary 🔤a🔤1 🔤e🔤1 🔤i🔤1 🔤l🔤1 🔤n🔤1 🔤o🔤1 🔤r🔤1 🔤s🔤1 🔤t🔤1 🔤u🔤1 🔤d🔤2 🔤g🔤2 🔤b🔤3 🔤c🔤3 🔤m🔤3 🔤p🔤3 🔤f🔤4 🔤h🔤4 🔤v🔤4 🔤w🔤4 🔤y🔤4 🔤k🔤5 🔤j🔤8 🔤x🔤8 🔤q🔤10 🔤z🔤10 🍆 👴 ^ dictionary contains letters(keys) and their numerical values 🍮score 0 👴 declare 'score' variable and set to 0 🍦iterator🍡🐕 👴 transform input string to iterator 🔂letter iterator🍇 👴 iterate over each byte in input string 🍮score➕score 🍺🐽values 🔡letter 👴 add value of each letter to score 🍉 🍎🔡score 10 👴 return the score as a string 🍉 🍉 🏁🍇 👴 begin the program here 😀🔥🔤abc🔤 👴 call scoring method and print the score 😀🔥🔤ppcg🔤 👴 repeat with other test cases 😀🔥🔤stewie🔤 😀🔥🔤fizzbuzz🔤 😀🔥🔤abcdefghijklmnopqrstuvwxyz🔤 🍉 ``` [Answer] # [Haskell](https://www.haskell.org/), 66 bytes ``` sum.map(\c->1+read["02210313074020029000033739"!!(fromEnum c-65)]) ``` [Try it online!](https://tio.run/##DcGxDoIwEADQXzmIA8SUHK1CGHAhxrWjiThcaivEtpgW4t9bfW@i@NLWJgP9mOLmKkfvYlTsVO@DpsctR85rFLXA9oAckXf4J0QrujzLChMWd/abA8WaY3kvk6PZQw@zX3UgtcIO4rR8oAKTpBwuX2UsPWNi10HKHw "Haskell – Try It Online") Same approach as [DanielIndie's JavaScript answer](https://codegolf.stackexchange.com/a/162608/56433). --- ### [Haskell](https://www.haskell.org/), ~~82~~ 81 bytes ``` sum.map(\c->1+sum(read.pure<$>lookup c(zip"DGBCMPFHVWYKJXQZ""1122223333347799"))) ``` [Try it online!](https://tio.run/##FcfBCoIwGADgV/kZHibhYBWIkB4yMopgXcrCy1gzxU3HpgQ9fMu@29dw10mlfA1p5d2kieYGVyLK6GIetpI/iZms3ASZGoZuMiDwpzVoV2zzM9sfrrf76VheHghRupyt/tZxnCQoDEOvedtDCm0/SsvFCAG4ZngDgdozlhdfUSv@cj4qc8Z@ "Haskell – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 60 bytes ``` $args|% t*y|%{$s+='02210313074020029000033739'[$_-65]-47} $s ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL24RlWhRKuyRrVapVjbVt3AyMjQwNjQ2MDcxMDIwMDI0gAIjI3NjS3Vo1Xidc1MY3VNzGu5VIr////v6OTs4urm7uHp5e3j6@cfEBgUHBIaFh4RGQUA "PowerShell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes Takes input as a lowercase list of characters. ``` •_JÊ¿ùã$Ƶ½œM•11вAIkèO ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcOieK/DXYf2H955eLHKsa2H9h6d7AsUNDS8sMnRM/vwCv///6PV09R1FNQzQUQVnEgCEaVIYrEA "05AB1E – Try It Online") or as a [Test suite](https://tio.run/##MzBNTDJM/V9TVvn/UcOieK/DXYf2H955eLHKsa2H9h6d7AsUNDS8sMmxMvvwCv//lUqH9yvo2ikc3q@k8z9aPVFdR0E9CUQkq8dyRasXgJgFED6QSAcLFoOYJSAiFUSUg4hMCBckXQpRCdNYCSKyQUQFiCgEq0mD66mCE2BrS5HEQAqRHQQkUuC2psFtyYCblQW3KgdE5IKIPBCRD3dNIYgoAhEIX4DtLIN7pQLuaqATAA) [Answer] # [Octave](https://www.gnu.org/software/octave/), 73 bytes ``` @(x)sum('09977433333222211'(([~,y]=ismember(x,'QZJXKFHVWYBCMPDG'))+1)-47) ``` [Try it online!](https://tio.run/##Vc1LC4JAFAXgfb/CTdwZKmlSmFwYpamZWWP5nGhRYdBCgl7Upr9uTi3Ks7rwncM97a/be14edFmWyyF64MutQNDVNEpVRaRXhRBAaP1qPzf68VLkxS4/o0cbAj5NPXsSJ5lh@mzsAMYtgjsqxeUBwcgwQRLBUlOSOgNx0kYFjJkO1IEQAavQSlwLagtNQOSwzEsD@ANFEWC7nBsR5/AD9bOono8t25m4U2/mzxcsWK7CKE7S7Futmn1avgE "Octave – Try It Online") Uses `ismember` to map each character in the input stream `x` onto it's index in the lookup string `'QZJXKFHVWYBCMPDG'`. Any element not found will be mapped to an index of 0 (this will include the 1-point characters). Next we add 1 to the index to make the 0's become valid 1-index references, and lookup into the string `'09977433333222211'`. This is one element longer than the first lookup string. The digits represent the point value of each element in the original string, minus 1, with the extra element being a '0' at the `beginning` . Finally the resultant string is converted to integers by subtracting `47` (`'0'-1`), yielding the point value for each letter, and all point values are then summed. [Answer] # C++, 95 bytes ``` char*m="02210313074020029000033739"; int f(char*p){int n=0;while(*p)n+=m[*p++-65]-47;return n;} ``` [Try it online](https://ideone.com/bdo5Ko) (not a TIO link sorry) Explanation: * Declares `m`, an array of the values of each letter in order, minus 1. The minus 1 is because of Q and Z: I couldn't have a two digit number in there * Iterates through through the string `p` until we get to null character, and adds the score of the number (`*p` gives us the letter, and `-65` so we can properly index the array). Since `m` is a `char*` it converts to a `char` so we minus `48` so bring it back to 0, but add `1` since `m` is declared as one score less for each character. I'm not an avid poster here so I hope I've done this correctly. I believe they returning `n` counts as printing the value, and that declaring a function is fine. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~60~~ 38 bytes **Solution:** ``` +/1+.:'"02210313074020029000033739"65! ``` [Try it online!](https://tio.run/##y9bNz/7/X1vfUFvPSl3JwMjI0MDY0NjA3MTAyMDAyNIACIyNzY0tlcxMFZUcnZxdXN3cPTy9vH18/fwDAoOCQ0LDwiMio5T@/wcA "K (oK) – Try It Online") **Explanation:** Index into the scores, sum up result. ``` +/1+.:'"02210313074020029000033739"65! / the solution 65! / input modulo 65 to get position in A-Z "02210313074020029000033739" / index into the scores (1 point lower) .:' / value (.:) each (') to convert to ints 1+ / increase by 1 +/ / sum up ``` [Answer] # PowerShell, 92 bytes ``` $args|% T*y|%{$i+=switch -r($_){[DG]{2}[BCMP]{3}[FHVWY]{4}K{5}[JX]{8}[QZ]{10}default{1}}};$i ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL24RlUhRKuyRrVaJVPbtrg8syQ5Q0G3SEMlXrM62sU9ttqoNtrJ2Tcgttq4NtrNIyw8MrbapNa72rQ22isittqiNjowKrba0KA2JTUtsTSnpNqwtrbWWiXz////jk7OAA "PowerShell – Try It Online") Didn't notice @Add-TheNewOne's answer before writing this, but I think it's fairly different in any case. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ``` •Q<ß÷λv¸Ïàœ¶•IÇè>O ``` [Try it online!](https://tio.run/##ATIAzf9vc2FiaWX//@KAolE8w5/Dt867dsK4w4/DoMWTwrbigKJJw4fDqD5P//9maXp6YnV6eg) Explanation: ``` •Q<ß÷λv¸Ïàœ¶• # compressed integer 30740200290000337390221031 IÇ # codepoints of the input è # index into the digits of the large integer > # increment each O # sum ``` The large integer encodes the point value of each letter. Since encoding numbers in the range 1-10 would be inconvenient, we subtract 1 so that each one fits on a single digit (this is why the `>` is needed). Note that indexing in 05AB1E wraps around, so the first digit of the number actually corresponds to "h" ("h"'s codepoint is 104, which is 0 mod 26). This is convenient: since numbers can't start with 0, we don't want the first digit to correspond to "a". Alternative 18-byter: ``` A•Θ¡₆öηÖ&'/α°•R‡>O ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f8VHDonMzDi181NR2eNu57Yenqanrn9t4aANQOOhRw0I7////o5XSlHQUlDJBRBWcSAIRpUhisQA) `A` pushes "abcdefghijklmnopqrstuvwxyz". `‡` transliterates, replacing each letter in the input with the corresponding digit in the compressed integer. `A‡` saves one byte over `IÇè`; unfortunately, this encoding puts "a" first, so we have to use `R` (reverse) to get around the issue that numbers can't start with 0. Yet another 18-byter: ``` žW•Δÿ¦ÝZ=áí4_ø•‡>O ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6L7wRw2Lzk05vP/QssNzo2wPLzy81iT@8A6g4KOGhXb@//9HK6Up6SgoZYKIKjiRBCJKkcRiAQ) Same idea as above, but this one uses the obscure `žW` built-in to push "qwertyuiopasdfghjklzxcvbnm". `žW` is one byte longer than `A`, but it saves the `R` since "q" isn't a 1-point letter. [Answer] # [Beatnik](https://esolangs.org/wiki/Beatnik), 379 bytes ``` K ZZZZKF ZD ZD ZD ZD ZD ZD ZD K ZZZZZZZZA J Z ZD ZB B K XA KD ZD ZF F ZA ZD KF KF ZD ZB B K D Z ZD ZB B K ZF Z ZD ZF KA ZA ZD ZD KF KF KF ZD ZB B K A KD ZD ZF D ZA KF ZD ZB B K ZF KD ZD ZB B K D Z ZD ZB B K A Z ZD ZB B K ZF Z ZD ZB B K D Z ZD ZF D ZA KF ZD ZB B K Z KD ZD ZB B K B Z ZD ZB B K Z Z ZD ZB B K A Z ZD ZF F ZA KF ZB Z K K KD ZD ZB B K B Z ZF A KF KF XX ZZZZZZZZZZZZZX ``` [Try it online!](https://tio.run/##dZBLDsIwDET3PYWv4hAM1ED5E7IDiUWFxIr7p3YTVVgEy4vIM/Ms5/G8f979KyWGKMUE0f92k1UthBbiOHXgZB4QOLsIJIz6FEoBZY83CTHGEmAsiSlkcl9or0Yjatz/XYL1ldZaxVqqs5zqjnK4YsQuAlcYpNdQIx3C9JljhZTQzfycFstVy@vNttvtD8fT@XIN8TYA "Beatnik – Try It Online") See also [MickyT's answer](https://codegolf.stackexchange.com/a/162975/25180). [Answer] # [Japt](https://github.com/ETHproductions/japt), 36 bytes ``` ¬£2+`dg bcmp fhvwy k jx qz`·bøX x ``` Takes input as a lowercase string, returns a number. Short explanation: ``` ¬£2+`dg ¬ // Split the input into chars, £ // then map over each char, returning 2+`dg // 2 plus qz`·bøX bøX // the char's index in qz`· // the hardcoded string split by newlines. x // And finally sum the whole thing. ``` [Try it online!](https://tio.run/##y0osKPn//9CaQ4uNtBNS0rmSknMLuNIyysorubK5uLiyKri4CqsSDm1POrwjgqvi/3@ltMyqqqTSqiolAA "Japt – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 60 bytes ``` ->s{s.sum{|c|"BDDCBECEBIFBDBBDKBBBBEEIEK"[c.ord-65].ord-65}} ``` [Try it online!](https://tio.run/##dY7daoNAEIXvfYphQGhBhZC2aQumdHW11v6YJjaJshdWVxJIk@AqpMQ8u11S0ytzbobhfHPOFNXXT5ObjT4Ue2GI6ntfpzUS27YItSjxHGITYvtEilKP@hinxqbI9Jtr1s7DoYkVgBgfiYXQLQ1gwLQjFQSWi@eoXq@lxhM69SieybprqdAN5v5shJ1Uv99SjhdFJIwi7KKuTlnye5s67pP37L@8vr0Ho4/xJPyczuYRanA7YAozeJIuINtAvVxvq1IDvtvytORZLQMKLqpVCSbk8dE10kVSCCYduQjAC1VcgipAH4KaIagQny7M/xx4ANwmQiDcA@bJciWb26o/mCl8nTW/ "Ruby – Try It Online") A lambda, accepting input as an array of (uppercase) characters and returning an integer. [Answer] # [Perl 5](https://www.perl.org/) `-pF`, 50 bytes ``` _1DG2BCMP3FHVWY4K7JX9QZ=~/\d\D*$_/,$\+=1+$&for@F}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/z/e0MXdyMnZN8DYzSMsPNLE29wrwjIwyrZOPyYlxkVLJV5fRyVG29ZQW0UtLb/Iwa22@v9/RydnF1c3dw9PL28fXz//gMCg4JDQsPCIyKh/@QUlmfl5xf91C9wA "Perl 5 – Try It Online") [Answer] # [Gforth](https://www.gnu.org/software/gforth/), 109 Bytes ``` : V s" 1332142418513113:11114484:" ; : C 0 NAME 0 DO DUP C@ 65 - V DROP + C@ 48 - ROT + SWAP 1+ LOOP DROP . ; ``` Input must be uppercase: `C PPCG 11 OK` ## Readable ``` \ String used as table with values for each letter in the alphabet \ : follows 9 in the ASCII-table : V s" 1332142418513113:11114484:" ; : C 0 \ Initialize sum ( sum ) NAME \ Get the string ( sum c-addr count ) 0 DO \ Start of loop ( sum c-addr ) DUP C@ \ Get letter ( sum c-addr char ) 65 - \ Calculate table index ( sum c-addr index ) V DROP + C@ \ Get table entry ( sum c-addr entry ) 48 - \ Calculate entry value ( sum c-addr value ) ROT + SWAP \ Update sum ( sum' c-addr ) 1+ \ Next character ( sum' c-addr' ) LOOP DROP . \ Drop c-addr and print result ; ``` [Try it online!](https://tio.run/##HYvNDoJAEINfpeFKMA47mM1ykewSLspO8O8N0JuJ8P7DYC9Nv7bz97d@qve8m2rAE0sBcq4mrpl8Q47IBTIxew4FWgREHDF2194sZaSHIJ5xalDZPU1ZUO6AvYEp3y3dXp2ASlyylf/FAa1GiMRBVTc "Forth (gforth) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 52 bytes ``` {TR/A..Z/02210313074020029000033739/.comb.sum+.ords} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJZq@786JEjfUU8vSt/AyMjQwNjQ2MDcxMDIwMDI0gAIjI3NjS319ZLzc5P0iktztfXyi1KKa/9bcxUngrRrKIW6B0R6RwQqaSKEHJ2cXVzd3D08vbx9fP38AwKDgkNCw8IjIqOAqv4DAA "Perl 6 – Try It Online") Maps every character to a digit, and sums them. And adds 1 for each character because there isn't a digit 10 without incurring unicode bytes. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 41 bytes ``` T`BCDGJKMPQXZF\HVWY`221174229793 . $*.. . ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyTBydnF3cvbNyAwIsotxiMsPDLByMjQ0NzEyMjS3NKYS49LRUtPj0vv/39HJ2eugABnd67gENdwT1euUPeASO@IQC43z6gop9CoKC6gAhdXN3cPTy9vH18//4DAoOCQ0LDwiMgoAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Like the Haskell answer, nontrivial letters are translated to 1 less than their score, and 1 is added later when the characters are converted to unary. Putting `FHVWY` last allows them all to map to a score of 3 + 1. [Answer] # C (gcc), ~~78~~ 72 bytes ``` i;f(char*s){for(i=0;*s;)i+="\n\n"[*s++-65];s=i;} ``` There are actually 26 characters in that string. See the code rendered properly and run it [here](https://tio.run/##S9ZNT07@/z/TOk0jOSOxSKtYszotv0gj09bAWqvYWjNT21aJkZmZiZGFiYWRg5WRmZGROSaPEQhYWDhYYvKUorWKtbV1zUxjrYttM61r/@cmZuZpaCpUc3EWFGXmlaRpKKmmAJXpKABZjk7OLq5u7h6eXt4@vn7@AYFBwSGhYeERkVFKmprWXLX/AQ). Thanks to [gastropner](https://codegolf.stackexchange.com/users/75886/gastropner) for golfing 6 bytes. Ungolfed version: ``` i; // declare a variable to store the score; it is implicitly of type int f(char* s) { // function taking a string as argument and implicitly returning an int for(i = 0; // initialize the score to 0 *s; ) // iterate over the string until we hit terminating NUL byte i += "\n\n"[*s++ - 65]; // this is a 26-char string containing the ASCII equivalent of each numeric scrabble value; 65 is ASCII code for 'A', mapping the alphabet onto the string s = i; // implicitly return the score } ``` [Answer] # Excel, 91 bytes ``` {=LEN(A1)+SUM(0+("0"&MID("02210313074020029000033739",CODE(MID(A1,ROW(A:A),1)&"z")-64,1)))} ``` Explanation: * Input is in cell `A1` * The formula must be entered as an array formula with `Ctrl`+`Shift`+`Enter`, which adds the curly brackets `{ }` to both ends. * `MID(A1,ROW(A:A),1)` pulls out each character in turn (and a lot of empty values, too, since it's going to return as many values as there are rows in the sheet) * `CODE(MID(~)&"z")` pulls out the ASCII value for the each character. The `&"z"` appends a `z` to the end of the `MID()` result because `CODE()` doesn't like empty inputs. The ASCII value for `z` is higher than every capital letter, though, so it's effectively ignored later. * `MID("02210313074020029000033739",CODE(~)-64,1)` pulls out a letter from the score string based on its ASCII value adjusted down by 64 so the letters run 1-26 instead of 65-90. * `"0"&MID(~)` prepends a zero to the `MID()` result because Excel won't let you do math with empty strings, of which there will be several. * `0+("0"&MID(~))` turns all those strings into numbers. * `SUM(0+("0"&MID(~)))` adds up all those strings that are now numbers. * `LEN(A1)+SUM(~)` adds the length of the input to the sum because all the values in the score string (`02210313074020029000033739`) were adjusted down by one so they would all be one digit long. --- There's a very similar solution in Google Sheets but it comes in at 97 bytes because `ArrayFromula()` is longer than `{}` (but at least it can handle `0 + "" = 0`). ``` =Len(A1)+ArrayFormula(Sum(0+Mid("02210313074020029000033739",Code(Mid(A1,Row(A:A),1)&"z")-64,1))) ``` ]
[Question] [ ## Introduction [OEIS sequence A127421](https://oeis.org/A127421 "OEIS sequence A127421") is the sequence of numbers whose decimal expansion is a concatenation of 2 consecutive increasing non-negative numbers. Put simply, every number in the sequence is formed by putting together *n* with *n+1* for some non-negative, integer value of *n*. The first several terms are: > > 1, 12, 23, 34, 45, 56, 67, 78, 89, 910, 1011, 1112, 1213, 1314, 1415, > 1516, 1617, 1718, 1819, 1920, 2021, 2122, 2223, 2324, 2425, 2526, > 2627, 2728, 2829, 2930, 3031, 3132, 3233, 3334, 3435, 3536, 3637, > 3738, 3839, 3940, 4041, 4142, 4243, 4344, 4445, 4546, … > > > ## Challenge Given a single positive integer *n*, print the first *n* entries of OEIS sequence A127421 in increasing order. * Input and output can be in [any acceptable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Strings or numbers are fine for output. * Leading zeroes are **not** permitted. * Either a full program or function is permitted. * For the purposes of this challenge, *n* will be positive and under 100. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed by default. * This question is code golf, so lowest byte-count wins. * Here is some sample input and output: ``` 1 => 1 2 => 1, 12 3 => 1, 12, 23 10 => 1, 12, 23, 34, 45, 56, 67, 78, 89, 910 ``` If you have any questions, don't hesitate to ask. Good luck. *P.S this is my first challenge, so hopefully this all makes sense.* *EDIT: Removed output restriction to allow numbers or strings.* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŻVƝ ``` A monadic link accepting an integer which yields a list of integers **[Try it online!](https://tio.run/##y0rNyan8///o7rBjc////29iBgA "Jelly – Try It Online")** ### How? ``` ŻVƝ - Link: integer e.g. 59 Ż - zero-range [0,1,2,3,4,5,6, ... ,58,59] Ɲ - apply to each pair: i.e: [0,1] or [5,6] or [58,59] V - evaluate* jelly code 1 or 56 or 5859 - -> [1,12,23,45,56, ... 5859] * When given a list V actually joins the Python string values and evaluates that ...so e.g.: [58,59] -> ['58','59'] -> '5859' -> 5859 ``` [Answer] # [Python 3](https://docs.python.org/3/), 39 bytes ``` f=lambda n:1//n or f'{f(n-1)} {n-1}{n}' ``` [Try it online!](https://tio.run/##DYtBCoAgFAXXdYq3U8FQcyd0GCMkob4ibkI8u7magWHyV@9EdoxwPP49Lw9yRilCKgisBU6bER1tojfqbIQZCJFgJHYJK2H0NO3WJZdIlc9FiPED "Python 3 – Try It Online") [Answer] # [R](https://www.r-project.org/), 32 bytes ``` strtoi(paste0((x=1:scan())-1,x)) ``` [Try it online!](https://tio.run/##K/r/v7ikqCQ/U6Mgsbgk1UBDo8LW0Ko4OTFPQ1NT11CnQlPzv@l/AA "R – Try It Online") Outgolfed by [MickyT](https://codegolf.stackexchange.com/a/168020/67312), so go upvote that answer! [Answer] ## Haskell, ~~38~~ 37 bytes ``` f n=("":)>>=zipWith(++)$show<$>[1..n] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz1ZDSclK087OtiqzIDyzJENDW1tTpTgjv9xGxS7aUE8vL/Z/bmJmnoKtQkFRZl6JgopCmoKhwX8A) Thanks to [Cat Wizard](https://codegolf.stackexchange.com/users/56656/cat-wizard) for a byte! [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 19 bytes ``` I.1.W)>OSo;u.uO;@!- ``` [Try it online!](https://tio.run/##Sy5Nyqz4/99Tz1AvXNPOPzjfulSv1N/aQVH3/39DAwA "Cubix – Try It Online") This wraps onto the cube as follows ``` I . 1 . W ) > O S o ; u . u O ; @ ! - . . . . . ``` [Watch It Run](https://ethproductions.github.io/cubix/?code=ICAgIEkgLgogICAgMSAuClcgKSA+IE8gUyBvIDsgdQouIHUgTyA7IEAgISAtIC4KICAgIC4gLgogICAgLiAuCg==&input=MTAK&speed=20) Got a little room to play with yet, but at the moment * `W` redirect to the top face heading down * `I1>` set up the stack with the input and 1 then redirect into the main loop * `OSo;u` output the top of stack, add space to stack, output, remove and uturn * `-!@;Ou)` subtract TOS from input, if 0 halt else pop result, output TOS, uturn and increment TOS. Back into the main loop. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~19~~ 18 bytes ``` {(^$_ Z~1..$_)X+0} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1ojTiVeIarOUE9PJV4zQtug9n9xYqVCmoahgYGm9X8A "Perl 6 – Try It Online") Anonymous code block that zips the range 0 to n-1 with 1 to n using the concatenation operator, then adds 0 to every element to force it to a number and remove leading 0s. [Answer] # [R](https://www.r-project.org/), ~~30~~ 29 bytes An extra byte thanks to @Giuseppe ``` 10^nchar(n<-1:scan())*(n-1)+n ``` [Try it online!](https://tio.run/##K/r/39AgLi85I7FII89G19CqODkxT0NTU0sjT9dQUzsPKPsfAA "R – Try It Online") A mostly mathematical solution, except for using `nchar()` rather than `floor(log10())`. I was really surprised that it came in shorter than the [string](https://codegolf.stackexchange.com/a/167836/31347) version. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~13~~ 12 bytes *1 byte saved thanks to @FrownyFrog* ``` (⍎⍕,∘⍕1∘+)¨⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OApMaj3r5HvVN1HnXMAFKGQEpb89CKR72b//9PUzDkSlMwBmJDAwA "APL (Dyalog Unicode) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 25 bytes ``` f=n=>--n?f(n)+','+n+-~n:1 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1k5XN88@TSNPU1tdR107T1u3Ls/K8H9yfl5xfk6qXk5@ukaahqGmpjUXqpARppAxppChAVDsPwA "JavaScript (Node.js) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` ⟦s₂ᶠcᵐ ``` [Try it online!](https://tio.run/##ASAA3/9icmFjaHlsb2cy///in6Zz4oKC4bagY@G1kP//MTD/Wg "Brachylog – Try It Online") ### Explanation ``` ⟦ Range: [0, …, Input] s₂ᶠ Find all substrings of length 2 cᵐ Map concatenate ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~42~~ 41 bytes ``` f=lambda n:n-1and f(n-1)+[`n-1`+`n`]or[1] ``` [Try it online!](https://tio.run/##NYuxCoAgFAB3v@KNigW@RqEvMUHDLKGeIi59vbk0HHfLlbddmZYe121w@2cPHkjTjJ4CRD5CSOOGnHTkbK4GbY@5QoJEUD2dB8cJldBQaqI2niQY@xuVEv0D) Recursive function that returns a mixed list of strings and integers [Answer] # [Haskell](https://www.haskell.org/), 34 bytes ``` f n="1":[show=<<[i-1,i]|i<-[2..n]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz1bJUMkqujgjv9zWxiY6U9dQJzO2JtNGN9pITy8vNvZ/bmJmnoKtQkFRZl6JgopCmoKhwX8A "Haskell – Try It Online") [Answer] # [Blossom](https://github.com/IMP1/blossom), 88 bytes ``` rule e<int x>[1(x)]=>[1(x-1),2(str(x)+str(x+1))];rule c[1(0)]=>[];e!c ``` Blossom is a graph programming language I'm working on. It can only take graphs as inputs, so this programme expects a graph comprising a single node with its label an integer. It returns a graph of connected edges to form the closest to an array I can get, and the resultant graph is printed to output. An unminified version of the code is this: ``` rule expand <int x> [ 1 (x) ] => [ 1 (x-1), 2(str(x)+str(x+1)) ] where x > 0; rule clean [ 1 (0) ] => []; expand! clean ``` It defines two rules: one called `expand`, which (while there is a node with an integer-valued label in the current graph) creates another node with its increment concatenated, and lowers the value. This rule also has the condition that x is greater than 0. The `!` executes this rule for as long as it can be applied on the graph, so in this case it will execute until x is 0. And then the `clean` rule removes this 0 node. Blossom was not made for golfing, but it doesn't do too badly, I don't think., considering what it is. There currently isn't really an easy way for people to test blossom code (and the interpreter I'm working on at the moment is not quite finished and a little buggy), but this isn't exactly a competing entry! [Answer] ## [Shakespeare](http://shakespearelang.sourceforge.net/), 703 bytes ``` Q.Ajax,.Ford,.Act I:.Scene I:.[enter Ajax and Ford]Ford:Open mind!Scene V:.Ajax:You is the sum of thyself the sum of myself the sum of a big bad fat old red pig a big bad fat old lie!Ford:Open mind!Is you nicer zero?Ajax:If so, you is twice the sum of the sum of twice thyself twice thyself thyself!If so,Let us Scene V!Ford:You a cat!Open heart!Scene X:.Ajax:You is the sum of thyself a pig!Is you worse than a cat?If so,let us Scene C.Remember thyself.You is the sum of the sum of a big old red cute rich cat a big old red cute joy a big old pig!Speak mind!You is a big old red cute rich cat!Speak mind!Recall!Ford:Open heart!You is the sum of thyself a joy!Open heart!Let us Scene X.Scene C:.[exeunt] ``` [try it here](https://tio.run/##hVJBasMwEPzK@m4E7dGXEAIFQ6E0gZJScpDldaNElowkk7ifdyVLoXIS0ou83llmZkcynRjHd7I80HNOXpSuc7JkFsqCbBhK9MUXSosa/AhQWYOf2vmjeOtQQstlnYXhj2IiKj5VD9yA3SOYvgXVuHIwKJq01d50KFT8GypaQ0MtKFGDxho617tFBMfsykNpYHDCkjPn9ge1WkxmygaMyifIezo5eO7sr4xYNDb/C98ssL2ihd5A3DoY8UtTYNRmk6U9Um1jLtt/c6F@zcsGJ6WNV6YyEC6CqEhFV2SNLbaVWzVykHvsV9leMmW9RdCc7T39PeyghqTtvW06pMcQdBR6QJlOr5FRIZLLCsk8ysKppyHO0t7Gh7nyD/OMvbS7cXx@@gU) ## ungolfed version ``` 127421th Night. Ajax, likes to read the stars. Ford, someone Ajax can always count on. Act I:. Scene I: Ajax reads a star. [enter Ajax and Ford] Ford: Open your mind! Scene V: Ford counts what ajax has learned. Ajax: you are the sum of thyself and the sum of myself and the sum of a big bad fat old red pig and a big bad fat old lie! Ford: Open Your mind! Are you nicer than zero? Ajax: If so, you are twice the sum of the sum of twice thyself and twice thyself and thyself! If so, Let us Scene V! Ford: You are a cat! Open your heart! Scene X: Ajax and Ford recall the nights. Ajax: You are the sum of thyself and a pig! Are you worse than a cat? If so, Let us Scene C. Remember thyself. You are the sum of the sum of a big old red cute rich cat and a big old red cute joy and a big old pig! Speak you mind! You are a big old red cute rich cat! Speak your mind! Recall your finest hour! Ford: Open your heart! You are the sum of thyself and a joy! Open your heart! Let us Scene X. Scene C: Fin. [exeunt] ``` [Answer] # [Groovy](http://groovy-lang.org/), 35 bytes ``` {(0..<it)*.with{""+it+++it as int}} ``` [Try it online!](https://tio.run/##Sy/Kzy@r/J9m@79aw0BPzyazRFNLrzyzJKNaSUk7s0RbG0goJBYrZOaV1Nb@LygC0jl5Cmkappr/AQ "Groovy – Try It Online") I came up last minute with the idea of using \*.with instead of .collect. I have no idea what `it+++it` parses to but whether it's `it++ + it` or `it + ++it` they both do the same thing. I tried to think of a way of getting rid of the < in ..< by turning it into 1..it and decrementing but I don't think it would get any shorter. [Answer] # [C (gcc)](https://gcc.gnu.org/), 44 43 bytes ``` f(i){i--&&printf(" %2$d%d"+5*!f(i),i+1,i);} ``` [Try it online!](https://tio.run/##VYk9DsIgFIB3TvGstgEKRkycanoR44Ag7UsqNYhdmp4dYXT7fowcjEl79Gb62idcP9HifBx78pcmfOSWHEW2opRN8w7oo6MV1OeDrW3VXviuXIGtEsi6LeUPL42eFtBhMMKMOgDnmRcGKwFAR8voFYNMccaiy03dGevIlpI6/QA "C (gcc) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~55 48 47~~ 43 bytes ``` f=lambda n:n-1and f(n-1)+[f"{n-1}{n}"]or[1] ``` [Try it online!](https://tio.run/##NcexCoAgEADQ3a84nDwq8GgL@hJpMOpKqFOkJcJvt5a299J97VH6Wnk8/DkvHmSQjrwswOYDNo7186E8UvQUs6OpcswQIAhkL9tqqCWLQ8pBLsMmICr1h6xFrC8 "Python 3 – Try It Online") Recursive function that takes an integer and returns a mixed list of strings and numbers. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~9~~ ~~8~~ 6 bytes ``` ms+`dh ``` [Try it online!](https://tio.run/##K6gsyfj/P7dYOyEFSJsAAA "Pyth – Try It Online") Explanation: ``` - implicit output m - map function with argument d: + - concatenate d - argument d ` - to string h - into implicit d + 1 - into Q (implicit input) ``` [Answer] # [Fig](https://github.com/Seggan/Fig), \$8\log\_{256}(96)\approx\$ 6.585 bytes ``` Mrx'_Jx} ``` [Try it online!](https://fig.fly.dev/#WyJNcngnX0p4fSIsIjIiXQ==) ``` Mrx'_Jx} Mrx' # For every number in the range [0, input) } # Input + 1 Jx # Prepend the input to that _ # Parse as number to remove leading 0s ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ḶżRV ``` [Try it online!](https://tio.run/##y0rNyan8///hjm1H9wSF/f//39AUAA "Jelly – Try It Online") ### How it works ``` ḶżRV Main link. Argument: n Ḷ Unlength; yield [0, ..., n-1]. R Range; yield [1, ... n]. ż Zipwith; yield [[0, 1], ..., [n-1, n]]. V Eval; cast each array to string and evaluate, yielding integers. ``` [Answer] # [Python 2](https://docs.python.org/2/), 44 bytes ``` for i in range(input()):print`i`*(i>0)+`i+1` ``` [Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFTITNPoSgxLz1VIzOvoLREQ1PTqqAoM68kITNBSyPTzkBTOyFT2zDh/39jAwA "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` >GNJ,N ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fzt3PS8fv/39DAwA "05AB1E – Try It Online") **Explanation** ``` >G # for N in [1 ... input] N # push N J # join stack , # print N # push N (for next iteration) ``` `LεD<ìï` would work for same byte count but with list output [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 9 bytes ``` 1,2,/⍕¨∘⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CYb/00CkjpGO/qPeqYdWPOqY8ah38///aQqGBgA "APL (Dyalog Classic) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 37 bytes ``` f x=[[y-1|y>1]++[y]>>=show|y<-[1..x]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwjY6ulLXsKbSzjBWWzu6MtbOzrY4I7@8ptJGN9pQT68iNvZ/bmJmnoKtQko@lwIQFBRl5pUoqCikKRii8Y3Q@Mbo6g3@AwA "Haskell – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) `-m`, ~~6~~ 5 bytes ``` ó2 ¬n ``` [Try it online!](https://tio.run/##y0osKPn///BmI4VDa/L@/9fN5TIyAAA "Japt – Try It Online") As always, *know the flags*. ### Unpacked & How it works ``` -m Convert to range and map... Uó2 q n Uó2 Construct [U, U+1] q Join n Convert to number Implicit output (Array is printed as comma-delimited values) ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~103~~ ~~71~~ ~~64~~ 56 bytes --- **Golfed** [Try it online!](https://tio.run/##VY9NSwMxEIbv@RVD2ENCP9i2t6a7Ij0JgqAHD9ZD2I4YqLPSTHEl5LevMe62dk4v82SemTR@1njX3zbsWtrcEa@WNVioelfV4a09KkcMXVWabuOMfvr2jB/zbUu@PeD8@egYVSGD6uryppDT0EW5llLHMJmkqE3sjRDZ@vIqIBWj56316KECwi8YGIRMf2sxPcflJa4ucVHmGJM5HYi2eVd/mrMcHP1bpAf59dVQyDT1eeI1hPFt3NHDiXNPgjZ5yqqRDo0rzb0jVHJH6asiCjGyR7T7jLTpfwA "C# (Visual C# Interactive Compiler) – Try It Online") ``` i=>{for(int x=0;x<i;)Write($"{(x>0?$",{x}":"")}{++x}");} ``` --- **Ungolfed** ``` i => { for( int x = 0; x < i; ) Write( $"{( x > 0 ? $",{x}" : "")}{ ++x }" ); } ``` --- **Full code** ``` Action<Int32> a = i => { for( int x = 0; x < i; ) Write( $"{( x > 0 ? $",{x}" : "")}{ ++x }" ); }; Int32[] testCases = new Int32[] { 1, 2, 3, 10, }; foreach( Int32[] testCase in testCases ) { WriteLine( $" Input: {testCase}\nOutput:" ); a(testCase); WriteLine("\n"); } ``` --- **Older versions:** * ***v1.2, 64 bytes*** ``` i=>{for(int x=0;x<i;)Write($"{(x>0?$",{x}":"")}{++x}");} ``` * ***v1.1, 71 bytes*** ``` i=>{for(int x=0;x<i;)System.Console.Write($"{(x>0?$",{x}":"")}{++x}");} ``` * ***v1.0, 103 bytes*** ``` i=>{for(int x=0;x<i;)System.Console.Write($"{(x>0?",":"")}{x++*System.Math.Pow(10,$"{x}".Length)+x}");} ``` --- **Releases** * **v1.3** - `- 8 bytes` - Removed `Console` thanks again to [raznagul](https://codegolf.stackexchange.com/questions/167818/concatenating-n-with-n-1/167878?noredirect=1#comment405677_167878) * **v1.2** - `- 7 bytes` - Removed `System` thanks to [raznagul](https://codegolf.stackexchange.com/questions/167818/concatenating-n-with-n-1/167878?noredirect=1#comment405670_167878) * **v1.1** - `-32 bytes` * **v1.0** - `103 bytes` - Initial solution. --- **Notes** * None [Answer] # J, 14 bytes ``` (,&.":>:)"0@i. ``` [Try it online!](https://tio.run/##y/r/P03B1kpBQ0dNT8nKzkpTycAhUw8kaMiVpmAExMZAbGgAAA) [Answer] ## ABAP, 101 bytes Not really a golfing language, but I'm having a lot of fun with it ``` WHILE x<w. CLEAR z. IF x=1. WRITE x. ELSE. CONCATENATE y x INTO z. WRITE z. ENDIF. y=x. x=x+1. ENDDO. ``` W is the input term, X is the counter from 1, Y is X-1 from the second pass onward, Z is concatenated string. [Answer] # Powershell, ~~27~~ 26 bytes ``` 1.."$args"|%{"$p$_";$p=$_} ``` -1 byte: thanks [AdmBorkBork](https://codegolf.stackexchange.com/users/42963/admborkbork) Test script: ``` $f = { 1.."$args"|%{"$p$_";$p=$_} } &$f 1 "" &$f 2 "" &$f 3 "" &$f 10 "" &$f 46 ``` [Answer] # [Python 2](https://docs.python.org/2/), 41 bytes ``` lambda l:[`n`[:n]+`n+1`for n in range(l)] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHHKjohLyHaKi9WOyFP2zAhLb9IIU8hM0@hKDEvPVUjRzP2f0FRZl6JQpqGoYnmfwA "Python 2 – Try It Online") ]
[Question] [ > > [This reminds me when a few years ago someone uploaded a torrent "Hacker tool: complete list of all IP addresses". This was, of course, just a generated list of the ~4 billion IPv4 addresses, but thousands of "h4xx0rz" downloaded it. Look mum, imahacker!](https://meta.stackoverflow.com/questions/307454/stackoverflow-has-been-compromised-post/307456#comment255186_307456) > > > This was then, but nowadays everybody has switched to [IPv6](https://en.wikipedia.org/wiki/IPv6). (Right?) Your task is to write a program that **prints out all [IPv6 addresses](https://en.wikipedia.org/wiki/IPv6_address)**. You should write a full program that takes no input and prints IPv6 addresses, one per line, and no other output. Your program must print all 2128 possible addresses, including invalid ones. Each address must be printed exactly once. You may print the addresses in any order. Each address may be printed in full, with 8 groups of 4 hexadecimal digits separated by colons, e.g. ``` 2001:0db8:85a3:0000:0000:8a2e:0370:7334 ``` You may, at your discretion, use any of the standard abbreviations from [RFC 5952](https://www.rfc-editor.org/rfc/rfc5952): * Leading zeros in a group may be omitted, except that `0` cannot be abbreviated further. * `::` may be used at most once per address to abbreviate a sequence of one or more all-zero groups. * The hexadecimal digits may use lowercase or uppercase. If you achieve the [representation recommendation from RFC 5952](https://www.rfc-editor.org/rfc/rfc5952#section-4) (lowercase letters only, shortest possible representation, with `::` used as early as possible if there are multiple places where it can be used), you get a **-20% bonus**. Due to the size of the output, your program is not expected to finish while we're sitting there. Your program may be interrupted by external means at some point (`Ctrl`+`C`, pulling out the power, …). Your program must produce output as a stream, so that after a “reasonable” wait, it will have produced some lines. Basically, building a giant string in memory only to print it at the end is not allowed. Any program that would run out of memory on a “standard” PC is disqualified. (Nonetheless, if your program was left to run for sufficiently long, it must print all IPv6 addresses and then exit.) (If this condition is a problem for web interpreters that run the program until completion and then let you see the output, and you don't have a hosted interpreter, test your program on a smaller version of the problem, and then carefully adjust it to the full 2128.) Your score is your program's length in bytes, multiplied by 0.8 if you get the bonus. It's code golf, so the lowest score wins. [Answer] # Python 3, 65 bytes · 0.8 = 52.0 ``` from ipaddress import* n=4**64 while n:n-=1;print(IPv6Address(n)) ``` [Answer] # Pyth, ~~27~~ ~~25~~ 24 bytes *Note: the code had a bug previously, fixing it saved 1 byte* ``` J^4 64WJj\:c%"%032x"=tJ4 ``` Prints the addresses like ``` ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffd ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc ... 0000:0000:0000:0000:0000:0000:0000:0003 0000:0000:0000:0000:0000:0000:0000:0002 0000:0000:0000:0000:0000:0000:0000:0001 0000:0000:0000:0000:0000:0000:0000:0000 ``` Previous (more complicated) version using the pad operator (also 24 bytes): ``` J^4 64WJj\:c.[\032.H=tJ4 ``` ### Explanation ``` J^4 64 set J to 2^128 WJ while J is not 0: =tJ decrement J %"%032x" format to length-32 hex string c 4 split every 4 chars j\: join by : and print ``` ## Pyth, 21 bytes (invalid) ``` jmj\:c.[\032.Hd4^4 64 ``` This can't be run since 1) it would consume at least 2132 bytes (252 yobibytes) of memory and 2) the interpreter doesn't like it (2128 doesn't fit in `ssize_t`, so no `list`s of that size). It would print the addresses in lexicographical order. You can try out the algorithm by changing the number(s) in the end to something usable. [Answer] # C (with GCC extensions), 76 bytes \* 0.8 = 60.8 ``` __uint128_t i;main(){char s[50];for(;inet_ntop(10,&i,s,49),puts(s),++i>0;);} ``` This uses the [128-bit integers GCC extension](https://gcc.gnu.org/onlinedocs/gcc-4.8.5/gcc/_005f_005fint128.html#_005f_005fint128) to simply count up from `::` to `ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff`. `inet_ntop()` correctly formats each address so the -20% bonus can be claimed. ### Output Using `sed` to output every millionth line up to 10 million: ``` $ ./ipv6all | sed -n '1~1000000p;10000000q' :: 4042:f00:: 8084:1e00:: c0c6:2d00:: 9:3d00:: 404b:4c00:: 808d:5b00:: c0cf:6a00:: 12:7a00:: 4054:8900:: $ ``` Note I am using a little-endian x86\_64 machine, and that network addresses are typically always in network-order (big-endian), so the endianness is effectively swapped by using `inet_ntop()`. This does not matter - all addresses will still (eventually) be displayed. [Answer] # CJam, ~~36~~ 27 bytes ``` G32#{(_"%032x"e%4/':*oNo}h; ``` -9 bytes thanks to @Dennis (I forgot that CJam has string formatting). Prints the addresses lowercase and descending. For obvious reasons, use the Java interpreter, not the online one. You can replace `G32#` with something smaller for testing online though, e.g. [here's the last 100](http://cjam.aditsu.net/#code=100%20%7B%28_%22%25032x%22e%254%2F'%3A*oNo%7Dh%3B). ### Explanation ``` G32# 16^32 = 2^128. Call this n { ... }h; While loop. The final ; is to pop n at the end ( Decrement n _ Copy n "%032x"e% String format to hex, padded to 32 digits 4/ Split into groups of 4 ':* Join with colons oNo Output with newline ``` [Answer] # Python 2.7, 67 bytes ``` n=4**64 while n:n-=1;s='%032x'%n;exec"s=s[4:]+':'+s[:4];"*7;print s ``` As a side effect of the method used to insert the colons, the addresses are printed with the rightmost column appearing at the left: ``` ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff fffe:ffff:ffff:ffff:ffff:ffff:ffff:ffff fffc:ffff:ffff:ffff:ffff:ffff:ffff:ffff ... 0003:0000:0000:0000:0000:0000:0000:0000 0002:0000:0000:0000:0000:0000:0000:0000 0001:0000:0000:0000:0000:0000:0000:0000 ``` [Answer] # Cinnamon Gum, 16 bytes ``` 0000000: 678b 36d0 b54c d44d 8bc5 455b 8d0c 0500 g.6..L.M..E[.... . ``` [Try it online. (TIO limits output)](http://cinnamon-gum.tryitonline.net/#code=MDAwMDAwMDogNjc4YiAzNmQwIGI1NGMgZDQ0ZCA4YmM1IDQ1NWIgOGQwYyAwNTAwICBnLjYuLkwuTS4uRVsuLi4uCg&input=) ## Explanation The `g` mode puts Cinnamon Gum in *generate mode*. The rest of the string decompresses to this regex: ``` [0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f] ``` It then creates a generator of all possible strings that match the regex and iterates through it, printing out each one. Somewhat amusingly, the golfier regex `([0-9a-f]{4,4}:){7,7}[0-9a-f]{4,4}` actually compresses to a longer string than the regex above. [Answer] # Verilog, 335 My first Verilog submission, probably could use more golfing but I don't have the energy to do so right now. `c` is clock, `o` is ASCII output. Does not qualify for formatting bonus due to zero-padding instead of abbreviating. ``` module b(output[0:38]o,input c);reg[127:0]a;wire[0:39]d;assign o=d[0:38];always @(posedge c) a<=a+(~(&a));genvar i,j;generate for(i=0;i<8;i=i+1) begin:q for(j=0;j<4;j=j+1) begin:r assign d[5*i+j]=a[16*i+4*j:16*i+4*j+7]>9?{4'h6,a[16*i+4*j:16*i+4*j+7]-9}:{4'h3,a[16*i+4*j:16*i+4*j+7]};end assign d[5*i+4]=8'h3A; end endgenerate endmodule ``` This is a simple iteration followed by some bit-twiddling to make the output ASCII. I chop the colon after the last group with a small hack. Synthesizes and appears to work for xc3s500e-4ft256-4 on ISE 13.7 lin64. [Answer] # Pyth, 21 bytes ``` KJ^8CdWJj\:ct.H+K=tJ4 ``` Uses a while loop with `J` as the iterator variable. Initializes the maximum using `8^chr(' ')`. Pads by adding that initial value, converting to hex, then removing the first character. [Answer] # C, 91-126 bytes My original version, 119 bytes. ``` long a[9],i; f(long*x){if(65536&++*x)*x=0,f(x+1);} main(){for(;!a[8];f(a))for(i=7;i+1;i--)printf(i?"%lx:":"%lx\n",a[i]);} ``` Best golfed portable-ish version, 103 bytes (thanks @Dennis for some of these concepts) ``` long*p,a[9]; main(i){while(!a[8]){ for(i=8;i--;printf(i?"%lx:":"%lx\n",a[i])); for(p=a;++*p>>16;*p++=0);}} ``` Explanation: The algorithm itself is reasonably straightforward. I used long rather than unsigned int because it's shorter. Declaring them at the file level means everything's preinitialized with zeros. The `f` function is a simple increment with carry that operates on the low 16 bits of each word. The loop ends when it carries into the 129th bit. Iterating backwards for the printf means that we print the addresses in the "proper" order and also the check for printing a newline is a few characters shorter. This does use some non-portable constructs. It's best regarded as a K&R dialect of C, since it uses implicit int return types and does not include stdio.h. And my use of long was informed by this - on most modern systems int is sufficient because it's 32 bits. This could probably run unmodified on PDP-11 Unix. However, it can be shorter. If we assume that we can use int (either as a type wider than 16 bits, or a type of exactly 16 bits with various properties that happen to be true on many systems such as twos complement and arithmetic rollover), we can get rid of the stuff related to using long. Version for int wider than 16 bits, 97 bytes. ``` a[9],*p;main(i){while(!a[8]){ for(i=8;i--;printf(i?"%x:":"%x\n",a[i])); for(p=a;++*p>>16;*p++=0);}} ``` Version for 16-bit systems, 91 bytes. ``` a[9],*p;main(i){while(!a[8]){ for(i=8;i--;printf(i?"%x:":"%x\n",a[i])); for(p=a;!++*p;p++);}} ``` Oddly enough, though, the original K&R compiler didn't actually support the declaration without int (it compiles fine, but treats the variables as external and therefore undefined at link time), so an additional three bytes are needed to change the declaration to `int*p,a[9];` for a total of 94. Also, if the assumption that it is interrupted before completing output were a hard constraint, we could remove the end check, saving five bytes. Bonus: fully ANSI portable version, 126 bytes: ``` #include<stdio.h> long*p,i,a[9]; int main(){while(!a[8]){ for(i=8;i--;printf(i?"%lx:":"%lx\n",a[i])); for(p=a;++*p>>16;*p++=0);}} ``` Newlines in all versions are inserted for readability and in locations where whitespace is not required, and are excluded from the byte count, except for the newline after the `#include` line in the ANSI version. All versions except the ANSI version fall through at the end of main and therefore may return a spurious exit code to the operating system. [Answer] # AutoIt3, ~~142~~ 231 Bytes ``` For $a=0 To 2^32-1 For $b=0 To 2^32-1 For $c=0 To 2^32-1 For $d=0 To 2^32-1 $s=StringFormat("%08x%08x%08x%08x",$a,$b,$c,$d) For $j=0 To 8 ConsoleWrite(StringMid($s,$j*4+1,4)&($j<7?":":"")) Next ConsoleWrite(@LF) Next Next Next Next ``` ## Explanation * `For $a=0 To 2^32-1`: Iterate 4 times over 0-2^32 ((2^32)^4=2^128) possible combinations. * `$s=StringFormat("%08x%08x%08x%08x",$a,$b,$c,$d)`: Convert the numbers to a hexadecimal string with a length of 32 (4\*32). * `For $j=0 To 8`: Iterate over all 8 sections of the string. * `ConsoleWrite(StringMid($s,$j*4+1,4)&($j<7?":":""))`: Extract the next 4 characters from the string and add a colon (`:`) at the end, if we haven't reached the last section, then output everything to the console * `Next`: End the inner for-loop * `ConsoleWrite(@LF)`: Add a line-feed at the end of the line * `Next`: End the outer for-loops Expected output size: (One line (39 bytes) + line-feed) (=40 bytes) \* 2^128 = 1.361\* 10^16 YB (yottabytes) [Answer] # Commodore BASIC 2.0, 339 bytes In order to get lower-case hex digits, this program is written in "shifted mode" (press `<SHIFT>+<C=>`) ``` 1k=65535:a=0 2fOb=0tok:fOc=0tok:fOd=0tok:fOe=0tok:fOf=0tok:fOg=0tok:fOh=0tok 3x=a:goS6:?":";:x=b:goS6:?":";:x=c:goS6:?":";:x=d:goS6:?":";:x=e:goS6:?":";:x=f 4goS6:?":";:x=g:goS6:?":";:x=h:goS6:? 5nE:nE:nE:nE:nE:nE:nE:nE:a=a+1:ifa<65536tH2 6y=x/4096:goS7:y=x/256aN15:goS7:y=x/16aN15:goS7:y=xaN15:goS7:reT 7?mI("0123456789abcdef",y+1,1);:reT ``` Simply making this *work* on the Commodore 64 was a challenge, because of memory, screen size, data size, and other limitations. I considered implementing the abbreviated representation, but other limitations (such as the undocumented inability to use array elements as loop indices) meant it would increase the length of the program by an estimated 1000 bytes. Line 7 is an implementation of `HEX$()`, which Commodore BASIC 2.0 is lacking. I can't use a `DEF FN` for this because those can only return numbers, not strings. Line 6 is a subroutine that applies it to a group of four digits, which would have been considerably shorter if functions could return strings. Lines 2 and 5 are eight nested loops, implemented as seven "for" loops and a conditional goto because eight "for" loops, when combined with the two "gosubs" for printing out the address, will overflow the C64's tiny stack. A C64 can print out about 1.2 addresses per second, for an estimated runtime of 1.3\*10^31 years. [Answer] ### PowerShell (v4), 193 166 162 145 103 bytes TimmyD's no-bonus version at 103 bytes: ``` $i=[bigint]::Pow(4,64);while($i-gt0){('{0:X32}'-f($i-=1)-replace'0(?=.{32})'-re‌​place'.{4}(?!$)','$0:')} ``` --- Previous with-bonus version at 145 \* 0.8 = 116 bytes With help from [TimmyD](https://codegolf.stackexchange.com/users/42963/timmyd) and [tomkandy](https://codegolf.stackexchange.com/users/25181/tomkandy), who points out that `0 -eq $false` but `([bigint]0) -eq $true`. So all my previous versions won't terminate. ``` $i=[bigint]::Pow(4,64);while($i-gt0){$i-=1;[IPAddress]::Parse((('{0:X32}'-f$i )-replace'0(?=.{32})'-replace'.{4}(?!$)','$0:')).IPAddressToString} ``` --- Previously at 162, before some regex changes: ``` $i=[bigint]::Pow(4,64) while($i){$i-=1;if(($x='{0:X32}'-f$i).Length-eq33){$x=$x.Substring(1)} [IPAddress]::Parse(($x-replace'.{4}(?!$)','$0:')).IPAddressToString} ``` *"A challenge where PowerShell ought to be reasonably competetive!"* - me, before I tried it. **Explanation** ``` # PowerShell (PS) has no IP address arithmetic, e.g. IP + 1 #- PS has no 128 bit integers #- PS has no automatic bignums # Start from the top, with the BigInteger specialised Power() $i = [BigInt]::pow(4,64) # Loop 4**64 through 1, work with $i-1 for ff... -> ::0 while ($i) { # PS has no decrement operator for bignums # (no using $i-- in the while loop test) $i-=1 # The Net.IPAddress class can't turn a BigInteger # into an IPv6 address directly. And because it mashes # IPv4 and IPv6 into one class, there's no obvious way # to make a small number always cast to an IPv6 address. # Format the bignum as a string of 32 hex digits. $x = '{0:X32}' -f $i # The BigInteger often formats as /33/ hex digits, # with a leading zero (to avoid unintentional +/- sign bits) # ( https://msdn.microsoft.com/library/dd268287 ) # So remove the leading 0, if there is one if (($x).Length-eq33){$x=$x.Substring(1)} # I can't always remove the leading zero, because it # can't parse FFFFF... into an address without colons # and this regex replace into groups of 4 with colons # would go wrong at length 31. No : after the last group # This is still better than split/join ... because there # isn't a split-into-groups-of-N that I know of. $x = ($x -replace '.{4}(?!$)', '$1:' # Woo! * 0.8 bonus! 45 characters to save 38! :D [IPAddress]::Parse($x).IPAddressToString } ``` [Answer] # AutoIt3, 137 Bytes ``` For $i=0 To 4^64 $s=StringFormat("%032x",$i) For $j=0 To 7 ConsoleWrite(StringMid($s,$j*4+1,4)&($j<7?':':'')) Next ConsoleWrite(@LF) Next ``` [Answer] # [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate) `-a`, 24 bytes ``` (($3:!)[0-9a-f]{4}()){8} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdVm0km6iUuyCpaUlaboWOzQ0VIytFDWjDXQtE3XTYqtNajU0NastaiHSUFULoDQA) ``` ( # Match ":" iff we're not on the first iteration ( $3 # Match iff we're not on the first iteration : # Match ":" ! # Short-circuiting alternation - only try matching the below # if it was impossible for the above to match. # Do nothing ) [0-9a-f]{4} # Match 4 hexadecimal digits () # $3 = signal that we're not on the first iteration anymore ) {8} # Repeat the above 8 times ``` Alternative 24 bytes: ``` (({#1}:!)[0-9a-f]{4}){8} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdVm0km6iUuyCpaUlaboWOzQ0qpUNa60UNaMNdC0TddNiq01qNastaiHSUFULoDQA) It might not be intended that this is possible, but Regenerate allows a quantifier to be preceded by nothing. This is what's happening with `{#1}` - it's impossible for it to match on the first iteration because `$1` hasn't been captured yet and doesn't have a length. On subsequent iterations, a match of nothing gets repeated 4 times (the length of `$1`). [Answer] # Python 2, 95 bytes ``` def i(p=0): while p<4**64:print':'.join(hex(p)[2:].zfill(32)[4*s:4*s+4]for s in range(8));p+=1 ``` Simply goes through every number from 0 to 2^128. First it converts the current number to hexadecimal string, then strips off the `'0x'` that that function gives. Next it adjusts the string to have 32 zeros in the front and then breaks it up into groups of four. Finally it joins the groups of four with colons, prints that out and adds 1 to the current number. Has the added bonus that you can start it at any value if you give it one, but no input is needed. [Answer] # Haskell 111 ``` s[]=[[]] s(a:b)=[y:z|z<-s b,y<-a] r=replicate main=mapM putStrLn$s$tail$concat$r 8$":":r 4"0123456789abcdef" ``` With my own sequence function `s` it no longer leaks memory, but does not feel golfed any more. [Answer] # CBM BASIC v7.0 (166 characters) ``` a=65535 fOi=0toa:fOj=0toa:fOk=0toa:fOl=0toa:fOm=0toa:fOn=0toa:fOo=0toa:fOp=0toa:?hE(i)":"hE(j)":"hE(k)":"hE(l)":"hE(m)":"hE(n)":"hE(o)":"hE(p):nE:nE:nE:nE:nE:nE:nE:nE ``` [Mark's answer](https://codegolf.stackexchange.com/a/60318/46220) is for the Commodore 64's BASIC 2.0, which lacks a built-in command for printing numbers in hexadecimal. However, thanks to the `HEX$()` function in BASIC 7.0, the Commodore 128 version is much shorter. It doesn't fit on a single logical line (which on the C128 is limited to 160 characters) but can still be entered as two separate lines in direct mode. [Answer] # Ruby 75 ``` x=->s,n{n>0?65536.times{|m|x.(s+?:*(8<=>n)+m.to_s(16),n-1)}: p(s)};x.('',8) ``` This is a recursive solution that takes a each prefix and finds every possible suffix. Recursively. [Answer] # [Zsh](https://www.zsh.org/) `-P`, 60 bytes ``` x=({0..9} {a..f}) eval for\ {1..8}' ($x$x$x$x)<<<${(j/:/)@}' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjWbSSboBS7IKlpSVpuhY3bSpsNaoN9PQsaxWqE_X00mo1uVLLEnMU0vKLYhSqDfX0LGrVFTRUKiBQ08bGRqVaI0vfSl_ToVYdYgbUqAVQGgA) (Warning: if you don't click the kill button fairly quickly, your browser will run out of memory and crash) `eval for\ {1..8}` creates 8 nested loops using the loop variables `$1`, `$2`, ..., `$8`. These numbered variables can then be referred to implicitly using `$@` (here, they're joined with colons using `${(j/:/)}`). The `<<<${...}` section is actually repeated for each level of nested loop as well, but (apart from the last one) they all do nothing, because they feed into the next loop, which ignores its input. The `-P` option enables an implicit cartesian product on the adjacent expansions `$x$x$x$x`. This is the shortest way I could find to count up to `0xffff` *in hex* without needing to convert each loop variable to hex individually. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 21 bytes ``` ₇E(nk6τ₅32ε\0*p4ẇ\:j, ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%82%87E%28nk6%CF%84%E2%82%8532%CE%B5%5C0*p4%E1%BA%87%5C%3Aj%2C&inputs=&header=&footer=) Ugh, we really need a zfill builtin. [Answer] # [Go](https://go.dev), \$243 \times 0.8 = \$ 194.4 bytes ``` import(."fmt";."net/netip") func F(){for a,M:=0,1<<32-1;a<M;a++{for b:=0;b<M;b++{for c:=0;c<M;c++{for d:=0;d<M;d++{s:="" for n,k:=0,Sprintf("%08x%08x%08x%08x",a,b,c,d);n<8;n++{s+=k[4*n:4*(n+1)]+":"} A,_:=ParseAddr(s[:len(s)-1]) Println(A)}}}}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TdAxasMwFAbgXacwgoAUyWncZjCSPXjpFgh0DKHIkhWM42djKxAoOUkXU-jWqbfpOXqBSomHCh6C70cPfr1_HLvpq1e6UccqalUNn2dn4_Tnt277bnBkhW3rsFxhqNyDn7rHFNkz6OiZ0DfbDZHiW5GveZJlT49xIlW2lYqxW1T6QJYeyhl0AO1Bz2ACGA_GwyhyjFFg4E3Y-dIPNThL8GKdXv4P5oqXXHNDJWSphPCY5c1-swSxWRJgCT0wLPAVFfxV5Ds1jFVhzEDGvThVQEYaJweKdmH9CUhBr-Hcq3_f2oWv8AWRb4nmYJru9x8) Prints to STDOUT. Uses the `netip.Addr` type from the Golang standard library to do the formatting for me. ### Explanation ``` import(."fmt";."net/netip") func F(){ for a,M:=0,1<<32-1;a<M;a++{ // first 8 digits for b:=0;b<M;b++{ // next 8 digits for c:=0;c<M;c++{ // next 8 digits for d:=0;d<M;d++{ // final 8 digits k:=Sprintf("%08x%08x%08x%08x",a,b,c,d) // join the numbers into a single string s:="" for n:=0;n<8;n++{s+=k[4*n:4*(n+1)]+":"} // split into 8 groups of 4, split by colons A,_:=ParseAddr(s[:len(s)-1]) // parse the address Println(A)}}}}} // print using the default String() method, which formats the address ``` [Answer] ## Tcl ~~341~~ ~~318~~ 301 ``` proc ip6 {p c} { set s %x:%x:%x:%x:%x:%x:%x:%x set p [scan $p $s] while {[set d 7]} { $c [format [string map {x 04x} $s] {*}$p] while {[set i [lindex $p $d]]==0xFFFF} { lset p $d 0 if {!$d} return incr d -1 } lset p $d [incr i] } } ip6 fFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:0000 puts ``` ]
[Question] [ Output the Nth term of the Van Eck Sequence. Van Eck Sequence is defined as: * Starts with 0. * If the last term is the first occurrence of that term the next term is 0. * If the last term has occurred previously the next term is how many steps back was the most recent occurrence. <https://oeis.org/A181391> <https://www.youtube.com/watch?v=etMJxB-igrc> <https://www.youtube.com/watch?v=8VrnqRU7BVU> Sequence: 0,0,1,0,2,0,2,2,1,6,0,5,0,2,... Tests: Input | Output * 1 | 0 * 8 | 2 * 19 | 5 * 27 | 9 * 52 | 42 * 64 | 0 **EDIT** 1 indexed is preferred, 0 indexed is acceptable; that might change some of the already submitted solutions. Just the Nth term please. Same (except for the seeing it already posted part), it seems code golfers and numberphile watchers have a decent overlap. [Answer] # JavaScript (ES6), ~~46 41~~ 37 bytes ``` n=>(g=p=>--n?g(g[p]-n|0,g[p]=n):p)(0) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k4j3bbA1k5XN88@XSM9uiBWN6/GQAfEsM3TtCrQ1DDQ/J@cn1ecn5Oql5OfrpGmYaipqaCgr69gwIUqbgEVN0ITN7QESgDFTdHEjcwh4pZo4qZGEHETdIPMTCASBv8B "JavaScript (Node.js) – Try It Online") ### How? We don't need to store the full sequence. We only need to keep track of the last position of each integer that appears in the sequence. We use the underlying object of the recursive function \$g\$ for that purpose. For a given term \$p\$, we don't need either to set \$g[p]\$ to its actual absolute position in the sequence because we're only interested in the distance with the current position. That's why we can just store the current value of the input \$n\$, which is used as a decrementing counter in the code. Therefore, the distance is given by \$g[p]-n\$. Conveniently, this evaluates to *NaN* if this is the first occurrence of \$p\$, which can be easily turned into the expected \$0\$. ### Commented ``` n => ( // n = input g = p => // g = recursive function taking p = previous term of the // sequence; g is also used as an object to store the // last position of each integer found in the sequence --n ? // decrement n; if it's not equal to 0: g( // do a recursive call: g[p] - n // subtract n from the last position of p // if g[p] is undefined, the above expression evaluates | 0, // to NaN, in which case we coerce it to 0 instead g[p] = n // update g[p] to n ) // end of recursive call : // else: p // we've reached the requested term: // stop the recursion and return it )(0) // initial call to g with p = 0 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~69~~ ~~63~~ 62 bytes ``` f=lambda n,l=0,*s:f(n-1,l in s and~s.index(l),l,*s)if n else-l ``` [Try it online!](https://tio.run/##FcoxDsIwDAXQGU7h0UYpKrBV6mGCEoMl97dKOrRLr57Cm9@yr98Zr9Z09Di9UyQEH/twq4MyukdwMlCliHTUuyHljV2C/4KYEih7zZ03nQvZv5aIT@ZnL8P1shTDysom0k4 "Python 3 – Try It Online") Note: as Erik the Outgolfer mentioned, this code works fine in Python 2 as well. 0-indexed (although, just to be utterly perverse, you can make it -1-indexed by changing `if n` to `if~n` :P) Makes use of Python's gorgeous unpacking "star operator", to recursively build up the series, until `n` reaches zero. The function builds up the series in the reverse order, to avoid having to reverse it for the search. Additionally, it actually stores the negations of all the elements, because converting them back at the end was free (else the `-` would have had to be a space) and it saves us a byte along the way, by using `~s.index(l)` instead of `-~s.index(l)`. Could be 51 bytes if Python tuples had the same `find` functions strings do (returning -1 if not found, instead of raising an error), but no such luck... [Answer] # [R](https://www.r-project.org/), 62 bytes ``` function(n){while(sum(F|1)<n)F=c(match(F[1],F[-1],0),F) +F[1]} ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPs7o8IzMnVaO4NFfDrcZQ0yZP0802WSM3sSQ5Q8Mt2jBWxy1aF0gaaOq4aXJpg0Rq/xcnFhTkVGoYWhka6KRp/gcA "R – Try It Online") Builds the list in reverse; `match` returns the *first* index of `F[1]` (the previous value) in `F[-1]` (the remainder of the list), returning `0` if no match is found. `F` is initialized to `FALSE` and is coerced to `0` on the first pass of the `while` loop. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~47~~ 42 bytes *-5 bytes thanks to nwellnhof* ``` {({+grep(@_[*-1],:k,[R,] @_)[1]}...*)[$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WqNaO70otUDDIT5aS9cwVscqWyc6SCdWwSFeM9owtlZPT09LM1olPrb2f3FipUKaRpyRgaY1F4QdbahjoWNoqWNkrmNqpGNmEhuha6j5HwA "Perl 6 – Try It Online") Anonymous codeblock that outputs the 0-indexed element in the sequence. ### Explanation: ``` { } # Anonymous codeblock ( )[$_] # Return the nth element ...* # Of the infinite sequence { } # Where each element is grep( :k )[1] # The key of the second occurrence @_[*-1], # Of the most recent element ,[R,] @_ # In the reversed sequence so far + # And numify the Nil to 0 if the element is not found ``` [Answer] # Bourne shell, 102 bytes ``` until [ 0"$i" -eq $1 ];do i=$((${i:-0}+1)) a=${n:-0};eval 'n=$(($i-${m'$a:-$i'}))' m$a=$i;done;echo $a ``` [try it online](https://tio.run/##HcxNCoMwFEXhrVzkQgwloIITgysRB69twAcaKf2ZBNf@ajs88HGu8lzM3vmlKyY0FbVCSA@wxRzvO3RkXbPoEJrj0noPGVnyr2L6yAqX/0ADy@YoQ6C6w3uHjafUc5FTTLdlB8XM@u4L) [Answer] # [Python](https://docs.python.org/2/), 51 bytes ``` f=lambda n,i=1:n>i and[f(n,i+1),i][f(n-1)==f(n+~i)] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU8n09bQKs8uUyExLyU6TQPI1zbU1MmMBbF1DTVtbYG0dl2mZuz/tPwihTyFzDyFosS89FQNQ0NNKy6FgqLMvBKgKQraQHWa/wE "Python 2 – Try It Online") Outputs `False` for `0`. Implements the spec pretty literally, looking for the lowest positive integer `i` such that `f(n-1)==f(n-i-1)`. If such a search leads to `i>=n`, the previous element hasn't appeared before and we produce `0`. Instead of doing something reasonable like storing earlier values in a list, the function just recomputes them recursively from scratch whenever they're needed, and sometimes when they're not needed. This makes the function run very slowly for inputs above 10 or so. [Answer] # [J](http://jsoftware.com/), ~~29~~ 23 bytes ``` 1{(,~#|1+}.i.{.)@]^:[&0 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Das1dOqUawy1a/Uy9ar1NB1i46yi1Qz@a3KlJmfkAxXaKqQpGEI4RmCOBYRjCpGxhPAswTwjcwjPBKLS1AjZEDOT/wA "J – Try It Online") The real work is done in the iteration verb of the power verb `^:`, which iterates as many times as the argument `[`, starting the iteration with the constant value 0 `&0`... * `(#|1+}.i.{.)` This is what iterates. Breaking it down... * `}.i.{.` Find the index of `i.` of the head of the list `{.` within the tail of the list `}.`. This will return a 0-based index, so if the current item is found 1 previous it will return 0. If it is not found, it will return the length of the list, ie, the length of the tail. * `1+` Add one to the value to correct for the 0-based indexing, since the Ven Eck's "how far back" is 1-based. Note that if it was not found, the value will now be the length of the full list. * `#|` Return the remainder of the value calculated in the previous step, when divided by the length of the full list. Note that this turns "not found" into 0, but leaves all other values unchanged. * `,~` Append the new value to the front of the list. We use the front rather than last merely for convenience. * `1{` return the 2nd item in the list, since we calculated one too many times because it's shorter that way. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~10~~ 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` é"▬π²"ô↕j ``` [Run and debug it](https://staxlang.xyz/#p=822216e3fd2293126a&i=1%0A8%0A19%0A27%0A52%0A64&a=1&m=2) If 0-based indexing is allowed: ### [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` à┐æ8Å/[┤ ``` [Run and debug it](https://staxlang.xyz/#p=85bf91388f2f5bb4&i=0%0A7%0A18%0A26%0A51%0A63&a=1&m=2) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 48 bytes ``` #<1||Last[#-1-Array[#0,#-2]~Position~#0[#-1],0]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9nGsKbGJ7G4JFpZ11DXsagosTJa2UBHWdcoti4gvzizJDM/r07ZACQbq2MQq/Y/sDQztSQ6oCgzD6TFLs1BOVZN3yEoMS891cHQIPY/AA "Wolfram Language (Mathematica) – Try It Online") Nonzero values are [returned as singleton lists](https://codegolf.meta.stackexchange.com/a/11884/81203). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~19~~ 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") Many thanks to ngn, Adám, Richard Park and H.PWiz for their help in writing and golfing this answer in [The APL Orchard](https://chat.stackexchange.com/rooms/52405/the-apl-orchard), a great place to learn APL and get APL help. **Edit:** -2 bytes from Adám. ``` ⊃(⊢,⍨≢|1∘↓⍳⊃)⍣⎕-1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKNdIe3/o65mjUddi3Qe9a541LmoxvBRx4xHbZMf9W4GSmg@6l38qG@qriFILVfao7YJj3r7DB/17FWvrVbXUQdKgXCR@qPerepAM4we9WwH8pOL1NPUFR71zlUoKUpMSctTKMlXAFL/q4HKFAwf9W4BMXTSgETtoRUgi4AMQwMDAA "APL (Dyalog Unicode) – Try It Online") **Explanation** ``` ⊃(⊢,⍨≢|1∘↓⍳⊃)⍣⎕-1 -1 We initialize our array of results with -1. ( )⍣⎕ ⍣ repeats the train (in parentheses) our input, ⎕, times. 1∘↓⍳⊃ We take the index of the head (our last element in the sequence). To signify "element not found", this returns the length of the array. ≢| We take our index modulo the length of the array. This turns our "element not found" from the length of the array to 0. ⊢,⍨ And we prepend to our array. ⊃ Finally, we return the first element of the array, which is the most recently-generated. This is the ⍵-th element of the Van Eck sequence. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` F¯Rćk>Dˆ ``` [Try it online](https://tio.run/##yy9OTMpM/f/f7dD6oCPt2XYup9v@/zc1AgA) or [output the first \$n\$ values in the list](https://tio.run/##yy9OTMpM/f/f7dD6oCPt2Xan22oPrf//39DAAAA). **Explanation:** ``` F # Loop the (implicit) input amount of times: ¯ # Push the global array R # Reverse it ć # Extract the head; push the remainder and the head to the stack k # Get the 0-based index of the head in the remainder (-1 if not found) > # Increase it by 1 to make it 1-indexed (or 0 if not found) Dˆ # Add a copy to the global array # (after the loop, output the top of the stack implicitly as result, # which is why we need the `D`/duplicate) ``` [Answer] ## Java, 96 80 76 bytes ``` n->{int i,v=0,m[]=new int[n];for(;--n>0;m[v]=n,v=i<1?0:i-n)i=m[v];return v;} ``` Not obfuscated: ``` Function<Integer, Integer> vanEck = n -> { int i; // i is the value of n when v was previously encountered int v = 0; // v is the current element of vanEck sequence int[] m = new int[n]; // m[v] is the value of n when v was previously encountered while (--n > 0) { // n is used as a decrementing counter i = m[v]; m[v] = n; v = i == 0 ? 0 : i - n; } return v; }; ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` Ḷ߀ṚiḢ$ ``` [Try it online!](https://tio.run/##y0rNyan8///hjm2H5z9qWvNw56zMhzsWqfw3NAEJtQOF/gMA "Jelly – Try It Online") 0-indexed. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` ≔⁰θF⊖N«≔⊕⌕⮌υθη⊞υθ≔ηθ»Iθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DQEehUNOaKy2/SEHDJTW5KDU3Na8kNUXDM6@gtMSvNDcptUhDU1NToZqLE6rDMw@hyi0zL0UjKLUstag4VaNUE2QWkMgAGsgZUFqcoVEKMR2mNQPCreUKKMrMK9FwTiwu0QDqsP7/39Dyv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⁰θ ``` Set the first term to 0. ``` F⊖N« ``` Loop `n-1` times. (If 0-indexing is acceptable, the `⊖` can be removed for a 1-byte saving.) ``` ≔⊕⌕⮌υθη ``` The next term is the incremented index of the current term in the reversed list of previous terms. ``` ⊞υθ ``` Add the current term to the list of previous terms. ``` ≔ηθ ``` Set the current term to the next term. ``` »Iθ ``` Print the current term at the end of the loop. [Answer] # Perl 5 (`-p`), 42 bytes ``` map{($\,$\{$\})=0|$\{$\};$_++for%\}1..$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saBaQyVGRyWmWiWmVtPWoAbCslaJ19ZOyy9Sjak11NNTia@t/v/f1OhffkFJZn5e8X/dAgA "Perl 5 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~8~~ 7 bytes ``` !¡oΓ€↔ø ``` [Try it online!](https://tio.run/##ATAAz/9odXNr/21vd1Ms4oKB/yHCoW/Ok@KCrOKGlMO4////WzEsOCwxOSwyNyw1Miw2NF0 "Husk – Try It Online") The behavior of `€` is surprisingly helpful here. [Answer] # [Haskell](https://www.haskell.org/), 42 bytes ``` f n=last$0:[n-j-1|j<-[0..n-2],f j==f(n-1)] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzYnsbhExcAqOk83S9ewJstGN9pATy9P1yhWJ00hy9Y2TSNP11Az9n9uYmaegq1CQVFmXomCikKago2KnQJIqaFB7H8A "Haskell – Try It Online") Other Haskell answers: [66 bytes by flawr](https://codegolf.stackexchange.com/a/186680/3852) and [61 bytes by nimi](https://codegolf.stackexchange.com/a/186707/3852). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ẎiḢ$;µ¡Ḣ ``` A monadic Link accepting a positive integer, \$n\$, which yields the \$n^{th}\$ term of the Van Eck Sequence. **[Try it online!](https://tio.run/##y0rNyan8///hrr7MhzsWqVgf2npoIZDx//9/UyMA "Jelly – Try It Online")** ### How? ``` ẎiḢ$;µ¡Ḣ - Link: n µ¡ - repeat this monadic link n times - i.e. f(f(...f(n)...)): - (call the current argument L) Ẏ - tighten (ensures we have a copy of L, so that Ḣ doesn't alter it) $ - last two links as a monad: Ḣ - head (pop off & yield leftmost of the copy) i - first index (of that in the rest) or 0 if not found ; - concatenate with L Ḣ - head ``` Note that without the final `Ḣ` we've actually collected `[a(n), a(n-1), ..., a(2), a(1), n]` [Answer] # [C (gcc)](https://gcc.gnu.org/), 63 bytes ``` f(n){n=g(n,--n);}g(n,i){n=n>0?f(--n)-f(i)?g(n,i)+!!g(n,i):1:0;} ``` [Try it online!](https://tio.run/##JcwxCsMwDIXh3adwAgEJW@CMjZrkIl2Kg4KGqiV0Cz67W5Pt53vwMu051ypgeNq8g0UiQy6ttJEtaRVoSAKK6zWErrtiGqfEpb6eaoCnk/cBal@vc2K9jzfWENB9jr8J9MPmafHD9rA@amx3yK7UHw "C (gcc) – Try It Online") 0-indexed. [Answer] # [Haskell](https://www.haskell.org/), ~~68 67~~ 66 bytes Quite straightforward implementation (using 0 based indexing). ``` f n|all((/=f(n-1)).f)[0..n-2]=0|m<-n-1=[k|k<-[1..],f(m-k)==f m]!!0 ``` [Try it online!](https://tio.run/##FcwxDsMgDADArxgpA0i1A5lxP4IYGGIFAVbVduTvpF1vuKt82tn7WgI6S@/W7ixWMThH4pInUjwy@zki/pRTmy1iCkT5IXZgc8wCIxvj1yhVgeH1rvqFDQTi9oR/EXxeNw "Haskell – Try It Online") [Answer] ## Haskell, 61 bytes ``` (([]#0)1!!) (l#n)i=n:(((n,i):l)#maybe 0(i-)(lookup n l))(i+1) ``` 0-based indexing. [Try it online!](https://tio.run/##BcHBDoIwDADQu19RMg9tFLIdvJDsS4DDJEwburKAHPx563vvdKyLiOU4GuIwOU@haeiC4pQ4ao@IemfqhVxJ3@cCHrkllG1bzwoKQoR8C2QlsUKEurN@4AolVcgw@K4Lj8l@c5b0Oqyda/0D "Haskell – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 11 bytes ``` @ÒZÔÅbX}hTo ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=QNJa1MViWH1oVG8&input=NTI) [Answer] ## CJam (15 bytes) ``` 0a{_(#)\+}qi*0= ``` [Online demo](http://cjam.aditsu.net/#code=0a%7B_(%23)%5C%2B%7Dqi*0%3D&input=9). This is a full program and 0-indexed. ### Dissection ``` 0a e# Push the array [0] { e# Loop... _(# e# Copy the array, pop the first element, and find its index in the array )\+ e# Increment and prepend }qi* e# ... n times, where n is read from stdin 0= e# Take the first element of the array ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 77 bytes ``` n=>{int i,v=0;for(var m=new int[n];--n>0;m[v]=n,v=i<1?0:i-n)i=m[v];return v;} ``` [Try it online!](https://tio.run/##HYyxCsMwDAV3f4VGm8TgrFXkbp27hwzFxKAhKjiJM5R@u6t0ePA4jkubTxu3xyFpZNl7XczUhOJHL3BfKWB@F1tfBVaS5QTlk8zovcSA61RnErV4HO7hxl4c0wWxLPtRBCp@GxpzJf5BGlDVEJC7zhmAZ1Fss2XnsP0A "C# (Visual C# Interactive Compiler) – Try It Online") Pretty much a port of the Java answer at this point. [Answer] # [Python 3](https://docs.python.org/3/), ~~128~~ ~~114~~ ~~111~~ ~~102~~ 99 bytes *102 -> 99 bytes, thanks to Jonathan Frech* ``` f=lambda n,i=1,l=[0]:f(n,i+1,l+[l[i-2::-1].index(l[-1])+1if l[-1]in l[:-1]else 0])if n>i else l[-1] ``` [Try it online!](https://tio.run/##RcpNCsIwEAXgvaeYXROaShP7D/UiIYtKExyIsWgXCt49xirjat773izP9XwNhxjd6KfLaZ4gCByl8KMuzeBYanlqufYaCzUMhTR7DLN9MK9T5rlEB1vEkO5nt/5uoTQ8DeGIsNXtIy43DCuTAjJ4ZQIck5zvvtj9sSOUfdLfZ0@qWlLVktaKtFakTUXaVJzHNw "Python 3 – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` W?(p:ḣḟ› ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiVz8ocDrhuKPhuJ/igLoiLCIiLCIxXG44XG4xOVxuMjdcbjUyXG42NCJd) 1-indexed. **Explanation:** Since \$a(n) < n\$, we can push \$n\$ to the beginning of the list. Also builds the sequence backwards. ``` W?(p:ḣḟ› # whole program W # [] ? # input ( # repeat for times: p # prepend to list (uses implicit input the first time) : # duplicate ḣ # split head from the rest ḟ # find its index on the list (-1 if none) › # increment # as we didn't prepend the last item, output it ``` [Answer] # [Python 3](https://docs.python.org/3/), 112 bytes ``` a=[0] for _ in a*int(input()):k=a[-1];a+=k in a[:-1]and[a[::-1].index(k)+~a[-2::-1].index(k)]or[0] print(-a[-2]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P9E22iCWKy2/SCFeITNPIVErM69EIzOvoLREQ1PTKts2MVrXMNY6Uds2GywdbQXkJualRANZIKZeZl5KaoVGtqZ2HVClEapYbH4RyPCCIpCZuiD5WM3//43MAQ "Python 3 – Try It Online") -3 bytes thanks to mypetlion [Answer] # [Red](http://www.red-lang.org), ~~106~~ 95 bytes ``` func[n][b: copy[0]loop n[insert b either not find t: next b b/1[0][-1 + index? find t b/1]]b/2] ``` [Try it online!](https://tio.run/##Pcu7DgIhFIThfp9iemNWiFca38H2hIblEEnMgbCYrE@PFEr3Jf9MYd8e7MlOwbTwloXEkjNYUv7Qwb5SyhCKsnKpcOBYn1wgqSJE8agGwlsvk5tV39NeYYdeeLv/FujFWjdr23KJ0o9Q01/XIXUb1JfBkx48H9sX "Red – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 18 bytes ``` VQ=Y+?YhxtYhY0Y;hY ``` [Try it online!](https://tio.run/##K6gsyfj/PyzQNlLbPjKjoiQyI9Ig0joj8v9/UyMA "Pyth – Try It Online") Builds up the sequence in reverse and prints the first element (last term of the sequence). ``` VQ # for N in range(Q) (Q=input) =Y+ Y # Y.prepend( xtY # Y[1:].index( ) hY # Y[0] h # +1 ?Y 0 # if Y else 0) ;hY # end for loop and print Y[0] ``` [Answer] # [Arn](https://github.com/ZippyMagician/Arn) `-f`, [13 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn) ``` f→S›J⁻僃N5═% ``` [Try it!](https://zippymagician.github.io/Arn?code=Ji57KysuezppOnspfH1b&input=MQo4CjE5CjI3CjUyCjY0&flags=Zg==) 0-indexed # Explained Unpacked: `&.{++.{:i:{)|}[` ``` &. Mutate S N times { With block, key of `_` ++ Increment _ Implicit .{ Behead :i Index of _ Implicit :{ Head ) Don't ask | Concatenated with _ Implicit } End block [ Where S is an array ] Ending implicit _ And N is STDIN; implicit Then take the head ``` ]
[Question] [ Last time when I tried to come up with something easy that wasn't a duplicate, it ended up being way too hard.. So hopefully this time it's indeed something newcomers can try as well. **Input:** An array/list with integers/decimals. (Or a string representing an array with integers/decimals.) **Output:** Loop through the numbers and apply the following five mathematical operands in this order: * Addition (`+`); * Subtraction (`−`); * Multiplication (`*` or `×` or `·`); * *Real / Calculator* Division (`/` or `÷`); * Exponentiation (`^` or `**`). (NOTE: The symbols between parenthesis are just added as clarification. If your programming language uses a completely different symbol for the mathematical operation than the examples, then that is of course completely acceptable.) Keep continuing until you've reached the end of the list, and then give the result of the sum. **Challenge rules:** * Exponentiation by 0 (`n ^ 0`) should result in 1 (this also applies to `0 ^ 0 = 1`). * There are no test cases for division by 0 (`n / 0`), so you don't have to worry about that edge-case. * If the array contains just a single number, we return that as the result. **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, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, 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. **Test cases:** ``` [1,2,3,4,5] -> 0 -> 1 + 2 = 3 -> 3 - 3 = 0 -> 0 * 4 = 0 -> 0 / 5 = 0 [5,12,23,2,4,4,2,6,7] -> 539 -> 5 + 12 = 17 -> 17 - 23 = -6 -> -6 * 2 = -12 -> -12 / 4 = -3 -> -3 ^ 4 = 81 -> 81 + 2 = 83 -> 83 - 6 = 77 -> 77 * 7 -> 539 [-8,50,3,3,-123,4,17,99,13] -> -1055.356... -> -8 + 50 = 42 -> 42 - 3 = 39 -> 39 * 3 = 117 -> 117 / -123 = -0.9512... -> -0.9512... ^ 4 = 0.818... -> 0.818... + 17 = 17.818... -> 17.818... - 99 -> -81.181... -> -81.181... * 13 = -1055.356... [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] -> 256 -> 2 + 2 = 4 -> 4 - 2 = 2 -> 2 * 2 = 4 -> 4 / 2 = 2 -> 2 ^ 2 = 4 -> 4 + 2 = 6 -> 6 - 2 = 4 -> 4 * 2 = 8 -> 8 / 2 = 4 -> 4 ^ 2 = 16 -> 16 + 2 = 18 -> 18 - 2 = 16 -> 16 * 2 = 32 -> 32 / 2 = 16 -> 16 ^ 2 = 256 [1,0,1,0,1,0] -> 1 -> 1 + 0 = 1 -> 1 - 1 = 0 -> 0 * 0 = 0 -> 0 / 1 = 0 -> 0 ^ 0 = 1 [-9,-8,-1] -> -16 -> -9 + -8 = -17 -> -17 - -1 = -16 [0,-3] -> -3 -> 0 + -3 = -3 [-99] -> -99 ``` [Answer] # Javascript ES7 49 bytes ``` a=>a.reduce((c,d,e)=>[c**d,c+d,c-d,c*d,c/d][e%5]) ``` Saved 9 bytes thanks to Dom Hastings, saved another 6 thanks to Leaky Nun Uses the new exponentiation operator. [Answer] # Haskell, ~~76~~ ~~65~~ ~~64~~ 62 bytes Thanks to @Damien for removing another two bytes=) ``` f(u:v)=foldl(\x(f,y)->f x y)u(zip(v>>[(+),(-),(*),(/),(**)])v) ``` This uses the `>>` which here just appends the list `[(+),...]` to itself `length v` times. The rest still works still the same as the old versions. Old versions: These solutions make use of the infinite lists, as `cycle[...]` just repeats the given list infinitely. Then it basically gets `zip`ed with the list of numbers, and we just `fold` (*reduce* in other languages) the zipped list via a lambda, that applies the operators to the accumulator/current list element. ``` f(u:v)=foldl(\x(f,y)->f x y)u(zip(cycle[(+),(-),(*),(/),(**)])v) f(u:v)=foldl(\x(y,f)->f x y)u(zip v(cycle[(+),(-),(*),(/),(**)])) f l=foldl(\x(y,f)->f x y)(head l)(zip(drop 1l)(cycle[(+),(-),(*),(/),(**)])) ``` [Answer] ## Pyke, ~~22~~ 21 bytes ``` lt5L%"+-*/^"L@\RJQ_XE ``` [Try it here!](http://pyke.catbus.co.uk/?code=lt5L%25%22%2B-%2a%2F%5E%22L%40%5CRJQ_XE&input=%5B-8%2C50%2C3%2C3%2C-123%2C4%2C17%2C99%2C13%5D) ``` lt5L% - map(len(input)-1, %5) "+-*/^"L@ - map(^, "+-*/^"[<]) \RJ - "R".join(^) E - pyke_eval(^, V) Q_X - splat(reversed(input)) ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “+_×÷*”ṁṖ⁸żFV ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCcK1_Dl8O3KuKAneG5geG5luKBuMW8RlY&input=&args=Wy04LDUwLDMsMywtMTIzLDQsMTcsOTksMTNd) or [verify all test cases](http://jelly.tryitonline.net/#code=4oCcK1_Dl8O3KuKAneG5geG5luKBuMW8RlYKw4figqw&input=&args=WzEsMiwzLDQsNV0sIFs1LDEyLDIzLDIsNCw0LDIsNiw3XSwgWy04LDUwLDMsMywtMTIzLDQsMTcsOTksMTNdLCBbMiwyLDIsMiwyLDIsMiwyLDIsMiwyLDIsMiwyLDIsMl0sIFsxLDAsMSwwLDEsMF0sIFstOSwtOCwtMV0sIFswLC0zXSwgWy05OV0). ### How it works ``` “+_×÷*”ṁṖ⁸żFV Main link. Argument: A (list of integers) “+_×÷*” Yield the list of operations as a string. Ṗ Yield A popped, i.e., with its last element removed. ṁ Mold; reshape the string as popped A. This repeats the characters of the string until it contains length(A)-1 characters. ⁸ż Zipwith; pairs the integers of A with the corresponding characters. F Flatten the result. V Eval the resulting Jelly code. Jelly always evaluates left-to-right (with blatant disregard towards the order of operations), so this returns the desired result. ``` [Answer] # Haskell, 61 Bytes ``` foldl(flip id)0.zipWith flip((+):cycle[(+),(-),(*),(/),(**)]) ``` Creates a series of transformations in a list, as in [add 1, add 2, subtract 3, ...], starting with 2 additions because we start with 0 in the fold. Next, we do what I call the List Application Fold, or foldl (flip id), which applies a list of homomorphisms in series. This starts with zero, adds the initial value, then does all of the above computed transformations to get a final result. Note that (flip id) is the same as (\x y->y x), just shorter. Sample usage: ``` f = foldl(flip id)0.zipWith flip((+):cycle[(+),(-),(*),(/),(**)]) f [1,2,3,4,5] -- Is 0.0 ``` [Answer] # TSQL ~~116~~ ~~115~~ 88 bytes Thanks to Ross Presser suggestion I was able to golf this down to 88 characters ``` -- In Try-it code, this must be DECLARE @y TABLE CREATE TABLE T(a real, i int identity) INSERT T values(5),(12),(23),(2),(4),(4),(2),(6),(7) DECLARE @ REAL SELECT @=CHOOSE(i%5+1,@/a,ISNULL(POWER(@,a),a),@+a,@-a,@*a)FROM T PRINT @ ``` [Try it online](https://data.stackexchange.com/stackoverflow/query/1064531/weapons-of-math-instruction) [Answer] # Pyth, ~~27~~ ~~26~~ 25 bytes ``` .v+>tlQ*lQ"^c*-+":jdQ\-\_ ``` [Test suite.](http://pyth.herokuapp.com/?code=.v%2B%3EtlQ%2alQ%22%5Ec%2a-%2B%22%3AjdQ%5C-%5C_&test_suite=1&test_suite_input=%5B1%2C2%2C3%2C4%2C5%5D%0A%5B5%2C12%2C23%2C2%2C4%2C4%2C2%2C6%2C7%5D%0A%5B-8%2C50%2C3%2C3%2C-123%2C4%2C17%2C99%2C13%5D%0A%5B2%2C2%2C2%2C2%2C2%2C2%2C2%2C2%2C2%2C2%2C2%2C2%2C2%2C2%2C2%2C2%5D%0A%5B1%2C0%2C1%2C0%2C1%2C0%5D%0A%5B-9%2C-8%2C-1%5D%0A%5B0%2C-3%5D%0A%5B-99%5D&debug=0) Pyth uses prefix notation: `1+2` is written as `+1 2` (space needed to separate numbers). Therefore, for the first testcase, the expression would be `(((1+2)-3)*4)/5`, which in prefix notation, would be written as `/*-+ 1 2 3 4 5`. In Pyth, float division is `c` instead of `/`, so it becomes `c*-+ 1 2 3 4 5`. Also, in Pyth, `-100` is written as `_100` instead. Therefore, for the third test case, which is `((((((((-8+50)-3)*3)/-123)^4)+17)-99)*13)`, it becomes: `*-+^c*-+ _8 50 3 3 _123 4 17 99 13`. ``` .v+>tlQ*lQ"^c*-+":jdQ\-\_ jdQ Join input by space. : \-\_ Replace "-" with "_". >tlQ*lQ"^c*-+" Generate the string "...^c*-+" of suitable length. + Join the two strings above. .v Evaluate as a Pyth expression. ``` ## History * 33 bytes: [`v:P+*lQ\(ssV+R\)Q*"+-*/p"lQ\p"**"`](https://codegolf.stackexchange.com/revisions/82774/1) * 27 bytes: [`.vs+_XUtQUQ"+-*c^"m:+;d\-\_`](https://codegolf.stackexchange.com/revisions/82774/2) * 26 bytes: [`.vs+_XUtQUQ"+-*c^":jdQ\-\_`](https://codegolf.stackexchange.com/revisions/82774/4) [Answer] ## Actually, 23 bytes ``` ;l"+-*/ⁿ"*@R':j':+'?o+ƒ ``` [Try it online!](http://actually.tryitonline.net/#code=O2wiKy0qL-KBvyIqQFInOmonOisnP28rxpI&input=MSwyLDMsNCw1) Actually uses postfix notation for mathematics, and operators that only ever take two arguments (such as the operators for addition, subtraction, multiplication, division, and exponentiation) do nothing when there is only one element on the stack. Thus, turning the input into Actually code is as simple as reversing the input, formatting it as numerics, and appending the operations. Then, the resultant code can be executed, giving the desired output. ## Explanation: ``` ;l"+-*/ⁿ"*@R':j':+'?o+ƒ ;l"+-*/ⁿ"* repeat the operations a number of times equal to the length of the input (since extraneous operations will be NOPs, there's no harm in overshooting) @R reverse the input ':j join on ":" (make a string, inserting ":" between every pair of elements in the list) ':+ prepend a ":" (for the first numeric literal) '?o append a "?" (this keeps the poor numeric parsing from trying to gobble up the first + as part of the numeric literal, since ? isn't interpreted as part of the literal, and is a NOP) + append the operations string ƒ cast as a function and call it ``` Example of translated code for input `1,2,3,4,5`: ``` :5:4:3:2:1?+-*/ⁿ+-*/ⁿ+-*/ⁿ+-*/ⁿ+-*/ⁿ ``` [Answer] # Julia, ~~53~~ 50 bytes ``` !x=(i=0;foldl((a,b)->(+,-,*,/,^)[i=i%5+1](a,b),x)) ``` [Try it online!](http://julia.tryitonline.net/#code=IXg9KGk9MDtmb2xkbCgoYSxiKS0-KCssLSwqLC8sXilbaT1pJTUrMV0oYSxiKSx4KSkKCmZvciB4IGluIChbMSwyLDMsNCw1XSwgWzUsMTIsMjMsMiw0LDQsMiw2LDddLCBbLTgsNTAsMywzLC0xMjMsNCwxNyw5OSwxM10sIFsyLDIsMiwyLDIsMiwyLDIsMiwyLDIsMiwyLDIsMiwyXSwgWzEsMCwxLDAsMSwwXSwgWy05LC04LC0xXSwgWzAsLTNdLCBbLTk5XSkKICAgIEBwcmludGYoIiUtMzNzIC0-ICVnXG4iLHgsIXgpCmVuZA&input=) [Answer] # J, 40 bytes ``` ^~`(%~)`*`(-~)`+/@(|.@,7#:~#&2)(5-5|4+#) ``` Finds the number of values needed to use a multiple of 5 operators, than pads with the identity values of those operators. In order, `+` is 0, `-` is 0, `*` is 1, `%` is 1, and `^` is 1, which can be a bit value `00111`, or 7 in base 10. Then operates on that list while cycling through operators. ## Usage ``` f =: ^~`(%~)`*`(-~)`+/@(|.@,7#:~#&2)(5-5|4+#) f 1 2 3 4 5 0 f 5 12 23 2 4 4 2 6 7 539 f _8 50 3 3 _123 4 17 99 13 _1055.36 f 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 256 f 1 0 1 0 1 0 1 f _9 _8 _1 _16 f 0 _3 _3 f _99 _99 ``` ## Explanation ``` ^~`(%~)`*`(-~)`+/@(|.@,7#:~#&2)(5-5|4+#) Input: A # Get length of A 4+ Add four to it 5| Take it mod 5 5- Find 5 minus its value, call it x #&2 Create x copies of 2 7#:~ Convert 7 to base 2 and take the last x digits , Append those x digits to the end of A |.@ Reverse it, call it A' ^~ Power, reversed operators %~ Division, reversed operators * Multiplication -~ Subtraction, reversed operators + Addition /@ Insert the previous operations, separated by `, into A' in order and cycle until the end Then evaluate the equation from right-to-left and return ``` [Answer] # Python 2, ~~81~~ ~~67~~ 64 bytes ``` i=10 for n in input():exec'r%s=n'%'*+-*/*'[i::5];i=-~i%5 print r ``` Input is an array of floats. Test it on [Ideone](http://ideone.com/7HKWKV). ### How it works `'*+-*/*'[i::5]` selects every fifth character of the string, starting with the one at index **i**, so this yields `**` if **i = 0**, `+` if **i = 1**, `-` if **i = 2**, `*` if **i = 3** and `/` if **i = 4**. Since the string has length **6**, the expression will yield an empty string if **i > 5**. We initialize the variable **i** to **10**. For each number **n** in the input array, we construct the string `r<op>=n`, which `exec` executes. Initially, **i = 10**, so `<op>` is the empty string, and it initializes **r** with `r+=n`. After each step, we increment **i** modulo **5** with `i=-~i%5`, so the next step will retrieve the proper operator. When all input numbers has been processed, and we print **r**, which holds the desired output. [Answer] # Matlab - 95 91 85 bytes / Octave - 81 bytes Input is in such form: `a = ['1' '2' '3' '4' '5'];`, I hope this is covered by "string representing an array with integers/decimals", else there are 2 num2str needed additionally. Every intermediate result gets printed to console because that saves me some semicolons. `a(1)` is executed so its value is then saved to `ans`. Also of course using `ans` in code is bad practice. ``` b='+-*/^' a(1) for i=2:length(a) ['(',ans,')',b(mod(i-2,5)+1),a(i)] end eval(ans) ``` In Octave, `'+-*/^'(mod(i+2,5)+1)` also works, which saves another 4 bytes, thanks Adám and Luis Mendo: ``` a(1) for i=2:length(a) strcat('(',ans,')','+-*/^'(mod(i-2,5)+1),a(i)) end eval(ans) ``` Changelog: * Removed spaces where possible * added Octave solution * replaced strcat() with [] [Answer] # Mathematica, ~~67~~ ~~66~~ 65 bytes ``` Fold[{+##,#-#2,#2#,#/#2,If[#2==0,1,#^#2]}[[i++~Mod~5+1]]&,i=0;#]& ``` Simple `Fold` with a variable `i` holding the index. [Answer] # CJam, 18 bytes ``` q~{"+-*/#"W):W=~}* ``` Input is an array of floats. [Try it online!](http://cjam.tryitonline.net/#code=cX57IistKi8jIlcpOlc9fn0q&input=Wy04LjAgNTAuMCAzLjAgMy4wIC0xMjMuMCA0LjAgMTcuMCA5OS4wIDEzLjBd) ### How it works ``` q~ Read and evaluate all input. { }* Reduce: "+-*/#" Push the string of operators. W Push W (initially -1). ):W Increment and save in W. = Retrieve the character at that index. ~ Evaluate. ``` [Answer] # [R](https://www.r-project.org/), ~~87 78~~ 70 bytes ``` i=0 Reduce(function(a,j)get(substr("+-*/^",i<<-i%%5+1,i))(a,j),scan()) ``` [Try it online!](https://tio.run/##fU/bCsIwDH3vVxwsg9at2rRmczB/wg8QdE6pDxPc9v0zDnxUDgkhORfymjUhIGIHhoZXmkEBIcpyJwgoUcmBY62024O9cCMchY@EKtQ1KArBkWfeRK6UFvlfaAQuleR6fEuDxL6GJDha3IQge7dYR5mdBC19Tgevjt11ajtzm/p2TM/enIuHvXejGabLML7MKnfr7WlVpKZxKcs4pyJZu7CKoT33xtr55zPzGw "R – Try It Online") [Answer] ## Haskell - 74 ``` f(x:xs)=foldl(\x(o,y)->o x y)x(zip(cycle[(+),(-),(*),(/),flip(^).floor])xs) ``` Test cases: ``` λ> f[1,2,3,4,5] -> 0.0 λ> f[5,12,23,2,4,4,2,6,7] -> 539.0 λ> f[-8,50,3,3,-123,4,17,99,13] -> -1055.356943846277 λ> f [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] -> 256.0 ``` It could probably be shorter; Haskell's support for infinite lists and higher order functions make the direct solution quite pleasant, though. A version of `^ :: Double -> Double -> Double` would be nicer for golfing, but I couldn't find one. Thankfully, I didn't need a full lambda, so pointless style shaved off a few bytes. [Answer] ## PowerShell v2+, 124 bytes ``` param($n)$o=$n[0];if($y=$n.count-1){1..$y|%{$o=if(($x=$i++%5)-4){"$o"+'+-*/'[$x]+$n[$_]|iex}else{[math]::pow($o,$n[$_])}}}$o ``` Long because PowerShell doesn't have a `^` or `**` operator, so we have to account for a separate case and use a .NET call. Takes input `$n` as an array, sets our output `$o` to be the first digit. We then check the `.count` of the array, and so long as it's greater than one we enter the `if`. Otherwise, we skip the `if`. Inside the `if` we loop through the array `1..$y|%{...}` and each iteration we re-set `$o` to a new value, the result of another `if/else` statement. So long as our counter `$i++` isn't modulo-5 equal to 4 (i.e., we're not at the `^` operator), we simply take `$o` and concatenate it with the appropriate symbol `'+-*/'[$x]` and the next number in the input array `$n[$_]`. We pipe that to `iex` (alias for `Invoke-Expression` and similar to `eval`), and that gets re-saved to `$o`. If we're on the `^` operator, we're in the `else`, so we execute a `[math]::Pow()` call, and *that* result gets re-saved back into `$o`. In either case, we simply output `$o` to the pipeline and exit, with output implicit. [Answer] # Rust, 123, 117 bytes Original answer: ``` fn a(v:&[f32])->f32{v.iter().skip(1).enumerate().fold(v[0],|s,(i,&x)|match i%5{0=>s+x,1=>s-x,2=>s*x,3=>s/x,_=>s.powf(x)})} ``` stupid long method names ^^ ahh much better ``` fn f(v:&[f32])->f32{v[1..].iter().zip(0..).fold(v[0],|s,(&x,i)|match i%5{0=>s+x,1=>s-x,2=>s*x,3=>s/x,_=>s.powf(x)})} ``` ungolfed ``` fn f(values : &[f32]) -> f32 { values[1..].iter().zip(0..) .fold(values[0], |state,(&x,i)| match i%5 { 0=>state+x, 1=>state-x, 2=>state*x, 3=>state/x, _=>state.powf(x) } ) } ``` [Answer] # [Perl 6](http://perl6.org), ~~70 68 65~~ 62 bytes ``` ~~{$/=[(|(&[+],&[-],&[\*],&[/],&[\*\*])xx\*)];.reduce: {$/.shift.($^a,$^b)}} {(@\_ Z |(&[+],&[-],&[\*],&[/],&[\*\*])xx\*).flat.reduce: {&^b($^a,$^c)}} {(@\_ Z |(\*+\*,\*-\*,&[\*],\*/\*,&[\*\*])xx\*).flat.reduce: {&^b($^a,$^c)}}~~ {reduce {&^b($^a,$^c)},flat @_ Z |(*+*,*-*,&[*],*/*,&[**])xx*} ``` ### Explanation: ``` -> *@_ { reduce -> $a, &b, $c { b($a,$c) }, flat # flatten list produced from zip zip @_, # input slip( # causes the list of operators to flatten into the xx list # list of 5 infix operators &infix:<+>, &infix:<->, &infix:<*>, &infix:</>, &infix:<**> ) xx * # repeat the list of operators infinitely } ``` Technically `* + *` is a Whatever lambda, but is effectively the same as `&[+]` which is short for `&infix:<+>` the set of subroutines that handle infix numeric addition. I didn't use that for multiplication or exponentiation as the ways to write them like that is at least as long as what I have (`*×*` or `* * *` and `* ** *`) ### Test: Test it on [ideone.com](https://ideone.com/dRHzhx) (after they upgrade to a [Rakudo](https://rakudo.org) version that isn't from a year and a half before the official release of the [Perl 6](http://perl6.org) [spectests](https://github.com/perl6/roast "ROAST: Repository Of All Spec Tests")) ``` #! /usr/bin/env perl6 use v6.c; use Test; my @tests = ( [1,2,3,4,5] => 0, [5,12,23,2,4,4,2,6,7] => 539, [-8,50,3,3,-123,4,17,99,13] => -1055.35694385, # -2982186493/2825761 [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] => 256, [1,0,1,0,1,0] => 1, [-9,-8,-1] => -16, [0,-3] => -3, [-99] => -99, ); plan +@tests; my &code = {reduce {&^b($^a,$^c)},flat @_ Z |(*+*,*-*,&[*],&[/],&[**])xx*} for @tests -> $_ ( :key(@input), :value($expected) ) { is code(@input), $expected, .gist } ``` ``` 1..8 ok 1 - [1 2 3 4 5] => 0 ok 2 - [5 12 23 2 4 4 2 6 7] => 539 ok 3 - [-8 50 3 3 -123 4 17 99 13] => -1055.35694385 ok 4 - [2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2] => 256 ok 5 - [1 0 1 0 1 0] => 1 ok 6 - [-9 -8 -1] => -16 ok 7 - [0 -3] => -3 ok 8 - [-99] => -99 ``` [Answer] # Python 3, ~~88~~ 93 bytes ``` f=lambda x:eval('('*(len(x)-1)+'){}'.join(map(str,x)).format(*['+','-','*','/','**']*len(x))) ``` It started off being much shorter but then operator precedence defeated me and I had to include lots of parenthesis... [Answer] # Oracle PL/SQL, ~~275~~ 254 Bytes ``` declare r number;begin for x in (select n,mod(rownum,5)r from t) loop if r is null then r:=x.n;elsif x.r=2then r:=r+x.n;elsif x.r=3then r:=r-x.n;elsif x.r=4then r:=r*x.n;elsif x.r=0then r:=r/x.n;else r:=r**x.n;end if;end loop;DBMS_OUTPUT.PUT_LINE(r);end; ``` The data must be inserted in a table called `T` with a column `N` of type `NUMBER` Usage: ``` drop table t; create table t (n number); insert into t values (-8); insert into t values (50); insert into t values (3); insert into t values (3); insert into t values (-123); insert into t values (4); insert into t values (17); insert into t values (99); insert into t values (13); declare r number;begin for x in (select n,mod(rownum,5)r from t) loop if r is null then r:=x.n;elsif x.r=2then r:=r+x.n;elsif x.r=3then r:=r-x.n;elsif x.r=4then r:=r*x.n;elsif x.r=0then r:=r/x.n;else r:=r**x.n;end if;end loop;DBMS_OUTPUT.PUT_LINE(r);end; ``` Output: ``` -1055,356943846277162152071601242992595623 ``` ### 275 Bytes version: ``` declare r number;cursor c is select n,mod(rownum,5) r from t;begin for x in c loop if r is null then r:=x.n;else case x.r when 2 then r:=r+x.n;when 3 then r:=r-x.n;when 4 then r:=r*x.n;when 0 then r:=r/x.n;else r:=r**x.n; end case;end if;end loop;DBMS_OUTPUT.PUT_LINE(r);end; ``` [Answer] # Java 8, ~~173~~ ~~172~~ ~~167~~ ~~138~~ ~~137~~ ~~118~~ 113 bytes ``` a->{double r=a[0],t;for(int i=1;i<a.length;r=new double[]{Math.pow(r,t),r+t,r-t,r*t,r/t}[i++%5])t=a[i];return r;} ``` **Explanation:** [Try it here.](https://tio.run/##lVBBbsIwELzzir1USho7JQmURm76A7hwRDm4wYBpcCJnA6pQ3p4uCajqrZZm7bVWMzvjozxLXtXKHLdffVHKpoGl1OY6AdAGld3JQsHq9gTYVu1nqaDwxmaTg/QFTToqQoMSdQErMJBBL/nH9U6wmdxMc4ZiV1mPVEFnkdDvMiyV2eNB2MyoCzxEr0uJh7CuLp5l6DMbILOc6pnqBbuNDoKnee4jiepcWIWtNWBF14sJmahJhEzcvZwrvYUT5fHWaLXZD5bHMOvvBtUprFoMaxphaTwTFt4fJxAxiBkkDGYM5tD5Q9x/cucMIiLHyaAxG0DNK4OFoxJ/o@3TwQeBR/FoKFowSFO6E0e9mLnAUZy@jKz@nq5ZKdAtL48cibSOJ87L0gejm3T9Dw) ``` a->{ // Method with double-array parameter and double return-type double r=a[0], // Result-double, starting at the first item of the input t; // Temp double for(int i=1; // Index-integer, starting at the second item i<a.length; // Loop over the input-array r=new double[]{ // After every iteration, change `r` to: Math.pow(r,t), // If `i%5` is 0: `r^t` r+t, // Else-if `i%5` is 1: `r+t` r-t, // Else-if `i%5` is 2: `r-t` r*t, // Else-if `i%5` is 3: `r*t` r/t}[i++%5]) // Else-if `i%5` is 4: `r/t` // And increase `i` by 1 afterwards with `i++` t=a[i]; // Change `t` to the next item in the array return r;} // Return result-double ``` [Answer] A few tricks can reduce @Willmore´s approach by 23 to 174 bytes (requires php 5.6 or later). The most saving part is removing unneccessary parentheses (-10 bytes). > > function f($a){while(count($a)>1){$l=array\_shift($a);$r=array\_shift($a);array\_unshift($a,($j=$i++%5)?($j==1?$l-$r:($j==2?$l\*$r:($j==3?$l/$r:$l\*\*$r))):$l+$r);}return end($a);} > > > But using the `**` operator instead of `pow()` also allows to use `eval` with an array for the operations; and with a few more tricks ... # PHP >= 5.6, 82 bytes ``` while(--$argc)eval('$x'.['/','**','+','-','*'][$i++?$i%5:2]."=$argv[$i];");echo$x; ``` takes list from command line parameters. Run with `php -nr '<code>'` or [try it online](http://sandbox.onlinephpfunctions.com/code/233f2ac985a4d668abfabc0411a2b48936e6ce63). ## old version, ~~161 157 151 145 144 140 137~~ 117 bytes ``` function f($a){while(count($a)>1)eval('$a[0]=array_shift($a)'.['+','-','*','/','**'][$i++%5].'$a[0];');return$a[0];} ``` The most effective golfing came from writing the intermediate result directly to the first element - after shifting the previous result from the array. **breakdown** ``` function f($a) { while(count($a)>1) // while array has more than one element ... eval('$a[0]=' // future first element := . 'array_shift($a)' // = old first element (removed) . ['+','-','*','/','**'][$i++%5] // (operation) .'$a[0];' // new first element (after shift) ); return$a[0]; // return last remaining element } ``` **test suite** ``` $cases = array ( 0=>[1,2,3,4,5], 539=>[5,12,23,2,4,4,2,6,7], '-1055.356...' => [-8,50,3,3,-123,4,17,99,13], 256 => [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2], 1 => [1,0,1,0,1,0], -16 => [-9,-8,-1], -3 => [0, -3], -99 => [-99] ); echo '<table border=1><tr><th>values</th><th>expected</th><th>actual result</th></tr>'; foreach ($cases as $expect=>$a) { $result=f($a); echo "<tr><td>[", implode(',',$a),"]</td><td>$expect</td><td>$result</td></tr>"; } echo '</table>'; ``` [Answer] # [PHP](https://php.net/), ~~135~~ 130 bytes Thanks @titus, -5 bytes, plus 0 case fix! ``` function f($z){return array_reduce($z,function($c,$x)use(&$i){eval('$c'.['/','**','+','-','*'][$i++?$i%5:5].'=$x;');return$c;});}; ``` [Try it online!](https://tio.run/##fZDfT4MwEMef17/islRLxzEHDCdW3JOJDybunTQL6UogmUD4YaYLfzsrynw0d9/L966fXJtWWTU8bStT065QbV4WkFr0m59r3XZ1AUldJ1/7Wh86pc0cr5RFFdIT7xpt3dKcn/VncrQYVWwZszuGbLEwxTZyxobJmOa2vaX5TfAYyCWL6EkwLn4voUr0XPRiILTVTdtABDGZxRAguB6C5xshrH/SmHuEDUgcCecBgxX6JhzXYGt0NxiG6PrTuYf/xkS5uMJJ170hmtWO@9eGIIkUhKRlrROVWTC9NGmMAw5nMtMqK4HFwBDyj@pYHrQ1epMjgTAHCdEzzNF88DTave72L@9vgvRkuAA "PHP – Try It Online") Less golfy: ``` function f( $t ) { return array_reduce( $t, function( $c, $x ) use( &$i ) { eval('$c'.['/','**','+','-','*'][$i++?$i%5:5].'=$x;'); return $c; } ); }; ``` Was really rooting for array\_reduce() to work for this, but requires too many chars to beat the current lowest PHP score. Posting it anyway in case anyone has any suggestions! [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 68 bytes ``` hI,?bL,1:+:-:*:/:^b:L:I{bhv?t.|[O:L:I]h$(P,LbM,OhA,Lh:Ir:A&:M:Pr&.}. ``` That's long… but it uses no evaluation predicate. ### Explanation * Main predicate ``` hI, Unify I with the first element of the input ?bL, L is the input minus the first element 1:+:-:*:/:^b Construct the list of predicates [+:-:*:/:^] :L:I{...}. Call predicate 1 with [[+:-:*:/:^]:L:I] as input ``` * Predicate 1 ``` bhv?t. If the second element of Input is empty (i.e. L), unify Output with the last element of Input | Or [O:L:I] Input = [O:L:I] h$(P, P is O circularly permutated to the left LbM, M is L minus the first element OhA, A is the first element of O Lh:Ir:A& Call predicate A on [I:First element of L] :M:Pr&. Call predicate 1 recursively with P:M: ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~29~~ 27 [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") Anomymous tacit prefix function. Note that `*` is exponentiation in APL. ``` ≢{⍎3↓⍕⌽⍵,¨⍨⍺⍴'+-×÷*',¨'⍨'}⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HnoupHvX3Gj9omP@qd@qhn76PerTqHVjzqBaJdj3q3qGvrHp5@eLuWOlBQHSiqXvuoa9H/tEdtE4C6HvVN9fR/1NV8aD1Q/0QgLzjIGUiGeHgG/09TMNQx0jHWMdEx5UpTMNUxNNIxMgaKmAChkY6ZjjlQ9NB6Cx1TA6AiY51D6w2NQIoNzXUsLXUMjYGyQA34IBfIBgMdKAabZqkDMhFoFJBnAKSNIaKWAA "APL (Dyalog Unicode) – Try It Online") Because APL executes right to left, we can just reverse the order of arguments of the inserted operations and reverse the entire expression. Postfix `⍨` reverses arguments. After doing a perfect shuffle of numbers and operations, we only just need to reverse, flatten, and evaluate: `≢{`…`}⊢` call the following function with count of and actual numbers as `⍺` and `⍵`:  `'⍨'` this character  `'+-×÷*',¨` prepend each of these characters to that; `["+⍨","-⍨","×⍨","÷⍨","*⍨"]`  `⍺⍴` use the left argument (count of numbers) to cyclically **r**eshape that  `⌽` reverse  `⍕` format as flat string  `3↓` drop leading 3 characters (a space and a symbol and `⍨`)  `⍎` execute as APL code [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 bytes ``` r@[XY]r"p+-*/"gZ ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=ckBbWFldciJwKy0qLyJnWg==&input=Wy04LDUwLDMsMywtMTIzLDQsMTcsOTksMTNd) Explanation: ``` r@ #Reduce the input list: "p+-*/" # The list of functions to apply (offset by one due to the behavior of Z) gZ # Choose the one at the current index, wrapping [ ]r # Apply that function to: X # The result of the previous step Y # and the current number #Implicitly return the result of the final step ``` [Answer] # x86-16 + 8087 FPU, 65 bytes ``` 00000000: 9bdf 04ad 499b de04 ad49 e334 9bde 24ad ....I....I.4..$. 00000010: 49e3 2d9b de0c ad49 e326 9bde 34ad 49e3 I.-....I.&..4.I. 00000020: 1fad 919b d9e8 85c9 7413 9c7f 02f7 d99b ........t....... 00000030: d8c9 e2fb 9d7d 069b d9e8 9bd8 f191 e2c5 .....}.......... 00000040: c3 . ``` Callable function: input array at `DS:SI`, length in `CX`. Output to `ST` top 8087 register stack. Listing: ``` 9B DF 04 FILD WORD PTR [SI] ; load first item to 8087 stack AD LODSW 49 DEC CX CALC: ; Add 9B DE 04 FIADD WORD PTR [SI] ; add AD LODSW ; SI = next input 49 DEC CX ; decrement counter E3 34 JCXZ WOMI_DONE ; exit if end of input array ; Subtract 9B DE 24 FISUB WORD PTR [SI] ; subtract AD LODSW ; SI = next input 49 DEC CX E3 2D JCXZ WOMI_DONE ; Multiply 9B DE 0C FIMUL WORD PTR [SI] ; multiply AD LODSW ; SI = next input 49 DEC CX E3 26 JCXZ WOMI_DONE ; Divide 9B DE 34 FIDIV WORD PTR [SI] ; divide AD LODSW ; SI = next input 49 DEC CX E3 1F JCXZ WOMI_DONE ; Exponent AD LODSW ; AX = exponent, SI = next input 91 XCHG AX, CX ; CX = counter for loop (exponent), save CX 9B D9 E8 FLD1 ; load 1 into ST 85 C9 TEST CX, CX ; is exponent pos, neg or 0? 74 13 JZ EXP_DONE ; exit (with value 1) if exponent is 0 9C PUSHF ; save result flags for later 7F 02 JG EXP_REP ; if exp > 1 start calculation F7 D9 NEG CX ; make exponent positive for loop EXP_REP: 9B D8 C9 FMUL ST(0), ST(1) ; multiply ST0 = ST0 * ST1 E2 FB LOOP EXP_REP 9D POPF ; restore sign flag from earlier 7D 06 JGE EXP_DONE ; if exponent was neg, divide 1 by result 9B D9 E8 FLD1 ; push 1 into numerator 9B D8 F1 FDIV ST(0), ST(1) ; ST0 = 1 / ST1 EXP_DONE: 91 XCHG AX, CX ; restore CX E2 C5 LOOP CALC ; if more input, start again WOMI_DONE: C3 RET ``` Sample Output: [![enter image description here](https://i.stack.imgur.com/argHc.png)](https://i.stack.imgur.com/argHc.png) [Answer] # c#, ~~238~~, 202 bytes ``` double d(double[]a){Array.Reverse(a);var s=new Stack<double>(a);int i=0,j;while(s.Count>1){double l=s.Pop(),r=s.Pop();j=i++%5;s.Push(j==0?l+r:j==1?l-r:j==2?l*r:j==3?l/r:Math.Pow(l,r));}return s.Peek();} ``` I didn't see any c# solution so I will give one. This is my first codegolf. I started writing in c# ["two months ago"](https://github.com/spookiecookie/NaturalLanguageDateTime/commit/7a74025562947fb8a784ac2ecdf2f9181782741a "Two months ago Natural Language Date Time parse") (though I know Java to some extent). It uses **Stack** [![Try online!](https://i.stack.imgur.com/X1Fva.png)](http://ideone.com/5uYmc0) **Ungolfed and test cases** ``` using System; using System.Collections.Generic; class M { double d(double[]a) { Array.Reverse(a); var s = new Stack<double>(a); int i=0,j; while (s.Count>1) { double l=s.Pop(),r=s.Pop(); j=i++%5; s.Push(j==0?l+r:j==1?l-r:j==2?l*r:j==3?l/r:Math.Pow(l, r)); } return s.Peek(); } public static void Main() { int[][] a = new int[][]{ new int[]{1,2,3,4,5}, new int[]{5,12,23,2,4,4,2,6,7}, new int[]{-8,50,3,3,-123,4,17,99,13}, new int[]{2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2}, new int[]{1,0,1,0,1,0}, new int[]{-9,-8,-1}, new int[]{0,-3}, new int[]{-99} }; for (int i = 0; i < a.Length; i++) { Console.WriteLine(new M().d(Array.ConvertAll(a[i], e => Convert.ToDouble(e)))); } Console.ReadKey(); } } ``` **Output:** ``` 0 539 -1055,35694384628 256 1 -16 -3 -99 ``` [Answer] # PHP, ~~206~~,~~198~~,197 bytes ``` function f($a){while(count($a)>1){$l=array_shift($a);$r=array_shift($a);array_unshift($a,($j=$i++%5)==0?($l+$r):($j==1?($l-$r):($j==2?($l*$r):($j==3?($l/$r):(pow($l,$r))))));}return array_pop($a);} ``` [![Try online!](https://i.stack.imgur.com/X1Fva.png)](http://ideone.com/rKGyUG) **Ungolfed** ``` <?php function f($a) { while(count($a)>1) { $l = array_shift($a); $r = array_shift($a); array_unshift($a,($j=$i++%5)==0?($l+$r):($j==1?($l-$r):($j==2?($l*$r):($j==3?($l/$r):(pow($l,$r)))))); } return array_pop($a); } echo f([1,2,3,4,5])."\n"; echo f([5,12,23,2,4,4,2,6,7])."\n"; echo f([-8,50,3,3,-123,4,17,99,13])."\n"; echo f([2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2])."\n"; echo f([1,0,1,0,1,0])."\n"; echo f([-9,-8,-1])."\n"; echo f([0,-3])."\n"; echo f([-99])."\n"; ``` In PHP, logic similar to my c# [answer](https://codegolf.stackexchange.com/a/83043/55472) (**202 bytes**) :) . ]
[Question] [ [IUPAC](https://en.wikipedia.org/wiki/International_Union_of_Pure_and_Applied_Chemistry) in their insufferable wisdom have created a [systematic element name](https://en.wikipedia.org/wiki/Systematic_element_name) for any newly created element. This is the temporary name of an element until they finally make up their minds about an actual name. It works like so: each digit of an element number is assigned a prefix based on its value. The prefixes are concatenated with ‘ium’ at the end. When this is done and if you get double i’s (ii) or triple n’s (nnn), replace them with single i’s and double n’s. The symbol for the element is the first letter of each prefix used concatenated and result capitalized. The prefixes used are below. ``` 0 nil 5 pent 1 un 6 hex 2 bi 7 sept 3 tri 8 oct 4 quad 9 enn ``` So for this golf, your code needs to generate both the element name and its symbol for a given positive integer. So if your code was given 137, it should print to stdout or return both `untriseptium` and `Uts`. It should be valid from at least 118 to [558](https://oeis.org/A018227). Any higher is valid if it doesn't increase your code's length. Python example showing the method: ``` def elename(n): '''Return name and symbol of new element for given element number.''' prefixes=['nil','un','bi','tri','quad','pent','hex','sept','oct','enn'] nmeFixes, symFixes = [], [] while n: # each digit of element number is assigned a prefix n, i = divmod(n, 10) pf = prefixes[i] symFixes.append(pf[0]) # symbol uses only first letter of prefix nmeFixes.append(pf) # loop assembled prefixes in reverse order nmeFixes.reverse() symFixes.reverse() nmeFixes.append('ium') # suffix name = ''.join(nmeFixes) symb = ''.join(symFixes).capitalize() # apply rule about too many n's or i's name = name.replace('nnn','nn') # can happen with -90- name = name.replace('ii','i') # -2ium or -3ium return name, symb ``` --- [Eric Towers](https://codegolf.stackexchange.com/a/60246/34315) wins with cadmium bytes! [Answer] # Python 3, Unhexseptium (167) bytes ``` h=x='';r=str.replace for i in input():s=r('nubtqphsoeinirueeecnl ianxptn dt t'[int(i)::10],' ','');h+=s;x+=s[0] print(r(r(h+'ium\n','ii','i'),'nnn','nn')+x.title()) ``` [These are the results when the program is run on every number from 1 to 999 (inclusive)](http://pastebin.com/raw.php?i=Azz7XP7R) [Answer] ## Mathematica 10.1, indium (49) cadmium (48) This solution uses a built-in library of element properties, including IUPAC names and abbreviations. (I haven't seen this as a technique to be avoided in Golf. It seems to be encouraged. But this might be on (perhaps over) the edge of acceptable -- Mathematica implements this library (and many others) by downloading data from Wolfram's servers the first time you use it (and I presume checks for updates occasionally).) ``` f=ElementData@@@{{#,"Abbreviation"},{#,"Name"}}& (* Improved by @user5254 from f[n_]:=ElementData[n,#]&/@{"Abbreviation","Name"} *) f[48] (* {"Cd", "cadmium"} *) f[118] (* {"Uuo", "ununoctium"} *) f[122] (* {"Ubb", "unbibium"} *) f[190] (* {"Uen", "unennilium"} *) f[558] (* {"Ppo", "pentpentoctium"} *) f[10^100-1] (* {"Eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "ennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennennium"} *) ``` How would this compare to using elements.py or periodictable.py in Python? Edit: Months later: Noticed I had typo'ed the abbreviation output for 122. I've re-run the code and verified that I made this error, not Mathematica. [Answer] # [Pip](http://github.com/dloscutoff/pip), ~~Thorium~~ ~~Actinium~~ Radon (86) *(Don't inhale this entry, it'll give you lung cancer.)* ``` P(aR,tY"nil un bi tri quad pent hex sept oct enn"^s)."ium"R`ii|nnn`_@>1Yy@_@0MaUC:y@0y ``` Takes the element number as a command-line argument and outputs the name & abbreviation on separate lines. Explanation (somewhat ungolfed): ``` Y"nil un bi tri quad pent hex sept oct enn"^s Build list of prefixes & store in y ,t Range(10) (aR y) Replace each digit in input with corresponding element in prefix list ."ium" Append "ium" R`ii|nnn`_@>1 Reduce too-long runs of letters P Print {y@a@0}Ma For each digit in input, get first character of corresponding prefix Y Store that list in y UC:y@0 Uppercase the first item of y in place y Print y (items concatenated) ``` The `ii` and `nnn` handling uses a regex replacement with a callback function (added in the most recent version of Pip): for every match of `ii|nnn`, take all but the first character and use as a replacement. [Answer] # GNU sed, 171 (unseptunium) ``` s/0/Nil/g s/1/Un/g s/2/Bi/g s/3/Tri/g s/4/Quad/g s/5/Pent/g s/6/Hex/g s/7/Sept/g s/8/Oct/g s/9/Enn/g s/$/ium/ h s/[a-z]//g G s/./\L&/g s/./\U&/ s/\n/ / s/ii/i/g s/nnn/nn/g ``` I assume it doesn't matter what order the name and symbol are returned in. Here, symbol comes first: ``` $ seq 180 190 | sed -f iupac.sed Uon unoctnilium Uou unoctunium Uob unoctbium Uot unocttrium Uoq unoctquadium Uop unoctpentium Uoh unocthexium Uos unoctseptium Uoo unoctoctium Uoe unoctennium Uen unennilium $ ``` [Answer] ## Mathematica, unhexunium ~~163~~ 161 bytes *now capitalises symbol* This is Mathematica without the built-in `ElementData`. ``` f=StringReplace[##<>"ium, "<>{ToUpperCase@#1,##2}~StringTake~1&@@ToString/@nil[un,bi,tri,quad,pent,hex,sept,oct,enn][[IntegerDigits@#]],{"ii"->"i","nnn"->"nn"}]& ``` Test on 10 random numbers: ``` # -> f[#]& /@ RandomInteger[{118, 558}, 10] // ColumnForm 155->unpentpentium, Upp 338->tritrioctium, Tto 477->quadseptseptium, Qss 261->bihexunium, Bhu 158->unpentoctium, Upo 164->unhexquadium, Uhq 266->bihexhexium, Bhh 331->tritriunium, Ttu 404->quadnilquadium, Qnq 389->trioctennium, Toe ``` [Answer] # JavaScript (ES6) 164 (unhexquadium) ~~171~~ The capitalization is the tricky part. (Test in FireFox) **Edit** 3 bytes saved thx user2786485 ``` f=n=>[([...n+(l='')].map(c=>(c='nil,un,bi,tri,quad,pent,hex,sept,oct,enn'.split`,`[c],n=l?n+c[0]:c[0].toUpperCase(),l+=c)),l+'ium').replace(/i(i)|n(nn)/g,'$1$2'),n] function test() { O.innerHTML=f(+I.value) } test() for(o='',i=99;i++<999;)o+=i+' '+f(i)+'\n';P.innerHTML=o ``` ``` <input id=I onchange="test()" value="164"><span id=O></span><pre id=P></pre> ``` [Answer] # Ruby - ~~163~~ ~~156~~ ~~147~~ ~~143~~ 134 (Untriquadium) bytes ``` o=u='';gets.bytes{|c|k=%w[Nil un bI trI quad pent hex sept oct enN Ium][c%48];o+=k;u+=k[0]};puts o.tr_s('IN','in'),u[0..-2].capitalize ``` I'm hoping to golf this way down Edit: Thanks for @steveverrill for shaving off 9 bytes! Edit2: Thanks for @steveverrill again for another 4 bytes! (Really clever solution!) [Answer] # Pyth, 67 bytes (Hol­mium) ``` rshMJ@Lcs@LGjC"]ß!âÿeóÑiSÑA¼R¬HE"24\fjQT3-"ium"epj"nn"csJ*\n3 ``` Try it online in the [Pyth Compiler/Executor](https://goo.gl/HIZ4c2). ### How it works ``` jC"…"24 Convert the string from base 256 to base 24. s@LG Select the letter that corresponds to each digit. c \f Split at 'f'. @L jQT Select the chunk that corresponds to each input digit. J Save in J. shM Form a string of the first letters of the chunks. r 3 Capitalize the first character. Print. (implicit) csJ*\n3 Split the flattened J at "nnn". j"nn" Join, separating by "nn". p Print. -"ium"e Remove the last character ('i'?) from "ium". Print. (implicit) ``` [Answer] # CJam, ~~74~~ ~~72~~ ~~71~~ ~~70~~ 69 bytes (Thulium) ``` r:i"ؾaÈÁaÎE<Ä+&:¬úD±"380b24b'af+)/f=_:c(euoS@s'n3*/"nn"*)"ium"| ``` Note that the code contains unprintable characters. *Thanks to @Sp3000 for pointing out an error in my initial revision and suggesting the `)/` approach.* Try it online in the [CJam interpreter:](http://cjam.aditsu.net/#code=r%3Ai%22%0E%C3%98%C2%BEa%C3%88%C2%90%C3%81%C2%9Da%C3%8E%1DE%3C%0B%C3%84%2B%26%3A%C2%AC%C3%BAD%C2%B1%22380b24b'af%2B)%2Ff%3D_%3Ac(euoS%40s'n3*%2F%22nn%22*)%22ium%22%7C&input=558). ### How it works ``` r:i e# Read a token and push the array of its character codes. "…" e# Push a string of unprintable characters. 380b24b e# Convert it from base 380 to base 24. 'af+ e# Add the character 'a' to each base-24 digit. e# This pushes "bijtrijquadjpentjhexjseptjoctjennjniljunj". )/ e# Pop the last character and split the string at the remaining occurrences. f= e# For each character code in the input, select the correspoding chunk. _:c e# Push a copy and cast each string to character. (euo e# Shift out the first character, convert to uppercase, and print. S@ e# Push a space and rotate the array of string on top of it. s e# Flatten the array of string. 'n3*/ e# Split at occurrences of "nnn". "nn"* e# Join, using "nn" as separator. )"ium"| e# Pop the last character and perform setwise union with "ium". e# If the last character is, e.g., 't', this pushes "tium". e# If the last character is 'i', this pushes "ium". ``` [Answer] # JavaScript (ES6), ~~210~~ 202 Bytes (~~Biunnilium~~ Binilbium) Minus octium (8) bytes, thanks to @edc65! ~~130 159 147 Bytes (Untrinilium Unpentennium Unquadseptium)~~ ``` f=z=>(c=(b=(z+"").split``.map(x=>"nil.un.bi.tri.quad.pent.hex.sept.oct.enn".split`.`[+x])).join``.replace(/nnn/g,"n"))+(c[c.length-1]!="i"?"i":"")+"um,"+(a=b.map(x=>x[0])).shift().toUpperCase()+a.join`` ``` Input like `f(324)`. Ugh, I felt so golf-y. [Answer] # TI-BASIC, ~~223~~ 218 bytes ``` Input N "nil un bi tri quadpenthex septoct enn→Str4 "int(10fPart(N/10^(X→Y₁ "sub(Str4,1+4Y₁,int(3fPart(e^(Y₁)1.5154)+2^not(X=2 and .9=fPart(N%) or X=1 and 1=int(5fPart(.1N→Y₂ "ium,"+sub("UBTQP",int(N%),1 For(X,1,3 Y₂+Ans+sub(Y₂(3-X),1,1 End sub(Ans,1,length(Ans)-1 ``` Element number N can only have a triple "n" if it ends in 90, and can only have a double-"i" if the last digit is 2 or 3. We use math to check those cases. The magic number `1.5154`, which stores the length of each prefix, was found using a Python script to search all decimals of length ≤7 using the functions `cosh(`, `cos(`, and `e^(`. Not done golfing yet, but TI-BASIC's two-byte lowercase letters and lack of string manipulation commands, as always, will hurt this program's score. [Answer] # Matlab, 170 (Unseptnilium) Works on all inputs you can throw at it, from `nilium` up to, well as far as you care to go. I got to `ennennennennennennennennennennennennennennennennennennennennennennium` before I gave up with pressing the 9 key. ``` l=['nubtqphsoe';'inirueeecn';'l ianxptn';' dt t '];i=input('','s')-47;s=l(1,i);s(1)=s(1)-32;a=l(:,i);disp([strrep(strrep([a(a>32)' 'ium '],'nnn','nn'),'ii','i') s]); ``` And an explanation: ``` %Create a 2D array of the prefixes transposed l=['nubtqphsoe';'inirueeecn';'l ianxptn';' dt t ']; %Grab the input number i=input('','s') %Request the input and convert to string -47; %Convert from ASCII into an array of indecies (1 indexed) %Generate the short form s=l(1,i); %Capitalise first letter in short form s(1)=s(1)-32; %Extract required prefixes for long form a=l(:,i); %Now the fun bit: a(a>32)' %Combine the prefixes removing spaces and transpose into a string [ 'ium '] %Append 'ium ' to the string (the space is to separate the short form) strrep( ,'nnn','nn') %Replace 'nnn' with 'nn' strrep( ,'ii','i') %Replace 'ii' with 'i' disp([ s]); %And display both full and short form strings together ``` [Answer] # Retina, ~~206~~ ~~196~~ ~~186~~ 179 (Unseptennium) bytes ([Try it online](http://retina.tryitonline.net/#code=VGBkYG51YnRxXHBcaHNcb2UKLisKJCYsICQmCig_PD0sLipuKQppbAooPzw9LC4qZSluPwpubgooPzw9LC4qdSkKbgooPzw9LC4qYikKaQooPzw9LC4qdCkKcmkKKD88PSwuKnEpCnVhZAooPzw9LC4qcCkKZW50Cig_PD0sLipoKQpleAooPzw9LC4qcykKZXB0Cig_PD0sLipvKQpjdApyYGk_JAppdW0KVGBsYExgXi4&input=MDEyMzQ1Njc4OTAy)) Thanks to @MartinBüttner (<https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner>) for teaching me this language. Thanks to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for chopping off 7 bytes. ``` T`d`nubtq\p\hs\oe .+ $&, $& (?<=,.*n) il (?<=,.*e)n? nn (?<=,.*u) n (?<=,.*b) i (?<=,.*t) ri (?<=,.*q) uad (?<=,.*p) ent (?<=,.*h) ex (?<=,.*s) ept (?<=,.*o) ct r`i?$ ium T`l`L`^. ``` Ueh-byte version: [here](http://retina.tryitonline.net/#code=VGBkYG51YnRxXHBcaHNcb2UKLisKJCYsICQmCig_PD0sLiopbgpuaWwKKD88PSwuKillbj8KZW5uCig_PD0sLiopdQp1bgooPzw9LC4qKWIKYmkKKD88PSwuKil0CnRyaQooPzw9LC4qKXEKcXVhZAooPzw9LC4qKXAKcGVudAooPzw9LC4qKWgKaGV4Cig_PD0sLiopcwpzZXB0Cig_PD0sLiopbwpvY3QKKC4rKWl8KC4rKQokMWl1bQpUYGxgTGBeLg&input=MDEyMzQ1Njc4OTAy) Bnh-byte version: [here](http://retina.tryitonline.net/#code=VGBkYG51YnRxXHBcaHNcb2UKKC4rKQokMSwgJDEKKD88PSwuKiluCm5pbAooPzw9LC4qKWUKZW5uCig_PD0sLiopdQp1bgooPzw9LC4qKWIKYmkKKD88PSwuKil0CnRyaQooPzw9LC4qKXEKcXVhZAooPzw9LC4qKXAKcGVudAooPzw9LC4qKWgKaGV4Cig_PD0sLiopcwpzZXB0Cig_PD0sLiopbwpvY3QKKD88PSwuKilubm4Kbm4KKC4rKWkKJDFpdW0KVGBsYExgXi4&input=MDEyMzQ1Njc4OTAy) [Answer] # CJam, 95 bytes ``` liAbA,"nil un bi tri quad pent hex sept oct enn"S/er_:c(eu\+_1>"en"={\W"il"t\}&S@:+)_'i=!*"ium" ``` [Try it online](http://cjam.aditsu.net/#code=liAbA%2C%22nil%20un%20bi%20tri%20quad%20pent%20hex%20sept%20oct%20enn%22S%2Fer_%3Ac(eu%5C%2B_1%3E%22en%22%3D%7B%5CW%22il%22t%5C%7D%26S%40%3A%2B)_'i%3D!*%22ium%22&input=137) This competes in the category "languages without regex, and only using printable characters." ;) Didn't really expect it to be as short as some of the already posted solutions, but I was curious how long it would end up anyway. And since I got it now, I might as well post it. Explanation: ``` li Get input and convert to int. Ab Encode in decimal. A, Build list [0 .. 9]. "..." String with prefixes. S/ Split at spaces. er Transliterate. We now have a list of the prefix for each digit. _:c Copy and take first character of each, for short form. ( Pop off first character. eu Convert it to upper case. \+ Put it back in place. Done with short form. _1> Remove first character. "en"= Compare with "en", corresponding to the 90 special case. { Handle 90 case, replace \ Swap full prefix list to top. W"il"t Replace "nil" by "il" to avoid "nnn". \ Swap short form back to top. }& End of 90 case. S Push space between short form and full name. @ Swap prefix list to top. :+ Concatenate all the prefixes. ) Pop off the last letter. _'i= Compare it with 'i. !* Multiply letter with comparison result. This gets rid of letter if it's 'i. "ium" Add the final part of the output. ``` [Answer] # Python 3, unpentquadium (~~156~~ ~~155~~ 154) bytes ``` n=e="" for c in input():s="nil un bi tri quad pent hex sept oct enn".split()[int(c)];n+=s[c<"1"<"nn"==n[-2:]:];e+=s[0] print(n.strip("i")+"ium",e.title()) ``` Instead of replacing `ii` with `i` we rstrip any `i`s before we tack on the `ium`, since that's the only possible source of double `i`s. Similarly, we strip `n`s by checking for an `enn/nil` case. [Answer] # PHP, 152 ~~153~~ ~~163~~ bytes, unpentbium Well, at least PHP is somewhere around average this time. ``` while(null!=$x=$argv[1][$i++]){$a.=$y=[nil,un,bi,tri,quad,pent,hex,sept,oct,enn][$x];$b.=$y[0];}echo str_replace([ii,nnn],[i,nn],$a.'ium ').ucfirst($b); ``` Runs form command line like: ``` pentium.php 163 ``` Output: ``` unhextrium Uht ``` --- **Ungolfed** ``` $y = array('nil','un','bi','tri','quad','pent','hex','sept','oct','enn'); while (null != ($x = $argv[1][$i++])) { $a .= $y[$x]; $b .= $y[$x][0]; } echo str_replace( array('ii','nnn'), array('i','nn'), $a . 'ium ') .ucfirst($b); ``` --- **Edit** * saved 10 bytes by replacing all (not only one, *duh*) `array()`-initializer with `[]` * saved 1 byte by adding the whitespace along with `'ium '` instead using an extra concatenation `.' '.` [Answer] # Go, 322 Bytes (tribibium) ``` package main import("os" "strings" "fmt") func main(){p,n,s:="nil un bi tri quadpenthex septoct enn ","",make([]byte,0) b:=make([]byte,3) os.Stdin.Read(b) var d byte=32 for _,r:=range b{i:=r-48 n+=p[4*i:4*i+4] s,d=append(s,p[4*i]-d),0} fmt.Printf("%sium %s",strings.NewReplacer(" ","","ii","i","nnn","nn").Replace(n),s)} ``` Reads three characters from STDIN, more are ignored, less result in a crash. So it works for every number between `unnilnilium` and `ennennennium`. [Answer] ## PowerShell, ~~170~~ ~~168~~ 165 (Unhexpentium) ``` -join($a="$input"[0..9]|%{(($x=(-split'Nil Un Bi Tri Quad Pent Hex Sept Oct Enn')["$_"]).ToLower(),$x)[!($y++)]})+'ium'-replace'(nn)n|(i)i','$1$2' -join($a|%{$_[0]}) ``` Fairly straightforward and no surprises here. Except maybe that I solved the capitalization issue by lower-casing everything but the first part and having the individual parts already in title-case. Agrressively inlined by now to avoid losing characters for bare variable assignments. Bonus after the last change: Now works for longer element numbers as well: ``` > echo 1337| powershell -noprofile -file "element.ps1" Untritriseptium Utts ``` [Answer] # C on x86, 192 (Unennbium) ``` int c,s,a[8],x,main(){while((c=getchar()-48)>=0)x="nil\0un\0\0bi\0\0tri\0quadpenthex\0septoct\0enn"+4*c,strncat(a,x+(c<s-8),4),strncat(a+5,x,1),s=c;printf("%s%s %s",a,"ium"+((s&14)==2),a+5);} ``` Reads digits from `stdin` and prints the results to `stdout`. Relies on `sizeof(char*) == sizeof(int)`. Ungolfed version: ``` int c, s, // Current and last digit, initially zero (0-9, not '0'-'9') a[8], // Buffer to write to (type doesn't matter when passed by pointer) x; // Int-pointer into lookup table main() { while ((c = getchar() - 48) >= 0) { // 48 == '0' x = "nil\0un\0\0bi\0\0tri\0quadpenthex\0septoct\0enn" + 4*c; strncat(a, x+(c<s-8), 4); // Write digit, skip first char if c==0 && s==9 strncat(a+5, x, 1); // Write first digit character somewhere else s = c; } printf("%s%s %s", a, "ium"+((s&14)==2), a+5); // Append "ium" (or "um" if s==2||s==3) } ``` [Answer] # Haskell, bipentbium (305 271 269 265 261 259 253 252 bytes) ``` import Data.Char main=getLine>>=putStr.a m=map toLower a n=(r.m$p)++(k.filter isUpper$p)where p=(n>>=(words"Nil Un Bi Tri Quad Pent Hex Sept Oct Enn"!!).digitToInt)++"ium " r('n':'n':'n':x)="nn"++r x r('i':'i':x)='i':r x r(x:z)=x:r z r x=x k(h:t)=h:m t ``` Shaved 34 bytes off thanks to nimi. [Answer] # GNU sed, unhexunium (161 bytes) ``` h y/0123456789/nubtqphsoe/ s/./\u&/ x s/$/ium/ : s/0/nil/ s/1/un/ s/2/bi/ s/3/tri/ s/4/quad/ s/5/pent/ s/6/hex/ s/7/sept/ s/8/oct/ s/9/enn/ s/nnn/nn/ s/ii/i/ t G ``` I generate the symbol first, then stash that into hold space and create the name. A loop is golfier than using `/g` for four or more replacements (we can have only one `ii` and/or one `nnn`, so they don't need to be inside the loop, but it doesn't hurt). Finally, retrieve and append the held symbol. (N.B. I hadn't seen the existing sed answer when I wrote this) ### Test cases These exercise the `ii` and `nnn` special rules: ``` $ seq 100 89 1000 | ./60208.sed unnilnilium Unn unoctennium Uoe biseptoctium Bso trihexseptium Ths quadpenthexium Qph pentquadpentium Pqp hextriquadium Htq septbitrium Sbt octunbium Oub ennilunium Enu ennennilium Een ``` And a ridiculous one, showing how much more this code gives, compared to the physical world: ``` $ ./60208.sed <<<281039817 bioctunniltriennoctunseptium Bounteous ``` [Answer] **T-SQL 329 bytes** ``` creat proc x(@a char(3))as select replace(replace((select a.b as[text()]from(select left(@a,1)a union select substring(@a,2,1)union select right(@a,1))z join(values(0,'nil'),(1,'un'),(2,'bi'),(3,'tri'),(4,'quad'),(5,'pent'),(6,'hex'),(7,'sept'),(8,'oct'),(9,'enn'))a(a,b)on z.a=a.a for xml path(''))+'ium','ii','i'),'nnn','nn') ``` Formatted: ``` create proc x(@a char(3))as select replace(replace( (select a.b as[text()]from ( select left(@a,1)a union select substring(@a,2,1) union select right(@a,1))z join(values(0,'nil'),(1,'un'),(2,'bi'),(3,'tri'),(4,'quad'),(5,'pent'),(6,'hex'),(7,'sept'),(8,'oct'),(9,'enn') )a(a,b)on z.a=a.a for xml path('') )+'ium','ii','i'),'nnn','nn') ``` [Answer] # R, 278 bytes ``` g<-function(x){k<-data.frame(c("nil","un","bi","tri","quad","pent","hex","sept","oct","enn"));row.names(k)<-0:9;n<-unlist(strsplit(as.character(x),""));return(sub("nnn","nn",sub("ii","i",paste(c(as.vector(k[n,]),"ium"," ",sapply(k[n,],function(x)substr(x,1,1))),collapse=""))))} ``` Not the best... but I'm still learning R so I thought I'd post my attempt. Any suggestions to make it better? Now that I think about it it's probably possible to subset on the nth-1 row rather than wasting space creating row names. ### Example usage ``` > g(118) [1] "ununoctium uuo" > g(999) [1] "ennennennium eee" > g(558) [1] "pentpentoctium ppo" > g(118) [1] "ununoctium uuo" > g(90) [1] "ennilium en" > g(2) [1] "bium b" ``` ### Ungolfed ``` g <- function(x) { k <- data.frame(c("nil","un","bi","tri","quad","pent","hex","sept","oct","enn")) row.names(k) <- 0:9 n <- unlist(strsplit(as.character(x),"")) return( sub("nnn", "nn", sub("ii", "i", paste(c(as.vector(k[n,]),"ium"," ", sapply(k[n, ],function(x)substr(x,1,1))), collapse = "")))) } ``` 1. Create a key, convert to data frame, and set as the variable `k` 2. Set the row names as `0-9` for easy identification 3. Take the input `x`, convert to character, split it up (e.g. 137 to "1" "3" "7") 4. Subset `k` based on the split number input and return the entries 5. Concatenate them together and add `-ium` 6. Also subset `k` using substring to pull the first letter of the matches. This is concatenated to the output of step 5 with a blank space between them 7. Use `sub()` to replace the `nnn` and `ii` patterns [Answer] # Javascript - 169 bytes ``` n=>eval(`q='nil0un0bi0tri0quad0pent0hex0sept0oct0enn'.split(0);for(b of (_=$='')+n){c=q[b];$+=q[b];_+=(_?c:c.toUpperCase())[0]}$.replace(/i$()|n(nn)/g,'$1$2')+'ium '+_`) ``` Bizarrely, my attempts to use map were *longer* than the for loop. **EDIT:** Oops, forgot to check the date. [Answer] # PHP, 131+1 bytes (untriunium) still awfully long: ``` for(;~$c=$argn[$i];print$i++?$n[0]:$n&_)$r.=$n=[nil,un,bi,tri,quad,pent,hex,sept,oct,enn][$c];echo strtr(_.$r.ium,[ii=>i,nnn=>nn]); ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/06667b7eb485eac78dbc555e803afffd8201f2f1). [Answer] # Perl, 109 (Unnilennium) bytes 108 code + 1 switch ``` perl -pe 's!.!qw{Nil Un Bi Tri Quad Pent Hex Sept Oct Enn}[$&]!ge;s!nnN!nN!g;s!i?$!ium!;$_=lc$_.y!a-z!!dr;s!\b.!\U$&!g' ``` Takes input from STDIN as one number per line. [Answer] **Java 8 216Bytes** ``` String f(int i){ String[] s = {"nil","un","bi","tri","quad","pent","hex","sept","oct","enn"}; return ((""+i).chars().mapToObj(y->s[y-48]).collect(Collectors.joining())+"ium").replace("ii","i").replace("nnn","n"); } ``` [Answer] ## C# ~~229 (Bibiennium)~~ 198 unennoctium bytes The "n-'0'" trick is a way to convert from ascii to int. Char 9 = ASCII 57. Char 0 = ASCII 48, so 57-48 = 9. ~~static private string ToText(int v) { return (string.Join("",v.ToString().Select((char n)=>"nil un bi tri quad pent hex sept oct enn".Split()[n-'0']))+"ium").Replace("nnn","nn").Replace("ii","i")+" "+string.Join("",v.ToString().Select((char n)=>"nubtqphsoe"[n-'0'])); }~~ ``` static private string ToText(int v) { string u,r="",t=""; return v.ToString().Select((char n)=>{u="nil un bi tri quad pent hex sept oct enn".Split()[n-48];r+=u;t+=u[0];return r;}).Last()+"ium".Replace("nnn","nn").Replace("ii","i")+" "+t; } ``` This approach takes the int, converts to a string, then performs a LINQ select of characters that fires off a lambda. The lambda generates an array on the fly (less characters than defining it) by splitting the string of prefixes. It then pulls the index of the prefix to use by looking at the current character's int value (the n-'0' trick mentioned above). All that is wrapped in a string.Join which concatenates all of the LINQ results together. Tack on the "ium", then a couple of .Replace statements at the end to clean up the nnn' and ii's. Added the missing symbol output. I think there's a more efficient way by merging the two LINQs, but it's way to late to keep poking at it. [Answer] # C, ~~210~~ ~~204~~ unennennium (199) bytes This requires ASCII as the runtime character set. ``` f(char*n,char*s){char*c="NilUnBiTriQuadPentHexSeptOctEnn",*p,*o=n,i,j;for(;*n;){for(j=i=*n-48,p=c;*p&32||i--;++p);for(*s++=*n=*p+32;*++p&32;)*s++=*p;s-=*n++-j==39||j/2-*n==1;}*o-=32;strcpy(s,"ium");} ``` I did try a recursive solution (which avoids the need for `p` and `o`) but that turned out longer. I'm particularly proud/ashamed of the matcher for the regexp `90|[23]$`, which relies on `9` and `0` being the furthest separated digits (and therefore the only pair that differ by 9 - the `39` in the code is a consequence of `j` being an integer value and `*n` still an ASCII character) and that `2` and `3` differ only in the last bit, so dividing by 2 conflates them. ### Expanded code: ``` void f(char *n, /* input number / output symbol */ char *s) /* output name */ { char *c = "NilUnBiTriQuadPentHexSeptOctEnn", /* digit names */ *p, *o = n, /* first char of input */ i, j; /* current digit value */ for (;*n;) { j = i = *n-48; for (p=c; *p&32 || i--; ++p) /* Find the i'th capital letter in c */ ; for (*s++ = *n++ = *p++ + 32; *p&32; ) /* Downcase and copy following lowercase */ *s++ = *p++; s -= *n-j==39 || j/2-*n==1; /* backup one if 9 is followed by 0, or if 2 or 3 is at end of input */ } *o -= 32; /* Capitalise symbol */ strcpy(s,"ium"); /* Finish name */ } ``` ### Test harness: ``` #include <stdlib.h> #include <stdio.h> #include <string.h> int main(int argc, char **argv) { char buf[1024]; while (*++argv) { f(*argv, buf); printf("%s %s\n", *argv, buf); } return EXIT_SUCCESS; } ``` ]
[Question] [ In this challenge fake marquee text is text that is shown part by part, in a scrolling-like fashion. Some examples: ``` testing 4 t te tes test esti stin ting ing ng g hello 2 h he el ll lo o foobarz 3 f fo foo oob oba bar arz rz z Something a bit longer 10 S So Som Some Somet Someth Somethi Somethin Something Something omething a mething a ething a b thing a bi hing a bit ing a bit ng a bit l g a bit lo a bit lon a bit long bit longe bit longer it longer t longer longer longer onger nger ger er r small 15 s sm sma smal small small small small small small small small small small small mall all ll l aaa 3 a aa aaa aa a brace yourself 6 b br bra brac brace brace race y ace yo ce you e your yours yourse oursel urself rself self elf lf f ``` You have to write a program or a function that takes in two input and prints the output as described above. You may or may not output trailing spaces in your output. This is code-golf so shortest code in bytes wins. If your program is standalone (i.e. when run actually prints the lines) (Input can be hard-coded but easy to change) and sleeps a bit between each line of output you get a -10 bonus. [Answer] # CJam, ~~12~~ 11 bytes *1 byte saved by Dennis.* ``` ,Sf*\f+$zN* ``` I'm making use of "Input can be hard-coded but easy to change": this expects the input to be already on the stack, so you can prepend `"testing" 4` to the above, for instance. [Test it here.](http://cjam.aditsu.net/#code=%22testing%224%0A%2CSf*%5Cf%2BW%25zN*&input=4%0Atesting) ## Explanation Notice that the transpose of the desired output is much simpler: ``` testing testing testing testing ``` So we just need to create `n` lines, prepending `i` spaces for `i` from `n-1` down to `0`. That's what the code does: ``` , e# Turn n into a range [0 1 .. n-1] Sf* e# Turn each i into a string of i spaces. \f+ e# Swap this array with the input string and append it to each of the e# strings of spaces. $ e# Sort the array to have the string with n-1 spaces first. z e# Transpose the grid. N* e# Join the lines with newline characters. ``` ## 19 - 10 = 9? I find the "sleeps a bit between each line" bonus a bit vague and dodgy, but here is a 19 byte version that simply stalls after each line by computing all permutations of the array `[0 1 .. 7]`. In the online interpreter this simply leads to the final result being shown a bit later, but if you use the Java interpreter this will actually print each line after "sleeping a bit": ``` ,Sf*\f+$z{oNo8e!;}/ ``` [Answer] # C, 69 bytes printf magic! ``` f(s,n,i)char*s;{for(i=n;*s;i?i--:s++)printf("%*s%.*s\n",i,"",n-i,s);} ``` Expanded version with some explanation: ``` f(s,n,i)char*s;{ /* s is the string, n is the width of the grid. */ for(i=n; /* i is the number of preceding spaces. */ *s; /* Stop once we reach the end of the string. */ i?i--:s++) /* Decrease the number of spaces, and when there's none left start truncating the string itself. */ printf("%*s /* The first argument is the minimum width to print the string (left padded with spaces) and the second argument is the string to print. We use the empty string just to print the i spaces. */ %.*s /* The third argument is the maximum number of characters from the string (which is the fourth argument) to print. */ \n",i,"",n-i,s); } ``` And here's an example: ``` $ ./marquee stackoverflow 12 s st sta stac stack stacko stackov stackove stackover stackoverf stackoverfl stackoverflo tackoverflow ackoverflow ckoverflow koverflow overflow verflow erflow rflow flow low ow w ``` [Answer] # Pyth, 13 bytes ``` jb.:++K*dQzKQ ``` Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=jb.%3A%2B%2BK*dQzKQ&input=brace%20yourself%0A6&debug=0) ### Explanation ``` implicit: z = input string, Q = input number K*dQ K = " " * Q ++K zK K + z + K .: Q all substrings of length Q jb join by newlines and print ``` [Answer] ## Python 65 63 ``` s=lambda t,s:'\n'.join((' '*s+t)[i:s+i]for i in range(len(t)+s)) ``` This was actually used to write the examples. Baseline solution. ``` >>> print(s("foobarz", 3)) f fo foo oob oba bar arz rz z ``` [Answer] # Javascript (*ES7 Draft*), 61 bytes ``` f=(s,l)=>[x.substr(i,l)for(i in x=' '.repeat(l)+s)].join(` `) ``` ``` <input id="str" value="Some String" /> <input id="num" value="5" /> <button onclick="out.innerHTML=f(str.value, +num.value)">Run</button> <br /><pre id="out"></pre> ``` # Javascript (*ES6*) Hardcoded Inputs, 47 bytes Assuming hard-coded inputs in variables `s` (string) and `l` (length), it can be reduced to **47** bytes printing with an alert for each line: ``` for(i in x=' '.repeat(l)+s)alert(x.substr(i,l)) ``` [Answer] # K, 19 bytes ``` {x#'![1]\(x#" "),y} ``` Tack `x` spaces (`x#" "`) onto the beginning of the string `y`. Then use the "fixed-point scan" form of the operator `\` to create the set of rotated strings. A fixed-point in K stops iterating if the result of applying the function returns a repeated result or if the initial input is revisited. Since `![1]` will rotate a string one step at a time, `![1]\` is a nice idiom for cyclic permutations. Then we just trim the results with `x#'`. A sample run: ``` {x#'![1]\(x#" "),y}[4;"some text"] (" " " s" " so" " som" "some" "ome " "me t" "e te" " tex" "text" "ext " "xt " "t ") ``` [Answer] # J (22) This ended up longer than I anticipated, but I guess it is not too bad. ``` [{."0 1[:]\.(' '#~[),] ``` Fun fact: non of the `[` and `]` are actually matched, or have anything to do with each other. [Answer] # Julia, 75 bytes ``` (s,n)->(n-=1;print(join([(" "^n*s*" "^n)[i:n+i]for i=1:length(s)+n],"\n"))) ``` This creates an unnamed function that accepts a string and integer as input and prints the output. To call it, give it a name, e.g. `f=(s,n)->(...)`. Ungolfed + explanation: ``` function f(s, n) # Decrement n by 1 n -= 1 # Construct the lines as an array using comprehension by repeatedly # extracting subsets of the input string padded with spaces lines = [(" "^n * s * " "^n)[i:n+i] for i = 1:length(s)+n] # Print the array elements separated by a newline print(join(lines, "\n")) end ``` Examples: ``` julia> f("banana", 3) b ba ban ana nan ana na a julia> f("Julia", 6) J Ju Jul Juli Julia Julia ulia lia ia a ``` Note that this solution is 66 bytes if `s` and `n` are assumed to already exist in the program. [Answer] # QBasic, 56 - 10 = 46 This is golfed QBasic--the autoformatter will expand `?` into `PRINT` and add some spaces. Tested with [QB64](http://qb64.net), though there shouldn't be anything in here that won't work with DOS QBasic. ``` s=SPACE$(n)+s FOR i=1TO LEN(s) ?MID$(s,i,n) SLEEP 1 NEXT ``` QBasic generally isn't good with string operations, but there very conveniently *is* a function that returns a given number of spaces! Taking some liberties with "input may be hard-coded," this code expects the variable `s` to be `DIM`'d `AS STRING`, in order to avoid the `$` type suffix, as well as the string being assigned to `s` and the number to `n`. Example preamble: ``` DIM s AS STRING s="string" n=4 ``` Output: ``` s st str stri trin ring ing ng g ``` The top blank row may be eliminated by starting the `FOR` loop at 2 instead of 1. **Bonus:** Adding `CLS` right before `NEXT` for a paltry four bytes turns this into... a *real marquee*! ![Marquee](https://i.stack.imgur.com/fAhdb.gif) I `PRINT CHR$(3)` QBasic. :^D [Answer] # Ruby, 68, 55 bytes ``` a=" "*$*[1].to_i+$*[0]+" ";a.size.times{|b|puts a[b...b+$*[1].to_i]} ``` After an update from @blutorange: ``` a=" "*(z=$*[1].to_i)+$*[0];a.size.times{|b|puts a[b,z]} ``` Output: ``` S So Som Some Somet Someth Somethi Somethin Something Something omething a mething a ething a b thing a bi hing a bit ing a bit ng a bit l g a bit lo a bit lon a bit long bit longe bit longer it longer t longer longer longer onger nger ger er r ``` `ruby marquee.rb "Something a bit longer" 10` First submission so asking for criticism. [Answer] # Haskell, ~~61~~ ~~59~~ 54 bytes ``` m n=unlines.scanr((take n.).(:))[].(replicate n ' '++) ``` Usage example: ``` *Main> putStr $ m 6 "stackoverflow" s st sta stac stack stacko tackov ackove ckover koverf overfl verflo erflow rflow flow low ow w *Main> ``` Edit: an empty line at the beginning / end is allowed [Answer] # Bash, 109 - 10 = 99 bytes I see that in the time it took me to write my solution, I have been soundly beaten. Nevertheless, I spent too long writing it to not post it... Besides which, it has some unique features, like the time between lines printing being user-adjustable based on how much is in the current directory! (Also somewhat inconsistent, depending on how your disk feels) ``` l=${#1};s=$1;for j in `seq 1 $2`;do s=" $s";done;for i in `seq 0 $((l+$2))`;do echo "${s:i:$2}";find 1>2;done ``` Example: ``` cd <some directory in which you own everything recursively> Marquee.sh "Test Case" 4 T Te Tes Test est st C t Ca Cas Case ase se e ``` Ungolfed and commented: ``` l=${#1} #Length of the incoming string s=$1 #Can't reassign to the parameter variables, so give it another name for j in `seq 1 $2`; do s=" $s" # Put on the padding spaces done for i in `seq 0 $((l+$2))`; do #Cut the string and print it. I wish I could lose "padding" that easily! echo "${s:i:$2}" #Format is ${string:index:length}, so always the same # length, with the index moving into the string as the loop advances find 1>2 #Wait "a bit". From ~/, about 6 minutes per line on my junky # computer with a huge home directory. Probably in the <1 sec range for # most people. #This actually has the same character count as sleep(X), but is much # more fun! done ``` I've never really tried this before. Suggestions and comments welcome! [Answer] # Pure Bash, 61 bytes ``` printf -vs %$2s"$1" for((;++i<${#1}+$2;)){ echo "${s:i:$2}" } ``` ### Output: ``` $ ./marquee.sh testing 4 t te tes test esti stin ting ing ng g $ ``` [Answer] # Perl, 50 ``` $c=$" x$^I;$_="$c$_$c";sleep say$1while(/(?<=(.{$^I}))/g) ``` `57` characters `+3` for `-i`, `-n` and `-l`. `-10` characters for the sleep. `-i` is used for the numeric input, which is stored in `$^I`. Basically, we add `i` spaces to the front and end of the input, and then search for every `i` characters and loop through them with `while`. `say` conveniently returns `1` which we can input to `sleep`. ``` echo "testing" | perl -i4 -nlE'$c=$" x$^I;$_="$c$_$c";sleep say$1while(/(?<=(.{$^I}))/g)' ``` [Answer] # POSIX shell, 94 ``` [ $3 ]||set "`printf "%${2}s"`$1" $2 t [ "$1" ]&&printf "%-.${2}s" "$1" " "&&$0 "${1#?}" $2 t ``` I know it looks closer to perl, but this really is shell! The first line adds the necessary leading spaces, only on the first time through the loop. It sets $3 to indicate that it has done so. The second line (N.B. embedded newline) recurses until input is exhausted, printing the first *n* characters of the string, then invoking itself with the first character removed from $1. Tested with Debian `/bin/dash` - sample outputs follow: ./marquee "testing" 4 ``` t te tes test esti stin ting ing ng g ``` ./marquee "Something a bit longer" 10 ``` S So Som Some Somet Someth Somethi Somethin Something Something omething a mething a ething a b thing a bi hing a bit ing a bit ng a bit l g a bit lo a bit lon a bit long bit longe bit longer it longer t longer longer longer onger nger ger er r ``` ./marquee "small" 15 ``` s sm sma smal small small small small small small small small small small small mall all ll l ``` [Answer] # Python 2, 51 bytes / 37 bytes **Without hardcoded input (51 bytes):** ``` def f(s,n): s=" "*n+s while s:print s[:n];s=s[1:] ``` Call like `f("testing", 4)`. **With hardcoded input (37 bytes):** ``` s="testing";n=4 s=" "*n+s while s:print s[:n];s=s[1:] ``` Both versions output an initial line of spaces. [Answer] # Pyth, 12 bytes ``` jb.:X*dyQQzQ ``` [Demonstration.](https://pyth.herokuapp.com/?code=jb.%3AX*dyQQzQ&input=testing%0A4&debug=0) --- # Pyth, 17 - 10 = 7 bytes ``` FN.:X*dyQQzQ&.p9N ``` This version employs a delay between line prints. This can be seen on the command line compiler, which you can get [here](https://github.com/isaacg1/pyth). Run the following: ``` pyth -c 'FN.:X*dyQQzQ&.p9N' <<< 'testing 4' ``` This has a delay of about 0.3 seconds before each print. If you prefer a longer delay, you can use: ``` FN.:X*dyQQzQ&.pTN ``` This has about a 4 second delay. [Answer] # Java, 133 ~~119~~ 115 ``` int i;void f(String s,int n){for(;++i<n;)s=" "+s+" ";for(;i<=s.length();)System.out.println(s.substring(i-n,i++));} ``` Long version: ``` int i; void f(String s, int n) { for(; ++i < n;) s = " " + s + " "; for(; i<=s.length();) System.out.println(s.substring(i-n, i++)); } ``` Padding is applied to the string, and then substrings of the padded string are printed to the console. *-4 bytes thanks to @KevinCruijssen.* [Answer] # Python 2, (52 bytes - 10 = 42) ~~64~~ ~~62~~ ~~60~~ ~~46~~ ~~44~~ (I assumed the line for hard-coded input doesn't add to byte count.) I didn't see a program yet that actually sleeps between printing lines, so I made one that does, since it looks more like a marquee that way. This program is 2 more bytes in Python 3. EDIT: The program now does a computation instead of sleeping. I used `i` in the calculation so that the program doesn't store it as a constant, but must compute it each time. [**Try It Online!**](https://tio.run/##K6gsycjPM/pfbKuem1hUWJqaqm7NlWdrav0/09aAqzwjMydVoTg6UzfPKtaqoCgzr0RDXUFdK0@7WDM60ypPOzPWOlPb1tA6U0vLHIj@/wcA) ``` i=0 while s[i-n:]:print(' '*n+s)[i:n+i];i+=1;i**7**7 ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 3 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` */⤢ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjBBJXVGRjBGJXUyOTIy,i=Zm9vYmFyeiUwQTM_,v=8) Input is string and integer (in either order) separated by a newline. --- Explanation: ``` * | Repeat a b times vertically (a=string input, b=int input) / | Make antidiagonal (add one extra space to each line bottom up) ⤢ | Transpose (reflect along top-left to bottom-right diagonal) ``` [Answer] # Matlab, 95 As always, it is a manipulation of matrices. The core here is the command `spdiags` which lets you create diagonal matrices very easily. ``` t=input(''); n=numel(t); k=input(''); flipud(char(full(spdiags(repmat(t,n+k-1,1),1-n:0,n+k-1,k)))) ``` With hardcoding 71 bytes (expected string stored in `t` and the number in `k`) ``` n=numel(t);flipud(char(full(spdiags(repmat(t,n+k-1,1),1-n:0,n+k-1,k)))) ``` [Answer] # APL, 50 - 10 = 40 chars I'm sure it could be shorter. 50 is the length of the program without the two constants. ``` {⍵≡⍬:⍬⋄⎕←↑⍵⋄⎕DL 99⋄∇1↓⍵}⊂[0]⊖s⍴⍨n,¯1+⍴s←'brace yourself',' '⍴⍨n←6 ``` Explanation: ``` ' '⍴⍨n←6 call the number 'n' and make n spaces s←'brace yourself', append them to the string and call it 's' ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ s⍴⍨n,¯1+⍴s make a len(s)-1 by n matrix by repeating s ⊂[0]⊖ reflect the matrix and extract the columns { } pass the list of columns to this function ⍵≡⍬:⍬⋄ return if the list is empty ⎕←↑⍵⋄ print the first column (as a row) ⎕DL 99⋄ wait for 99ms ∇1↓⍵ recurse with the rest of the columns ``` Developed for [ngn APL](https://github.com/ngn/apl) on the terminal. [Answer] # [J](http://jsoftware.com/), ~~15~~ 14 bytes ``` ,.~/@(' '&,~<) ``` [Try it online!](https://tio.run/##y/r/P03B1kpBR69O30FDXUFdTafORpOLKzU5I19BPSM1JydfXSFNwQgqUJJaXJKZlw4SMoEKFZckJmfnl6UWpeXkl4MkDI3@/wcA "J – Try It Online") [Answer] # Powershell - 85 83 bytes It's late, it's not going to win :-) But I thought I'd throw in a Powershell one for completeness: `function m($s,$n){1..$($n+$s.length)|%{-join(" "*$n+$s+" "*$n)[$_-1..$($n+$_-1)]}}` [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 38 bytes ``` L#,b]*ApR1€Ω_32C€*dbR@$BcB]€¦+bU@BcBJn ``` [Try it online!](https://tio.run/##S0xJKSj4/99HWScpVsuxIMjwUdOacyvjjY2cgQytlKQgBxWnZKdYIOfQMu2kUAcgxyvvv0pOYm5SSqKCoZ29nT2X////SiWpxSWZeelK/00A "Add++ – Try It Online") [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `N`, 8 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` L€ṣs+rðƬ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPUwlRTIlODIlQUMlRTElQjklQTNzJTJCciVDMyVCMCVDNiVBQyZmb290ZXI9JmlucHV0PTQlMEElMjJ0ZXN0aW5nJTIyJmZsYWdzPU4=) #### Explanation ``` L€ṣs+rðƬ # Implicit input L€ṣ # Push [" " * 0, " " * 1, ..., " " * (n-1)] s+ # Prepend each to the input rðƬ # Reverse and transpose with filler space # Implicit output, joined on newlines ``` [Answer] # Cobra - 60 ``` def f(n,s) s=' '.repeat(n)+s while''<s,print (s=s[1:])[:n] ``` [Answer] # Groovy - 82 ``` n=args[1]as int;t=" "*n+args[0]+" "*n;(0..t.size()-n).each{println t[it..it+n-1]} ``` [Answer] # Lua, 79 bytes ``` r=io.read;t=r()w=r()s=" "t=s:rep(w)..t;for i=1,t:len()do print(t:sub(i,i+w))end ``` [Answer] # C#, 112 bytes ``` s=>n=>{var r=new string(' ',n-1);s=r+s+r;r="";for(int i=0;i<s.Length-n+1;)r+=s.Substring(i++,n)+"\n";return r;}; ``` Full program with ungolfed method and test cases: ``` using System; namespace FakeMarqueeText { class Program { static void Main(string[] args) { Func<string,Func<int,string>>f= s=>n=> { var r=new string(' ',n-1); s=r+s+r; r=""; for(int i=0;i<s.Length-n+1;) r+=s.Substring(i++,n)+"\n"; return r; }; // test cases: Console.WriteLine(f("testing")(4)); Console.WriteLine(f("hello")(2)); Console.WriteLine(f("foobarz")(3)); Console.WriteLine(f("Something a bit longer")(10)); Console.WriteLine(f("small")(15)); Console.WriteLine(f("aaa")(3)); Console.WriteLine(f("brace yourself")(6)); } } } ``` ]
[Question] [ [Hodor](http://gameofthrones.wikia.com/wiki/Hodor) is a slow-minded but endearing character on the show [Game of Thrones](http://en.wikipedia.org/wiki/Game_of_Thrones) ([he's](http://awoiaf.westeros.org/index.php/Hodor) in [the books](http://en.wikipedia.org/wiki/A_Song_of_Ice_and_Fire) as well of course). The only word he ever says is ['hodor'](https://twitter.com/grrm/status/456824016641486848). Surprisingly, despite not having much of a vocabulary, Hodor always speaks in complete sentences with correct capitalization and punctuation, and does in fact convey meaning. Hodor is capable of expressing all 128 [ASCII](http://www.asciitable.com/) characters, though it takes him an entire sentence to say each one. Each character has a single, exact representation as a sentence. An ASCII string is *Hodorized* by translating all the characters in the string to their Hodor sentence equivalents, then joining all the sentences. Since all characters map to exact sentences, all ASCII strings have a single, unique Hodorized representation. ### Hodorizing Characters Hodor divides his 128 expressible characters into 4 sets of 32 by using 4 different types of punctuation for the sentences that represent characters. The sentence ends with... * `.` if the ASCII character code [mod](http://en.wikipedia.org/wiki/Modulo_operation) 4 is 0. * `.[newline][newline]` (for a new paragraph) if the code mod 4 is 1. * `?` if the code mod 4 is 2. * `!` if the code mod 4 is 3. For example, the ASCII character code for `b` is 98, and 98 mod 4 is 2, so Hodor's sentence for `b` is sure to end in `?`. The content of the sentence is one of 32 distinct strings only containing the word 'hodor'. Each of the 32 characters of a particular punctuation type map to a different sentence content string. So with 32 sentence content strings and 4 punctuation types, all 128 ASCII character can be represented as distinct Hodor sentences. To determine the sentence content for a character with ASCII code C, compute `(floor(C / 4) + 16) mod 32`; everything after the colon on that line in this list is the sentence content: ``` 0:Hodor 1:HODOR 2:Hodor hodor 3:Hodor, hodor 4:Hodor hodor hodor 5:Hodor, hodor hodor 6:Hodor hodor hodor hodor 7:Hodor hodor, hodor hodor 8:Hodor hodor hodor hodor hodor 9:Hodor hodor, hodor hodor hodor 10:Hodor hodor hodor hodor hodor hodor 11:Hodor hodor hodor, hodor hodor hodor 12:Hodor hodor hodor hodor hodor hodor hodor 13:Hodor hodor hodor, hodor hodor hodor hodor 14:Hodor hodor hodor hodor hodor hodor hodor hodor 15:Hodor hodor hodor hodor, hodor hodor hodor hodor 16:Hodor hodor hodor hodor hodor hodor hodor hodor hodor 17:Hodor hodor hodor hodor, hodor hodor hodor hodor hodor 18:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor 19:Hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor 20:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor 21:Hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor 22:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor 23:Hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor 24:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor 25:Hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor 26:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor 27:Hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor 28:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor 29:Hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor hodor 30:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor 31:Hodor hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor hodor ``` It can be seen that, apart from the `HODOR` special case, these strings are generated by joining more and more `hodor`'s, and every other string has a comma halfway between all the words (with the "larger half" right of the comma for an odd number of words). Joining sentence content with punctuation, we can form the Hodor sentences for all 128 characters (the number on the left is the character code): ``` 0:Hodor hodor hodor hodor hodor hodor hodor hodor hodor. 1:Hodor hodor hodor hodor hodor hodor hodor hodor hodor.[newline][newline] 2:Hodor hodor hodor hodor hodor hodor hodor hodor hodor? 3:Hodor hodor hodor hodor hodor hodor hodor hodor hodor! 4:Hodor hodor hodor hodor, hodor hodor hodor hodor hodor. 5:Hodor hodor hodor hodor, hodor hodor hodor hodor hodor.[newline][newline] 6:Hodor hodor hodor hodor, hodor hodor hodor hodor hodor? 7:Hodor hodor hodor hodor, hodor hodor hodor hodor hodor! 8:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. 9:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor.[newline][newline] 10:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor? 11:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor! 12:Hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor. 13:Hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor.[newline][newline] 14:Hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor? 15:Hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor! 16:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. 17:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor.[newline][newline] 18:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor? 19:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor! 20:Hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor. 21:Hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor.[newline][newline] 22:Hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor? 23:Hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor! 24:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. 25:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor.[newline][newline] 26:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor? 27:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor! 28:Hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor. 29:Hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor.[newline][newline] 30:Hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor? 31:Hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor! 32:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. 33:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor.[newline][newline] 34:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor? 35:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor! 36:Hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor. 37:Hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor.[newline][newline] 38:Hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor? 39:Hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor! 40:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. 41:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor.[newline][newline] 42:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor? 43:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor! 44:Hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor. 45:Hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor.[newline][newline] 46:Hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor? 47:Hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor! 48:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. 49:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor.[newline][newline] 50:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor? 51:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor! 52:Hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor hodor. 53:Hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor hodor.[newline][newline] 54:Hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor hodor? 55:Hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor hodor! 56:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. 57:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor.[newline][newline] 58:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor? 59:Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor! 60:Hodor hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor hodor. 61:Hodor hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor hodor.[newline][newline] 62:Hodor hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor hodor? 63:Hodor hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor hodor! 64:Hodor. 65:Hodor.[newline][newline] 66:Hodor? 67:Hodor! 68:HODOR. 69:HODOR.[newline][newline] 70:HODOR? 71:HODOR! 72:Hodor hodor. 73:Hodor hodor.[newline][newline] 74:Hodor hodor? 75:Hodor hodor! 76:Hodor, hodor. 77:Hodor, hodor.[newline][newline] 78:Hodor, hodor? 79:Hodor, hodor! 80:Hodor hodor hodor. 81:Hodor hodor hodor.[newline][newline] 82:Hodor hodor hodor? 83:Hodor hodor hodor! 84:Hodor, hodor hodor. 85:Hodor, hodor hodor.[newline][newline] 86:Hodor, hodor hodor? 87:Hodor, hodor hodor! 88:Hodor hodor hodor hodor. 89:Hodor hodor hodor hodor.[newline][newline] 90:Hodor hodor hodor hodor? 91:Hodor hodor hodor hodor! 92:Hodor hodor, hodor hodor. 93:Hodor hodor, hodor hodor.[newline][newline] 94:Hodor hodor, hodor hodor? 95:Hodor hodor, hodor hodor! 96:Hodor hodor hodor hodor hodor. 97:Hodor hodor hodor hodor hodor.[newline][newline] 98:Hodor hodor hodor hodor hodor? 99:Hodor hodor hodor hodor hodor! 100:Hodor hodor, hodor hodor hodor. 101:Hodor hodor, hodor hodor hodor.[newline][newline] 102:Hodor hodor, hodor hodor hodor? 103:Hodor hodor, hodor hodor hodor! 104:Hodor hodor hodor hodor hodor hodor. 105:Hodor hodor hodor hodor hodor hodor.[newline][newline] 106:Hodor hodor hodor hodor hodor hodor? 107:Hodor hodor hodor hodor hodor hodor! 108:Hodor hodor hodor, hodor hodor hodor. 109:Hodor hodor hodor, hodor hodor hodor.[newline][newline] 110:Hodor hodor hodor, hodor hodor hodor? 111:Hodor hodor hodor, hodor hodor hodor! 112:Hodor hodor hodor hodor hodor hodor hodor. 113:Hodor hodor hodor hodor hodor hodor hodor.[newline][newline] 114:Hodor hodor hodor hodor hodor hodor hodor? 115:Hodor hodor hodor hodor hodor hodor hodor! 116:Hodor hodor hodor, hodor hodor hodor hodor. 117:Hodor hodor hodor, hodor hodor hodor hodor.[newline][newline] 118:Hodor hodor hodor, hodor hodor hodor hodor? 119:Hodor hodor hodor, hodor hodor hodor hodor! 120:Hodor hodor hodor hodor hodor hodor hodor hodor. 121:Hodor hodor hodor hodor hodor hodor hodor hodor.[newline][newline] 122:Hodor hodor hodor hodor hodor hodor hodor hodor? 123:Hodor hodor hodor hodor hodor hodor hodor hodor! 124:Hodor hodor hodor hodor, hodor hodor hodor hodor. 125:Hodor hodor hodor hodor, hodor hodor hodor hodor.[newline][newline] 126:Hodor hodor hodor hodor, hodor hodor hodor hodor? 127:Hodor hodor hodor hodor, hodor hodor hodor hodor! ``` (`[newline]`'s are to be replaced with actual newlines.) ### Hodorizing Strings Hodorizing a string really just involves concatenating all the character sentences of the string's characters together. There are only a couple caveats: * A space is inserted after every sentence except for the `.[newline][newline]` punctuated ones and the very last sentence. * If the last sentence is punctuated with `.[newline][newline]`, the punctuation becomes `...` so there is no trailing whitespace. ### Examples The string `F0` is Hodorized as ``` HODOR? Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. ``` * `F` has ASCII code 70. 70 mod 4 is 2, so the first sentence ends in `?`. `(floor(70 / 4) + 16) mod 32` is 1 so the content is `HODOR`. * `0` has ASCII code 48. 48 mod 4 is 0, so the second sentence ends in `.`. `(floor(48 / 4) + 16) mod 32` is 28 so the content is 15 `hodor`'s strung together with no comma. * Notice that there is no trailing space. The string `CEE` is Hodorized as ``` Hodor! HODOR. HODOR... ``` * Notice that there is no space before the last sentence. * Notice that the the last sentence punctuation was changed to `...`. The string ``` Hodor's real name is Walder. Did you know? ``` is Hodorized as ``` Hodor hodor. Hodor hodor hodor, hodor hodor hodor! Hodor hodor, hodor hodor hodor. Hodor hodor hodor, hodor hodor hodor! Hodor hodor hodor hodor hodor hodor hodor? Hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor! Hodor hodor hodor hodor hodor hodor hodor! Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor? Hodor hodor, hodor hodor hodor. Hodor hodor hodor hodor hodor. Hodor hodor hodor, hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor, hodor hodor hodor? Hodor hodor hodor hodor hodor. Hodor hodor hodor, hodor hodor hodor. Hodor hodor, hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor! Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor, hodor hodor! Hodor hodor hodor hodor hodor. Hodor hodor hodor, hodor hodor hodor. Hodor hodor, hodor hodor hodor. Hodor hodor, hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor? Hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor? Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor? HODOR. Hodor hodor hodor hodor hodor hodor. Hodor hodor, hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor, hodor hodor hodor! Hodor hodor hodor, hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor! Hodor hodor hodor, hodor hodor hodor? Hodor hodor hodor, hodor hodor hodor! Hodor hodor hodor, hodor hodor hodor hodor! Hodor hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor hodor! ``` (assuming the [newline](http://en.wikipedia.org/wiki/Newline#Representations) is a single `\n`) # Challenge Write a program or function that takes in an ASCII string and Hodorizes it, printing or returning the resulting string. Take input in any standard way (from text file, command line, stdin, function arg). **The solution with the fewest bytes wins. Tiebreaker is earlier post.** ([Handy byte counter.](https://mothereff.in/byte-counter)) [Answer] # Hodor, ~~602~~ 582 bytes ``` HoDoRHoDoR HODOR! (Hodor ){r='';Hodor!? =Hodor .Hodor!? hodor? HODOR? hodor! hodor. h;HODOR{}(Hodor? =0;Hodor? <Hodor!? ;++Hodor? ){hodor =Hodor .hodor hHODOR rHodor... odhodor? hodor?!? hodor. (Hodor? );HODOR? =(0|hodor /4+16)%32;r+='H';HODOR =HHHOOODDDDOOORRR!!! hodor?!? rrHODOR HODOR!?! (0|HODOR? /2+2);HOdor!!!(HODOR? %2)HODOR [0|(HODOR? +1)/4]=',';r+=HODOR? ==1?'ODOR':HODOR .HODOR?! oHodor? HODOR? (' hodor').Hodor Hodor!? Hodor? hodor hodor? (2);r+=['. ',Hodor? ==Hodor!? -1?'....':'.\HODOR? \HODOR? ','? ','! '][hodor %4]}HODOR:: r.Hodor Hodor!? Hodor? hodor hodor? (0,-1)} ``` Here is an ungolfed version... you know... for readability: ``` HoDoRHoDoR HODOR! (Hodor ){ r=''; Hodor!? =Hodor .Hodor!? hodor? HODOR? hodor! hodor. h; HODOR{}(Hodor? =0;Hodor? <Hodor!? ;++Hodor? ){ hodor =Hodor .hodor hHODOR rHodor... odhodor? hodor?!? hodor. (Hodor? ); HODOR? =(0|hodor /4+16)%32; r+='H'; HODOR =HHHOOODDDDOOORRR!!! hodor?!? rrHODOR HODOR!?! (0|HODOR? /2+2); HOdor!!!(HODOR? %2)HODOR [0|(HODOR? +1)/4]=','; r+=HODOR? ==1?'ODOR':HODOR .HODOR?! oHodor? HODOR? (' hodor').Hodor Hodor!? Hodor? hodor hodor? (2); r+=['. ',Hodor? ==Hodor!? -1?'....':'.\HODOR? \HODOR? ','? ','! '][hodor %4] } HODOR:: r.Hodor Hodor!? Hodor? hodor hodor? (0,-1) } ``` Yep, there is a language called [Hodor](http://www.hodor-lang.org/). (And it's rather new.) It's essentially just a string substitution for JavaScript. The corresponding JS looks like this: ``` function f(s){ r=''; l=s.length; for(i=0;i<l;++i){ c=s.charCodeAt(i); n=(0|c/4+16)%32; r+='H'; a=new Array(0|n/2+2); if(n%2)a[0|(n+1)/4]=','; r+=n==1?'ODOR':a.join(' hodor').slice(2); r+=['. ',i==l-1?'....':'.\n\n','? ','! '][c%4] } return r.slice(0,-1) } ``` Hence, my submission is a function taking a string and returning the Hodorised equivalent. Unfortunately, there doesn't seem to be any information about how Hodor actually works (apart from the source code of the interpreter), but it comes with a JS2HD translation script. Note that Hodor's substitutions are also applied within string literals. So while you may just call the above function as ``` HODOR! ("CEE") ``` You can also use the following: ``` HODOR! ("Hodor... HooodorrHodor HooodorrHodor ") ``` where `Hodor... HooodorrHodor HooodorrHodor` will be substituted with `CEE`. Note that this means, that if your string itself contains certain forms of `Hodor` you'll *have* to encode it, or else it will be substituted. E.g. `"Hodor. "` is actually `"m"` in JavaScript. The catch is that the letters `[dhor]` (case insensitively) are not replaced at all, so you can't even encode this. One solution is to split up the literal, like `"Hod"+"or. "`, such that the substitution step doesn't find anything to decode. [Answer] ### Hodor! Hodor hodor? Hodor hodor hodor hodor hodor. ### Hodor hodor hodor, hodor hodor hodor. ### Hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor, hodor hodor hodor hodor hodor hodor hodor hodor. ### Hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor? Hodor hodor hodor hodor hodor hodor hodor hodor. ### Hodor hodor hodor, hodor hodor hodor hodor. Hodor hodor, hodor hodor hodor. ### Hodor hodor hodor hodor hodor hodor hodor! That's just the language and size header!? Nevermind then, let's just encode the post in boring old ASCII. Sorry if you have trouble understanding the post, Hodor. --- # CJam, 85 bytes Here's my attempt. Some parts of this code felt rather clunky when I wrote them, so there's likely potential to beat this! ``` qW%{'@^4md('.X1$N?_++a"?!."XLS?f++=\(_)2md","*1$)"hodor":Ha*H@+@(2/\tS*0:X'HtHeu?}%W% ``` [Try it online.](http://cjam.aditsu.net/#code=qW%25%7B'%40%5E4md('.X1%24N%3F_%2B%2Ba%22%3F!.%22XLS%3Ff%2B%2B%3D%5C(_)2md%22%2C%22*1%24)%22hodor%22%3AHa*H%40%2B%40(2%2F%5CtS*0%3AX'HtHeu%3F%7D%25W%25&input=Hodor's%20real%20name%20is%20Walder.%0ADid%20you%20know%3F) ### Explanation ``` qW% "Read and reverse the input."; { "Map each character c:"; '@^4md "Calculate (c^64)/4, which is the sentence content determiner, and c%4, which is the sentence ending determiner."; ( "Calculate c%4-1 for later."; '.X1$N?_++ "Produce the sentence ending string for the case that c%4==1, which is '.' followed by two copies of: - '.' if this is the first processed (last actual) character - or a newline otherwise. a"?!."XLS?f "Produce a list of the sentence ending strings for the cases that c%4 is 2, 3, or 0, which are: - '?', '!', and '.' if this is the first processed character - or these punctuation marks each followed by a space otherwise."; ++=\ "Prepend the sentence ending string for the case that c%4==1 to the list for the other cases and select the element at the index (c%4-1)%4 as the correct sentence ending string."; ( "Calculate (c^64)/4-1 for later."; _)2md "Calculate the quotient and remainder of the sentence content content determiner divided by 2."; ","* "Produce a string of commas with a length of the remainder calculated above (either 0 or 1)."; 1$)"hodor":Ha* "Produce a list of copies of 'hodor' with a length of the quotient calculated above plus one."; H@+@(2/\t "Append the string of commas (either empty or one comma) to the middle 'hodor'."; S* "Join the sentence words into a string a space between each."; 0:X "Signal that later characters are not the first processed."; 'Ht "Capitalize the first letter of the sentence (always 'h')."; Heu "Produce the string 'HODOR'."; ? "Select the correct sentence content, which is 'HODOR' if (c^64)/4-1 is zero or the full sentence produced before that otherwise."; }% W% "Reverse the reversed translation to obtain the forward one."; "Implicitly print the result."; ``` [Answer] # Python 2, ~~219~~ 198 bytes [Try it here](http://repl.it/jGL/5) Uses the same method as Martin's JavaScript, and it's several bytes shorter in Python. I make use of Python 2.7's handy integer division. Thanks to Sp3000 for some golfing. ``` def f(s,r='',i=2): for j in s:c=ord(j);n=(c/4+16)%32;a=['']*(n/2+2);a[-~n/4]=','[:n%2];r+='H'+[' hodor'.join(a)[2:],'ODOR'][n==1]+['. ',['.\n\n',4*'.'][i>len(s)],'? ','! '][c%4];i+=1 return r[:-1] ``` And for your own entertainment and my own enjoyment and curiosity... Here it is as a **lambda function**!!! ### Python 2, 349 [Try it here](http://repl.it/jGL/3), along with an older version of the program above. ``` f=lambda s:'H'.join(['']+[('ODOR'if(ord(s[i])/4+16)%32==1 else' hodor'.join((['']*(((ord(s[i])/4+16)%32)/2+2))[:((ord(s[i])/4+16)%32+1)/4]+([',']if ord(s[i])/4%2 else[''])+(['']*(((ord(s[i])/4+16)%32)/2+2))[((ord(s[i])/4+16)%32+1)/4+1*(ord(s[i])/4%2<1):])[2:])+['. ',4*'.'if i+2>len(s)else'.\n\n','? ','! '][ord(s[i])%4]for i in range(len(s))])[:-1] ``` Creating this involved deeper and deeper substitutions as well as some extra creativity. * Every `j` is replaced with `s[i]`. * Every `c` is replaced with `ord(s[i])`. * Every `n` is replaced with `(ord(s[i])/4+16)%32`. + *Except* where I only need `n%2`, so I use `(ord(s[i])/4%2` instead. * Finally, `a` is replaced with `(['']*(((ord(s[i])/4+16)%32)/2+2))[:((ord(s[i])/4+16)%32+1)/4]+([',']if ord(s[i])/4%2 else[''])+(['']*(((ord(s[i])/4+16)%32)/2+2))[((ord(s[i])/4+16)%32+1)/4+1*(ord(s[i])/4%2<1):]`. + This is because we cannot assign a value, so we must split the list in half, conditionally append the comma, then append the last half again. [Answer] ## [MUMPS](http://en.wikipedia.org/wiki/MUMPS), 284 236 bytes New version: After looking at it for a while I came up with a shorter version (236 bytes): ``` H(H) S L=$L(H) F O=1:1:L D .S D=$A($E(H,O)),R=D#4,P=$S('R:".",R=2:"?",R=3:"!",O=L:"...",1:"."_$C(10,10)),E=D\4+16#32,(S,Q)="hodor" F F=1:1:E\2 S Q=S_$S(E#2&(F=(E\4+1)):", ",1:" ")_Q,$E(Q)="H" S:E=1 Q="HODOR" .W Q_P_$S(L=O:"",1:" ") Q ``` First version: ``` H(H) S L=$L(H) F O=1:1:L D .S S=$C(10),D=$A($E(H,O)),R=D#4,P=$S('R:".",R=2:"?",R=3:"!",O=L:"...",1:"."_S_S),E=D\4+16#32,(S,Q)="hodor ",G=6*(E+1\4) F F=1:1:E\2 S Q=S_Q .S Q=$E(Q,1,$L(Q)-1) S:E=1 Q="HODOR" S:E#2&(E>2) Q=$E(Q,1,G-1)_","_$E(Q,G,99) S $E(Q)="H" W Q_P_$S(L=O:"",1:" ") Q ``` Damn you, CJam! *Maybe* I could save some bytes using [ObjectScript](http://en.wikipedia.org/wiki/Cach%C3%A9_ObjectScript) (there're list operators), but I doubt it. Here's a somewhat verbose version: ``` VH(H) F I=1:1:$L(H) D ; iterate over input string H .S O=$E(H,I) ; O is a single char .S D=$A(O) ; ascii code (dec) .S R=D#4 ; #: mod, $S: $SELECT(condition:result,cond...) .S P=$S(R=0:".",R=2:"?",R=3:"!",I=$L(H):"...",1:"."_$C(10)_$C(10)) .S E=D\4+16#32 ; \: integer division .S (S,Q)="hodor " ; hodor .F J=1:1:E\2 S Q=S_Q ; build hodor -"list" .I E=1 S Q="HODOR" ; HODOR .I E'=1 S Q=$E(Q,1,$L(Q)-1) ; remove trailing _ .; ; insert , .I E#2,E>2 S Q=$E(Q,1,6*(E+1\4)-1)_","_$E(Q,6*(E+1\4),99) .S $E(Q)="H" ; ^h->^H .W Q_P_$S($L(H)=I:"",1:" ") ; Write and remove trailing _ Q ``` [Answer] # C# 378 Bytes ``` string x(string h){string[]f={". ",".\n\n","? ","! "};string[]a=new string[32];string s="";int i,j,c=0;for(i=0;i<32;i++){a[i]="hodor";if(i==1)a[i]=a[i].ToUpper();else{for(j=0;j<i/2;j++){if(i%2==1&&j==c/2)a[i]+=",";a[i]+=" hodor";}if(i%2==1)c++;a[i]=char.ToUpper(a[i][0])+a[i].Substring(1);}}foreach(char b in h){s+=a[(int)(Math.Floor((double)b/4)+16)%32]+f[(int)b%4];}return s;} ``` It's my first time golfing, so bare with me. [Answer] ## C++, ~~547~~ 452 bytes ``` void H(string s){string e[4]={".",".\n\n","?","!"};string r;char c,m;int n=s.size();for(int i=0;i<n;i++){r.clear();c=s.at(i);m=c%4;r.append(A(c));r.append(e[m]);if(i==n-1){int k=r.size();r.pop_back();if(m==1){r.pop_back();r.append("..");}}cout<<r.c_str();}}string A(char x){string h("Hodor");int c=((int )floor(x/4)+16)%32;int n=c;bool o=(c%2==1);if(n==1)h="HODOR";else{while(n>1){h.append("hodor");if(o&&n==(int )(c/2)){h.append(",");}n--;}}return h;} ``` Ungolfed: ``` #include <iostream> #include <math.h> using namespace std; void Hodorise(string s); string FromAscii(char c); void Hodorise(string s) { string end[4] = {". ",".\n\n","? ","! "}; string res; char c, m; int n = s.size(); for (int i = 0; i < n; i++) { res.clear(); c = s.at(i); m = c % 4; res.append(FromAscii(c)); res.append(end[m]); if (i == n - 1) { int k = res.size(); res.pop_back(); if (m == 1) { res.pop_back(); res.append(".."); } } cout << res.c_str(); } } string FromAscii(char c) { string hodor("Hodor"); int code = ((int)floor(c / 4) + 16) % 32; int n = code; bool odd = (code % 2 == 1); if (n == 1)hodor = "HODOR"; else { while (n > 1) { hodor.append(" hodor"); if (odd && n==(int)(code/2)) { hodor.append(","); } n--; } } return hodor; } #define N 3 int main() { string x[N] = { "F0", "CEE", "Hodor's real name is Walder.\nDid you know ?" }; for (size_t i = 0; i < N; i++) { cout << endl << x[i].c_str() << ":\n"; Hodorise(x[i]); } char c; cin >> c; return 0; } ``` ]
[Question] [ The Ackermann function is notable for being the one of the simplest examples of a total, computable function that isn't primitive recursive. We will use the definition of \$A(m,n)\$ taking in two nonnegative integers where $$\begin{align} A(0,n) & = n+1 \\ A(m,0) & = A(m-1,1) \\ A(m,n) & = A(m-1,A(m,n-1)) \end{align}$$ You may implement * a named or anonymous function taking two integers as input, returning an integer, or * a program taking two space- or newline-separated integers on STDIN, printing a result to STDOUT. You may not use an Ackermann function or hyperexponentiation function from a library, if one exists, but you may use any other function from any other library. Regular exponentiation is allowed. Your function must be able to find the value of \$A(m,n)\$ for \$m \le 3\$ and \$n \le 10\$ in less than a minute. It must at least *theoretically* terminate on any other inputs: given infinite stack space, a native Bigint type, and an arbitrarily long period of time, it would return the answer. *Edit:* If your language has a default recursion depth that is too restrictive, you may reconfigure that at no character cost. The submission with the shortest number of characters wins. Here are some values, to check your answer: $$\begin{array}{c|cccccccccc} A & n = 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\ \hline m=0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 \\ 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 \\ 2 & 3 & 5 & 7 & 9 & 11 & 13 & 15 & 17 & 19 & 21 & 23 \\ 3 & 5 & 13 & 29 & 61 & 125 & 253 & 509 & 1021 & 2045 & 4093 & 8189 \\ 4 & 13 & 65533 & \text{big} \end{array}$$ [Answer] # Haskell, 35 ``` 0%n=1+n m%n=iterate((m-1)%)1!!(n+1) ``` this defines the operator function `%`. this works by noticing that `m%n` (where `a` is the ackerman function) for nonzero `m` is `(m-1)%` applied `n+1` times to `1`. for example, `3%2` is defined as `2%(3%1)` which is `2%(2%(3%0))`, and this is `2%(2%(2%1))` [Answer] # [Binary lambda calculus](https://tromp.github.io/cl/cl.html), 54 bits = 6.75 bytes Hexdump: ``` 00000000: 1607 2d88 072f 68 ..-../h ``` Binary: ``` 000101100000011100101101100010000000011100101111011010 ``` This is λ*m*. *m* (λ*g*. λ*n*. *g* (*n* *g* 1)) (λ*n*. λ*f*. λ*x*. *f* (*n* *f* *x*)), where all numbers are represented as [Church numerals](https://en.wikipedia.org/wiki/Church_encoding#Church_numerals). [Answer] ## GolfScript (30) ``` {1$1>{1\){1$(\A}*\;}{+)}if}:A; ``` [Online demo](http://golfscript.apphb.com/?c=ezEkMT57MVwpezEkKFxBfSpcO317Kyl9aWZ9OkE7CgozIDEwIEE%3D) Without the `1>` (which special-cases `A(1, n)`) it takes 9 minutes to compute `A(3, 10)` on the computer I've tested it on. With that special case it's fast enough that the online demo takes less than 10 seconds. Note that this *isn't* a naïve translation of the definition. The recursion depth is bounded by `m`. ### Dissection ``` { # Function boilerplate 1$ # Get a copy of m: stack holds m n m 1>{ # (Optimisation): if m is greater than 1 1 # Take this as the value of A(m, -1) \){ # Repeat n+1 times: # Stack: m A(m, i-1) 1$(\ # Stack: m m-1 A(m, i-1) A # Stack: m A(m, i) }* \; # Lose that unwanted copy of m }{ # Else +) # A(m in {0, 1}, n) = m + n + 1 }if }:A; # Function boilerplate ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 19 ``` DaGHR?atG?aGtHH1GhH ``` Defines `a`, which works as the Ackermann function. Note that this requires a higher recursion depth than the official pyth compiler allowed up until today to compute `a 3 10`, so I increased the recursion depth. This is not a change to the language, just to the compiler. ### Test: ``` $ time pyth -c "DaGHR?atG?aGtHH1GhH ;a 3 10" 8189 real 0m0.092s user 0m0.088s sys 0m0.000s ``` ### Explanation: ``` DaGH def a(G,H): R return ? G (if G: atG (a(G-1, ? H (if H: aGtH a(G,H-1) 1 else:1) hH else:H+1) ``` Essentially, it first conditions on the truth value of `G` whether to recurse or return H+1. If it is recursing, the first argument is always G-1, and it conditions on the truth value of `H` whether to use `a(G,H-1)` as the second argument, or to use `1` as the second argument. [Answer] # J - 26 char ``` ($:^:(<:@[`]`1:)^:(0<[)>:) ``` There is an alternate, more functional definition of Ackermann: ``` Ack 0 n = n+1 Ack m n = Iter (Ack (m-1)) n Iter f 0 = f 1 Iter f n = f (Iter f (n-1)) ``` It so happens that `Iter` is very easy to write in J, because J has a way of passing in the `m-1` to `Ack` and also to define the initial value of `Iter` to be 1. Explained by explosion: ``` ( >:) NB. increment n ^:(0<[) NB. if m=0, do nothing to n+1; else: ^: NB. iterate... ($: ) NB. self ($: is recursion) (<:@[ ) NB. with left arg m-1 `] NB. n+1 times `1: NB. starting on 1 ``` This relies on what J calls the gerund form of `^:`—basically a way to have more control over all the bounds in a tacit (point-free) fashion. At the REPL: ``` 3 ($:^:(<:@[`]`1:)^:(0<[)>:) 3 61 ack =: ($:^:(<:@[`]`1:)^:(0<[)>:) (i.4) ack"0 table (i.11) +-----+------------------------------------------+ |ack"0|0 1 2 3 4 5 6 7 8 9 10| +-----+------------------------------------------+ |0 |1 2 3 4 5 6 7 8 9 10 11| |1 |2 3 4 5 6 7 8 9 10 11 12| |2 |3 5 7 9 11 13 15 17 19 21 23| |3 |5 13 29 61 125 253 509 1021 2045 4093 8189| +-----+------------------------------------------+ 6!:2 '3 ($:^:(<:@[`]`1:)^:(0<[)>:) 10' NB. snugly fits in a minute 58.5831 ``` We need to define `ack` by name to be able to put it in a table, because `$:` is a horrible, ugly beast and lashes out at anyone who attempts to understand it. It is self-reference, where self is defined as the largest verb phrase containing it. `table` is an adverb and so would love to become part of the verb phrase if you give it the chance, so you have to trap `$:` in a named definition to use it. --- ### Edit: 24 char? Years later, I found a solution which is two characters shorter. ``` (0&<~(<:@#~$:/@,1:^:)>:) ``` It's a lot slower, though: `3 ack 8` takes over a minute on my machine. This is because (1) I use a fold `/` instead of iteration, so J probably has to remember more things than usual, and (2) while `0&<~` performs the same calculation as `(0<[)`, it actually gets executed `n+1` times *before taking the recursive step* when invoking `m ack n`—`0&<` happens to be idempotent, so it doesn't ruin the calculation, but `n` gets big fast and `ack` is highly recursive. I am doubtful that a more powerful machine could push the new code under a minute, because this is a computer where the old code can find `3 ack 10` in less than 15 seconds. [Answer] ## JavaScript, ES6, ~~41~~ 34 bytes ``` f=(m,n)=>m?f(m-1,!n||f(m,n-1)):n+1 ``` Run this in a latest Firefox Console and it will create a function called `f` which you can call with different values of `m` and `n` like ``` f(3,2) // returns 29 ``` OR try the code below in a latest Firefox ``` f=(m,n)=>m?f(m-1,!n||f(m,n-1)):n+1 B.onclick=_=>alert(f(+M.value, +N.value)) ``` ``` #M,#N{max-width:15px;border: 1px solid;border-width:0 0 1px 0} ``` ``` <div>f(<input id=M />,<input id=N />)</div><br><button id=B>Evaluate</button> ``` [Answer] # Python 2.7.8 - ~~80, 54, 48, 46~~ 45 ``` A=lambda m,n:m and A(m-1,n<1or A(m,n-1))or-~n ``` (Credits to xnor!) More readable, but with 1 more character: ``` A=lambda m,n:n+(m<1or A(m-1,n<1or A(m,n-1))-n) ``` Not that I had to set `sys.setrecursionlimit(10000)` in order to get a result for `A(3,10)`. Further golfing using logical indexing did not work due to the dramatically growing recursion depth. [Answer] # C - 41 bytes Nothing to it--the small limits mean that all the required values can be calculated in less than 1 second by naively following the function definition. ``` A(m,n){return!m?n+1:A(m-1,n?A(m,n-1):1);} int main() { int m,n; for(m = 0; m <= 3; m++) for(n = 0; n <= 10; n++) printf("%d %d %d\n", m,n,A(m,n)); return 0; } ``` [Answer] # Javascript ES6 (34) ``` a=(m,n)=>m?a(m-1,n?a(m,n-1):1):n+1 ``` ### Implementation: ``` a=(m,n)=>m?a(m-1,n?a(m,n-1):1):n+1 ``` ``` td[colspan="2"] input{width: 100%;} ``` ``` <table><tbody><tr><td>m=</td><td><input id="m" type="number" value="0" /></td></tr><tr><td>n=</td><td><input id="n" type="number" value="0" /></td></tr><tr><td colspan="2"><input type="button" value="Calculate!" onclick="document.getElementById('out').value=a(document.getElementById('m').value, document.getElementById('n').value)" /></td></tr><tr><td colspan="2"><input id="out" disabled="disabled" type="text" /></td></tr></tbody></table> ``` [Answer] # Coq, 40 ``` nat_rec _ S(fun _ b n=>nat_iter(S n)b 1) ``` This is a function of type `nat -> nat -> nat`. Since Coq only allows the construction of total functions, it also serves as a formal proof that the Ackermann recurrence is well-founded. Demo: ``` Welcome to Coq 8.4pl6 (November 2015) Coq < Compute nat_rec _ S(fun _ b n=>nat_iter(S n)b 1) 3 10. = 8189 : nat ``` Note: Coq 8.5, released after this challenge, renamed `nat_iter` to `Nat.iter`. [Answer] # JavaScript (ES6) - 34 ``` A=(m,n)=>m?A(m-1,!n||A(m,n-1)):n+1 ``` And a test: ``` > A=(m,n)=>m?A(m-1,!n||A(m,n-1)):n+1;s=new Date().getTime();console.log(A(3,10),(new Date().getTime() - s)/1000) 8189 16.441 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` +‘ð;x’ß@ƒ1ðỊ? ``` [Try it online!](https://tio.run/##AS8A0P9qZWxsef//K@KAmMOwO3jigJnDn0DGkjHDsOG7ij//M8W7w6fDvjEwxbvCpFpH/w "Jelly – Try It Online") Again uses [proud haskeller's approach](https://codegolf.stackexchange.com/a/40172/78410): `A(m+1,n)` is `A(m,?)` applied `n+1` times to 1. The base case should've been simply `A(0,n) = n+1`, but unfortunately it (the code at the bottom) times out badly, so I had to use `A(m,n) = m+n+1 if m <= 1` instead. ### How it works ``` +‘ð;x’ß@ƒ1ðỊ? Dyadic link. Left = m, Right = n AAðBBBBBBBðC? If C, do A; otherwise, do B Ị If m <= 1... +‘ Return m+n+1 ;x’ß@ƒ1 Otherwise do this: ;x Concatenate m to n copies of m (which gives n+1 copies of m) ’ Decrement each number (n+1 copies of m-1) ƒ1 Reduce with seed 1... ß@ This function, args swapped (since new m is on the right side) ``` --- # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes, times out on A(3,9) ``` ;x’ß@ƒ1ð‘}ḷ? ``` [Try it online!](https://tio.run/##ASwA0/9qZWxsef//O3jigJnDn0DGkjHDsOKAmH3huLc//zPFu8Onw741xbvCpFpH/w "Jelly – Try It Online") [Answer] ## Mathematica, 46 bytes ``` 0~a~n_:=n+1 m_~a~n_:=a[m-1,If[n<1,1,a[m,n-1]]] ``` Takes pretty much exactly a minute for `a[3,10]`. Note that Mathematica's default recursion limit is too small for `a[3,8]` and beyond (at least on my machine), but that can be fixed by configuring ``` $RecursionLimit = Infinity ``` [Answer] ## Haskell, ~~48~~ 44 chars (36 for the list) While not as short as the other Haskell solution, this one is notable because it expresses the Ackermann function as an infinite list, which I think is kinda neat. The result is an infinite list (of infinite lists) such that at position *[m,n]* it holds the value *A(m,n)*. The infinite list itself: ``` iterate(tail.(`iterate`1).(!!))[1..] ``` As a function (to comply with the specification): ``` i=iterate;m%n=i(tail.(`i`1).(!!))[1..]!!m!!n ``` --- The formulation was derived by observing that the general/common case for the Ackermann function is to use the value to the left as an index in the row above. The base case for this recursion (i.e. the leftmost column of a row, i.e. *A(m,0)*) is to use the second left-most value in the row above. The base case for *that* recursion is the *A(0,n) = n+1* case, i.e. the first row is `[1..]`. Thus, we get ``` let a0 = [1..] let a1 = tail $ iterate (a0 !!) 1 -- 'tail' because iterate starts by applying let a2 = tail $ iterate (a1 !!) 1 -- the function 0 times -- etc ``` Then we simply add another level of iteration based on that pattern, and do some [pointless](http://en.wikipedia.org/wiki/Tacit_programming) juggling. [Answer] # Julia, ~~34~~ ~~31~~ 28 bytes ``` m\n=m>0?~-m\(n<1||m\~-n):n+1 ``` This is a named anonymous function. It is a straightforward implementation of the recursive definition, abusing Julia's ability to [redefine operators](https://codegolf.stackexchange.com/a/81028). [Try it online!](http://julia.tryitonline.net/#code=bVxuPW0-MD9-LW1cKG48MXx8bVx-LW4pOm4rMQoKcHJpbnQoM1wxMCk&input=) [Answer] # [Python 3](https://docs.python.org/3/), ~~58~~ 49 bytes ``` a=lambda m,n:m and a(m-1,n and a(m,n-1)or 1)or-~n ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P9E2JzE3KSVRIVcnzypXITEvRSFRI1fXUCcPxtbJ0zXUzC9SABG6dXn/C4oy80o0EjWMdRTMNDX/AwA "Python 3 – Try It Online") I didn't see a Python 3 answer (there was a Python 2), so I decided to fix that and put my own answer in here. (-(43+21) thanks to caird, -9 thanks to HN) [Answer] # Racket 67 ``` (define(a m n)(if(= m 0)(+ n 1)(a(- m 1)(if(= n 0)1(a m(- n 1)))))) ``` [Answer] ## Javascript with lambdas, 34 ``` A=(m,n)=>m?A(m-1,n?A(m,n-1):1):n+1 ``` A tipical answer, can't make anything shorter. [Answer] # [Tiny Lisp](https://codegolf.stackexchange.com/q/62886/2338), 70 (out of competition) This runs out of competition, as the language is newer than the question, and it also doesn't succeed to run the `(A 3 10)` as required in the question, due to a stack overflow. `(d A(q((m n)(i m(i n(A(s m 1)(A m(s n 1)))(A(s m 1)1))(s n(s 0 1))))))` This defines a function `A` which calculates the Ackermann function. Formatted: ``` (d A (q( (m n) (i m (i n (A (s m 1) (A m (s n 1) ) ) (A (s m 1) 1 ) ) (s n (s 0 1) ) ) ) ) ) ``` We are using all builtin macros (`d` (define) and `q` (quote) and `i` (if)) and one builtin function (`s` – subtract) here. `i` executes its true part when the condition is a number > 0 (and otherwise the false part), so we don't have to do an explicit comparison here. `s` is the only arithmetic operation available, we use it for the `n-1`/`m-1`, as well as as `(s n (s 0 1))` for `n+1`. Tiny lisp is using tail recursion optimization, but this only helps for the outer `A` call in the result, not for the `A(m, n-1)` call which is used for the parameters. With [my tiny lisp implementation](https://codegolf.stackexchange.com/a/63352/2338) in Ceylon on the JVM, it works up to `(A 3 5) = 253`, but it seems to break down when trying to calculate `(A 2 125)` directly (which should give the same result). If calculating that after `(A 3 4) = 125`, the JVM seems to got to optimize the functions enough to inline some intermediate function calls in my interpreter, allowing more recursion depth. Strange. The [reference implementation](https://gist.github.com/dloscutoff/254267bce8cb09f009ad) gets up to `(A 3 5) = 253` and also `(A 2 163) = 329`, but doesn't succeed `(A 2 164)`, and therefore even less `(A 3 6) = (A 2 253)`. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 90 bytes ``` >>>>+>,>,<<[>[>[-[->>>+<<<]<[->+>>+<<<]>-[-<+>]>+>>>>>]<[->+>>]]<[>>+[-<<<+>>>]<<-]<<<]>>. ``` [Try it online!](https://copy.sh/brainfuck/?c=Pj4-Pis-LD4sPDwKWwogID4KICBbCiAgICA-CiAgICBbCiAgICAgIC1bLT4-Pis8PDxdCiAgICAgIDxbLT4rPj4rPDw8XQogICAgICA-LVstPCs-XT4rPj4-Pj4KICAgIF0KICAgIDwKICAgIFsKICAgICAgLT4rPj4KICAgIF0KICBdCiAgPAogIFsKICAgID4-K1stPDw8Kz4-Pl08PC0KICBdCiAgPDw8Cl0KPj4uCg$$) Assumes an implementation with arbitrary sized cell size, with IO as numbers. -6 bytes if you don't mind using negative cells. Finishes in about 30 seconds for 3,8 in the linked interpreter, provided you tick the correct settings. Type inputted numbers prepended with `\`s, e.g. `3,9` is `\3\9`. [Answer] # [Ral](https://esolangs.org/wiki/Ral), ~~81~~ 61 bytes ``` ,,/:11+-111:++:+:++:+:+?/0=:1/-/1/10*-0*1:+?+0=11:+?1++/1:+?. ``` [Try it online!](https://tio.run/##VVFBb4MgGL3zK750B1FQIb2xMbNjT22W3YxZqGJKopZo221Z9tsdtDbay8fHe@97PMD@nA7Hbj0@wRu8qwZMd9K97bWrUB97@Nhs0UY2qt1XSjgSm86eTzgM0XZC4SJs75lLiCpdQ3/ucBkKBCU1dKCtzMurU@m8famvXcA4iUUaSZpkn0FBGc0L@vuHwM62Q6Ks1V3lnWF3DzEk9mhx6HwG0M2ggSH4OphGg3lp9HQ2GFpJQzgtc1P4bQ3V7dRAWOzTVu4KN1zKgHh0h0Oyw0s4nuD4ERaBUNJBzxarW5m51HF071m6UOwXimiebnNVOFT5l2mnyyyU8q70Ot/MFPXJNg@pkkBs8WPQLPBPAWqa9bDrXpkwslXfmFGXHPn/Wq1WI6Wp4O5TOOeCEEGmkqVMCp7GKU85i2IWOTYjTHpVxglJ/ZqMziEc14izfw) **Commented** ``` Code Stack after Description ,, 0, m, n Input m and n Loop: /:11+-111:++:+:++:+:+? r, n, m Jump to SmallM if m < 2 /0=:1/-/1/10*- r, m-1, 1, m, n-1 Perform [m, n] => [m-1, 1, m, n-1] 0*1:+? r, m-1, 1, m, n-1 Jump to Loop if n>0 +0= r, m-1, 1 Remove the last two elements 11:+? r, m-1, 1 Jump to Loop SmallM: 1++ n+m+1, r Perform [m, n] => [n+m+1] /1:+? n+m+1 Jump to Loop if r>0 . Print n+m+1 ``` **Explanation** Because there are no built in function calls (or recursion) in Ral, we need to simulate the stack frame. One way to do that is as follows: 1. Start with the stack [m, n] 2. Repeatedly apply the following rules, until a single element remains: * [..., 0, n] => [..., n+1] * [..., m, 0] => [..., m-1, 1] * [..., m, n] => [..., m-1, m, n-1] 3. Print the remaining element However, since there is no way to know the current length of the stack in Ral, an additional flag is stored to test if the recursion should continue, resulting in the following rules: * [..., 0, 0, n] => Print n+1 and exit * [..., 1, 0, n] => [..., n+1] * [..., m, 0] => [..., m-1, 1] * [..., m, n] => [..., m-1, 1, m, n-1] [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 16 bytes ``` {x/[;1]1+}/[;1+] ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6qu0I+2Now11K4F0dqxXFxp0Qax6oqGhkCGIYxhBGMYgxkAj2QNVg==) Same structure as my K answer for [fast growing hierarchy](https://codegolf.stackexchange.com/a/264876/78410), and happens to be the same length too. Can compute f(0..3)(0..10) in a couple seconds. Again uses "`A(m+1,n)` is `A(m,?)` applied `n+1` times to 1." ``` {x/[;1]1+}/[;1+] input: m, returns function that takes n { }/[;1+] iterate m times on the function 1+ (increment): 1+ create a function that increments n and then x/[;1] run `x/[n+1;1]` == `(n+1)x/1` == iterate function x n+1 times to 1 ``` [Answer] ## APL, 31 ``` {⍺=0:⍵+1⋄⍵=0:1∇⍨⍺-1⋄(⍺-1)∇⍺∇⍵-1} ``` Pretty straightforward. Uses the ⍨ character once to save one byte by reversing arguments. Takes m as the left argument and n as the right argument. [TryAPL.org](http://tryapl.org/) [Answer] # Go, ~~260~~ ~~243~~ ~~240~~ 122 bytes I didn't see that the question allowed anon funcs. far from competitive but i'm learning this language and i wanted to test it out. ``` func (m,n int)int{r:=0 switch{case m==0&&n!=0:r=n+1 case m!=0&&n==0:r=a(m-1,1) case m!=0&&n!=0:r=a(m-1,a(m,n-1))} return r} ``` use it like `go run ack.go` and then supply two numbers, `m` and `n`. if m>4 or n>30, execution time may be in excess of half a minute. for `m=3 n=11`: ``` $ time go run ack 16381 real 0m1.434s user 0m1.432s sys 0m0.004s ``` *edit*: saved total 17 bytes by switching to `switch` over `if/else` and dot-imports [Answer] ## Ceylon, ~~88~~ ~~87~~ 85 ``` alias I=>Integer;I a(I m,I n)=>m<1then n+1else(n<1then a(m-1,1)else a(m-1,a(m,n-1))); ``` This is a straightforward implementation. Formatted: ``` alias I => Integer; I a(I m, I n) => m < 1 then n + 1 else (n < 1 then a(m - 1, 1) else a(m - 1, a(m, n - 1))); ``` The alias saves just one byte, without it (with writing `Integer` instead of `I`) we would get to 86 bytes. Another two bytes can be saved by replacing `== 0` by `< 1` twice. With the default settings of `ceylon run`, it will work up to `A(3,12) = 32765` (and `A(4,0) = 13`), but `A(3,13)` (and therefore also `A(4,1)`) will throw a stack overflow error. (`A(3,12)` takes about 5 seconds, `A(3,11)` about 3 on my computer.) Using `ceylon run-js` (i.e. running the result of compiling to JavaScript on node.js) is a lot slower (needs 1 min 19 s for `A(3,10)`), and breaks already for `A(3, 11)` with a »Maximum call stack size exceeded« (using default settings) after running for 1 min 30 s. --- ## Ceylon without recursion, 228 As a bonus, here is a non-recursive version (longer, of course, but immune to stack overflows – might get an out-of-memory error at some point). ``` import ceylon.collection{A=ArrayList}Integer a(Integer[2]r){value s=A{*r};value p=s.addAll;while(true){if(exists m=s.pop()){if(exists n=s.pop()){if(n<1){p([m+1]);}else if(m<1){p([n-1,1]);}else{p([n-1,n,m-1]);}}else{return m;}}}} ``` Formatted: ``` import ceylon.collection { A=ArrayList } Integer a(Integer[2] r) { value s = A { *r }; value p = s.addAll; while (true) { if (exists m = s.pop()) { if (exists n = s.pop()) { if (n < 1) { p([m + 1]); } else if (m < 1) { p([n - 1, 1]); } else { p([n - 1, n, m - 1]); } } else { // stack is empty return m; } } } } ``` It is quite slower on my computer than the recursive version: `A(3,11)` takes 9.5 seconds, `A(3,12)` takes 34 seconds, `A(3,13)` takes 2:08 minutes, `A(3,14)` takes 8:25 minutes. (I originally had a version using lazy iterables instead of the tuples I now have, which was even much slower, with the same size). A bit faster (21 seconds for `A(3,12)`) (but also one byte longer) is a version using `s.push` instead of `s.addAll`, but that needed to be called several times to add multiple numbers, as it takes just a single Integer each. Using a LinkedList instead of an ArrayList is a lot slower. [Answer] ## R - ~~54~~ 52 I've used this as an excuse to try and get my head around R, so this is probably really badly done:) ``` a=function(m,n)"if"(m,a(m-1,"if"(n,a(m,n-1),1)),n+1) ``` Example run ``` > a(3,8) [1] 2045 ``` I get a stack overflow for anything beyond that ## T-SQL- 222 I thought I would try to get T-SQL to do it as well. Used a different method because recursion isn't that nice in SQL. Anything over 4,2 bombs it. ``` DECLARE @m INT=4,@n INT=1;WITH R AS(SELECT 2 C, 1 X UNION ALL SELECT POWER(2,C),X+1FROM R)SELECT IIF(@m=0,@n+1,IIF(@m=1,@n+2,IIF(@m=2,2*@n+3,IIF(@m=3,POWER(2,@n+3)-3,IIF(@m=4,(SELECT TOP(1)C FROM R WHERE x= @n+3)-3,-1))))) ``` [Answer] # [Tcl](http://tcl.tk/), 67 bytes ``` proc tcl::mathfunc::A m\ n {expr {$m?A($m-1,$n?A($m,$n-1):1):$n+1}} ``` [Try it online!](https://tio.run/##PY/BaoQwEIbP@hQ/kkOXum2kp4YNxXfYm@tB0mwbMGNIIhQkz26jazsMzMB888/8UY2roai9g9dq9sFMNBprIpaEd8756vykENUohB3i930mJUQLewNh0T/OY2H2o31i9tzUjPYu13NzEjkZPTcprfcpY0FHWPC0LVzkW66GlIfNTVn8E/Qg6CIb/ofQjhTb@IpuP9qF6A19wQ4OS2WN8lPQaqLPAKc9THY0xOylyj4Sumisfui3h8Dx56lPff/a8D1e@hsOlXzOzTGgsjJzIMmoRitZW2PTkuxalUUq0/oL "Tcl – Try It Online") --- # [Tcl](http://tcl.tk/), 77 bytes ``` proc A m\ n {expr {$m?[A [expr $m-1] [expr {$n?[A $m [expr $n-1]]:1}]]:$n+1}} ``` [Try it online!](https://tio.run/##PY/BasMwEETP9lcMRre6jUxPLRHF/5Cb40NQ1SLIroWkQMHo252141QHacW8nd3J9rp4zi4GRGdvMfmJr558xlzwobVeQpwsetAZjNn9hYhZ0dfQY9g@il67ca9nxaug6KmxaONnV@RS/NKVsvxMgiWXQdBldTqad3k92wiSoq7@CX4QfDSdfiK8IdUqn/YhQ8rR8y/oEjA35G2ckrMTfycEF@El2yVLqkYSFQzZk3v4S4JtV8WjLHjo9HbexjP2fhkUbjmhIaOoBRvFLXqj@hari1Gnpq5KXZY7 "Tcl – Try It Online") In the online compiler it fails to run due to time-out, but in a local Tcl interpreter it runs well. I profiled of each root call to `A` function, to see how much time the calculation took for each pair `{m,n}` subject to be tested: ``` m=0, n=0, A=1, time=3.5e-5 seconds m=0, n=1, A=2, time=2e-6 seconds m=0, n=2, A=3, time=8e-6 seconds m=0, n=3, A=4, time=1e-6 seconds m=0, n=4, A=5, time=2e-6 seconds m=0, n=5, A=6, time=1e-6 seconds m=0, n=6, A=7, time=1e-6 seconds m=0, n=7, A=8, time=1e-6 seconds m=0, n=8, A=9, time=1e-6 seconds m=0, n=9, A=10, time=0.0 seconds m=0, n=10, A=11, time=1e-6 seconds m=1, n=0, A=2, time=4e-6 seconds m=1, n=1, A=3, time=6e-6 seconds m=1, n=2, A=4, time=1e-5 seconds m=1, n=3, A=5, time=1.2e-5 seconds m=1, n=4, A=6, time=1.5e-5 seconds m=1, n=5, A=7, time=2e-5 seconds m=1, n=6, A=8, time=2e-5 seconds m=1, n=7, A=9, time=2.6e-5 seconds m=1, n=8, A=10, time=3e-5 seconds m=1, n=9, A=11, time=3e-5 seconds m=1, n=10, A=12, time=3.3e-5 seconds m=2, n=0, A=3, time=8e-6 seconds m=2, n=1, A=5, time=2.2e-5 seconds m=2, n=2, A=7, time=3.9e-5 seconds m=2, n=3, A=9, time=6.3e-5 seconds m=2, n=4, A=11, time=9.1e-5 seconds m=2, n=5, A=13, time=0.000124 seconds m=2, n=6, A=15, time=0.000163 seconds m=2, n=7, A=17, time=0.000213 seconds m=2, n=8, A=19, time=0.000262 seconds m=2, n=9, A=21, time=0.000316 seconds m=2, n=10, A=23, time=0.000377 seconds m=3, n=0, A=5, time=2.2e-5 seconds m=3, n=1, A=13, time=0.000145 seconds m=3, n=2, A=29, time=0.000745 seconds m=3, n=3, A=61, time=0.003345 seconds m=3, n=4, A=125, time=0.015048 seconds m=3, n=5, A=253, time=0.059836 seconds m=3, n=6, A=509, time=0.241431 seconds m=3, n=7, A=1021, time=0.971836 seconds m=3, n=8, A=2045, time=3.908884 seconds m=3, n=9, A=4093, time=15.926341 seconds m=3, n=10, A=8189, time=63.734713 seconds ``` It fails for the last pair `{m,n}={3,10}`, as it takes a very little more than one minute. For higher values of `m`, it will be needed to increase the `recursionlimit` value. --- I coult get it shorter to 65 bytes, but it will not meet the question's requirement "Your function must be able to find the value of A(m,n) for m ≤ 3 and n ≤ 10 in less than a minute.". Without the `{}` it will timeout on TIO and not do the demo of the last two entries. # [Tcl](http://tcl.tk/), 65 bytes ``` proc tcl::mathfunc::A m\ n {expr $m?A($m-1,$n?A($m,$n-1):1):$n+1} ``` [Try it online!](https://tio.run/##PY/BasMwEETP8VcMRoeGOq1MTzURxf@Qm@ODUZVW4F0LSYaC0be7iuN2WdiFfczsRD2ulqPxDt7o2Qc78WjJRiwJ71LK1flJI@qxaWiI37eZddO0oCsYi/lxHoI@2idBp7oSvG15nupjk1vwc53W2@SxBBNBkAmLoLN6y9Oy9qC8FId/gh8En1Ut/xDekMP9fEG3WXYhestfoMFhKclqPwWjJ/4McMbD5jxDzEnKnCKhi5bMQ7/dBfY3j33q@9dabvXSX7GrZDs3x4CSVObASnCFVom2wl1LiUtZHFKR1l8 "Tcl – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 36 bytes ``` A(m,n){m=m?A(m-1,n?A(m,n-1):1):n+1;} ``` Naive strategy with a little bit of optimization. [Try it online!](https://tio.run/##TY7BCsIwDIbvfYowEVrWisWbWx2@hxdpnRZsOub0MvbsNa0g@wnJnz/fIVbdrU3pzINEMQcTOrJKS@xKpLQ4UmGtmyVtPNrn292gfU3Ox93jxJjHCcLVI/9E7wSbGZD6OPJyAAP7hkZr4ECzrkW5rxn8MZgZnc0ayhpGwnpeBbN1ErD0/BugIH/BSkJe/qFo2JK@ "C (gcc) – Try It Online") [Answer] # [Verilog (Icarus Verilog)](http://iverilog.icarus.com/), 81 bytes Based on the [C answer](https://codegolf.stackexchange.com/a/201372/62493). Verilog is not really intended for this kind of thing - Yosys crashes on this - but it's possible with Icarus. ``` function automatic[15:0]a;input[15:0]m,n;a=(m==0)?n+1:(n==0)?a(m-1,1):a(m-1,a(m,n-1));endfunction ``` Testbench: ``` module test(); function automatic[31:0]a;input[31:0]m,n;a=m?a(m-1,n?a(m,n-1):1):n+1;endfunction initial begin $display("%d", a(3,10)); end endmodule ``` Icarus is really not intended for this kind of constant abuse, though: ``` $ time ./a.out 8189 real 0m55.422s user 0m55.375s sys 0m0.063s ``` [Answer] # Haskell, 47 bytes ``` a 0 n=n+1 a m 0=a(m-1)1 a m n=a(m-1)(a m (n-1)) ``` (Run using `ghci <filename>`) Almost directly copies from the problem definition (thank you pattern matching!). ]
[Question] [ Write a rectangular block of text that when arranged into a [Sierpinski carpet](http://en.wikipedia.org/wiki/Sierpinski_carpet), using same-sized blocks of spaces for the empty portions, creates a program that outputs the iteration number of the carpet. For example, if your text block is ``` TXT BLK ``` then running the program ``` TXTTXTTXT BLKBLKBLK TXT TXT BLK BLK TXTTXTTXT BLKBLKBLK ``` should output `1` because the shape of the program represents the first iteration of the Sierpinski carpet. Similarly, running ``` TXTTXTTXTTXTTXTTXTTXTTXTTXT BLKBLKBLKBLKBLKBLKBLKBLKBLK TXT TXTTXT TXTTXT TXT BLK BLKBLK BLKBLK BLK TXTTXTTXTTXTTXTTXTTXTTXTTXT BLKBLKBLKBLKBLKBLKBLKBLKBLK TXTTXTTXT TXTTXTTXT BLKBLKBLK BLKBLKBLK TXT TXT TXT TXT BLK BLK BLK BLK TXTTXTTXT TXTTXTTXT BLKBLKBLK BLKBLKBLK TXTTXTTXTTXTTXTTXTTXTTXTTXT BLKBLKBLKBLKBLKBLKBLKBLKBLK TXT TXTTXT TXTTXT TXT BLK BLKBLK BLKBLK BLK TXTTXTTXTTXTTXTTXTTXTTXTTXT BLKBLKBLKBLKBLKBLKBLKBLKBLK ``` should output 2 because this is the shape of the second Sierpinski carpet iteration. Running the text block as is ``` TXT BLK ``` should output `0` because it can be considered the zeroth iteration. This should work for all further iterations. (At least theoretically, assuming the computer has the memory and all.) # Details * Programs may not read or access information about their source code. Treat this like a strict quine challenge. * Output goes to stdout or similar alternative. Only output the number and an optional trailing newline. There is no input. * The text block may contain any characters that are not considered [line terminators](http://en.wikipedia.org/wiki/Newline#Unicode). The text block may contain spaces. * The "empty space" in the carpet must consist entirely of [space characters](http://www.fileformat.info/info/unicode/char/0020/index.htm). * You may optionally assume all the programs have a trailing newline. You can use this stack snippet to generate a carpet for a given text block at any iteration: ``` <style>#o,#i{font-family:monospace;}</style><script>function c(e){e=e.split("\n");for(var n=new Array(3*e.length),t=0;t<n.length;t++){var l=t%e.length;n[t]=e[l]+(t>=e.length&&t<2*e.length?e[l].replace(/./g," "):e[l])+e[l]}return n.join("\n")}function f(){for(i=document.getElementById("i").value,n=parseInt(document.getElementById("n").value);n>0;)i=c(i),n--;document.getElementById("o").value=i}</script><textarea id='i'placeholder='code block...'rows='8'cols='32'></textarea><br>Iterations <input id='n'type='text' value='1'><br><br><button type='button'onclick='f()'>Generate</button><br><br><textarea id='o'placeholder='output...'rows='8'cols='32'style='background-color:#eee'readonly></textarea> ``` # Scoring The submission whose initial text block is smallest by area (width times height) is the winner. The `TXT\nBLK` example is 3 by 2 for a score of 6. (Basically the shortest code wins, hence the code-golf tag.) Tiebreaker goes to the submission that uses the fewest distinct characters in their text block. If still tied, answer posted first wins. [Answer] # piet - 32\*6 = 192 ![enter image description here](https://i.stack.imgur.com/nnkcv.png) I filled the empty space with the checker pattern. I think it makes the Sierpinski a bit trippier. Here is the second iteration: ![enter image description here](https://i.stack.imgur.com/G89bd.png) ## original : 32\*7 ![enter image description here](https://i.stack.imgur.com/uVxUK.png) [Answer] # CJam, 9 bytes I think this can be improved, but for now, lets go with it... ``` ];U):U8mL ``` **How it works**: ``` ]; "Wrap everything on stack in an array and discard it"; "Before this point, the only thing on array can be the log 8 result of"; "last updated value of U, or nothing, if its the first code"; U):U "Increment by 1 and update the value of U (which is pre initialized to 0)"; 8mL "Take log base 8 of U. This is the property of Sierpinski carpet that"; "the occurrence of the code is 8 to the power iteration count, indexed 0"; ``` [Try it online here](http://cjam.aditsu.net/#code=%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%0A%5D%3BU)%3AU8mL%20%20%20%20%20%20%20%20%20%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%20%20%20%20%20%20%20%20%20%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%20%20%20%20%20%20%20%20%20%5D%3BU)%3AU8mL%0A%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%0A%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%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%20%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%0A%5D%3BU)%3AU8mL%20%20%20%20%20%20%20%20%20%5D%3BU)%3AU8mL%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%20%5D%3BU)%3AU8mL%20%20%20%20%20%20%20%20%20%5D%3BU)%3AU8mL%0A%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%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%20%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%0A%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%0A%5D%3BU)%3AU8mL%20%20%20%20%20%20%20%20%20%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%20%20%20%20%20%20%20%20%20%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%20%20%20%20%20%20%20%20%20%5D%3BU)%3AU8mL%0A%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL%5D%3BU)%3AU8mL) [Answer] # [><>](http://esolangs.org/wiki/Fish), 11 \* 2 = 22 ``` ";n"00pbi1v +$3*:@3-0.> ``` Here we take a different approach by using ><>'s jump/teleport functionality. The program only executes blocks in the top row, running the 1st/2nd block, then the 3rd/4th blocks, 9th/10th blocks, 27th/28th blocks, etc. (going up in powers of 3). As the top row has `3^n` blocks, only `n` blocks are executed before the program wraps back to the start, outputs the top of the stack and halts (due to the `n` instruction placed via `p`). The program exploits the rule "There is no input.", as the `i` command pushes -1 onto the stack if EOF is met. So to test this you'll need to pipe in an empty file. --- ## Previous submission, 7 \* 4 = 28 ``` l"v"10p v>:1=?v 3 ;n{< <^}+1{, ``` The first line continuously pushes the length of the stack for every block, and changes the first `"` quote to a down arrow `v` using the `p` put command. By the time the first line is over, the stack looks like ``` [0, 1, 2, .., 3^n] ``` (Note that the initial `l` is used twice.) The last three lines then count how many times we need to divide by 3 before we hit 1 (since ><> doesn't have a log function). The bottom zero is used to keep track of the count. [Answer] # Perl, 26 ``` $_+=.91/++$n; die int."\n"; ``` This uses the harmonic series to approximate the base 3 logarithm. I think it works, but I've only tried it for small numbers. Thanks to squeamish ossifrage for the idea of using `die`. Old version (34): ``` $n--or$n=3**$s++; print$s-1if!$o++; ``` [Answer] # Perl, 30 (15×2) First of all, I'm going to claim that 10 iterations is a reasonable limit, not 232. After 10 iterations, a program consisting of *N* bytes will have expanded to (*N* × 320) bytes (plus line breaks), which is over 3 gigabytes even for *N*=1. A 32-bit architecture would be completely unable to handle 11 iterations. (And obviously there aren't enough particles in the universe for 232 iterations). So here's my solution: ``` $n++; $_=log$n; print int;exit; ``` This works by incrementing the variable `$n` in the first line and calculating its logarithm at each step. The second line prints the integer part of this logarithm and quits. A simple logarithm to base *e* (2.718..) is close enough to give correct results for the first 10 iterations. [Answer] # Golfscript, 9 \* 2 = 18 ``` 0+ ,3base,(} ``` *(Note that the first line has trailing spaces to make it rectangular)* I couldn't find a log function for Golfscript, so `base` had to do. Golfscript starts off with an empty string, so `0+` just increases the length of the string by 1 (by coersion). By the time the first line is over, the stack will have a string of length `3^n`, which we take the log base 3 of before we super comment. `n` is then automatically printed. [Answer] # **C, 12x8 = 96** Inspired by @ciamej, I've reduced it. It uses that divide by 3 trick, plus the realization that the carpet effectively converts an if into a while loop. The code was tested on gcc/Ubuntu for iterations up to 3. ``` #ifndef A // #define A // x;main(a){// a++;/* */ if(a/=3)x++; printf( // "%d",x);} // #endif // ``` --- *Previous Solution: **C, 11x12*** Not a size winner, but hey, it's C. It finds log2 of the blockcount by bitshifting, then uses some magic numbers and int truncation to estimate log3. The math should work up to 26 iterations (a 42 bit number). ``` #ifndef A// #define A// int n=0;//_ int main//_ (v,c){//___ n+=1;/*..*/ while(n//__ >>=1)v++;// n=.3+.62*v; printf(//__ "%d",n);}// #endif//__ ``` [Answer] # CJam, 9 bytes The idea of using `]` is from Optimizer, but it uses a very different method to count. ``` X~]:X,8mL ``` [Try it online](http://cjam.aditsu.net/#code=X~%5D%3AX%2C8mL) How it works: ``` X~ "push X and dump its contents. On the zeroth iteration, X is a single number, but later is it an array."; ] "wrap everything into an array. The stack would contain the contents of X plus the result of the previous instance of the code"; :X "store this array back into X. X is now 1 element longer"; , "take the length of X"; 8mL "do a base-8 logarithm of it"; ``` ## Two other 9 byte solutions ``` ]X+:X,8mL ],X+:X8mL ``` [Answer] # Python 2, 15 \* 3 = 45 ``` m=n=0;E=exit ; m+=1;n+=m>3**n; print n;E() ; ``` Another implementation of the count-first-row-then-log-three-and-exit idea. Can probably still be golfed a fair bit more. [Answer] # ><> (Fish), 12 \* 3 = 36 A more straightforward ><> solution: ``` 'v'00p0l1+ > :2-?v$1+v ^$+1$,3< ;n< ``` We first run the top row of the top blocks. `'v'00p` puts `v` at the very first position of the whole program directing the program pointer downwards when it gets back to the start after reaching the end of the line. Before that every block pushes 0 and the length of the stack + 1 onto it. (stack will be `0 2 0 4 0 6 ...`) On the first half of the second and third we count how many times we can divide the top stack element before we get 2 (we store this in the second to top element). At the end we output the second to top element of the stack. [Answer] # bc, 2\*16+1 = 33 The extra +1 in the score is because the `-l` bc option is required: ``` a+=1; l(a)/l(3);halt; ``` [Answer] # Golfscript, 7 \* 2 = 14 ``` 1+~abs( 3base,} ``` This is inspired by Sp3000's [answer](https://codegolf.stackexchange.com/a/47065/194), and in particular by the desire to optimise the long second line. `3base,` is as short as a base-3 logarithm will get in GS, and the super-comment `}` is clearly optimal. What's required for the first line is to map the empty string `''` from the initial stdin to 0, and then to map each non-negative integer to its successor. In this way we end the first line with `3^n - 1` on the stack, and `3base,` doesn't require any decrement. [Answer] # C, 13x8 ``` #ifndef A//__ #define A//__ x;a;main(){// a++;;;;;;;;;; while(a/=3)// x++;printf(// "%d",x);}//__ #endif//_____ ``` [Answer] # Perl, 76 I know there's probably not much point in posting this since it's already been thoroughly beaten, but here's my current solution anyways. ``` $_++; if(not$_&$_-1){print log()/log 8;$_--} ``` [Answer] # Lua, 3 \* 17 = 51 Same strategy as most people: ``` x=(x or 0)+1; y=math.log(x,3) print(y)os.exit() ``` [Answer] # PHP, 22×2 = 44 27×2 = 54 ``` <?php $i++ ?> <?php die(log($i,3))?> ``` Just another take on count-log3-out. Not very small, but my first golf ;) ]
[Question] [ Since 2009, Android's version code names have been confectionery-themed. Android 1.5 is Cupcake, Android 1.6 is Donut, Android 2.0 is Eclair, etc.. In fact, the version names are alphabetical! ``` C -> Cupcake D -> Donut E -> Eclair F -> Froyo G -> Gingerbread H -> Honeycomb I -> Ice Cream Sandwich J -> Jellybean K -> Kitkat L -> Lollipop M -> Marshmallow N -> Nougat O -> Oreo ``` In order: ``` Cupcake, Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwich, Jellybean, Kitkat, Lollipop, Marshmallow, Nougat, Oreo ``` ## Challenge Write a **program/function** that takes a letter from `C` to `O` and outputs its respective Android version code name. ### Specifications * [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods "Default for Code Golf: Input/Output methods") **apply**. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default "Loopholes that are forbidden by default") are **forbidden**. * You can choose to either support lowercase input or uppercase input or even both. * The output may be in title case (`Cupcake`) or completely lower case (`eclair`). `Ice cream sandwich` may be capitalized however you like. (I didn't expect it to cause so much confusion...) * This challenge is not about finding the shortest approach in all languages, rather, it is about finding the **shortest approach in each language**. * Your code will be **scored in bytes**, usually in the encoding UTF-8, unless specified otherwise. * Built-in functions (Mathematica might have one :P) that compute this sequence are **allowed** but including a solution that doesn't rely on a built-in is encouraged. * Explanations, even for "practical" languages, are **encouraged**. ### Test cases These are uppercase and title case. ``` Input Output F Froyo I Ice Cream Sandwich J Jellybean N Nougat G Gingerbread L Lollipop ``` In a few better formats: ``` F, I, J, N, G, L f, i, j, n, g, l F I J N G L f i j n g l ``` [Answer] # Bash + Core Utils ~~131~~ ~~128~~ ~~122~~ 117 bytes. The script is encoded as Base64 because it contains special (weird) characters. Accepts the Android codename letter **only in lowercase** as its first positional parameter. Returns the full codename **also in lowercase**. ``` CiPBUeICicG5tJ8W5a0Pc/hYuw7hkNMSIYkAPjARkdgFrdbh3NJgTmB4gRPiiQDJAaOyBH4ki14C QDeKRNQJ8IJYER411DAnx0SO4CAKYmFzZTMyICQwfHRyICdBLVo0NwonICdhLXoKICd8Z3JlcCBe JDEK ``` --- ### Explanation: ``` #�Q��������s�X����!�>0�������`N`x������~$�^@7�D� ��X5�0'�D�� base32 $0|tr 'A-Z47 ' 'a-z '|grep ^$1 ``` * The first two lines are the binary blob with the data (see a the end of the answer for more information). The first line is empty, to avoid problems with Bash, as otherwise it may think that is being fed with a binary file. * `base32 $0` encodes the script contents with Base32, with the default line wrapping of 76 characters. * `tr 'A-Z47\n' 'a-z\n '` (note that the `\n` is written as a literal newline) will lowercase the input and replace ***4***, ***7*** and `\n` by `\n`, ***space*** and ***space*** respectively. * `grep ^$1` will output the lines matching the string provided as first argument to the script. --- ### Binary data This octet stream was forged so it doesn't contain newlines and when it's decoded with Base32 as per RFC 4648, the resulting string is the list of Android codenames (using ***4*** as item delimiter and ***7*** to replace the *space* character). Among its peculiarities, it begins with a newline character and a hash (`#`) so it behaves as a comment and, therefore, isn't executed by the interpreter. Also, the default line wrapping to 76 characters of this Base32 implementation helped me a byte, as I reordered the items to use the line break as one of the *Ice cream sandwich* spaces. --- Also, and going a bit off-topic, I think that Google shouldn't ~~in~~directly advertise commercial products in the Android codenames. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 73 bytes ``` θ§⪪”%↖↙1¬¢/vy⁵⸿ψJPP±≔S×5Jρνξ–Gu ◧;Yx³F▶ψ;εB↥:P¹N﹪J$α✂χ✳⦄⟲*±¶Sp:ς↘V◧◧”x℅θ ``` [Try it online!](https://tio.run/##AZ0AYv9jaGFyY29hbP//zrjCp@KqquKAnSXihpbihpkxwqzCoi92eeKBteK4v8@I77yqUFDCseKJlO@8s8OXNUrPgc69zr5/wpbvvKd1IOKXp@@8m1l4wrNG4pa2z4g7zrVC4oalOlDCuU7vuapKJM6x4pyCz4finLPipoTin7IqwrHCtlNwOs@C4oaY77y24pen4pen4oCdeOKEhc64//9p "Charcoal – Try It Online") I/O is in lower case. Based on this [verbose version](https://tio.run/##JY5BCoMwEADvfUXwZEBf4KnHnlroC9bNosE1m66xrq9Phd4GBobBGRQFuNaXxlTajx9uf7qXRwpk7TtzLG0jiU6UdTQkh0qwug1SOCLORsznSJAslgWKCXPMkg10m1dglsNkny6hJLZnhIVM0l4MGaKayikW00Q6XtnQdK6xxnfuqSEm4OvI@6FWrP239hv/AA "Charcoal – Try It Online"). Explanation: ``` Implicitly print: θ Input character Implicitly print: ”...” Long compressed string "oneycombx...xingerbread" ⪪ Split on x The string "x" § Circularly indexed by ℅ Character code of θ Input character ``` [Answer] # [Python 3](https://docs.python.org/3/), 139 bytes ``` lambda x:x+'upcake,onut,clair,royo,ingerbread,oneycomb,ce cream sandwich,ellybean,itkat,ollipop,arshmallow,ougat,reo'.split(",")[ord(x)-67] ``` [Try it online!](https://tio.run/##LY1BDoIwEADvvqLxQhtXY2KChkQ/oh6WUmDj0m2WEuH1yMHjzBwmLbmXeFnb@2tlHOoGzVzNh2JKHj8BJE4ZPCMpqCwCFLugtQZsthQWL0MNPhi/mcGMGJsv@R4C81IHjED5gxmEmZIkQB37AZnlCzJ1W9AgxWlMTNnuYe@eoo2d3bG8vtdW1JChaBS3pS2vcDu7ameSUszW92rJQXF8FND@ybn1Bw "Python 3 – Try It Online") [Answer] # Bash + Core Utils (Grep): 132 130 Bytes Simple as could be ``` grep ^$1<<<'Cupcake Donut Eclair Froyo Gingerbread Honeycomb Ice Cream Sandwich Jellybean Kitkat Lollipop Marshmallow Nougat Oreo' ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 57 bytes ``` Oị“¡ȥọ⁴ḷæĿɱ}#n#i®ÞSỊ3ƙɼıjṁ)-⁵g7ḥjC?4ƘẠʂ+ḋ¤⁺jṣð£?v»Ḳ¤F⁾! y ``` [Try it online!](https://tio.run/##AXMAjP9qZWxsef//T@G7i@KAnMKhyKXhu43igbThuLfDpsS/ybF9I24jacKuw55T4buKM8aZybzEsWrhuYEpLeKBtWc34bilakM/NMaY4bqgyoIr4biLwqTigbpq4bmjw7DCoz92wrvhuLLCpEbigb4hIHn///9j "Jelly – Try It Online") -5 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). [Answer] # C++, ~~206~~ ~~201~~ 198 bytes *Thanks to @sergiol for helping to save 3 bytes!* ``` #import<cstdio> void f(int l){char*w[]={"upcake","onut","clair","royo","ingerbread","oneycomb","ce Cream Sandwich","ellybean","itkat","ollipop","arshmallow","ougat","reo"};printf("%c%s",l,w[l-67]);} ``` [Try it online!](https://tio.run/##PZDBjoMgEIbvPAVh06hbe91NqvbSB9jDHrs94EiVdGQI4hpjfHYXbLJcfvjnA@YfsPbUAmzbm@4tOV/C4BtNF/ZLuuGPVBvPMVugk@59ut2rRYwW5FOJXJAZfRBAqV1QRzMF0aZVrnZKNjuiZqC@jpji1@D2/FuaZtLQBU8hzrWSJl7zTxlfI0RtyYaddEPXS0Saoj22e9kpEmthXWjrkYoDHAaRYz7d8PTxec@KNcQwgGOjeKlp8PHDC2MxRC@1STO2MB7WgxxPYyaOVXJNCo5llXwFPR4x24kXt7MpZsX/KUznfAYaPS9LLn6MeJVWtm5/) # C, 173 bytes ``` f(l){char*w[]={"upcake","onut","clair","royo","ingerbread","oneycomb","ce Cream Sandwich","ellybean","itkat","ollipop","arshmallow","ougat","reo"};printf("%c%s",l,w[l-67]);} ``` Well, it started as C++, but now it's also valid C, and some bytes can be saved by compiling it as C. [Try it online!](https://tio.run/##PY@xjoMwDIZ3niKKVBGudL0OlKkPcEPHqoNJA0Q1SWRACCGenTq0Oi@//fuzZetTo/W21QqzRbdAP9P9US5yDBpeRubSu3Fg0QiWWMnPnsW6xlBFBp47YmbtuypiRlzZ7cQN3HOyumXPIM6VARfHhhfEbR7RBh84A@rbDhD9FO2x2dtkvFyLQNYNtZIHfehljvl0x9Pv@ZEV68YN0YF1KkuWRHDUnoSK5wss02taCLyU6R/r8YjZTny4neVXi/8qjEOvpPw6a7Jubw) [Answer] # JavaScript (ES6), ~~137~~ 136 bytes *Saved 1 byte thanks to Neil* ``` c=>'CupcakeDonutEclairFroyoGingerbreadHoneycombIce Cream SandwichJellybeanKitkatLollipopMarshmallowNougatOreo'.match(c+'([a-z]| .)+')[0] ``` ### Demo ``` let f = c=>'CupcakeDonutEclairFroyoGingerbreadHoneycombIce Cream SandwichJellybeanKitkatLollipopMarshmallowNougatOreo'.match(c+'([a-z]| .)+')[0] ;[...'CDEFGHIJKLMNO'].map(c => console.log(c, '->', f(c))) ``` [Answer] # [Japt](https://github.com/ethproductions/japt/), ~~81~~ 79 bytes Contains a few characters that won't display here. ``` U+`Æ+tfÆ÷¯kef©fclairfê $ßdfey¬mbf­ ×Äm ÑØrfÁKÞ fkfo¥ipopfÂâÚaow`qf gUc ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=VStgxit0ZpzG969rZWaNqWZjbGFpcmae6gGgJN+EZGaNZXmsbWJmrSDXxG0g0YDYcmbBS94gZoprhWZvpWlwb3BmwuLaYW93YHFmIGdVYw==&input=IkUi) * 2 bytes saved thanks to [Oliver](https://codegolf.stackexchange.com/users/61613/oliver). --- ## Explanation Implicit input of uppercase character string `U`. A compressed string (everything between the backticks) of the names, separated with an `f` and without their first letter is split (`q`) into an array on `f`. Within that array we get the element at the index (`g`) of `U`s character code. (Yay, index wrapping!) We append that to `U` and implicitly output the resulting string. [Answer] # Excel VBA, ~~137~~ ~~134~~ 132 Bytes Anonymous VBE immediate window function that takes input as expected type `Variant\String` and length `1` holding a **capital** letter from cell `[A1]` and outputs to the VBE immediate window function ``` ?[A1]Split("upcake onut clair royo ingerbread oneycomb ce cream sandwich ellybean itkat ollipop arshmallow ougat reo")(Asc([A1])-67) ``` -5 Bytes for changing the spaces in `ce cream sandwich` from (char 32) to ~~(char 160)~~ `` (char 127) and removing comma delimiter in the `Split` function [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 81 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ]&ŗ√‰fō¶č▓'▼$»3↕█γb└a}⅟∑─b¹¦Æ:↕┘∞½Σ#gī±⅔≡≥\3Qy-7todΥ7ā‼D←εPρρ:¬c‰ƨ}f沑θ╔@ŗz,WHHw ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTVEJTI2JXUwMTU3JXUyMjFBJXUyMDMwZiV1MDE0RCVCNiV1MDEwRCV1MjU5MyUyNyV1MjVCQyUyNCVCQjMldTIxOTUldTI1ODgldTAzQjNiJXUyNTE0YSU3RCV1MjE1RiV1MjIxMSV1MjUwMGIlQjklQTYlQzYlM0EldTIxOTUldTI1MTgldTIyMUUlQkQldTAzQTMlMjNnJXUwMTJCJUIxJXUyMTU0JXUyMjYxJXUyMjY1JTVDM1F5LTd0b2QldTAzQTU3JXUwMTAxJXUyMDNDRCV1MjE5MCV1MDNCNVAldTAzQzEldTAzQzElM0ElQUNjJXUyMDMwJXUwMUE4JTdEZiVFNiVCMiV1MjAxOCV1MDNCOCV1MjU1NEAldTAxNTd6JTJDV0hIdw__,inputs=aQ__) Explanation: ``` ...‘ push "cupcake donut eclair froyo gingerbread honeycomb ice_cream_sandwich jellybean kitkat lollipop marshmallow nougat oreo" θ split on spaces ╔@ŗ replace underscores with spaces z,W find the inputs index in the lowercase alphabet HH decrease by 2 w get that item from the array ``` Now there is a shorter [80 byte](https://dzaima.github.io/SOGLOnline/?code=JTVEJTI2JXUwMTU3JXUyMjFBJXUyMDMwZiV1MDE0RCVCNiV1MDEwRCV1MjU5MyUyNyV1MjVCQyUyNCVCQjMldTIxOTUldTI1ODgldTAzQjNiJXUyNTE0YSU3RCV1MjE1RiV1MjIxMSV1MjUwMGIlQjklQTYlQzYlM0EldTIxOTUldTI1MTgldTIyMUUlQkQldTAzQTMlMjNnJXUwMTJCJUIxJXUyMTU0JXUyMjYxJXUyMjY1JTVDM1F5LTd0b2QldTAzQTU3JXUwMTAxJXUyMDNDRCV1MjE5MCV1MDNCNVAldTAzQzEldTAzQzElM0ElQUNjJXUyMDMwJXUwMUE4JTdEZiVFNiVCMiV1MjAxOCV1MDNCOCV1MjU1NEAldTAxNTd6JTJDVyV1MjA3RXc_,inputs=aQ__) version, but I added the +2/-2 built-ins because of this challenge :p The compressed string is split like `"cup","cake"," donut eclair fro","yo gingerbread honeycomb ice","_","cream","_","sandwich jelly","bean kit","kat loll","i","pop marsh","mallow"," nougat oreo"` for maximum usage of english words (many weren't in SOGLs dictionary), right now I can't find any improvements. [Answer] # [><>](https://esolangs.org/wiki/Fish), 181 bytes ``` !vi:od5*-0$6a*@p! v< v"upcake" v"onut" v"clair" v"royo" v"ingerbread" v"oneycomb" v"ce Cream Sandwich" v"ellybean" v"itkat" v"ollipop" v"arshmallow" v"ougat" v"reo" o<> ``` [Try it online!](https://tio.run/##LY0xDoMwDEV3TgGoE1KlLu1QoapSx449gUlcsDBxFEgQp09pwvbk//z/l@YhxirQXfS1OV9ON2ietipCW5Sh9lbBiPUfxfglgWIgl8jJJgnI9Og6h6APFTclU5d1LF97MpUfMHolNaQrMm8dgsnvywi5W5jJik0Mbh4mYJY1R74/JIf7qrSPGN8/ "><> – Try It Online") This works by self-modifying the program to place a `<` in front of the correct name to print, the position of which is determined by the value of the inputted letter. [Answer] # [Cubically](https://github.com/aaronryank/cubically), ~~1047~~ ~~852~~ 830 bytes Functions sure help golf large programs... ``` ⇒+552 ⇒+551 ⇒+553 ⇒+55 ⇒/1+52 ⇒/1+53 ~@7+4f5=?{:5+53@:4/1f1@:5+51@:5+2/1f4@:5+3/1f2@:2/1f2@} +5f5=?{:3/1f1@:2/1f1@:5+53@:5+3/1f1@} +51f5=?{:5+51@+1@:5+2/1f4@:5+1/1+551@+1@} +52f5=?{:5+1/1f1@:3/1f1@:4/1f3@:3/1f1@} +53f5=?{:5+1/1f2@:2/1f1@:4/1f2@:2/1f2@:5+1/1f1@:5+3/1f4@:5+1/1f1@:2/1f2@:5+2/1f4@:1/1f2@} +53=?{:3/1f1@:2/1f1@-1@:4/1f3@:5+51@:3/1f1@:1/1f1@:5+3/1f4@} +1f6=?{:5+51@:2/1f2@:5/1+3@:4/1+52@:5+1/1f1@:2/1f2@:5+2/1+55@:1/1f1@:5/1+3@:2/1+54@:5+2/1f4@6:2/1f1@6:1/1f2@6:2/1f3@6:5+1/1f2@6:5+51@6:5/1f2@6} +2f6=?{:2/1f2@:5+52@@:4/1f3@:5+3/1f4@:2/1f2@:5+2/1f4@:2/1f1@} +3f6=?{:5+1/1f2@:5+3/1f1@-1@:5+2/1f4@:5+3/1f1@} +4f6=?{:3/1f1@:5+52@@:5+1/1f2@:4/1f1@:3/1f1@:4/1f1@} +5f6=?{:5+2/1f4@:5+1/1f1@:5+2/1f1@:5/1f2@:1/1f1@:5+2/1f4@:5+52@@:3/1f1@:2/1f3} +51f6=?{:3/1f1@:5+53@:4/1f2@:5+2/1f4@:5+3/1f1@} +52f6=?{:5+1/1f1@:2/1f2@:3/1f1@} ``` [Try it online!](https://tio.run/##dVJLagMxDN3PVUwpkuwpDIR6m2OkgUAg2y5CaLfZ94i9yESyZNlxks1oJD89PX3231/H/e50Oq/r//UvpISTWjBLZqff/BHiO4SEm8/LkkKivLB/gCxO@SK7UX6IfzAvWMzPFJLnkWagJ1LFQwFCXwFyuOctrxoWMHZgUEbjF2FUPYHSAEXXEHutjUhFxS7iCJMD3h09dPbWNOhw7HUg5@TSEnnDXoXDOmCW/UIEj6IxKr5EYxM5m57Z1KpPbOsYZq07C4O4LAldkldjDV1DNplxIFinTV1PUEHkgxkOpaRETyE/DanpBPFhv@CXZaVwWJhGdDhCcReOXqJbHPkJDlLI7@SZ@IRDw21RhlnX7Q0) This is 830 bytes in [Cubically's SBCS](https://github.com/aaronryank/Cubically/wiki/Code-page). * `~` reads input, `@` prints it. (This breaks when the input is invalid.) * Each of the `+.../...+...=7?6{...}` compares the input to each ASCII value (`C`, `D`, `E`, `F`, etc) and executes the code within `{...}` if they are equal. * Each code block (`{...}`) prints the rest of the name (the first character is already printed). Thanks to [TehPers' ASCII to Cubically translator](https://codegolf.stackexchange.com/a/135775/61563) which was very helpful. [Answer] # Dyalog APL, ~~158~~ ~~143~~ 131 bytes *1 byte saved thanks to @Zacharý* *12 bytes saved thanks to @Gil* ``` {⍵,(⎕A⍳⍵)⊃','(1↓¨=⊂⊢)',,,upcake,onut,clair,royo,ingerbread,oneycomb,ce Cream Sandwich,ellybean,itkat,ollipop,arshmallow,ougat,reo'} ``` [Try it online!](https://tio.run/##DY47CsJAFACvkm4VnoUHsJD4/xae4GWzxsWXvLAmhCA2CikCEUG8gJW9eAGPshfR7YaZZjClTlgicfT7bW11O9rmAy17ffRt83bctvVFgGh1bXX/vnq2Ptv62RYAkKcS9wo4yTOQhNqA4ZJBJ5EygVEYuqRKyXEAUnm@M7G3wSQstNyBIioDhQnobI8ZMJFOOQU0h12MRFwA55ELRrE4uTPv@xL@YDgaT6az@WK5Wos/) **How?** `',,,upcake...'` - list of words `','(1↓¨=⊂⊢)` - split by `','` `(⎕A⍳⍵)⊃` - take from the place of the argument in the alphabet `⍵,` - and append to the letter [Answer] # EXCEL, 154 bytes ``` =A1&CHOOSE(CODE(A1)-66,"upcake","onut","clair","royo","ingerbread","oneycomb","ce Cream Sandwich","ellybean","itkat","ollipop","arshmallow","ougat","reo") ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~195~~ ~~192~~ 190 bytes -2 bytes thanks to @Quentin ``` *V[]={"upcake","onut","clair","royo","ingerbread","oneycomb","ce Cream Sandwich","ellybean","itkat","ollipop","arshmallow","ougat","reo"};main(c,v)char**v;{printf("%c%s",c,V[(c=*v[1])-67]);} ``` [Try it online!](https://tio.run/##HYy7CoQwEEV/RQKChlhss1uI1bbbLdiIxThmNZgX8YWI355NrM5w5t6LxYDoPa2btjrJahEmThgxel0CUIJwgc4cJkDogbvOcejvCD/QqC7GePIOViVf0P0ucAyOS3l0HHSsLRPENSOlsMaGC9w8KpDS7FGvw/123JCrVCB0hmzLcQRH6Vae1gm9/DKSYjoThqxuMqzo1jzavHi@2ry8vPefPw "C (gcc) – Try It Online") [Answer] # [Tcl](http://tcl.tk/), 158 bytes ``` proc A s {puts $s[lindex {upcake onut clair royo ingerbread oneycomb "ce Cream Sandwich" ellybean itkat ollipop arshmallow ougat reo} [expr [scan $s %c]-67]]} ``` [Try it online!](https://tio.run/##Dco7DoMwEEXRrTwhUqZNapTsICWiMMMILAaP5Y8AIdbuuL3nJpJSfFBCh4jL5xTRxl6sm/jAlT2ZlaEuJ5AYGxD0VFg3cxgDm6kSn6TbiIYYn5o2/IybdktLAxY5RzYONq0mQUWsVw8T4rIZEd2hea4QWG/0fPiAPlL924gHDc/Xexju0uFbyh8 "Tcl – Try It Online") [Answer] # Haskell, 145 bytes ``` f c=takeWhile(/=succ c)$dropWhile(/=c)"CupcakeDonutEclairFroyoGingerbreadHoneycombIce Cream SandwichJellybeanKitkatLollipopMarshmallowNougatOreo" ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 110 bytes ``` :c“reo“upcake“onut“clair“royo“ingerbread“oneycomb“ce Cream Sandwich“ellybean“itkat“ollipop“arshmallow“ougat”=+ ``` [Try it online!](https://tio.run/##HYwxDsMwCEWvkr03qNQpU@eeADvIQcHGIrEibz1Ie7lexIEu8PXehwQEY9zj7/1RFJutRtjQgpR22IoMpG6lu6aSUIMiLP8K9ig5eA2n2WieXlCWk@JqDJl7QCh@dmzg34SZqlRLoPuagVlOxy25/j5uYzwv "Gaia – Try It Online") ### Explanation ``` : Push two copies of the input c Get the codepoint of the top one “...” Push the list of version names without their first letters = Modularly index the code point into the list + Append to the input ``` [Answer] # Ruby, 127 bytes ``` ->c{c+%w[upcake onut clair royo ingerbread oneycomb ce\ Cream\ Sandwich ellybean itkat ollipop arshmallow ougat reo][c.ord-67]} ``` Takes uppercase input. [Try it online!](https://tio.run/##TcmxDoIwEIDhWZ/iFsNgdNRJFwajMS6O0OEoBzSUXlPakMb47JXFpNuX/3ehiam7pMNVfuR@t1TBShwJ2AQPUqNy4DgyKNOTaxxhuy6KkqcGJNVQrmmq4Y2mXZQcgLSODaEB5Uf0wForyxbQzcOEWvMCHPp1OGJRySO79nA6i2@ywc/QVUVZiO3f98yPzK/Mt8zPQmzSDw "Ruby – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), ~~117~~ 116 bytes Port of [my Python answer](https://codegolf.stackexchange.com/a/140076/59487). ``` +Q@c"upcake,onut,clair,royo,ingerbread,oneycomb,ce cream sandwich,ellybean,itkat,ollipop,arshmallow,ougat,reo"\,a67C ``` **[Try it here!](https://pyth.herokuapp.com/?code=%2BQ%40c%22upcake%2Conut%2Cclair%2Croyo%2Cingerbread%2Coneycomb%2Cce+cream+sandwich%2Cellybean%2Citkat%2Collipop%2Carshmallow%2Cougat%2Creo%22%5C%2Ca67C&input=%22C%22&debug=0)** or **[Check out the Test Suite](https://pyth.herokuapp.com/?code=%2BQ%40c%22upcake%2Conut%2Cclair%2Croyo%2Cingerbread%2Coneycomb%2Cce+cream+sandwich%2Cellybean%2Citkat%2Collipop%2Carshmallow%2Cougat%2Creo%22%5C%2Ca67C&input=%22C%22&test_suite=1&test_suite_input=%22C%22%0A%22D%22%0A%22E%22%0A%22F%22%0A%22G%22%0A%22H%22%0A%22I%22%0A%22J%22%0A%22K%22%0A%22L%22%0A%22M%22%0A%22N%22%0A%22O%22&debug=0)** # [Pyth](https://pyth.readthedocs.io), 99 bytes (70 characters) *-15 bytes thanks to [@insert\_name\_here](https://codegolf.stackexchange.com/users/59682/insert-name-here)!* ``` +Q@c." y|çEC#nZÙ¦Y;åê½9{ü/ãѪ#¤ ØìjX\"¦Hó¤Ê#§T£®úåâ«B'3£zÞz~Уë"\,a67C ``` **[Try it here!](https://pyth.herokuapp.com/?code=%2BQ%40c.%22+y%08%7C%C3%A7%C2%85%C2%87EC%23nZ%C3%99%C2%A6Y%3B%C3%A5%C3%AA%C2%BD%C2%819%06%7B%C3%BC%2F%C3%A3%C3%91%C2%8A%C2%AA%23%06%C2%95%12%C2%A4%0A%C3%98%C3%AC%1AjX%5C%22%C2%8E%0F%C2%93%C2%A6H%C3%B3%C2%90%C2%A4%C3%8A%23%1D%0B%1D%C2%A7T%C2%85%C2%A3%04%07%10%C2%99%1D%C2%AE%18%C3%BA%C3%A5%C2%91%C3%A2%0B%C2%91%C2%ABB%14%273%C2%A3z%C3%9Ez%7E%C2%81%C3%90%16%C2%A3%C3%AB%19%22%5C%2Ca67C&input=%22C%22&debug=0)** [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 128 bytes ``` c->c+"upcake#onut#clair#royo#ingerbread#oneycomb#ce Cream Sandwich#ellybean#itkat#ollipop#arshmallow#ougat#reo".split("#")[c-67] ``` [Try it online!](https://tio.run/##NU/LbgIxDLzzFVYipF0VcmylPpAqWvqkPXBEHLzZLASycZQHaFXx7dtA6cGyNTO2Z7a4xzE5Zbf1rnepMlqCNBgCzFFb@BkAXNAQMea2J11Dm7liEb226@UK0K9DeZYCbPM9kaI2oklWRk1WzC7D/XSDHmVUfvS3OoEGHqCX44m8YslJ3ClONkWeDWjPPXXEs0z5yiusM6U6SW3FpYJpRlpYoK0PWm64MqarFFqu4w4jJ2O0I8fRh02LxtCBU1pnwitiIjijY8E4K5dyfH2z6u/OzhvyUMhsEcItsOnT8@zl9e3943P@9c1EpJP5R@@xK8r/rACLLkTVCkpRuJwoNgUb5u1hGFo2CiNoBDpnuiKU5d@T4@BUx/4X "Java (OpenJDK 8) – Try It Online") --- # Using regexes, 149 bytes ``` s->"CupcakeDonutEclairFroyoGingerbreadHoneycombIce cream sandwichJellybeanKitkatLollipopMarshmallowNougatOreo".replaceAll(".*?("+s+"[a-z ]+).*","$1") ``` [Try it online!](https://tio.run/##NVDJbgIxDL33K6yoSDMskXrtQoXY9wNHxMETMhDIxFGSAU0rvp2GpQfL1vOzn58PeMIWWWkO2@PVlplWAoRG72GOysDvC8AT9QFDTCdSWyhiL1kFp8xuvQF0O5/eqQCHuI@XQWmel0YERYYPnsVnd48ORZCu@RhtQw5fcPWtNuuWVuBR9siUoR/1lRs4qmgYWdJlTuJ2REZWgopsLCSIiBTg0WzPSuwnUusqk2imKhwxzEhrZcnO0fl9gVrTeUHlDsPSSWLcSatRyI7WCeP174Q1fIOtsfUDm0bK66zJXt9Yev2428nJQSLi3eDfgXV7/cFwNJ5MZ/PFkvFAN0cd57BK0v8HAKwqH2TBqQzcRpshT1gtTtd8zbCmb0LO0VpdJT5NHyKXl1tcrn8 "Java (OpenJDK 8) – Try It Online") * 4 bytes saved on the regex solution thanks to Kevin Cruijssen! [Answer] # [V](https://github.com/DJMcMayhem/V), 125 bytes ``` Ccupcake donut eclair froyo gingerbread honeycomb ice cream sandwich jellybean kitkat lollipop marshmallow nougat oreoÇ^"/d ``` [Try it online!](https://tio.run/##DcnBDcMgDADAv5/99hN1gQ7RPSoZ44CLwYhAo0yQwToYzffuO@eLRiVMDN7K6MCkKA3WZodBkBK4ucboIVrhgyw7EOKFLsvLhsXvQhE@rHo4xgJJesIOaqpSrULGtsWMqrZDsRGus8Z2/53v2@Pp51z/ "V – Try It Online") [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 117 bytes Port of my [Python answer](https://codegolf.stackexchange.com/a/140076/59487). ``` "upcake,onut,clair,royo,ingerbread,oneycomb,ce cream sandwich,ellybean,itkat,ollipop,arshmallow,ougat,reo"\,cQ.o67-@+ ``` **[Try it here!](http://pyke.catbus.co.uk/?code=%22upcake%2Conut%2Cclair%2Croyo%2Cingerbread%2Coneycomb%2Cce+cream+sandwich%2Cellybean%2Citkat%2Collipop%2Carshmallow%2Cougat%2Creo%22%5C%2CcQ.o67-%40%2B&input=%22C%22&warnings=0)** Encoded as hex codes, the new technique of golfing in Pyke, it would be **116 bytes**: ``` 22 75 70 63 61 6B 65 2C 6F 6E 75 74 2C 63 6C 61 69 72 2C 72 6F 79 6F 2C 69 6E 67 65 72 62 72 65 61 64 2C 6F 6E 65 79 63 6F 6D 62 2C 63 65 20 63 72 65 61 6D 20 73 61 6E 64 77 69 63 68 2C 65 6C 6C 79 62 65 61 6E 2C 69 74 6B 61 74 2C 6F 6C 6C 69 70 6F 70 2C 61 72 73 68 6D 61 6C 6C 6F 77 2C 6F 75 67 61 74 2C 72 65 6F 22 5C 2C 63 51 EF 36 37 2D 40 2B ``` (Paste in and check `Use hex encoding?`). [Answer] ## [C#](http://csharppad.com/gist/7e894e195de97060659364635cbae838), ~~147~~ ~~136~~ 129 bytes --- ### Data * **Input** `Char` `c` The first letter of the version name * **Output** `String` The full name of the version --- [Answer] ## R, 169 155 bytes ``` sub(paste0(".*(",scan(,""),"[^A-Z]+).*"),"\\1","CupcakeDonutEclairFroyoGingerbreadHoneycombIce cream sandwichJellybeanKitkatLollipopMarshmallowNougatOreo") ``` [Answer] # Dyalog APL, 125 bytes ``` {⍵/⍨⍞=⎕A[+\⍵∊⎕A]}'ABCupcakeDonutEclairFroyoGingerbreadHonecombIce cream sandwichJellybeanKitkatLollipopMarshmallowNougatOreo' ``` [Try it online!](https://tio.run/##Fcs9CsIwGIDhq3TrIMUTONT6/3sAdfiahjb0a76QpJQiriJCxcXV2Qt4oVykxvF94AWFUdYCUh4xBGME63v3eLnr8@y679B1H9e9R17iw@Doxd3u/zhdwnic1IpBySckazv1t9AzTS3Nhcy5TjWHbEGSM6rSJeMB81AFBmTWCFasOGKbcpBrYUuwG0IUitQWtCkqQKRmR3UOdq85hX2f/AA) ## How? * `⍵∊⎕A` `⍵` (the long string) with 1 for capital letters, 0 for lowercase/spaces. * `+\` Group (returning numbers) ⍵ by capital letters. * `⎕A[...]` The capital letter signified by a number * `⍵/⍨⍞=` The group signified by that number * `{...}'...'` Set `⍵` to the long string [Answer] # R, ~~131~~, ~~126~~, ~~123~~, ~~112~~, 178 bytes ``` grep(paste0('^',scan(,'')),c("Cupcake","Donut","Eclair","Froyo","Gingerbread","Honeycomb","Ice Cream Sandwich","Jellybean","Kitkat","Lollipop","Marshmallow","Nougat","Oreo"),v=T) ``` Thanks for @Mark for saving 5 + 8 + 3 bytes [Answer] # [Recursiva](https://github.com/officialaimm/recursiva), ~~130 119~~ 118 bytes ``` +aYQ'upcake!onut!clair!royo!ingerbread!oneycomb!ce cream sandwich!ellybean!itkat!ollipop!arshmallow!ougat!reo''!'-Oa99 ``` [Try it online!](https://tio.run/##DckxDsMgDADAr8QTQ9UH5BVVx47GsRIrBiMDjXg9yXrnTN2r/HHOF/6@oRfCk8Fyb0CK4uA2DCTv7NEZt6d4kKUIxAs9kpaKebuEDmDVERkzSDuxgalKsQLo9UioahdY359wthAgvD@4rnMGCzc "Recursiva – Try It Online") * saved 11 bytes thanks to [@Mr.Xcoder's idea](https://codegolf.stackexchange.com/a/140081/59523) [Answer] # [C (gcc)](https://gcc.gnu.org/), 168 bytes ``` main(){puts(memchr("Cupcake\0Donut\0Eclair\0Froyo\0Gingerbread\0Honeycomb\0Ice cream sandwich\0Jellybean\0Kitkat\0Lollipop\0Marshmallow\0Nougat\0Oreo",getchar(),117));} ``` [Try it online!](https://tio.run/##Fcy7CoNAEEDRXxErBQNjlSJl3u8fmGYcB13c3ZHVRSTk241p74HLm4Z5WRwZn@WfPo5D5sRxG7J0H3umThAO6uOIcGRLJiCcgs6KcDa@kVAFoRrhol5mVlchXFkSXqtLBvL1ZLhFuIm1cyXkEe5m7Gi9PdRa02uP8KQwtI6s1QnhpbH58zuIpkUjI7cUsrwoy22e777Lcv4B "C (gcc) – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 136 134 bytes ``` param($c)$c+('upcake0onut0clair0royo0ingerbread0oneycomb0ce cream sandwich0ellybean0itkat0ollipop0arshmallow0ougat0reo'-split0)[$c-99] ``` [Try it online!](https://tio.run/##DY1BCoQwDAC/4kGosgi5@hbxkMagxbQpaUV8fbfXGZjJ@rKVi0Vay2gYp5HmkX6TezLhzaDpqUCCwcD0UwjpZPPGeHTFH2n0QDxQJ3EomI430AW993nGBKHeWEFFQtYM2FcRRfQFfc4ujNUtJUuoMG8jLeu6t9amjS603amb/w "PowerShell – Try It Online") Takes a `[char]` input character, in lowercase, and outputs in lowercase. -2 thanks to AdmBorkBork's suggestion to `-split0` instead of `-split','`. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. ### Tasks All competitors try to solve the following list of 10 tasks: [math](/questions/tagged/math "show questions tagged 'math'") 1. Read a positive integer **n** from input and return the sum of the cubes of the first **n** non-negative integers. For input `1`, this should return `0`. 2. Read a positive integer **n** from input and return a truthy value if and only if **n** is a [Mersenne prime](https://en.wikipedia.org/wiki/Mersenne_prime). 3. Read a non-empty list of **n** integers from input and return their [median](https://en.wikipedia.org/wiki/Median). If **n** is even, use the lesser of the two middle values. For example, the median of `[1 4 3 2]` is `2`. 4. Read an integer (positive, negative or 0), or a string representation in base 10 or unary, from input and return its digits in [negabinary](http://mathworld.wolfram.com/Negabinary.html), without leading zeroes (with the exception of input 0). The output can be formatted in any convenient way (digits, array, string, etc.). [string](/questions/tagged/string "show questions tagged 'string'") 5. Return `pneumonoultramicroscopicsilicovolcanoconiosis`. 6. Check the current date and return `Happy New Year!` if appropriate according to the Gregorian calendar. 7. Pseudo-randomly select 64 unique assigned code points from the Unicode block [CJK Unified Ideographs Extension-A](https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_Extension_A) (U+3400 – U+4DB5) and return the string of the corresponding characters. All possible strings should have the same probability of getting selected. 8. Read two strings of printable ASCII characters from input and return a truthy value if and only if the character of the first string form a subsequence of the second string. For example, `abc`, `axbxc` should return truthy and `bac`, `axbxc` should return falsy. [array-manipulation](/questions/tagged/array-manipulation "show questions tagged 'array-manipulation'") 9. Read a multidimensional, rectangular array of integers and an integer **n** from input and return the modified array with all integers multiplied by **n**. [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") 10. Read a non-negative integer **n** from input and return a chain of **n** train wagons, as shown below. Example output for **n = 3**: ``` ______ ______ ______ | | | | | | ()--() ~ ()--() ~ ()--() ``` The output may be surrounded by any amount of whitespace as long as it looks like in the example. ### Clarifications * **0** is neither positive nor negative. * Trailing whitespace is always permitted in the output. * Several pieces of input may be read in any consistent, convenient order. ### Rules 1. **No answer may solve two different tasks in the same programming language.**1 2. For each individual task, standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. In particular, you can submit programs or functions with the usual [I/O defaults](http://meta.codegolf.stackexchange.com/q/2447), but cannot take advantage of [these loopholes](http://meta.codegolf.stackexchange.com/q/1061). Task 5 is essentially a [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenge, so hardcoding the output is not only allowed but expected. 3. Only one answer per user should be posted, containing at most one solution for each of the tasks. Please format your answer as in the following example: ``` ## Task 1, Python, 42 bytes <code goes here> Explanation, I/O, required Python version, etc. go here. --- ## Task 7, C, 42 bytes <code goes here> Explanation, I/O, required compiler (flags), etc. go here. ``` ### Scoring 1. For every task you solve, you get one point. **This means that you don't have to solve *all* tasks to participate.** 2. If your solution for the task **n** is the shortest one in that programming language, you get an additional point. 3. If your solution for the task **n** is the shortest one of all programming languages, you get an additional point. 4. The bonus points will be awarded only once for each task-language combination and each task, respectively. As usual, if two solutions have the same byte count, posting time is the tie breaker. If somebody outgolfs you later, you lose the bonus point(s) the other answerer earns. 5. You can golf submission, add/remove languages from your answer or swap the languages used for two tasks. Any time somebody edits his answer, all answers are rescored. 6. Once you change languages for a task, you forfeit seniority.2 The answer with the highest score wins.3 ### Per-task leaderboard ``` <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:700}table td{padding:5px}</style><script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><link rel=stylesheet href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id=answer-list><table class=answer-list><thead><tr><td>Task<td>Author<td>Language<td>Score<tbody id=answers></table></div><table style=display:none><tbody id=answer-template><tr><td>{{TASK}}<td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}</table><script>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 getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function process(){answers.forEach(function(e){var s=e.body_markdown.split("\n").filter(function(e){return"#"==e[0]});s.forEach(function(s){var r=s.match(NUMBER_REG)[0],t=(s.match(SIZE_REG)||[0])[0],a=s.match(LANGUAGE_REG)[1],n=e.owner.display_name;entries.push({task:r,user:n,language:a,size:t})})}),entries.sort(function(e,s){var r=e.task-s.task;return r?r:e.size-s.size});for(var e=0;e<entries.length;e++){var s=jQuery("#answer-template").html();s=s.replace("{{TASK}}",entries[e].task).replace("{{NAME}}",entries[e].user).replace("{{LANGUAGE}}",entries[e].language).replace("{{SIZE}}",entries[e].size),s=jQuery(s),jQuery("#answers").append(s)}}var QUESTION_ID=52152,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*.*?,\s*\[*([^,\]]+)/,entries=[];</script> ``` ### Combined leaderboard (2015-07-30 20:00 UTC) ``` User / Task 1 2 3 4 5 6 7 8 9 A TOTAL Tie breaker (if any) DLosc 2 2 3 2 2 2 2 3 2 2 22 Sp3000 2 2 2 2 2 3 2 2 2 2 21 Doorknob 2 2 2 2 2 2 2 2 2 2 20 mathmandan 2 2 2 2 2 2 2 2 2 2 20 Combined byte count. MickyT 2 2 2 2 2 2 1 2 2 2 19 Alex A. 2 1 2 2 2 2 1 2 2 2 18 Jacob 2 2 2 2 2 1 0 0 0 2 13 alephalpha 2 2 2 0 2 2 0 0 2 0 12 Martin Büttner 2 0 0 2 2 0 0 2 2 2 12 Combined byte count. kirbyfan64sos 1 2 2 0 2 X 0 2 0 3 12 Per-language wins. Maltysen 3 0 0 0 3 2 1 X 2 0 11 plannapus 2 2 0 0 2 2 0 2 0 2 10 jimmy23013 0 0 2 3 0 0 3 2 0 0 10 Solved tasks. Tom 0 3 0 0 2 2 0 X 3 0 10 Combined byte count. FryAmTheEggman 1 0 2 0 2 0 2 0 2 0 9 Vioz- 1 0 2 2 2 2 0 0 0 0 9 Combined byte count. Toby Speight 2 0 0 0 2 2 0 0 0 2 8 Ismael Miguel 0 0 0 0 2 2 0 0 0 2 6 Pulga 0 2 2 0 0 0 0 0 0 2 6 Combined byte count. flawr 2 0 2 0 0 0 0 0 0 0 4 manatwork 2 0 0 0 0 2 0 0 0 0 4 Combined byte count. TheNumberOne 1 0 0 0 2 0 0 0 0 0 3 ``` Tasks marked with `X` are present but invalid. The combined leaderboard has been constructed by hand. Please tell me if there are any errors. --- 1 Languages count as different if they are not different versions of the same language, so there's only one JavaScript, one Python, and one TI-BASIC, but C, C++, Octave and MATLAB are four different languages. 2 If you solve task **n** using language **L** in **x** bytes, somebody else solves the same task in the same language with the same byte count, you change to language **M** and roll back your edit, the other answerer will keep the bonus point. 3 The number of points earned from scoring rules 1, 2 and 3 (in that order), the combined byte count of all solved tasks (lower is better) and, finally, the vote tally (higher is better) serve as tiebreakers. [Answer] Huzzah, first to complete all the tasks! \o/ ## Task 1, Perl, 32 bytes ``` $_=eval join"+",map$_**3,0..$_-1 ``` +1 byte for the `-p` flag. Commentary: Perl is *weird*. --- ## Task 2, CJam, 14 bytes ``` {_mp\)2mL_i=&} ``` My first CJam program! --- ## Task 3, GolfScript, 8 bytes ``` ~$.,(2/= ``` Eval STDIN input, sort, take length, decrement, divide by two, then take the item of the sorted array at that index. --- ## Task 4, Python, 77 bytes ``` def f(i,d=''): while i:i,r=i/-2,i%2;i+=r<0;r+=2*(r<0);d=`r`+d return d or 0 ``` Thanks to @mbomb007 for shaving off 24 (!) bytes, and to @Sp3000 for another 11. --- ## Task 5, Java, 66 bytes ``` String f(){return"pneumonoultramicroscopicsilicovolcanoconiosis";} ``` Boring. Knocked out a verbose language here to save room for golfier languages later. --- ## Task 6, Bash, 39 bytes ``` ((`date +%j`<2))&&echo Happy New Year\! ``` Thanks to @manatwork for teaching me about `%j`, shaving off 10 bytes in the process. --- ## Task 7, JavaScript, 148 bytes ``` a=[];Array(65).join('x').replace(/./g,function(){while(a.push(s=String.fromCharCode(13312+Math.random()*6582))&&a.indexOf(s)==s.length-1);return s}) ``` Generate a string of 64 `x`'s, then replace them all with a callback function that returns a random one of those characters if it isn't already in the array of used characters. --- ## Task 8, Rust, 130 bytes ``` fn f(a:String,b:String)->bool{let mut c=b.chars();for x in a.chars(){match c.find(|&y|x==y){Some(_)=>(),None=>return false}};true} ``` Yes, Rust is very very bad at golfing. --- ## Task 9, Ostrich, 18 bytes ``` {:n;'`\d+`{~n*}X~} ``` Version [0.7.0](https://github.com/KeyboardFire/ostrich-lang/releases/tag/v0.7.0-alpha). Inspects the array, does a regex replace to change numbers to their multiplied versions, and then evals the resulting string again. --- ## Task 10, Ruby, 58 bytes ``` ->n{([' ______ '*n,'| | '*n,' ()--() ~'*n]*$/).chop} ``` `"\n"` is one character longer than `"{actual newline}"`, which is one character longer than `$/`. Thanks to @MartinBüttner for shaving off {indeterminate but large number} bytes with various tricks of black magic. [Answer] ## Task 1, 3var, ~~14~~ 13 bytes ``` '><k*>#aa/>sp ``` *([Esolang wiki page for 3var](http://esolangs.org/wiki/3var))* ``` ' R = n > A = n <k B = n-1 * R = A*B = n(n-1) > A = n(n-1) #aa B = 2 / R = A/B = n(n-1)/2 >s A = (n(n-1)/2)^2 p Output A ``` Takes input via a code point, e.g. space is 32. Thankfully all the operations we need to implement the formula `n^2 (n-1)^2 / 4` are single chars (decrementing, multiplication and squaring), yet it takes 3 bytes to set `B` to 2 (reset-increment-increment). --- ## Task 2, Retina, ~~38~~ 33 bytes ``` ^ 1 ^(..|.(..+)\2+|(.(..)+)\3*)$ <empty> ``` *([Github repository for Retina](https://github.com/mbuettner/retina))* Each line goes in a separate file, but you can test the above as is with the `-s` flag (replacing `<empty>` with nothing). Input should be unary with 1s, e.g. `1111111` for 7. Here's what each regex substitution (specified by a pair of lines) does: 1. Tack on an extra 1 to the front 2. Replace anything of the form `2`, `1 + composite` or `not power of 2` with nothing. This adds an extra `1` to Mersenne primes, while every other number is obliterated. --- ## Task 3, Racket, 71 bytes ``` #lang racket (define(m x)(list-ref(sort x <)(quotient(-(length x)1)2))) ``` Lisp-like languages are just too wordy. Example run: ``` > (m `(1 3 4 2)) 2 ``` --- ## Task 4, ><>, 31 bytes ``` :?!v:2%:@-02-, )?~\l1 !;n>l? ``` *([Esolang wiki page for ><>](http://esolangs.org/wiki/Fish))* The above is 28 bytes, and requires the `-v` flag in the Python interpreter for [another 3 bytes](http://meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions), e.g. run like ``` $ py -3 fish.py negabinary.fish -v -137 10001011 ``` The nice thing about ><> here is that we can calculate the digits one by one via modulo and division, which gives the digits in reverse order, perfect for printing off a stack. --- ## Task 5, Parenthetic, ~~1448~~ 1386 bytes ``` ((()()())(()()()())((()())((()(())()))((()(())(())())((()(()))(()(())())((()(()))((())())((()()(()))((())()()()()()()()())((())()()()()()()()()()()()())))))))((()()())(()()())((()())((()(())()))((()()()())((()(()))(()(())())((())()()()()()()()()()()())))))((()(()))((()()())((())()()()()))((()()())((())()()))((()()()())((())()()()()))((()()())((())()()()()()()()()()))((()()())((())()))((()()())((())()()()))((()()())((())()()))((()()())((())()()()))((()()())((())()()()()()()()()()))((()()())((())))((()()())((())()()()()()()()()))((()()())((())()()()()()()))((()()()())((())))((()()())((())()))((()()()())((())()()()()()()()()))((()()()())((())()()))((()()())((())()()()()()()))((()()())((())()()()))((()()())((())()()()()()()()))((()()()())((())()()))((()()())((())()()()))((()()())((())()()()()))((()()()())((())()()()()()()()()))((()()()())((())()()))((()()())((())()()()()()()()))((()()()())((())()()()()()()()()))((()()())((())))((()()()())((())()()()()()()()()))((()()()())((())()()))((()()())((())()()()))((()()())((())()()()()()()()()()()))((()()())((())()()()))((()()())((())))((()()()())((())()()))((()()()())((())))((()()())((())()()))((()()())((())()()()))((()()()())((())()()))((()()())((())()()()))((()()())((())()()))((()()()())((())()()()()()()()()))((()()())((())()()()))((()()())((())()()()()()()()))((()()()())((())()()()()()()()()))((()()())((())()()()()()()()))) ``` *([Github repository for Parenthetic](https://github.com/cammckinnon/Parenthetic))* I have a CJam answer for this which is shorter than the string itself, but I can't use it so I thought I'd go the other way. Python 3 generating code: ``` char97 = "((()()())(()()()())((()())((()(())()))((()(())(())())((()(()))(()(())())((()(()))((())())((()()(()))((())()()()()()()()())((())()()()()()()()()()()()())))))))" char108 = "((()()())(()()())((()())((()(())()))((()()()())((()(()))(()(())())((())()()()()()()()()()()())))))" open_str = "((()(()))" close_str = ")" target = "pneumonoultramicroscopicsilicovolcanoconiosis" output = [char97, char108, open_str] for c in target: if ord(c) >= 108: output.append("((()()())((())%s))"%("()"*(ord(c)-108))) else: output.append("((()()()())((())%s))"%("()"*(ord(c)-97))) output.append(close_str) print("".join(output)) ``` Here's the corresponding Lisp-like code: ``` (define f (lambda (n) (char (+ n 97)))) (define g (lambda (n) (f (+ n 11)))) (+ (g 4) // p (g 2) // n (f 4) // e ... ) ``` Apparently it was okay to override `define` by naming `g` as `()()`, which saved a lot of bytes. --- ## Task 6, CJam, 26 bytes ``` XY]et1>>"Happy New Year!"* ``` Checks that the `[month day]` part of the local time array is less than `[1, 2]`. --- ## Task 7, Python, 73 bytes ``` from random import* print(*map(chr,sample(range(13312,19894),64)),sep="") ``` Just a straightforward Python 3 implementation. --- ## Task 8, Prelude, ~~46~~ 41 bytes ``` ?(?)#(#)?(v-(#)?)10)! ^ 1 # (0 ``` *([Esolang wiki page for Prelude](http://esolangs.org/wiki/Prelude))* I think this works – it's probably still golfable, but it's my first time doing a non-trivial golf in Prelude. The input format is `<needle>NUL<haystack>`, where `NUL` is `0x00`. This works best with `NUMERIC_OUTPUT = True` in the Python interpreter, since that'll make it output `1` or `0` as appropriate. I chose Prelude because there's two properties which make it very nice for this task: * It is stack-based, so you can first read in the needle, then process the haystack one char at a time, and * Prelude's stack has an infinite number of 0s at the bottom, so you don't need to handle the case where the needle runs out of characters. This would have been even better if Prelude had a NOT operator. Here's the breakdown: ``` ?(?)# Read input up to the NUL, discarding the NUL afterwards (#) Move the needle to the second voice, effectively reversing the stack ^ ?(...?) Read haystack v- Compare top needle char with haystack char by subtraction (#) If equal, pop the needle char 1 # 10)! Output 1 if the top needle char is 0 (bottom of stack), 0 otherwise (0 ``` *(-5 bytes thanks to @MartinBüttner)* --- ## Task 9, Mathematica, 4 bytes ``` #2#& ``` Something like `2 {{0, 1}, {1, 0}}` is implicitly multiplication in Mathematica, so this just puts the arguments side-by-side. As noted by [@MartinButtner](https://codegolf.stackexchange.com/revisions/52188/1) and [@alephalpha](https://codegolf.stackexchange.com/revisions/52185/2), `1##&` is another 4 byte answer. See the former for an explanation. --- ## Task 10, Rail, ~~246~~ 237 bytes ``` $'main' 0/aima19-@ @------e< -(!!)()[ ][ ______ ]{f}[\n\]o()[ ][| |]{f}[\n\]o()[~][ ()--() ]{f}# $'f' # # -(!x!)(!y!)(!!)()0g< -(x)o()1g< -(y)o()1s(y)(x){f}# -/ -/ ``` *([Esolang wiki page for Rail](http://esolangs.org/wiki/Rail))* I couldn't pass up the opportunity to do a train-related task in Rail :) The whitespace looks pretty golfable, but with branching taking up three lines it'll take a bit of work to compact. Input is an integer via STDIN, but there needs to be an EOF. The top-left portion ``` 0/aima19-@ @------e< ``` is an atoi loop which converts the input to an integer while not EOF (checked by the `e` instruction). The function `f` on the last three lines takes `x, y, n`, and outputs the string `x` `n` times, separated by `y`. The function is recursive, with `n` decrementing by one each time until it becomes zero. `f` is called three times, supplying different strings for each row. Weirdly, Rail allows variable names to be empty, which saves a few bytes. Most of the bytes unfortunately come from `(!x!)`, which pops the top of the stack and assigns it to variable `x`, and `(x)`, which pushes `x` onto the stack. This is necessary because there's no duplicate operator in Rail, so `(!x!)(x)(x)` is the only way to copy the top of the stack. [Answer] ## Task 1, CJam, 7 bytes ``` q~,:+_* ``` I just wanted to get the (presumably) optimal CJam solution for this in. It makes use of the fact that the sum of the first *n* cubes is the square of the *nth* triangular number, which is itself the sum of the first *n* integers. [Test it here.](http://cjam.aditsu.net/#code=q~%2C%3A%2B_*&input=6) --- ## Task 4, Fission, ~~173~~ ~~88~~ ~~78~~ ~~69~~ 68 bytes [GitHub repository for Fission.](https://github.com/C0deH4cker/Fission/) ``` /@\O/S@+>\ ^{ }[<X/ @/; ,\?/@\J^X\ 'M~\$ $ UK/W%@] / D ?\{\/ 0'A Y ``` My second reasonably complicated Fission program. :) The input format is a bit weird. To support negative inputs, the first character is expected to be either `+` or `-` to indicate the sign. The second character's byte value is then the magnitude of the input (since Fission can't natively read decimal integers). So if you want `111` you'd pass it `+o` on STDIN. And if you want `-56` you pass it `-8`. In place of `+` and `-` you can use any character with a lower or higher character code, respectively. This can be helpful to pass in something like `-n` (which your `echo` might treat as an argument) as, e.g., `0n`. Let's look at how we can find the negabinary representation of a positive number. We want to compute the number from least to most significant bit (we'll push those bits on a stack and print them all at the end to get them in the right order). The first digit is then just the parity of the number, and we integer-divide the number by 2 to continue processing. The next digit is now negative (with value -2) - but it should be noted that this bit will be set whenever the 2-bit would be set in a normal binary number. The only difference is that we need to counter the -2 with positive higher valued digits. So what we do is this: * We determine the parity again - this is the next negabit - and divide by 2 as before. * If that digit was a `1`, we increment the remaining number by 1 in order to counter-act the negative bit (the difference between a negabit and a bit is *once* the value of the next more-significant bit). A great simplification of the code results from noticing that conditionally adding one here is equivalent to rounding the number *up* when integer dividing (if the discarded bit was 1, we increment the integer-divided result by 1). Then, the next bit is just a positive value again so we can determine it normally. That means we want a loop that computes two bits at a time, alternating between rounding up and rounding down for the remaining number, but we want to enter the loop in the middle so we start with rounding down. How can we handle negative integers? The problem is that Fission can't really do arbitrary arithmetic on negative integers, because masses are always non-negative. So one would have to do something really complicated like working with the magnitude and keeping track of the sign somewhere else. However, the negabinary representation of a negative number can be computed based on a related positive number: If *n* is negative, compute the negabinary representation of *n/2* (rounded *up*) and append the parity of *n*. This is exactly the first step of our two-bit loop. So all we need to do is start the loop at a different point if the sign is negative. Most of the savings from the 173 original bytes came from these insights which allowed me to compress three parity checks and a two-section loop into a single loop with a single parity check. This post will get too long if I explain all the code in detail, but I'll point out a few sections to give the rough layout of the control flow, and you can puzzle out the details with the Fission reference. ``` /@\ ^{ }[ ,\?/ ' U D ? ``` Starting from the `D`, this reads a sign bit into the energy and the magnitude into the mass of an atom that ends up in the `[` (going right). This sign bit will alternate after each pass through the parity check and will determine whether we retain the rounded down or rounded up half of the loop input. ``` /S@+>\ [<X/ @/ \ @\J^X\ M $ $ K %@] / ``` This is the loop which computes the individual bits and feeds the correct half into the next iteration. The `S` and the `J` are used to create a copy of the right half based on the current sign bit, the `X`s do the copying. The `>` in the top right corner computes the actual bit which is then sent to the stack `K` to be retrieved later. I think the layout of the top right corner is pretty nifty and definitely worth studying in detail if you're interested in Fission. The `%` is a switch which feeds the number back into the loop as long as it's greater than 0. ``` O M~\ K/W% \{\/ 0'A Y ``` Once the number reaches 0 it's reflected down instead. This starts another loop which retrieves the bits from the stack, adds them to the character code of `0` and prints them with `O`. The program terminates once the stack is empty, because the control atom will end up being pushed on the stack (and afterwards there are no more moving atoms left). --- ## Task 5, Prelude, ~~219~~ ~~179~~ 96 bytes [Esolangs page for Prelude.](http://esolangs.org/wiki/Prelude) [Stack Snippet interpreter for Prelude.](https://codegolf.stackexchange.com/a/52454/8478) ``` 29+129+716705-7607-05-4759+705-14129+05-18705-29+719+05-1507-19+39+449+767549+03-68(67+^+^+^++!) ``` This started out as a standard hand-crafted fixed-output Prelude program with three voices. After some chat with Sp3000 I decided to try a single voice. It turned out that this worked quite well, because it's much easier to reuse older letters. Then Dennis gave me a few hints and I found the current version: the idea is push all the offsets from the letter `h` onto the stack of a single voice in reverse order, and then just print them one at a time in a loop. `h` is chosen because there is no `h` in the string (which is important - otherwise the `0` offset would terminate the loop) and because it minimises the encoding of the offsets in terms of two-digit and negative offsets. The offset encoding was generated with [this CJam script](http://cjam.aditsu.net/#code=qW%25%7B'h-_0%3C%5Cz_9%3E%7B%5B9m9'%2B%5D%7D%26%5C%7B0%5C'-%7D%26%7D%2F&input=pneumonoultramicroscopicsilicovolcanoconiosis). --- ## Task 8, Mathematica, 28 bytes ``` LongestCommonSequence@##==#& ``` Yay for built-ins. (Mathematica's naming is a bit weird here... `LongestCommonSubsequence` finds the longest common *substring* while `LongestCommonSequence` finds the longest common *subsequence*.) --- ## Task 9, J, 1 byte ``` * ``` Same as the APL and K answers, but it seems no one has taken J yet. --- ## Task 10, Retina, ~~67~~ 60 bytes [GitHub repository for Retina.](https://github.com/mbuettner/retina) ``` (.*). ______ $1<LF>| | $1<LF> ()--() ~$1 +`(.{9})1 $1$1 ~$ <empty> ``` Each line goes in a separate file, and `<LF>` should be replaced with a newline character and `<empty>` should be an empty file. You could also put all of this in a single file, and use the `-s` option, but that does not allow embedding of newline characters in place of `<LF>` yet. You could emulate that by doing something like ``` echo -n "111" | ./Retina -s train.ret | ./Retina -e "<LF>" -e "\n" ``` As the above example shows, input is expected to be unary. The idea of the code is to create three copies of the unary input (minus 1), each with a copy of the corresponding line. Then we repeatedly duplicate the last nine characters in front of a `1` until all the `1`s are gone, thereby repeating the lines as necessary. Finally, we remove the extraneous trailing `~`. [Answer] Eh, I'll start out with a couple I guess. First time golfing. ## Task 1, Python, ~~38~~ 21 bytes ``` lambda n:(n*n-n)**2/4 ``` Sum a list of all the cubes up to x. Changed expression thanks to xnor ## Task 2, TI-Basic 89, 244 bytes ``` Func If iPart(log(x+1)/log(2))=log(x+1)/log(2) Then Return log(x+1)/log(2) Else Return 0 EndIf EndFunc Func If isPrime(x)=false Return 0 If ipart(log(x+1)/log(2))=log(log(x+1)/log(2)) Then Return log(x+1)/log(2) Else Return 0 EndIf EndFunc ``` Not 100% certain on this one, will test when I find new batteries for my calculator. isPrime is a builtin, ipart is integer part (2.3 ->2) ## Task 3, Perl, ~~45~~ 34 Bytes ``` @n=sort{$a-$b}@ARGV;print$n[$#n/2] ``` perl file 1 2 3 4 --> 2. Saved a couple of bytes thanks to @nutki. Printed rather than saving to variable then printing variable. ## Task 4, Ruby, ~~43~~ 40 bytes ``` x=2863311530 p ((gets.to_i+x)^x).to_s(2) ``` At least it works in 1.9, don't know about 1.8. In binary, '10'\*16 (or 2863311530) plus a number, xor with that 10101010... is the negbinary. Outputs a string representation with quotes (3 -> "111" rather than 3 -> 111). Can't find math to write x in less characters. ## Task 5, Malbolge, ~~682~~ 354 bytes ``` D'``_]>n<|49ixTfR@sbq<(^J\ljY!DVf#/yb`vu)(xwpunsrk1Rngfkd*hgfe^]#a`BA]\[TxRQVOTSLpJOHlL.DhHA@d>C<`#?>7<54X8165.R2r0/(L,%k)"F&}${zy?`_uts9Zvo5slkji/glkdcb(fed]b[!B^WVUyYXQ9UNrLKPIHl/.JCBGFE>bBA@"!7[;{z276/.R2r0)(-&J$j('~D${"y?w_utyxq7Xtmlkji/gf,MLbgf_dc\"`BA]\UyYXWP8NMLpPIHGLEiIHGF(>C<A@9]7<;:3W7w5.-210/(L,%k#('~}C{"y?`_uts9wpXn4rkpoh.lNMiha'eGF\[`_^W{h ``` Test online [here](http://www.matthias-ernst.eu/malbolge/debugger.html) Think this is as short as it'll go. Golfed as much as I could. Saved 300 bytes, so whee? ## Task 6, bash, ~~62~~ ~~50~~ 40 bytes ``` [ `date +%j`=1 ]&&echo 'Happy New Year!' ``` Found out about %j from another post. ## Task 10, Befunge-98, 121 Bytes ``` >&:>1-:" ____"v |,k8: '"__"< >a,$:>1-v > | >' 8k,^ # ^|':k4 '|':< v ',*25$< >,:1-: ")(--)("v ^," ~"_@#,k6" "< ``` Changed to befunge-98. Old was Befunge-93, ~~227 157~~ 147 bytes. Used [Fungi, written in Haskell](https://hackage.haskell.org/package/Fungi) for testing. Used the "do multiple times k" and adding single characters to the stack with '. I have a feeling it can be golfed down to 110 or less, but I've spent far too much time on this already... [Answer] First thing: task 6 technically does **NOT** count; I uploaded [unc](https://github.com/kirbyfan64/unc) under an hour ago. However, I *almost* uploaded it this morning, but decided to write a test suite first. Idiot. So, anyway, here goes! Note that most unc things are intentionally backwards, so `&&` really means `||` and such, which is why some operations look weird (e.g. using `-` to calculate the cube). ## Task 1, Haskell, 21 bytes ``` f n=sum$map(^3)[0..n] ``` ## Task 2, Hy, 135 bytes ``` (import math)(fn[n](and(if(and(not(% n 2))(> n 2))false(all(genexpr(% n i)[i(->> n(math.sqrt)int inc(range 3))])))(->> n dec(& n)not))) ``` ## Task 3, Dart, 37 bytes My first Dart function! ``` f(l){l.sort();return l[l.length~/2];} ``` ## Task 5, INTERCAL, 1047 bytes ``` DO ,1 <- #46 DO ,1SUB#1 <- #242 DO ,1SUB#2 <- #152 DO ,1SUB#3 <- #208 PLEASE DO ,1SUB#4 <- #248 DO ,1SUB#5 <- #248 DO ,1SUB#6 <- #192 PLEASE DO ,1SUB#7 <- #128 DO ,1SUB#8 <- #128 DO ,1SUB#9 <- #72 PLEASE DO ,1SUB#10 <- #120 DO ,1SUB#11 <- #8 DO ,1SUB#12 <- #224 PLEASE DO ,1SUB#13 <- #200 DO ,1SUB#14 <- #208 DO ,1SUB#15 <- #32 PLEASE DO ,1SUB#16 <- #208 DO ,1SUB#17 <- #120 DO ,1SUB#18 <- #88 PLEASE DO ,1SUB#19 <- #40 DO ,1SUB#20 <- #8 DO ,1SUB#21 <- #208 PLEASE DO ,1SUB#22 <- #232 DO ,1SUB#23 <- #120 DO ,1SUB#24 <- #208 PLEASE DO ,1SUB#25 <- #248 DO ,1SUB#26 <- #56 DO ,1SUB#27 <- #96 PLEASE DO ,1SUB#28 <- #160 DO ,1SUB#29 <- #208 DO ,1SUB#30 <- #208 PLEASE DO ,1SUB#31 <- #136 DO ,1SUB#32 <- #120 DO ,1SUB#33 <- #192 PLEASE DO ,1SUB#34 <- #112 DO ,1SUB#35 <- #64 DO ,1SUB#36 <- #16 PLEASE DO ,1SUB#37 <- #128 DO ,1SUB#38 <- #48 DO ,1SUB#39 <- #208 PLEASE DO ,1SUB#40 <- #128 DO ,1SUB#41 <- #224 DO ,1SUB#42 <- #160 PLEASE DO ,1SUB#43 <- #40 DO ,1SUB#44 <- #56 DO ,1SUB#45 <- #200 PLEASE DO ,1SUB#46 <- #126 PLEASE DO READ OUT ,1 DO GIVE UP ``` ## Task 6, unc, 157 bytes ``` !include>=fgQVb%U<= !include>=gVZR%U<= false lRNe[]<<gVZR_g t:=gVZR[5]:volatile gZ m:=-YbPNYgVZR[&t]:for[#m%gZ_Zba||m%gZ_ZQNl!=6]chgf[L'uNccl ARj LRNe#']:>> ``` ## Task 8, rs, 42 bytes ``` # +#(.)(.*) .*?\1/\1#\2 .*# .*$/1 [^1]+/0 ``` [Live demo.](http://kirbyfan64.github.io/rs/index.html?script=%23%0A%2B%23(.)(.*)%20.*%3F%5C1%2F%5C1%23%5C2%20%0A.*%23%20.*%24%2F1%0A%5B%5E1%5D%2B%2F0&input=abc%20axbx%0Aabc%20axbxc%0Aabc%20axcxbx) ## Task 10, Pyth, 46 bytes ``` jb(j*d2m+\ *\_6Qjdm"| |"Qj\~m" ()--() "Q) ``` [Live demo.](https://pyth.herokuapp.com/?code=jb(j*d2m%2B%5C+*%5C_6Qjdm"%7C++++++%7C"Qj%5C~m"+()--()+"Q)&input=2&debug=1) [Answer] ## Task 1, APL, 7 bytes ``` +/3*⍨⍳⎕ ``` You can [try it online](http://ngn.github.io/apl/web/index.html#code=+/3*%u2368%u2373%u2395) using ngn/apl, though it will work with any APL implementation that defaults to a 0 index origin. This cubes each integer from 0 to the input (`⍳⎕`) -1 by commuting (`⍨`) the arguments to the power operator (`*`). The resulting vector is reduced by summing (`+/`) and a scalar is returned. --- ## Task 2, Julia, 42 bytes ``` n->(isprime(n)&&int(log2(n+1))==log2(n+1)) ``` This creates an anonymous function that accepts as integer as input and returns a boolean. To call it, give it a name, e.g. `f=n->...`. First we use Julia's built-in function `isprime` to check whether `n` is prime. If it is, we check that `log2(n+1)` is an integer. If so, `n` can be written as `2^k-1` for some `k`, and thus `n` is a Mersenne prime. --- ## Task 3, [ELI](http://fastarray.appspot.com), 19 bytes ``` {f:x[<x][~.0.5*#x]} ``` This creates a monad `f` that returns the median of the input vector. Ungolfed + explanation: ``` {f: // Define a function f x[<x] // Sort the input vector [ // Select the element at index... ~.0.5*#x // ceiling of 0.5 * length(input) ]} ``` Examples: ``` f 1 2 3 4 2 f ?.!20 // Apply f to 20 random integers in 1..20 4 ``` --- ## Task 4, Octave, 39 bytes ``` @(n,x=2863311530)dec2bin(bitxor(n+x,x)) ``` This creates a function handle that accepts an integer as input and returns the associated negabinary string. To call it, give it a name, e.g. `f=@...`, and run with `feval(f, <input>)`. You can [try it online](https://ideone.com/okXUXR). --- ## Task 5, CJam, 47 bytes ``` "pneumonoultramicroscopicsilicovolcanoconiosis" ``` The string is simply printed to STDOUT. You can [try it online](http://cjam.aditsu.net/#code=%22pneumonoultramicroscopicsilicovolcanoconiosis%22) if you feel so inclined. --- ## Task 6, Windows Batch, 46 bytes ``` if "%date:~4,5%"=="01/01" echo Happy New Year! ``` The variable `%date%` contains the current date in the form `Thu 06/25/2015`. We can select the month and day by getting the substring of length 5 after skipping the first 4 characters: `%date:~4,5%`. From there we just check if it's January 1st and say Happy New Year if it is. --- ## Task 7, Pyth, 26 bytes ``` =Gr13312 19895FNU64pC.(.SG ``` First we assign `G` to the range 13312 through 19894 inclusive. Then we loop 64 times, and at each iteration we shuffle `G` (`.SG`), remove and return the last element (`.(`), and print its character representation (`pC`). You can [try it online](https://pyth.herokuapp.com/?code=%3DGr13312+19894FNU64pC.(.SG&debug=0). --- ## Task 8, Ruby, 36 bytes ``` def f(a,b)!b.tr("^"+a,"")[a].nil?end ``` This defines a function `f` which accepts two strings `a` and `b`, where `a` is the string to find within `b`. Everything but the characters in `a` are removed from `b` using `.tr()` and we check whether the result contains `a` exactly using `[]`. This will return `nil` if the string isn't found, so we can get a boolean value by using `!` with `.nil?`. --- ## Task 9, R, 16 bytes ``` function(x,n)n*x ``` This creates an unnamed function object that accepts any kind of array or matrix `x` and an integer `n` and multiplies each element of `x` by `n`. If you'd like, you can [try it online](http://www.r-fiddle.org/#/fiddle?id=EIviowQc). --- ## Task 10, Python 3, 92 bytes ``` n=int(input()) l="\n" w=" ()--() " print(" ______ "*n+l+"| | "*n+l+(w+"~")*(n-1)+w) ``` Pretty straightforward. You can [try it online](http://ideone.com/QCt0R1). [Answer] # Task 1, ><>, 10 + 3 = 13 bytes ``` ::*-:*4,n; ``` Run this using the [official Python interpreter](https://gist.github.com/anonymous/6392418) using the `-v` flag (at a cost of 3 bytes). This squares the quantity `(n - n*n)` and divides by `4`, which of course is equivalent to squaring `(n*n - n)` and dividing by `4`. # Task 2, GAP, 63 62 bytes ``` b:=function(m)return[2]=AsSet(Factors(m+1))and IsPrime(m);end; ``` (Saved a space by writing the equality the other way around.) # Task 3, R, 43 39 bytes ``` f=function(v)sort(v,d=T)[length(v)%/%2] ``` Thanks to Plannapus for the nice improvement! # Task 4, Piet, 155 135 115 5\*19 = 95 codels ![enter image description here](https://i.stack.imgur.com/JvzGG.png) Test using [this online interpreter](http://www.rapapaing.com/blog/?page_id=6), with codel size 13. Or use your preferred interpreter--let me know if you have one you like! Making it output `0` instead of the empty string for input `0` was inconvenient. I used an if-then near the beginning to take care of this case; then a while-loop to calculate the digits in the nonzero case, and finally another while-loop at the end to output the digits from the stack. Many thanks to Sp3000 for some very helpful comments, which helped me to save some codels! # Task 5, Lua, 52 bytes ``` print"pneumonoultramicroscopicsilicovolcanoconiosis" ``` You can try it [here](http://www.lua.org/cgi-bin/demo). # Task 6, LaTeX, 157 139 136 127 128 bytes ``` \documentclass{book}\begin{document}\count1=\day\multiply\count1 by\month \ifcase\count1\or Happy New Year!\else~\fi\end{document} ``` If the product of the day and the month is `1`, print the message; otherwise, nothing. (New Year's Day is particularly convenient for this design: since the output we're looking for is `1`, we only need one `or` statement. The `n`th `or` statement specifies behavior for the value `n`.) Note: my previous version was missing the line return, which was a mistake. (I did try to test this function, but to really test it properly might take a while...) My original version used the `calc` package, which was much more convenient than my current version. Something to keep in mind for "real life"! # Task 7, Ruby, 62 bytes ``` for r in Array(13312..19893).sample(64) puts [r].pack('U*')end ``` # Task 8, JavaScript, 78 bytes ``` h=function(l,m){u=1+m.indexOf(l[0]);return(!l||u&&h(l.substr(1),m.substr(u)))} ``` Recursive solution, testing whether `l` is a substring of `m`. If `l` is empty, then the `!l` results in `true` and the function terminates. (In this case, `l[0]` is undefined, but JavaScript is OK with that.) Otherwise, it looks for the first instance of `l[0]` in `m`. If it doesn't find one, then `m.indexOf(l[0])` results in `-1` and so `u` results in `0` and the function terminates. Otherwise, it strips off the first entry of `l` and the first `u` entries of `m` and continues checking. # Task 9, Python, 72 60 bytes ``` def i(a,n): try:return[i(c,n)for c in a] except:return n*a ``` Drills down to the "lowest level", where `a` isn't a list anymore, just an integer, then carries out the multiplication. Many thanks to Dennis for saving me 12 bytes! # Task 10, Groovy, 81 bytes ``` def j(n){(' ------ '*n+'\n'+'| | '*n+'\n'+' ()--() ~'*n).substring(0,27*n)} ``` Try it [here](https://groovyconsole.appspot.com/). I originally tried to implement something like Python's `.join()` method for strings, which puts strings together with a particular "linking string" (like the linkages between train cars). But that cost a lot more than it saved. *I hope I haven't run afoul of any conventions for acceptable answers in these various languages, but please let me know if I have.* **Thank you to Dennis for a fantastic challenge!** [Answer] ## Task 1, Pyth, 5 bytes ``` s^R3Q ``` Takes number from stdin. Thanks @Jakube for pointing out the useless `U`. ## Task 6, javascript, 56 bytes ``` if(Date().slice(4,10)=="Jan 01")alert("Happy New Year!") ``` ## Task 7, CJam, 16 bytes ``` 6581,mr64<'㐀f+ ``` Generates range, shuffles, picks first 64, and maps addition of start value and converting to character. 14 chars, 16 bytes. ## Task 8, Octave, 23 bytes ``` @(x,y)intersect(x,y)==x ``` Defines anonymous function. ## Task 5, PHP, 45 bytes ``` pneumonoultramicroscopicsilicovolcanoconiosis ``` No compression, just prints. ## Task 9, APL 1 byte ``` × ``` The same as the K answer. [Answer] ## Task 1, R, ~~21~~ 19 bytes ``` sum((1:scan()-1)^3) ``` Fairly straight forward. Input from STDIN. ## Task 2, Perl, ~~40~~ 66 bytes ``` $a=log(<>+1)/log(2)+1;print$a==int($a)&&(1x$a)!~/^1?$|^(11+?)\1+$/ ``` Added a prime checker (Abigails prime number checker regex) ## Task 3, PARI/GP, ~~24~~ 22 bytes ``` m(v)=vecsort(v)[#v\2]; ``` First time I touched this. Might have to learn a bit more of it. ## Task 4, T-SQL, 235 bytes ``` CREATE FUNCTION D(@ INT)RETURNS TABLE RETURN WITH R AS(SELECT @/-2+(IIF(@%-2<0,1,0))D,CAST(ABS(@%-2) AS VARCHAR(MAX))M UNION ALL SELECT D/-2+(IIF(D%-2<0,1,0)),CAST(ABS(D%-2)AS VARCHAR(MAX))+M FROM R WHERE D<>0)SELECT M FROM R WHERE D=0 ``` Inline table function using recursive CTE. Very large, but fun to do. To use ``` SELECT * FROM D(18) M ------ 10110 ``` ## Task 5, GAP, 48 bytes ``` "pneumonoultramicroscopicsilicovolcanoconiosis"; ``` ## Task 6, Excel, ~~51~~ 48 bytes ``` =IF(TEXT(NOW(),"md")="11","Happy New Year!","") ``` Thanks to @Bond for the 3 bytes. ## Task 7, Python 2.6, ~~98~~ ~~93~~ 85 bytes ``` from random import* l=range(13312,19893) shuffle(l) print ''.join(map(unichr,l[:64])) ``` This is the first time I've tried to do anything in Python, so could be lots better. Thanks @Dennis and @Jacob for the great tips ## Task 8, TCL, 57 bytes ``` proc m {a b} {string match [regsub -all (.) $a *\\1]* $b} ``` Shame that removing whitespace kills this ## Task 9, Pike, 53 bytes ``` mixed m(array(array(int))a,int n){return(a[*])[*]*n;} ``` A function that returns the multiplied array ## Task 10, Powershell, 88 bytes ``` Function t($n){Foreach($s in " ______ "," | |","~ ()--() "){($s*$n).Substring(1)}} ``` A Powershell function. I think I can shortened it a bit, but here it is at the moment. And finally finished :) [Answer] ## Task 1, GolfScript, 8 bytes ``` ~,{+}*.* ``` Same idea as [Martin's CJam](https://codegolf.stackexchange.com/a/52188/16766) answer. --- ## Task 2, QBasic, ~~74~~ 71 bytes ``` INPUT a r=a>1 FOR i=2 TO a-1 r=r*(a MOD i) NEXT ?r*((a\2AND a)=a\2) ``` Tested on [QB64](http://qb64.net) with syntax expansion turned off.1 The bulk of the program tests whether the given number `a` is prime by taking `a` mod every number 2<=`i`<`a` and multiplying the results. The result is that `r` is 0 if the number is not prime, and nonzero otherwise. The last line uses bitwise `AND` with integer division by 2 to check whether the binary representation of `a` is all ones, i.e. `a` is of the form 2n-1. Multiplying this by `r` gives 0 (false) if a number is not a Mersenne prime and some nonzero (truthy) value otherwise. `?` is a shortcut for `PRINT`. The largest Mersenne prime I tested, 8191, gives a result of `1.#INF`--which is still truthy! (I checked with an `IF` statement to make sure.) 1 This doesn't change the semantics of the program. If you type the above code into the standard DOS QBasic, it will be autoformatted with extra spaces, but it will run exactly the same. --- ## Task 3, Pyth, 6 bytes ``` ehc2SQ ``` Reads a Python-style list from stdin. The main magic here is the `c`hop operator: given an int and a list, it splits the list into n pieces. So `c2SQ` chops the sorted input list in half. Conveniently, when the length is odd, the first half is the bigger one, so the median is always the last element of the first half. This is the `e`nd of the `h`ead of the chop results. --- ## Task 4, CJam, 26 bytes ``` ri{_2%z\_0>\-2/_3$+?}h;]W% ``` This could be shortened, I suspect. Algorithm: * Read integer. * Do while value is not 0: + Take abs(i%2). This is the next digit (negabit?). + Divide i by -2. + Iff i was nonpositive, add abs(i%2) to the result. This is to correct a corner case: 3 goes to -1, but -3 should go to 2, not 1. * Drop the superfluous 0, collect the stack into an array, reverse and print. The fact that it's a do-while loop takes care of the 0 case. --- ## Task 5, Bash, 50 bytes ``` echo pneumonoultramicroscopicsilicovolcanoconiosis ``` Not much to explain. --- ## Task 6, Python, 78 bytes ``` from datetime import* d=date.today() if d.day<2>d.month:print"Happy New Year!" ``` Requires Python 2. Python's chaining inequality operators can be nicely exploited here. --- ## Task 7, ActionScript, 82 bytes ``` x="" while(x.length<64){c=chr(13312+random(6582));if(x.indexOf(c)<0)x+=c} trace(x) ``` [ActionScript](https://en.wikipedia.org/wiki/ActionScript) is a member of the ECMAScript family. This code requires ActionScript 2--much better for code golf because I get to use deprecated functions like `chr` instead of version 3's `String.fromCharCode`! Output is to the console pane: [![Task 7 screenshot](https://i.stack.imgur.com/UYhHC.png)](https://i.stack.imgur.com/UYhHC.png) --- ## Task 8, Pip, ~~9~~ 19 bytes The regex solution didn't quite work, so here's one with string operations instead. ``` Fcab@>:o&:(b@?c)+1o ``` [Github repository for Pip](http://github.com/dloscutoff/pip). Takes the two strings as command-line args. When `a` is a subsequence, outputs a positive integer (truthy); otherwise, the result is nil (falsy), which produces no output. Explanation: ``` Cmdline args -> a,b; o = 1 (implicit) Fca For each character in a: b@?c Find character's index in b (nil if not found) ( )+1 Add 1; all possible indices except nil are now truthy o&: Logical AND with o b@>: Slice b to everything at index o and afterward (Python b=b[o:]) (If c wasn't found, b becomes nil, but we don't care at that point) o Auto-print o ``` --- ## Task 9, Prolog (SWI), 68 bytes ``` m(L,N,R):-L=[H|T],m(H,N,I),m(T,N,U),R=[I|U];L=[],R=[];R is L*N. ``` Prolog is not usually at all competitive in code golf, so I'm pretty happy with this solution. Defines a [predicate](https://en.wikipedia.org/wiki/Prolog_syntax_and_semantics#Prolog_programs) `m` with input parameters `L` for the list and `N` for the number and output parameter `R`. The definition of `m` is a triple disjunction: * If `L` can be [unified](https://en.wikipedia.org/wiki/Unification_(computer_science)#Application:_Unification_in_logic_programming) with `[H|T]`, it is a list with at least one item in it. Call `m` recursively on the head and tail of that list, and put the results together again into a new list which is unified with `R`. * If `L` can be unified with `[]`, unify `R` with `[]` as well. * Otherwise, `L` is assumed to be a number; `L*N` is calculated and assigned to `R`. Example run using `swipl` on Ubuntu: ``` dlosc@dlosc:~/golf$ swipl -qs arrayMult.prolog ?- m([1,2,3],5,R). R = [5, 10, 15] . ?- m([[3,4],[5,6]],3,R). R = [[9, 12], [15, 18]] . ?- m([[[1,2],[3,4]],[[5,6],[7,8]]],2,R). R = [[[2, 4], [6, 8]], [[10, 12], [14, 16]]] . ``` --- ## Task 10, C, ~~114~~ ~~112~~ 106 bytes ``` #define F;printf("\n");for(i=0;i<c;i++)printf( i;t(c){F" ______ ")F"| | ")F" ()--() ~");putchar(8);} ``` Tested with `gcc` on Ubuntu. Defines a function `t` that takes an integer argument. Uses three `for` loops to output, greatly condensed via macro abuse. Using the backspace character to erase a trailing `~` results in a rather odd whitespace pattern, but `The output may be surrounded by any amount of whitespace as long as it looks like in the example.` Example run of `t(3)`: ``` dlosc@dlosc:~/golf$ ./a.out ______ ______ ______ | | | | | | ()--() ~ ()--() ~ ()--() dlosc@dlosc:~/golf$ ``` [Answer] # Task 2, J, 10 bytes ``` 1&p:*/@,#: ``` Prepends a boolean 0 or 1 if the input is prime to its binary representation, then takes the product. Works on the current version of J. --- # Task 5, HTML, 45 bytes ``` pneumonoultramicroscopicsilicovolcanoconiosis ``` --- # Task 6, fish, 53 bytes ``` test 0101 = (date '+%d%m');and echo 'Happy New Year!' ``` Based on the bash answer. --- # Task 8, APL, 12 bytes ``` {(⍳⍴⍺)≡⍋⍵⍳⍺} ``` This is a function expression. It compares the order of characters found in the larger string with what would be expected if they were sorted. --- # Task 9, K, 1 byte ``` * ``` Should work in any version. Arithmetic operations distribute over arrays. [Answer] ## Task 1, Ruby, 40 bytes ``` def f n;(0..n-1).inject{|a,b|a+b**3};end ``` First time ever writing anything in Ruby. Tested with ruby 1.8.7. --- ## Task 2, R, 50 bytes ``` n=scan();p=log(n+1,2);!p%%1&sum(!n%%2:n,!p%%2:p)<3 ``` Computes `p`, check if it is an integer, and if n and p are primes. --- ## Task 5, PostgreSQL, 54 bytes ``` SELECT'pneumonoultramicroscopicsilicovolcanoconiosis'; ``` --- ## Task 6, Lua, 55 bytes ``` print(os.date("%j")=="001" and "Happy New Year!" or "") ``` --- ## Task 8, Python, 65 bytes ``` import re;f=lambda s,S:bool(re.search(re.sub(r'(.)',r'\1.*',s),S)) ``` Usage: ``` >>> import re;f=lambda s,S:bool(re.search(re.sub(r'(.)',r'\1.*',s),S)) >>> f('abc','axbxcx') True >>> f('bac','axbxcx') False >>> f('abc','axdxcx') False >>> f('abc','abc') True ``` --- ## Task 10, Julia, 73 bytes ``` f(n)=print(" ______ "^n*"\n"*"| | "^n*"\n"*(" ()--() ~"^n)[1:9n-1]) ``` Thanks to @AlexA. for helping shortening this code! Example of outputs: ``` julia> f(0) julia> f(1) ______ | | ()--() julia> f(2) ______ ______ | | | | ()--() ~ ()--() julia> f(3) ______ ______ ______ | | | | | | ()--() ~ ()--() ~ ()--() ``` [Answer] ## Task 1, Haskell, 17 bytes ``` f x=(x*(x-1)/2)^2 ``` --- ## Task 2, Mathematica, 30 bytes ``` PrimeQ@#&&Mod[Log2[#+1],1]==0& ``` --- ## Task 3, JavaScript, 46 bytes ``` function(x){return x.sort()[0|(x.length-1)/2]} ``` --- ## Task 5, MATLAB, 47 bytes ``` 'pneumonoultramicroscopicsilicovolcanoconiosis' ``` --- ## Task 6, Ruby, 56 bytes ``` print Time.now.to_s[5,5]=="01-01"?"Happy New Year!":"" ``` --- ## Task 7, Python, 106 bytes (indenting with `\t`) ``` from random import* s='' while len(s)<64: c=unichr(randint(0x3400,0x4DB5)) if c not in s: s+=c print s ``` Note that straightforward usage of `list(set(s))` does **not** work here as this will cause a non-uniform probability distribution in the space of **all possible strings** due to re-ordering of list members. --- [Answer] ## Task 1, Haskell, 15 bytes ``` f n=(n*n-n)^2/4 ``` ## Task 2, Julia, 28 bytes ``` n->(isprime(n)&&ispow2(n+1)) ``` ## Task 3, Octave, 30 bytes ``` @(x)sort(x)(ceil(length(x)/2)) ``` ## Task 5, [Yacas](http://yacas.sourceforge.net/homepage.html), 45 bytes ``` pneumonoultramicroscopicsilicovolcanoconiosis ``` ## Task 6, Mathematica, 46 bytes ``` If[DateList[][[{2,3}]]=={1,1},Happy New Year!] ``` ## Task 9, PARI/GP, 10 bytes ``` (n,a)->n*a ``` [Answer] ## Task 3, Clip, 13 bytes ``` gHk[tivt}l`sk ``` Another version: ``` gHkci`v``l`sk ``` The ``` seemed to cost too much. ## Task 4, KSFTgolf, 16 bytes ``` g:]2%:)-2/:;xgpc ``` [The interpreter is here.](https://github.com/KSFTmh/KSFTgolf) I'm not sure what I am doing... It will print the negabinary and then crash. There is a bug in the interpreter. Or I'll be able to golf it down to 12 bytes using built-in base conversion (but it only work with positive integers): ``` 2*02-ba'Z=;x ``` Original CJam version: ``` qi{_1&_@^-2/}h;]W% ``` I tried Pip, Ostrich, Clip and Burlesque to find out if there is an esolang with built-in negabinary. None of them worked. KSFTgolf used `numpy`, which seemed to have some convienent weird behavior when the base is negative. But it's not easy to make it work with non-positive numbers. ## Task 7, CJam, 15 bytes ``` '䶶,DAm<>mr64< ``` ## Task 8, APL, 21 bytes ``` ∨/↑{⍺∧0,2∧/∨\⍵}/⌽⍞=↓⍞ ``` [Try it online.](http://tryapl.org/?a=%27abc%27%7B%u2228/%u2191%7B%u237A%u22270%2C2%u2227/%u2228%5C%u2375%7D/%u233D%u237A%3D%u2193%u2375%7D%27axbxc%27&run) [Answer] ## Task 2, x86 masm, 40 bytes ``` C7 45 FC FF FF 07 00 B9 00 00 00 00 B8 02 00 00 00 D3 E0 3B 45 FC 7D 03 41 EB F1 B8 02 00 00 00 D3 E0 48 3B 45 FC 75 13 ``` (excluding header, MessageBox, etc - only relevant bytes) ``` include \masm32\include\user32.inc includelib \masm32\lib\user32.lib .data ClassName db "Mersenne Prime Found",0 .data? .code start proc LOCAL IsMersenne: DWORD mov IsMersenne, 524287 ; put number to test in this input mov ecx, 0 l00p: mov eax, 2 shl eax, cl cmp eax, IsMersenne jge br3ak inc ecx jmp l00p br3ak: mov eax,2 shl eax, cl dec eax cmp eax, IsMersenne jnz n0pr1me invoke MessageBox, 0, addr ClassName, addr ClassName, 40h n0pr1me: ret start endp end start ``` --- ## Task 3, C, 136 bytes ``` #include<stdio.h> int C(void*A,void*B){return(*(int*)A-*(int*)B);} main(){int S=4;int A[]={3,1,2,4};qsort(A,S,4,C);printf("%i",A[((S&1)?S:S-1)/2]);} ``` Compile using `gcc -o Prime main.c` --- ## Task 10, C++, 478 bytes ``` #include<stdio.h> #include<string.h> #include<stdlib.h> void D(int Z){int L=9,i,X=0;const char*A=" ______ ";const char*B="| | ";const char* C = " ()--() ~ ";char*P=(char*)malloc(27*Z+5);for(i=0;i<Z-1;i++){if(!i){memcpy(P,A,L);X+=L;}memcpy(&P[X],A,L);X+=L;if(i==Z-2){memcpy(&P[X],"\n",1);X++;}}for(i=0;i<Z;i++){memcpy(&P[X],B,L);X+=L;if(i==Z-1){memcpy(&P[X],"\n",1);X++;}}for(i=0;i<Z;i++){memcpy(&P[X],C,L);X+=L;if(i==Z-1)P[X-1]='\0';}printf("%s\n",P);free(P);} main(){D(15);} ``` Compile using `g++ -o Trucks main.cpp` C & C++ can be shortened but it'd add compiler error. Don't know the exact rules so I tried to leave code w/no compiler errors. [Answer] ## Task 1, Python, 35 Bytes ``` lambda x:sum(_**3for _ in range(x)) ``` ## Task 3, CJam, 9 Bytes ``` q~$_,(2/= ``` ## Task 4, JavaScript, ~~55~~ 53 Bytes ``` function(n){s=0xAAAAAAAA;return((n+s)^s).toString(2)} ``` ## Task 5, Pyth, 46 Bytes ``` "pneumonoultramicroscopicsilicovolcanoconiosis ``` ## Task 6, C#, 65 Bytes ``` string c(){return DateTime.Now.DayOfYear<2?"Happy New Year!":"";} ``` [Answer] ## Task 1, jq, 24 bytes ``` [range(1;.)|.*.*.]|add+0 ``` ## Task 6, PostgreSQL, 54 bytes ``` select'Happy New Year!'where'001'=to_char(now(),'DDD') ``` [Answer] ## Task 1, Cjam, 7 bytes ``` q~,:+_* ``` Edit: Just noticed martin posted this before me. I'll try something else... ## Task 3, Python, 30 bytes ``` lambda l:sorted(l)[~-len(l)/2] ``` Python 2. ## Task 5, ///, 45 bytes ``` pneumonoultramicroscopicsilicovolcanoconiosis ``` [///](https://esolangs.org/wiki////) will just echo something without any `/` characters. ## Task 7, Pyth, 19 bytes ``` s>64.SmC+13312d6582 ``` Program. Please tell me if I mucked up the maths. [Try it here](https://pyth.herokuapp.com/?code=s%3E64.SmC%2B13312d6582&debug=0) ## Task 9, Octave, 9 bytes ``` @(a,n)a*n ``` Anonymous function handle. Octave automatically does this with matrix \* scalar. [Answer] I haven't found time to attempt them all, but here's a start # Task 1, dc, 8 bytes ``` d1+*d*4/ ``` Input and output to top of stack, as per `dc` convention. # Task 5, Emacs Lisp, 46 bytes ``` 'pneumonoultramicroscopicsilicovolcanoconiosis ``` Abuse of the rules: ``` grep 'pn.*v' /usr/*/*/brit*-large ``` The best I could manage by unpacking from compressed form was 55, in Perl: ``` unpack("H45",'uïFVóÙ¤¼g°0Æö<¥le°°')=~y/0-9bdf/i-v/r ``` (non-printable chars above get garbled by SE, but as it's not actually my answer, I'm not fixing it) # Task 6, SQL, 54 bytes ``` SELECT IF(now()LIKE'%-01-0_%','Happy New Year!','Hi'); ``` I consider the first ten days of January to be 'appropriate' days for this greeting, but you can adjust to taste. The `now() LIKE` construct works out shorter than extracting day-of-year with `DATE_FORMAT(now(),'%j')`. # Task 10, sed, 58 bytes ``` s/./ ()--() ~/g;s/.$//;h;y/()-~/___ /;p;g;y/ ()-~/| /;G ``` Input in unary. [Answer] # Task 5, [MarioGolf](https://github.com/ismael-miguel/mariogolf), 50 bytes This was a language I've developed for some time. The current version has enough functionality to allow to run this challenge. ``` Y|<pneumonoultramicroscopicsilicovolcanoconiosis|O ``` You can try it online on <http://htmlpreview.github.io/?https://raw.githubusercontent.com/ismael-miguel/mariogolf/master/js/testpage.html#c:Y|<pneumonoultramicroscopicsilicovolcanoconiosis|O> Currently, the development is stopped and the implementation is incomplete. The latest commit was on 13th March 2015. # Task 6, PHP, 37 bytes This one is really easy, and fun! ``` <?=date(jn)==11?'Happy New Year!':''; ``` # Task 10, Javascript, 121 byes Yeah, not so golfed... But it does the job! ``` console.log((' ______ '.repeat(i=prompt()))+'\n'+('| | '.repeat(i))+'\n'+(' ()--() ~'.repeat(i).replace(/~$/,''))); ``` Try it: ``` //Required to show the console messages on the document console._RELAY_TO_DOC = true; console.log((' ______ '.repeat(i=prompt()))+'\n '+('| | '.repeat(i))+'\n '+(' ()--() ~'.repeat(i).replace(/~$/,''))); ``` ``` <script src="http://ismael-miguel.github.io/console-log-to-document/files/console.log.min.js"></script> ``` The code won't display well in the stack snippet due to it starting with `"` in the output. Adicional spaces were added to compensate it. The original code can be executed on Chrome's console without any problem, and the output will be the expected. [Answer] ## Task 1, CJam, 10 bytes ``` li,{3#}%:+ ``` [Try Here](http://cjam.aditsu.net/#code=li%2C%7B3%23%7D%25%3A%2B&input=5) ## Task 5, Retina, 46 bytes ``` <empty> pneumonoultramicroscopicsilicovolcanoconiosis ``` [Answer] # Task 1, Octave, 15 bytes ``` @(n)(n^2-n)^2/4 ``` EDIT: I thought I added this but it seems I forgot to save: This uses the fact that `sum(1^3+2^3+3^3+...+n^3) = sum(1+2+3+...+n)^2 = [n*(n+1)/2]^2` # Task 3, Javascript, 24 bytes ``` x=>x.sort()[x.length>>1] ``` [Answer] Okay, let's get the easy stuff done first: ## Task 5, ASP, 45 bytes ``` pneumonoultramicroscopicsilicovolcanoconiosis ``` ## Task 6, JavaScript, 46 bytes ``` /an 01/.test(Date())&&alert("Happy New Year!") ``` [Answer] # Task 1, VBA, 126 bytes ``` Function f(n As Integer) Dim i As Integer For i = 0 To n - 1 f = f + i ^ 3 Next i End Function ``` I haven't got a clue how to golf in VBA. I didn't type a single space, VBA automatically insert whitespaces. `=f(5)` in a cell in Excel will display 100. # Task 2, Octave, 32 Bytes ``` @(n)isprime(n)&~mod(log2(n+1),1) ``` # Task 5, Golfscript, 47 bytes ``` "pneumonoultramicroscopicsilicovolcanoconiosis" ``` # Task 9, MATLAB, 9 bytes ``` @(A,n)A*n ``` Well, it's a start... ]
[Question] [ # Introduction Aron Nimzowitsch was a leading chess master and a influential chess writer. In his book 'My System', the first chapter deals about the importance of the center and why you should dominate it. The simple reason is that your pieces have more possible direct next moves when being in the center which again gives the player more power. This gets very clear when looking at different positions of a knight and its potential next moves (shown in pink) on an empty board: [![enter image description here](https://i.stack.imgur.com/InzGQ.png)](https://i.stack.imgur.com/InzGQ.png) # Objective Evaluate the number of potential direct next moves of a knight on an empty board based on its position. # Input Specs The position of the knight. First the x (column) and then the y (row). `0 0` is the left bottom corner. For simplicity, I changed the labels of a chess board to numbers only. For our examples and test cases we use a 0-based index, you are free to use a 1-based index though. You can use any type of possible input formats, an array, function arguments, etc. # Output Specs The number of potential direct next moves for a knight on an empty board. # Test Cases ``` 3 4 => 8 4 6 => 6 7 7 => 2 1 0 => 3 ``` *Test cases are employing a 0-based index.* The full grid of values is: ``` 2 3 4 4 4 4 3 2 3 4 6 6 6 6 4 3 4 6 8 8 8 8 6 4 4 6 8 8 8 8 6 4 4 6 8 8 8 8 6 4 4 6 8 8 8 8 6 4 3 4 6 6 6 6 4 3 2 3 4 4 4 4 3 2 ``` [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` lambda x,y:50/(8+x*x/7-x+y*y/7-y)-4 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCp9LK1EBfw0K7QqtC31y3QrtSqxJIV2rqmvwPsi1KzEtP1bDQ5ErLL1KoUMjMUwiyKijKzCtRV1DXy8rPzNMoLinSSNMAGqOpqQBSVAlWpPkfAA "Python 2 – Try It Online") --- **[Python 2](https://docs.python.org/2/), 39 bytes** ``` lambda x,y:50/(8-x*(7-x)/5-y*(7-y)/5)-4 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCp9LK1EBfw0K3QkvDXLdCU99UtxLEqgSyNHVN/gfZFiXmpadqWGhypeUXKVQoZOYpBFkVFGXmlagrqOtl5WfmaRSXFGmkaQCN0tRUACmqBCvS/A8A "Python 2 – Try It Online") Takes inputs 0-indexed. The expression `x*(7-x)/5` takes the coordinate values `0..7` to ``` [0, 1, 2, 2, 2, 2, 1, 0] ``` (`min(x,7-x,2)` does the same, but is longer.) Summing this for `x` and `y` gives the right pattern but with the wrong numbers ``` 0 1 2 2 2 2 1 0 1 2 3 3 3 3 2 1 2 3 4 4 4 4 3 2 2 3 4 4 4 4 3 2 2 3 4 4 4 4 3 2 2 3 4 4 4 4 3 2 1 2 3 3 3 3 2 1 0 1 2 2 2 2 1 0 ``` (See [Neil's solution](https://codegolf.stackexchange.com/a/83945/20260) for better reasoning as to why this gives about the right pattern.) Finally, the mapping `a -> 50/(8-a)-4` with floor-division gives the right values ``` 2 3 4 4 4 4 3 2 3 4 6 6 6 6 4 3 4 6 8 8 8 8 6 4 4 6 8 8 8 8 6 4 4 6 8 8 8 8 6 4 4 6 8 8 8 8 6 4 3 4 6 6 6 6 4 3 2 3 4 4 4 4 3 2 ``` An alternative equally-long solution with 1-indexed inputs: ``` lambda x,y:(x*(9-x)/6+y*(9-y)/6)**2/6+2 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~17~~ ~~14~~ ~~13~~ 12 bytes *Thanks to @Neil for 1 byte off!* ``` 8:HZ^ZP5X^=s ``` Input is 1-based. [**Try it online!**](http://matl.tryitonline.net/#code=ODpIWl5aUDVYXj1z&input=WzUgN10) ### Explanation This computes the Euclidean distance from the input to each of the 64 positions in the chessboard, and finds how many of those values equal the square root of 5. Since the coordinates are integer values, we can be sure that the two floating-point values representing the square root of 5 (that computed from the coordinates and that computed directly) are indeed the same. ``` 8: % Push array [1 2 ... 8] H % Push 2 Z^ % Cartesian power. Gives 2D array [1 1; 1 2; ... 1 8; 2 1; ... 8 8] ZP % Implicit input. Compute Euclidean distances, considering each row as a point 5X^ % Square root of 5 =s % Compute how many squared distances equal sqrt(5). Implicit display ``` [Answer] # Mathematica ~~63~~ 43 bytes With 20 bytes saved thanks to suggestions by Martin Ender! ``` EdgeCount[8~KnightTourGraph~8,#+1+8#2/<->_]& ``` The above finds the number of squares that are 1 hop away from the given cell on the complete knights tour graph. --- `g=KnightTourGraph[8,8,VertexLabels->"Name",Axes->True]` displays the complete knight's tour graph, with vertex names and coordinates. Note that Mathematica defaults to one-based indexing for the coordinates. [![graph](https://i.stack.imgur.com/1vUvr.png)](https://i.stack.imgur.com/1vUvr.png) --- [Answer] ## JavaScript (ES6), 38 bytes ``` (x,y)=>+"23468"[((7-x)*x+(7-y)*y)/5|0] ``` Takes 0-indexed inputs. Explanation: Look at the squares of the distances to the centre: ``` 24.5 18.5 14.5 12.5 12.5 14.5 18.5 24.5 18.5 12.5 8.5 6.5 6.5 8.5 12.5 18.5 14.5 8.5 4.5 2.5 2.5 4.5 8.5 14.5 12.5 6.5 2.5 0.5 0.5 2.5 6.5 12.5 12.5 6.5 2.5 0.5 0.5 2.5 6.5 12.5 14.5 8.5 4.5 2.5 2.5 4.5 8.5 14.5 18.5 12.5 8.5 6.5 6.5 8.5 12.5 18.5 24.5 18.5 14.5 12.5 12.5 14.5 18.5 24.5 ``` The number of reachable squares falls into five bands: ``` 8 0-5 6 5-10 4 10-15 3 15-20 2 20-25 ``` I actually calculate 24.5 - (3.5 - x) \*\* 2 - (3.5 - y) \*\* 2 = (7 - x) \* x + (7 - y) \* y as it's a shorter calculation, but all it does is reverse the order of the bands. [Answer] # Jelly, 10 bytes ``` 8ṗ2_³²S€ċ5 ``` 1-indexed. Takes a single argument of the form `[x,y]`. [Try it here.](http://jelly.tryitonline.net/#code=OFLhuZcyX8KzwrJT4oKsxIs1&input=&args=WzYsNl0) ``` 8ṗ2 Cartesian square [[1,1],[1,2]…[8,8]] _³ Subtract the input ²S€ Compute the norm of each vector ċ5 Count fives ``` Dennis saved a byte! [Answer] ## Mathematica, ~~44~~ 40 bytes I've currently got three solutions at the same byte count: ``` 2[3,4,6,8][[Tr@⌊3.2-.8Abs[#-4.5]⌋]]& Tr@⌈.85(4-Abs[#-4.5])⌉/.{5->6,6->8}& ⌊Tr@⌈.85(4-Abs[#-4.5])⌉^1.1608⌋& ``` All of those are unnamed functions that take pair of coordinates like `{3, 4}`, which are 1-based. I tried coming up with a somewhat explicit formula. The general pattern on the entire board looks like this: [![enter image description here](https://i.stack.imgur.com/jSi6s.png)](https://i.stack.imgur.com/jSi6s.png) The actual values of those colours (from lightest to darkest) are `2, 3, 4, 6, 8`. That is: ``` 2 3 4 4 4 4 3 2 3 4 6 6 6 6 4 3 4 6 8 8 8 8 6 4 4 6 8 8 8 8 6 4 4 6 8 8 8 8 6 4 4 6 8 8 8 8 6 4 3 4 6 6 6 6 4 3 2 3 4 4 4 4 3 2 ``` We first exploit the symmetry by shifting the origin to the centre, taking the absolute value and subtracting the result from `4`. This gives us coordinates `0.5` to `3.5` increasing from each corner. In order to make the centre coordinates the same we need to map `0.5` and `1.5` to different values and `2.5` and `3.5` to the same value. This is easily done by multiplying by `0.8` (gives`{0.4, 1.2, 2., 2.8}`) and flooring the result. So now we've got `{0, 1, 2, 2}` as distances from the centre. If we add up the coordinates in each cell, we get this table: ``` 0 1 2 2 2 2 1 0 1 2 3 3 3 3 2 1 2 3 4 4 4 4 3 2 2 3 4 4 4 4 3 2 2 3 4 4 4 4 3 2 2 3 4 4 4 4 3 2 1 2 3 3 3 3 2 1 0 1 2 2 2 2 1 0 ``` This has unique values for all the different possible results, so we simply use it as an index into `2[3,4,6,8]`. In the second version we use ceiling instead floor. This way, `2`, `3` and `4` are already correct, but we get `5` and `6` instead of `6` and `8`, so we correct those manually with a substitution rule. Finally, in the third version, we extend `5` and `6` upwards to `6` and `8` by means of exponentiation, followed by another floor operation. [Answer] ## APL, 21 chars ``` {+/,5=+/¨×⍨(⍳8 8)-⊂⍵} ``` In English: * `(⍳8 8)`: 8x8 rank-2 array containing the coordinates of all the cells; * `+/¨×⍨(⍳8 8)-⊂⍵`: square of the euclidean distances of the given cell with respect to every cell on the board; * `5=`: matrix of 0/1, where the 1s appear at squared distances equal 5; * `+/,`: sum the flattened matrix Test (in origin 1): ``` f←{+/,5=+/¨×⍨(⍳8 8)-⊂⍵} f¨1+(3 4)(4 6)(7 7)(1 0) 8 6 2 3 ``` In this form: ``` f←{+/,5=+/¨×⍨(⍳⍺)-⊂⍵} ``` the left argument can specify the dimensions of the board. Hence `8 8 f` will work for the standard square chessboard. But on a larger and rectangular board, the test cases would give different results. For instance, on a 12x10 board: ``` g←(10 12)∘f g¨1+(3 4)(4 6)(7 7)(1 0) 8 8 8 3 ``` [Answer] # Java - ~~160~~ 150 bytes ``` int m(int r,int c){int m=0,i,j;for(i=0;i<3;i+=2)for(j=0;j<3;j+=2){m+=r+i>0&r+i<9&c+2*j>1&c+2*j<11?1:0;m+=r+2*i>1&r+2*i<11&c+j>0&c+j<9?1:0;}return m;} ``` Ungolfed: ``` public static int m(int r, int c) { int m=0; for(int i=-1;i<2;i+=2) for(int j=-1;j<2;j+=2){ m += r+i>-1 && r+i<8 && c+2*j>0 && c+2*j<8 ? 1:0; m += r+2*i>0 && r+2*i<8 && c+j>1 && c+j<8 ? 1:0; } return m; } ``` The ungolfed code is identical except for changing the bounds of the for loop to save 4 bytes. Works by iterating through each possible move and performing a bounds check (>0 and <8). Uses the fact that the offsets are (1, 2), (2, 1), (-1, 2), (-2, 1), etc. and is able to check 2 moves for each value of i and j. Edit: 10 bytes saved thanks to suggestions by Leaky Nun and u902383. [Answer] # C, 44 Bytes ``` f(x,y){return "23468"[((7-x)*x+(7-y)*y)/5];} ``` But this is better: ``` f(x,y){return "2344443234666643468888644688886446888864468888643466664323444432"[x*8+y];} ``` [Answer] ## Haskell, ~~49~~ 48 bytes ``` w=[0..7] x%y=sum[1|a<-w,b<-w,(a-x)^2+(b-y)^2==5] ``` [Answer] # Java, 81 characters (113 bytes) ``` int r(int a,int b){return "⍄䐲㑦晃䚈衤䚈衤䚈衤䚈衤㑦晃⍄䐲".codePointAt(a*2+b/4)>>(3-b%4)*4&15;} ``` Encode the whole result table as unicode table and then get appropriate bytes doing bitwise operations. You can see it online here: <https://ideone.com/K9BojC> [Answer] # Python, 94 bytes ``` lambda x,y,a=[2,1,-1,-2,-2,-1,1,2]:list((9>x+a[i]>0)&(9>y+a[5-i]>0)for i in range(8)).count(1) ``` Uses 1 based indexing. Demo at <https://repl.it/C6gV>. [Answer] # Pyth - ~~33~~ 15 bytes *Thanks to @LeakyNun for reducing my size by half.* Rearranging the maps and `V`'s will probably lemme golf a little off. ``` /sM*Fm^R2-Rd8Q5 ``` [Test Suite](http://pyth.herokuapp.com/?code=%2FsM%2aFm%5ER2-Rd8Q5&test_suite=1&test_suite_input=3%2C+4%0A4%2C+6%0A7%2C+7%0A1%2C+0&debug=0). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 [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") ``` ≢⍸2=|×.-∘⎕¨⍳8 8 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKNdIe3/o85Fj3p3GNnWHJ6up/uoY8ajvqmHVjzq3WyhYAFS8Z8zjctYwYQLSJkomIEocwVzEGWoYAgA "APL (Dyalog Unicode) – Try It Online") [Answer] # [J](http://jsoftware.com/), 23 bytes ``` 1#.1#.5=[:+&*://]-/i.@8 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1gMjUNtpKW03LSl8/Vlc/U8/B4r8mV2pyRr5CGlCpgQKMbQiECLYRjGkEhP8B "J – Try It Online") Homage to Lynn's method, converted to J [Answer] ## Actually, 18 bytes ``` `;7-2km`MΣ8-:50\¬¬ ``` [Try it online!](http://actually.tryitonline.net/#code=YDs3LTJrbWBNzqM4LTo1MFzCrMKs&input=Myw0) This implements the same formula that many other answers have been using: `50/(8-x*(7-x)//5+y*(7-y))//5)-4`. Input is taken as a list: `[x,y]` (or any iterable literal in Python, like `(x,y)` or `x,y`). Explanation: ``` `;7-2km`MΣ8-:50\¬¬ `;7-2km`M for each value in input: ;7- make a copy, subtract from 7 2 push 2 km minimum of the three values (x, 7-x, 2) Σ sum 8- subtract from 8 :50\ integer divide 50 by the value ¬¬ subtract 2 twice ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 44 bytes ``` {+grep {5==[+] $_>>²},((^8 X, ^8)XZ-(@_,))} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJZm@79aO70otUCh2tTWNlo7VkEl3s7u0KZaHQ2NOAuFCB2FOAvNiChdDYd4HU3N2v/WXGn5RQo2xgomQGimYA6EhgoGdgq6dgoqiToKKkkK1VycxYmVCkpQrq2dQnWaBoSjWatkzVX7HwA "Perl 6 – Try It Online") [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 49 bytes ``` : g 9 over - 6 */ ; : f g swap g + dup 6 */ 2 + ; ``` [Try it online!](https://tio.run/##VYxLCoAwDET3OcWslSq6EGxPI9b6QUipVY9fo125mjcTXhyHuKjZvZGSxowefE0BCh2KGoY0nKzHPXiJEvb0@dJKMWLE6YgE0RpYFvghsGKTB9XXdmaPMVAmMp@bHg "Forth (gforth) – Try It Online") Port of [xnor's 1-based solution](https://codegolf.stackexchange.com/a/83944/78410). `f` takes `x y` (1-based) on the stack and computes `(x(9-x)/6 + y(9-y)/6)**2/6+2`. Uses the built-in `*/` to do a multiplication followed by division at once and save a space. ``` : g ( x -- x(9-x)/6 ) 9 over - \ ( x 9-x ) 6 */ \ x*(9-x)/6 ; : f ( x y -- ans ) g swap g \ apply g to y, then to x + dup 6 */ \ (gx+gy)*(gx+gy)/6 2 + ; ``` ]
[Question] [ Do you have any tips for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")ing in [05AB1E](https://github.com/Adriandmen/05AB1E), a golfing language created by [Adnan](https://codegolf.stackexchange.com/users/34388/adnan)? Your tips should be at least somewhat specific to 05AB1E. Please post one tip per answer. [Answer] Since it wasn't part of the [Wiki on 05AB1E's GitHub pages](https://github.com/Adriandmen/05AB1E/wiki) (I think it should), I'm just gonna add it here now that I better understand it myself. # How to use the dictionary? 05AB1E has the following [words.ex dictionary file](https://github.com/Adriandmen/05AB1E/blob/master/lib/reading/dictionary/words.ex) containing all the words it knows. But how do we access the words in this dictionary? Let's take the word `"testing"` as example: `"testing"` can be found on row 1453 of the dictionary file. Since the first two lines aren't words, and we need the 0-indexed word, we subtract 3. So, now we have the index (`1450`), but how to use it? We open and start a compressed string with `“`*†*. We then look at the second column of the [info.txt file](https://github.com/Adriandmen/05AB1E/blob/master/docs/info.txt). (So `€` is 00; `‚` is 01; etc.) In the case of `"testing"` this means `î` (14) and `»` (50). The compressed String for `"testing"` is therefore: `“` [Try it online.](https://tio.run/##MzBNTDJM/f//UcOcw@sO7QZS//8DAA) As with almost all 05AB1E pieces of code, the trailing `“` is optional if you don't access the string, so [without works as well in this case](https://tio.run/##MzBNTDJM/f//UcOcw@sO7f7/HwA). **Some things to note:** All characters that doesn't have any index in the info.txt file can be used as is. This can be useful for adding an `s` to output a plural instead of singular word or use punctuation like `,.?!` for example. `ÿ` (string-interpolation) can also be used when you want to insert values from the stack within the string. NOTE: Every loose character that doesn't have any index in the info.txt file counts as a word for the compression types below. *†* There are different types of compressed strings you can use: * `'`: Take a single compressed word as is (no trailing `'` required) - [`'î»`](https://tio.run/##MzBNTDJM/f9f/fC6Q7v//wcA): "testing" * `„`: Takes two compressed words with space delimiter (no trailing `„` required) - [`„î»î»`](https://tio.run/##MzBNTDJM/f//UcO8w@sO7Qbh//8B): "testing testing" * `…`: Takes three compressed words with space delimiter (no trailing `…` required) - [`…î»î»î»`](https://tio.run/##MzBNTDJM/f//UcOyw@sO7Ybh//8B): "testing testing testing" * `“`: Take the compressed string with space delimiter - [`“î»î»“`](https://tio.run/##MzBNTDJM/f//UcPMw@sO7QZhIPP/fwA): "testing testing" * `’`: Take the compressed string as is without implicit spaces - [`’î»î»’`](https://tio.run/##MzBNTDJM/f//UcPMw@sO7Qbh//8B): "testingtesting" * `”`: Take the compressed string in title-case with space delimiter - [`”î»î»”`](https://tio.run/##MzBNTDJM/f//UcPcw@sO7QZhIPP/fwA): "Testing Testing" * `‘`: Take the compressed string in full uppercase with space delimiter - [`‘î»î»‘`](https://tio.run/##MzBNTDJM/f//UcOMw@sO7QZhIPP/fwA): "TESTING TESTING" Here a useful program to get the compressed string based on a space-delimited input of words: ``` '“? lAð«Ã#¸˜ vyU "€‚ƒ„…†‡ˆ‰Š‹ŒŽ•–—™š›œžŸ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîï" Dâ vy"“ÿ“".V XlQi y?1#] '“, ``` ### [Try it online.](https://tio.run/##FZC5TgJRGEZf5WYobIyRwppofAAtNDYWmFCYkJhQmNBdAXHfADdEZAYYVgF3QIHk@3JteIv/RcaxOTntOfML4a1gxPNmRBdCKrrIHlpMBtCfFtRufE1ZkmiLzv9mRBdFu6JLou1pWnTP@DYwGTMS7YjOis5JyjG26KHJmrHpw4aDMiqowkUNdTTQRAttdNBFDy94xRve8YFPfKGPAYb4xg9GGGNCzT0mmGSK@0zzgIc84jFPeMoznvOCl7xihlnmeM0b3vKO98zzgQU@ssgnlmjTYZkVVumyxjobbLLFNp/ZYddSy3T8Psuv5sSHNbeuNqKr2yoeCgY21f@NWc9b2YmGY2opEo79AQ) This program will: 1. Take the input as lowercase, removes any non-alphabetic characters (except for spaces), and then splits the words by spaces (`lAð«Ã#`), or wraps the words in a list if only a single word was inputted (`¸˜`) 2. Loops over each word (`vyU`) 3. Then has an inner loop over each compressed word from the dictionary (`"€...ï"Dâvy`), which it will try to run as 05AB1E program (`"“ÿ“".V`) 4. And if it's equal to the current word it will print it and break the inner loop `XlQiy?1#` With an input `good bye world` the output would therefore be `“‚¿Þ¡‚ï“`. [Try it online.](https://tio.run/##FZC5TgJRGEZf5WYobIyRwpqY@AIWGhsLCcSYkJBYaOiugLhvgBsiMsO@CLgDCiTfl2vDW/wvMo7NyWnPmV/YCPrDrjsjOh9QkUX20GLCh/40r3ZiK8qSeFt07jctuiC6Kroo2p6mRPeMZwOTNiPRjuiM6KwkHWOLHpqMGZs@bDgooYwKqqihjgaaaKGNDrro4QWveMM7PvCJL/QxwBDf@MEIY0youcc4E0xynyke8JBHPOYJT3nGc17wkldMM8Msr3nDW97xnjk@MM9HFvjEIm06LLHMCqussc4Gm2yxzWd22LXUEh2vz/KqOfFgza2qtcjylooF/L519X9j1nU3o9GQCsbCaje6HQn9AQ) NOTE: You'd still have to see if the word exist in the dictionary in order for this generator to work, and it will ignore any special characters or plural words. Only the words that are exactly the same in the dictionary will be found. [Here an example where I use `…Ÿ™‚ï!` for the string "hello world!" and `’‚¿Þ¡ ÿ ‚ï!’` for the string "goodbye ÿ world!".](https://codegolf.stackexchange.com/a/170983/52210) Note how the spaces and exclamation mark are used as is, because they don't have indices in the info.txt file. In addition, it uses `ÿ` to insert the "cruel" that was at the top of the stack, which unfortunately wasn't part of the dictionary (but was still compressed using the method at the section below). # How to compress strings not part of the dictionary? Although the words.ex dictionary file is pretty big (10,000 words to be exact), it can happen that you need a word which isn't part of it, or a string which is just plain gibberish. So is there a way to compress those as well? There certainly is, by using `.•`, which is a compressed base-255 alphabet based string. NOTE: This method can only be used for characters in the lowercase alphabet and spaces. Here is a useful program to convert a word/string to the compressed base-255 alphabet based string: ``` vAyk})> 27β 255B ".•ÿ•" ``` ### [Try it online.](https://tio.run/##MzBNTDJM/f@/zLEyu1bTTsHI/NwmBSNTUycFJb1HDYsO7wcSSv//J@fnFhSlFhcrpOfnF6cCAA). What this program above does is: * `vAyk})>`: Take the 1-indexed alphabet indices of the individual letters of the input, with spaces becoming index 0 * `27β`: Convert these indices from base 27 to a single number * `255B`: Convert this number to Base-255 using 05AB1E's own code page * `".•ÿ•"`: Places a leading `.•` and trailing `•` before this compressed string [Here an example answer where *@Kaldo* uses `.•zíΘ•` to compress the word "goose".](https://codegolf.stackexchange.com/a/157910/52210) # How to compress large integers? Let's say we want to use a very big number for something, but it can't really be retrieved by pow-calculations. For example, let's say we want to access the large integer `18238098189071058293` for whatever reason. In this case we can use both a leading and trailing `•` to compress a number in the format `[1-9][0-9]+`. The example number above will become `•15Y₁Ò'Θpc•`. [Try it online.](https://tio.run/##MzBNTDJM/f//UcMiQ9PIR02Nhyepn5tRkAzk//8PAA) Again, just like with the compressed dictionary string, [the trailing `•` can optionally be removed](https://tio.run/##MzBNTDJM/f//UcMiQ9PIR02Nhyepn5tRkPz/PwA). Optionally, when the integer is small enough so only 2 compressed characters have to be used, we can use `Ž` instead, in which case we won't need a trailing byte to close it and the integer is compressed in 3 bytes instead of 4. For example, the integer `13562` would result in [`•rl•`](https://tio.run/##yy9OTMpM/f//UcOiohwg8f8/AA), but because it only uses two characters, it can be [`Žrl`](https://tio.run/##yy9OTMpM/f//6N6inP//AQ) instead. Also, numbers in the range `[101, 355]` can be compressed in 2 bytes using `Ƶ` plus an additional character from 05AB1E's codepage. So for example, [`Ƶ–`](https://tio.run/##yy9OTMpM/f//2NZHDZP//wcA) can be used for the integer `250`. [Here an overview of all available numbers.](https://tio.run/##DZBpU1JhGIb/CtFeZlrZvmf7bmV7LmX7vlhWNC9HRLRsASpUIBZFEVK2A4d95rk5NJMz79BfeP4I8e2eueb6cN0tbT29rX31OqUpIlVjVUXZ2N7cyWLCJINSM/UPdHQbUTaw1W5ooKZ6/Y/nr13GZUImZUqqMi0zUqslalqtUCv@U6RDOqVLZhtymEd8bBtl2xjbvKyYWVFYGWTFwsoQK1bDEuPSZctXrFy1es3apnXN61taN2zc1LZ5y9Zt23fs3LV7z959@w@0Hzx0@MjRY8dPnDx1@szZjnPnL3RevHT5ytVr1290dff03rzVd/vO3Xv3Hzx89PjJ02fPX7x81f/6zcDbd@9NH6oqK1E52Qip2ll4WYRY@Fj4F60sYnpjZXV7xaoXq@mKYOFiMc7CzcLDwsHCuehmS0D3s8jpjsqwXtK1ipn8FKAgTdE0hWiGZilMcxShqMzTPC1QjOKUoCSlSG2cmSGNspSjPBWoSCUqQ8AMBYOwYAhWDMOGEYziIz5hDJ/xBV/xDXY44MR3/MBPuDCOCUzCDQ@8@AUf/AggiClMI4QZzCKMOUQQxW/MYwExxJFAEimoSCMDDVnkkEcBRZRQ/g8) These characters are converted from Base-255 to Base-10, and then 101 is added (since the numbers in the range `[0,100]` are already 1 or 2 bytes). How are these `15Y₁Ò'Θpc` and `rl` created? Very simple, the number is converted to Base-255 using 05AB1E's own codepage. So you can use the following program to get a compressed number, for which it will then use `Ƶ.`, `Ž..`, or `•...•` depending on the size of the compressed integer: ``` 101 355Ÿså i 101-255B"Ƶÿ" ë 255B Dg2Qi "Žÿ" ë "•ÿ•" ``` ### [Try it online.](https://tio.run/##yy9OTMpM/f/f0MBQwdjU9OiO4sNLFTIVgFxdI1NTJ6VjWw/vV1I4vFoBxFNwSTcKzFRQOroXKqj0qGHR4f1AQglogoWRsYWBpYWhhaWBuaGBqYWRpTEA) [Here an example answer where *@Emigna* uses `•3Èñ•` for the integer `246060`.](https://codegolf.stackexchange.com/a/164461/52210) # How to compress integer lists? Sometimes you want to compress an entire list of integers instead of a single number. For example, let's say we want the list `[5,94,17,83,4,44,32,19,4,45,83,90,0,14,3,17,17,81]` for whatever reason. In this case, we can use the following instead: `•5O›YJ&p‘ÑÎ!6¯8,•₃в` [Try it online.](https://tio.run/##MzBNTDJM/f8/yu7QSoVzmxSMTE2dFA6tK1Z61LDo8H4wcWGT0v//0aY6liY6huY6FsY6JjomJjrGRjqGliCmKUjI0kDHQMcQKApSAlJlGAsA) Here a useful program to generate both this compressed number and the Base we want to convert to: ``` Z>© β 255B ®s"•ÿ•ÿв" ``` ### [Try it online.](https://tio.run/##MzBNTDJM/f8/yu7QSoVzmxSMTE2dFA6tK1Z61LDo8H4wcWGT0v//0aY6lsY6huY6FsY6JjomJjrGRjqGliCmKUjI0kDHQMcQKApSAlJlGAsA) What this program above does is: * `Z>`: Get the max number + 1 of the input-list (`©`: and store it in the register) * `β`: Convert the input list from base `max+1` to a single number * `255B`: Compress this single number (as we did at the section above) * `®s"•ÿ•ÿв"`: Returns the result in the format: leading `•`, compressed number, `•`, max+1, trailing `в` [Here an example answer where I use `•4Œ”dóŒfÝŸĀTUÕáOyÖOÀÁàu¼6¹₆Žr‡_›y³eß₂©ǝ²ƶ"SAÎAñ'¡û†Ø(•91в` to compress the list `[85,30,29,39,28,37,33,88,31,40,34,89,35,41,32,90,36,38,42,43,44,60,45,61,46,62,47,63,48,64,49,65,81,50,66,51,67,52,68,53,69,86,54,70,87,55,71,56,72,82,57,73,79,80,58,74,59,75,76,77,78,83,84]`.](https://codegolf.stackexchange.com/a/169126/52210) PS: In this answer [`•6j|eDEJÞó(ÍêΓλùÄÞKüzHÇ-ø`JδŠ₂+Öηôî®À8†6/ðÎ6ùøΓ°ÓĆ;ˆ©Ā•2ô`](https://tio.run/##AWsAlP9vc2FiaWX//@KAojZqfGVERUrDnsOzKMONw6rOk867w7nDhMOeS8O8ekjDhy3DuGBKzrTFoOKCgivDls63w7TDrsKuw4A44oCgNi/DsMOONsO5w7jOk8Kww5PEhjvLhsKpxIDigKIyw7T//w) is an equal-bytes (57) alternative, since all numbers have exactly two digits. In some cases (especially small lists) this can be a shorter alternative. One thing to note is that it's usually shorter to use a slightly larger single-byte integer constant (i.e. `T₂₆₃т₅₁₄` for `10,26,36,95,100,255,256,1000` respectively) instead of the maximum+1 found by the program above. Let's say our example `[5,94,17,83,4,44,32,19,4,45,83,90,0,14,3,17,17,81]` was `[5,95,17,83,4,44,32,19,4,45,83,90,0,14,3,17,17,81]` instead, it would find [`•6MÖ∊]ć;?,ćiåÑ6Š•96в` (20 bytes)](https://tio.run/##MzBNTDJM/f8/yu7QSoVzmxSMTE2dFA6tK1Z61LDo8H4wcWGT0v//0aY6lqY6huY6FsY6JjomJjrGRjqGliCmKUjI0kDHQMcQKApSAlJlGAsA) as shortest, but [`•CRā»ïζyˆö͆y“a±•тв` (19 bytes)](https://tio.run/##AS8A0P9vc2FiaWX//@KAokNSxIHCu8OvzrZ5y4bDtsON4oCgeeKAnGHCseKAotGC0LL//w) with the single-byte constant `100` would be 1 byte shorter. You can still get the compressing program above by replacing the `Z>` with the single-byte constant (or its value): [Try it online](https://tio.run/##MzBNTDJM/f/f0MDg0EqFc5sUjExNnRQOrStWetSw6PB@MHFhk9L//9GmOpamOobmOhbGOiY6JiY6xkY6hpYgpilIyNJAx0DHECgKUgJSZRgLAA). **Integer compression vs Integer list compression:** With these two it can go either way. Sometimes a compressed list is shorter, sometimes a compressed integer, sometimes a completely different alternative is shorter. So always use your own judgment and golfing skills to possibly golf things further, instead of relying on the above generators completely. Here some examples: `[44, 59]` ([used in this answer of *@Emigna*](https://codegolf.stackexchange.com/a/171988/52210)): * [`•A–•60в`](https://tio.run/##yy9OTMpM/f//UcMix0cNk4GUmcGFTf//m5iYWgIA) is 7 bytes (generated by the compressed integer list generator) * [`•H|•2ô`](https://tio.run/##yy9OTMpM/f//UcMijxogYXR4y///JiamlgA) or [`•H|•2ä`](https://tio.run/##yy9OTMpM/f//UcMijxogYXR4yf//JiamlgA) or hardcoded [`44 59‚`](https://tio.run/##yy9OTMpM/f/fxETB1PJRw6z//wE) are all 6 bytes * [`ŽH|2ô`](https://tio.run/##yy9OTMpM/f//6F6PGqPDW/7/NzExtQQA) or [`ŽH|2ä`](https://tio.run/##yy9OTMpM/f//6F6PGqPDS/7/NzExtQQA) are both 5 bytes * But in this case, [`„,;Ç`](https://tio.run/##yy9OTMpM/f//UcM8HevD7f//AwA) with 4 bytes would be the best option (codepoints of characters ',' and ';') `[2,4,6,0]` ([used in this answer of *@Emigna*](https://codegolf.stackexchange.com/a/173636/52210)): * [`•3ā•7в`](https://tio.run/##yy9OTMpM/f//UcMi4yONQNL8wqb//wE) is 6 bytes (generated by the compressed integer list generator) * [`Ž3ā7в`](https://tio.run/##yy9OTMpM/f//6F7jI43mFzb9/w8A) is 5 bytes * But in this case, [`Ž9¦S`](https://tio.run/##yy9OTMpM/f//6F7LQ8uC//8HAA) with 4 bytes would be the best option (compressed integer 2460 to a list of digits) `10101001100101001` ([initially used in this answer of mine](https://codegolf.stackexchange.com/a/173556/52210)): * [`•a½₄Ƶ6®í•`](https://tio.run/##yy9OTMpM/f//UcOixEN7HzW1HNtqdmjd4bVA/v//AA) is 9 bytes (generated by compressed large integer generator) * [`•1∊}•2вJ`](https://tio.run/##yy9OTMpM/f//UcMiw0cdXbVA2ujCJq///wE) is 8 bytes (generated by compressed integer list generator with added join) * [`•1∊}•b`](https://tio.run/##yy9OTMpM/f//UcMiw0cdXbVAOun/fwA) with 6 bytes would be even shorter (compressed integer list, with a *to binary* instead of `2в`, which implicitly joins) * But [`Ž«ǝbĆ`](https://tio.run/##yy9OTMpM/f//6N5Dq4/PTTrS9v8/AA) with 5 bytes would be the shortest option here (compressed integer, to binary, and enclose - appending its own head) `[85,30,29,39,28,37,33,88,31,40,34,89,35,41,32,90,36,38,42,43,44,60,45,61,46,62,47,63,48,64,49,65,81,50,66,51,67,52,68,53,69,86,54,70,87,55,71,56,72,82,57,73,79,80,58,74,59,75,76,77,78,83,84]` ([used in this answer of mine](https://codegolf.stackexchange.com/a/169126/52210)): * [`•4Œ”dóŒfÝŸĀTUÕáOyÖOÀÁàu¼6¹₆Žr‡_›y³eß₂©ǝ²ƶ"SAÎAñ'¡û†Ø(•91в`](https://tio.run/##AW4Akf9vc2FiaWX//@KAojTFkuKAnWTDs8WSZsOdxbjEgFRVw5XDoU95w5ZPw4DDgcOgdcK8NsK54oKGxb1y4oChX@KAunnCs2XDn@KCgsKpx53Cssa2IlNBw45Bw7EnwqHDu@KAoMOYKOKAojkx0LL//w) is 57 bytes (generated by compressed integer list generator) * [`•6j|eDEJÞó(ÍêΓλùÄÞKüzHÇ-ø`JδŠ₂+Öηôî®À8†6/ðÎ6ùøΓ°ÓĆ;ˆ©Ā•2ô`](https://tio.run/##AWsAlP9vc2FiaWX//@KAojZqfGVERUrDnsOzKMONw6rOk867w7nDhMOeS8O8ekjDhy3DuGBKzrTFoOKCgivDls63w7TDrsKuw4A44oCgNi/DsMOONsO5w7jOk8Kww5PEhjvLhsKpxIDigKIyw7T//w) is also 57 bytes (compressed integer, split into parts of size 2) * [`•Bšā¿ÑáζΔÕæ₅"®GÙ₂®°ƶío"§óÏ4¸bćÔ!₃ùZFúÐìŸ ,λ₂ϦP(Ì•65в₂+`](https://tio.run/##AW4Akf9vc2FiaWX//@KAokLFocSBwr/DkcOhzrbOlMOVw6bigoUiwq5Hw5nigoLCrsKwxrbDrW8iwqfDs8OPNMK4YsSHw5Qh4oKDw7laRsO6w5DDrMW4CizOu@KCgsOPwqZQKMOM4oCiNjXQsuKCgiv//w) is however 2 bytes shorter, by compression the list with each value 26 lower, and then add that afterwards with `₂+`. This trick of adding a single-byte value later on can be used pretty often to save bytes in compressed lists. [Answer] # Using the Canvas (`Λ` or `.Λ`) Since it wasn't part of the docs, and *@Adnan* is currently a bit too busy to write it, I asked permission to add it as a tip here for now. The Canvas function (`Λ` or `.Λ`) can be used to draw ASCII-lines on the screen. It has three required parameters: * ***a*** Length: The size of the line(s). This can be a single integer, or a list of integers * ***b*** String: The character(s) we want to display. This can be a single character, a string, a list of characters, or a list of strings (in the last three cases it will use all of them one-by-one including wrap-around) * ***c*** Direction: The direction the character-lines should be drawn in. In general we have the digits `[0,7]` for the directions, for which we can use one or multiple. There are also some special options that require a certain character (more about that later). The direction-digits `[0,7]` map to the following directions: ``` 7 0 1 ↖ ↑ ↗ 6 ← X → 2 ↙ ↓ ↘ 5 4 3 ``` Some example 05AB1E answers where the Canvas is used: * [Print a negative of your code](https://codegolf.stackexchange.com/a/169298/52210) * [ASCII Art Octagons](https://codegolf.stackexchange.com/a/175412/52210) * [Eiffel Towers: Create a large “A” from “A”s](https://codegolf.stackexchange.com/a/160031/52210) * [Make an alphabet searchlight!](https://codegolf.stackexchange.com/a/141741/52210) * [A nicely-spaced ASCII spiral](https://codegolf.stackexchange.com/a/167486/52210) Let's do something similar as the last one, so assume we use the Canvas `Λ` function with the following three parameters: * ***a***: `[3,3,5,5,7,7,9,9]` * ***b***: `!@#` * ***c***: `[0,2,4,6]` This will give the following output: ``` !@#!@#! # @ @ #!@ # ! @ # ! # ! ! @ @ @ # !#@!# ! @ @!#@!#@!# ``` [Try it online.](https://tio.run/##yy9OTMpM/f//3Oz//6MNdIx0THTMYrkUHZS5oo11jHVMgdAcCC11LGMB) So how does it work? Well, here are the steps with these inputs above: 1. Draw `3` characters (`!@#`) upwards (direction `0`) 2. Draw `3-1` characters (`!@`) towards the right (direction `2`) 3. Draw `5-1` characters (`#!@#`) downwards (direction `4`) 4. Draw `5-1` characters (`!@#!`) towards the left (direction `6`) 5. Draw `7-1` characters (`@#!@#!`) upwards (direction `0`) 6. Draw `7-1` characters (`@#!@#!`) towards the right (direction `2`) 7. Draw `9-1` characters (`@#!@#!@#`) downwards (direction `4`) 8. Draw `9-1` characters (`!@#!@#!@`) towards the left (direction `6`) The `-1` are there because the lines overlap. So the first two steps are: ``` # @ ! ``` And ``` !@ ``` Which combined is: ``` #!@ @ ! ``` **Some minor notes:** * Apart from the options `[0,7]` there are a few specific options available, which basically translate to a certain direction-sequence. + `+` (`'+` inline) translates to the pattern `04402662`, which creates a `+`-cross with arms of the given length. [See it in action.](https://tio.run/##yy9OTMpM/f//3Oz//7W5HJ24TAE) + `×` (`'×` inline) translates to the pattern `15513773`, which creates a `X`-cross with arms of the given length. [See it in action.](https://tio.run/##yy9OTMpM/f//3Oz//w9P53J04jIFAA) + `8` returns to the origin of where we started drawing from. [See it in action](https://tio.run/##yy9OTMpM/f//3Oz//40sjC1MuRyduEwB) and [see the difference without the `8`](https://tio.run/##yy9OTMpM/f//3Oz//42MTbkcnbhMAQ). * The Canvas builtin will implicitly add trailing spaces to make the output a rectangle. * The `Λ` will output immediately, and `.Λ` results a string that is pushed to the stack, which we can still re-use, modify, and do anything with that we'd want. Some examples: + We can convert it [to a list of strings](https://tio.run/##yy9OTMpM/f/f/PBcvXOz9Zz@/zcGAA) or [to a list of characters](https://tio.run/##yy9OTMpM/f/f/PBcvXOzg///NwYA). + [We could replace a certain character](https://tio.run/##yy9OTMpM/f/f/PBcvXOzPdWVrf7/NwYA) + [Insert a certain character](https://tio.run/##yy9OTMpM/f/f/PBcvXOzXdKt1f2Lj8/9/98YAA) + etc. etc. * Depending on the given options, either the lengths or directions are leading when drawing the output: + If a list of lengths is given, those lengths will always be leading. In this case, wrap-around can be used for the directions-list. Some examples: - [`lengths = [3,4]` and `directions = [2,3,4,5]`](https://tio.run/##yy9OTMpM/f//3Oz//6ONdIx1THRMY7kcuaKBrFgA) will use directions `[2,3]` (the `4,5` are ignored), since only two lengths are given. - [`lengths = [3,4,4,2,3]` and `directions = [1,2]`](https://tio.run/##yy9OTMpM/f//3Oz//6MNdYxiuRy5oo11TIDQKBYA) will use directions `[1,2,1,2,1]` since there are five given lengths. + If a single length-integer is given, the directions will be leading instead. In this case, you can't use wrap-around of the directions-list. For example: - [`length = 2` and `directions = [3,3,5,5,7,7,1,3]`](https://tio.run/##yy9OTMpM/f//3Oz//6ONdYx1TIHQHAgNdYxjuRy5jAA) will use length `2` for all directions in the list. In this case you can't remove the trailing direction `3` despite already having a leading `3`, since the directions are leading for drawing the output. This would [give a different output](https://tio.run/##yy9OTMpM/f//3Oz//6ONdYx1TIHQHAgNY7kcuYwA). [Answer] # Implicit input Back in the days when 05AB1E was released, implicit input was quite new and fancy. Nowadays it seems to be necessary in order to keep track with other competitive languages (like Jelly, MATL, Pyth, etc.). For example, when you want to add two numbers, you can do `II+`: ``` I # Input_1. I # Input_2. + # Add them up. ``` [**Test it here**](http://05ab1e.tryitonline.net/#code=SUkr&input=Nwo2) --- However, using **implicit input**, we can shorten in to just 1 byte, namely `+`: ``` + # Take two numbers implicitly and add them up. ``` [**Test it here**](http://05ab1e.tryitonline.net/#code=Kw&input=Nwo2) --- This only happens when the length of the stack is smaller than the arity of the operator. A last example is `3+`. The arity of the `+` operator is **2** while there is only **1** element in the stack: ``` 3 # Push the number 3 on top of the stack. + # Request implicit input and add to the 3. ``` [**Test it here**](http://05ab1e.tryitonline.net/#code=Mys&input=Nw) [Answer] # Substrings `£` is the command for taking the first `b` characters of string `a`. **ex:** [`"hello_world"5£`](http://05ab1e.tryitonline.net/#code=ImhlbGxvX3dvcmxkIjXCow&input=) `->` `"hello"` But if `b` is a list of indices it instead splits the string into parts of (upto) those sizes. **ex:** [`"hello_world"5L£`](http://05ab1e.tryitonline.net/#code=ImhlbGxvX3dvcmxkIjVMwqM&input=) `->` `['h', 'el', 'lo_', 'worl', 'd']` [Answer] # Predefined variables They are a bit hidden in 05AB1E. Here's a list of all the predefined variables: * [`¾`](http://05ab1e.tryitonline.net/#code=wr4&input=), pushes **`0`** if the counter\_variable is not changed before this command. * [`X`](http://05ab1e.tryitonline.net/#code=WA&input=), pushes **`1`** if variable X is not changed before this command with `U`. * [`Y`](http://05ab1e.tryitonline.net/#code=WQ&input=), pushes **`2`** if variable Y is not changed before this command with `V`. * [`®`](http://05ab1e.tryitonline.net/#code=wq4&input=), pushes **`-1`** if the register is not changed before this command with `©`. * [`¯`](https://tio.run/##yy9OTMpM/f//0Pr//wE), pushes **`[]`** (empty array) if nothing is added to the global\_array before this command. * [`¸`](https://tio.run/##yy9OTMpM/f//0I7//wE), pushes **`[""]`** on an empty stack if there is no input. (Thank you @Emigna for finding this one.) [Answer] # Small [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) golfing tips Will expand this with small golfing tips I learned along the way. (Only just started 05AB1E personally.) * If you have a list of lists and first want to join each inner list by spaces, and then those space-delimited strings by newlines, the to-the-point approach would be [`ðý»`](https://tio.run/##yy9OTMpM/f//8IbDew/t/v8/OlrJKz8zT0lHKakSSBQXJCanFivF6kQrJealAAVKMlLhknmp5TmZeSDpWAA) of course. However, the `»` already implicitly joins inner lists by spaces before joining by newlines, so the `ðý` isn't necessary in this case: [try it online](https://tio.run/##yy9OTMpM/f//0O7//6OjlbzyM/OUdJSSKoFEcUFicmqxUqxOtFJiXgpQoCQjFS6Zl1qek5kHko4FAA). * `D` (duplicate) and `Ð` (triplicate) in combination with `s` (swap) and `Š` (triple-swap `a,b,c` to `c,a,b`) are usually shorter than using `©` (save in *global\_variable*) and `®` (push *global\_variable*) inside loops. This [saved a byte in this answer of mine](https://codegolf.stackexchange.com/a/166305/52210), as well as two in [this answer of mine](https://codegolf.stackexchange.com/a/165755/52210). * `½` (if 1, then increase *counter\_variable* by 1) isn't necessary at the end of a `µ` (while *counter\_variable* != a, do...), since it's done implicitly ([saved a byte in this answer of mine](https://codegolf.stackexchange.com/a/164398/52210)). * `.B` implicitly splits on new-lines. This was useful in [this answer of mine](https://codegolf.stackexchange.com/a/166162/52210) when we were looking for an alternative for `¡` (split) while still keeping empty items (NOTE: Solution in the linked answer doesn't work when elements contain trailing spaces after splitting.) - Hopefully a builtin will be added to split but keep empty lines in the future. * [legacy version only] `SÖ` (which of the digits of the input-integer can evenly divide the input-integer) will contain the number itself for the digits `0` (instead of divide-by-zero errors). For example, [`1053` will result in `[1,1053,0,1]`](https://tio.run/##MzBNTDJM/f8/@PC0//8NDUyNAQ) (1053 is divisible by 1 and 3; is not divisible by 5; and gives a division-by-zero error for 0). This was pretty useful in [this answer of mine](https://codegolf.stackexchange.com/a/164415/52210) by taking the power of the list, since only `1` is truthy in 05AB1E and everything else is falsey. `SÖP` resulting in truthy (`1`) therefore means an input-integer is evenly divisible by each of its digits. * After seeing `û` (palindromize a given string) I was surprised there isn't an *is\_palindrome* builtin. But later on I realized only 2 bytes are needed to accomplish that, which are [`ÂQ`](https://tio.run/##MzBNTDJM/V9TVmmvpPCobZKCkn3l/8NNgf91/ufllygkKhQk5mTmpRTl56ZyGRoZm5hy5aWWpRblp6TkFwEZeSBBI0MA) (where `Â` is bifurcate, which is short for `DR`: Duplicate & Reverse copy; and `Q` is to check if the top two values on the stack are equal). * When you want to filter a list by multiple things, it's usually cheaper to have multiple loose filters, rather than all combined in one filter. Because when you have two filters you'll need something along the lines of `Ds*` (duplicate, swap, multiply to act as logical-AND) vs `}ʒ` (close first filter, filter again) when you use two filters. For example: in [this challenge](https://codegolf.stackexchange.com/q/174049/52210) we have to list all numbers of four digits long, containing at least one `0`, and with a digit sum equal to `9`. Using a range `[1000,10000]` covers the number of four digits long, but then you are left with two more filters. Initially I used [`₄4°ŸʒD0åsSO9Q*`](https://tio.run/##yy9OTMpM/f//UVOLyaENR3ecmuRicHhpcbC/ZaDW//8A) (14 bytes), but by using two filters a byte can be saved: [`₄4°Ÿʒ0å}ʒSO9Q`](https://tio.run/##AR4A4f9vc2FiaWX//@KChDTCsMW4ypIww6V9ypJTTzlR//8) (13 bytes). (Which later got golfed to [`₄4°ŸεW°ö9Q`](https://tio.run/##ARsA5P9vc2FiaWX//@KChDTCsMW4ypJXwrDDtjlR//8) (10 bytes) by *@Grimmy*.) * When you want to zip with integer `0` as filler, you could use `0ζ`. One issue with this however is that the filler `0` will become a string `"0"`, so if you later try to sort with mixed strings and integer, this will most likely not give the result you'd want. Here an example of how it will sort the zipped inner lists: [`0ζ€{`](https://tio.run/##yy9OTMpM/f/f4Ny2R01rqv//j442jNWJNtUx0DEG0oY6RrGxAA). This can be fixed by adding an explicit cast to int (`ï`) after the zip, and only then sort: [`0ζï€{`](https://tio.run/##yy9OTMpM/f/f4Ny2w@sfNa2p/v8/OtowVifaVMdAxxhIG@oYxcYCAA). However, using the `¾` as constant `0` with the zip-filler, will cause it to remain an integer instead of a string during the zip. So [`¾ζ€{`](https://tio.run/##yy9OTMpM/f//0L5z2x41ran@/z862jBWJ9pUx0DHGEgb6hjFxgIA) will save a byte here. This tip was provided by *@Mr.Xcoder* to save a byte [in this answer of mine](https://codegolf.stackexchange.com/a/175101/52210). (The same applies to `X` instead of `1` and `Y` instead of `2`.) * If you want to sum the digits of multiple numbers in a list, you could use `€SO`. Shorter however is using `1ö`, which automatically vectorizes. This tip was provided by *@Grimmy* to [save a byte here](https://codegolf.stackexchange.com/a/164398/52210) (and [2 bytes here](https://codegolf.stackexchange.com/a/174058/52210)). * If you're only dealing with non-negative integers, and you want to get a truthy value (`1`) when the integer is either 0 or 1, you could of course use the obvious `2‹`. However, using `!` (factorial) will also only result in 1 (truthy) for `0` and `1`, and every other value will result in something higher (and thus falsey, since only `1` is truthy in 05AB1E). This tip was provided by *@Grimmy* to [save a byte here](https://codegolf.stackexchange.com/a/191389/52210). * If you want a list of all overlapping pairs (i.e. `[1,2,3,4,5,6,7,8,9]` → `[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9]]`), most probably already know `ü‚` can be used ([Try it online](https://tio.run/##yy9OTMpM/W/p8//wnkcNs/7/BwA)). But what if you want a list of overlapping triplets or quartets? The most obvious approach would seem to be `Œ3ù` (substrings & keep those of length 3 - [Try it online](https://tio.run/##yy9OTMpM/W/p8//oJOPDO///BwA)). But `ü` actually has a (currently undocumented) feature as shortcut for this `ü3` ([Try it online](https://tio.run/##yy9OTMpM/W/p8//wHuP//wE)), which works with any integer given to `ü`, including `2` to create overlapping pairs ([Try it online](https://tio.run/##yy9OTMpM/W/p8//wHqP//wE)). * If the stack is empty, some builtins will use the last value that was previously on the stack (and thus there is also no implicit input!), saving you on a potential duplicate. For example, in [this 05AB1E answer](https://codegolf.stackexchange.com/a/201191/52210) the `×` will use the `9L` list twice, without a need to duplicate it first. And in [this 05AB1E program](https://codegolf.stackexchange.com/questions/200713/print-a-list-of-iphones#comment482343_200719) the `ÿ` inside the string will use the `11` all three times, without the need to triplicate it first. * If we've used `|` to get all (remaining) inputs, the next `I` or implicit input will push this same list instead of the final input. Knowing this can sometimes save bytes, like in [the top program of this answer of mine](https://codegolf.stackexchange.com/a/211092/52210). * There is a flatten builtin `˜` to flatten a multi-dimensional list to a single list: [try it online](https://tio.run/##FYrLEYAgEEN7yZmOdjiAouIPFf@12JFFrfGQTF7mpex8DKrvoyoicL6AQRkqdt1EWCNou540jIk9zQvsf2bCymwg7BwHc/6@4LrpWPsB). There is also a way to flatten a (potentially multi-dimensional) list of strings to a single list of characters with `S`: [try it online](https://tio.run/##FYpJEoAgEAP/kjO/8TjFARQVN1TcPz@GQ1LpVKfsfAyqlaqIwPkaBk1o2V0fYY1gGCfSvCT2uu2w5cyEgzlBuDhu5im@4P3oWPsD). But what if we only want to flatten it down one level, instead of all the way? In that case, `€`` can be used if the order of items isn't important ([try it online](https://tio.run/##yy9OTMpM/f//UdOahP//o6OjlRKTkpV0lFJS04BkekamUqxOtFJWdg6Ql5uXDyQLCouUYkGCxUBOCRCXKgE5ZUBGORBXgNRHK1VWAdXExgIA)) or `í€`` if retaining the order of items is important ([try it online](https://tio.run/##yy9OTMpM/f//8NpHTWsS/v@Pjo5WSkxKVtJRSklNA5LpGZlKsTrRSlnZOUBebl4@kCwoLFKKBQkWAzklQFyqBOSUARnlQFwBUh@tVFkFVBMbCwA)). The unordered version is used pretty often in matrix-related challenges, like I used in [this answer of mine](https://codegolf.stackexchange.com/a/240671/52210). * You probably know how `δ` (apply double-vectorized) can be used on two list arguments to execute it on every pair (e.g. `δ‚` will create pairs using the values in the two lists - [try it online](https://tio.run/##yy9OTMpM/f//3JZHDbP@/4821DHSMY7lijbRMdUxiwUA)). You probably also know how it can be used as an apply-map with both a list and loose argument (e.g. `0δK` will remove all 0s from each inner list, which is shorter than a regular map `ε0K}` - [try it online](https://tio.run/##yy9OTMpM/f/f4NwW7///o6MNdQx0jGJ1ok10THXMgLQ5iA/EhgaxsQA)). What you might not know, at least it was new to me, is when two integers are given as arguments, it implicitly uses their `[1,n]` ranged lists instead (e.g. `δ‚` again on two integer arguments will convert both to a list and applies the pairing to those - [try it online](https://tio.run/##yy9OTMpM/f//3JZHDbP@/zfmMgEA)). This saved two bytes in a couple of answers of mine ([here](https://codegolf.stackexchange.com/a/235746/52210) and [here](https://codegolf.stackexchange.com/a/241528/52210) for example). [Answer] # Pop or get As in other stack-based languages, 05AB1E's functions usually **pop** (consume) their inputs from the stack and push their outputs onto the stack. However, some functions **get** their inputs from the stack without consuming them. An example is the `head` function, `¬`, which produces the first element from the input list. See an example program here: [`¬+`](http://05ab1e.tryitonline.net/#code=wqwr&input=WzEwLCAyMCwgMzBd). This adds the first number of the input list to each number of that list. To know which functions pop and which get, see the corresponding column in the [function information file](https://github.com/Adriandmen/05AB1E/blob/master/docs/info.txt). [Answer] # 05AB1E ASCII-Art Golfing The below code helps turn ASCII-art into 05AB1E using a custom base conversion. ``` |»©ÐÙSDŠ¢øΣθ}R€н¬®sÅ?iD2£RDŠKsì}J©žLR‡®gö₅B®s"•ÿ•“ÿ“ÅвJ" ``` [Try it online.](https://tio.run/##JU/LSgNBEPyV9olKEI3vkw@CSFSQKHgTJru9uwOTmTA9Y1wwEAK5exVyUHMKhBw8SEBU2CXXkG/YH4mzeuluqoqqakWsynE2e0w@k376lD5fl8YvyVs6mvQmo2Ylaw@mX8kgGVLaOeSlYtKrOP6c0kGznPTH3xeVrPWaDMP0I2t3TpxsPmu9pT9uZK1uvrtpZ/penp/N4JjgSiNxH6WBG21rdSAeSvSBATUQ61yGgA/oWcPvEZT2UYOScKq5z@ICUGSNyTUmQqj@0QRGgcbAhogETPqgHOngQKsaEN6jBMF0iCKGS0uC18BTVhrNkQp/PoSeRsN0DCqASNVQ5C4OtZqbGBqM8goMbiNuEM6UJXQWMkCN0nMnEwJC/O8VcRfMNRkIrIOrLiXIcWeQR4VCVZlwb/DAAJdQV4J78frc0cLi0t3y2srqZnFre2d3b/9g4xc) This is accomplished by: 1. Listing out the unique characters in the ASCII drawing. 2. Order them by how many times they occur in the string in descending order (most occurring to least occurring characters). 3. Reverse the first two items if the ASCII drawing starts with the most occurring character (to prevent leading 0s in the compressed integer). 4. Map the characters of the input to `0-9A-Za-z` in that order, each distinct character getting its own mapping-character, until every one has been replaced. 5. Base compress it, using the highest base you needed to replace (based on the amount of unique characters). 6. Base convert it again to base-255 (for 05AB1E compression). 7. Format everything in the format: `•<compressed_integer>•“<sorted_distinct_characters>“ÅвJ`. The `“` allows you to also compress string-quotes `"`; the `Åв` will use this string to base-convert the generated integer using the string as custom base; and `J` will join all these characters together to a single string, which is output implicitly. Accepts patterns with up to and including 62 unique characters, good for ASCII-art. The less amount of unique characters, the better the compression. --- **Example output for [Draw the XNOR digital timing diagram](https://codegolf.stackexchange.com/questions/105853/draw-the-xnor-digital-timing-diagram) (214 bytes, 9 unique characters):** ``` ┌─┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐ ┌───┐ A ──┘ └─┘ └─┘ └─┘ └─┘ └─┘ └── ┌───┐ ┌───┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐ B ┘ └─┘ └─┘ └─┘ └───┘ └─┘ └ ┌─────┐ ┌─┐ ┌─┐ ┌───┐ X ──┘ └───┘ └───┘ └───┘ └──── ``` Would be: # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 106 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •I£.µ*:]ó±øqaµb₄ΘYQmœ¹µû₄p´ζÂĆ_5ŠKÑ×ðòË|₄#¹¶úôÂ-Í|¯ε¼É₂ïδ&é–9»ÞFò1î×HÃBjý2ĆÉ≠FYÂÂèC j‘£Å₅Œ•“─ └┘┐┌ XBA“ÅвJ ``` [Try it online.](https://tio.run/##AckANv9vc2FiaWX//@KAoknCoy7CtSo6XcOzwrHDuHFhwrVi4oKEzphZUW3Fk8K5wrXDu@KChHDCtM62w4LEhl81xaBLw5HDl8Oww7LDi3zigoQjwrnCtsO6w7TDgi3DjXzCr861wrzDieKCgsOvzrQmw6nigJM5wrvDnkbDsjHDrsOXSMODQmrDvTLEhsOJ4omgRlnDgsOCw6hDIGrigJjCo8OF4oKFxZLigKLigJzilIAg4pSU4pSY4pSQ4pSMClhCQeKAnMOF0LJK//8) **(106/214)\*100 = 49.53% the size of the original ASCII-art string.** Which is the same byte-count as [my actual submission for that challenge](https://codegolf.stackexchange.com/a/106621/52210) in 05AB1E (legacy). --- # Code explanation: NOTE: Code is absolutely not golfed. It's quickly written to convert ASCII art to the most efficient compression, so it's quite ugly and long.. ``` |» # Take multi-line input © # Store it in the register to reuse later ÐÙS # Only leave unique characters (as list) DŠ¢ø # Map it with the count for each of those characters Σθ}R # Sort it based on that count (highest to lowest) €н # Remove the count again, so the sorted characters remain ¬®sÅ?i # If the input starts with the most occurring character: D2£RDŠKsì} # Swap the first two characters in the list J© # Join everything together, and store it in the register to reuse later žLR‡ # Map each character to [0-9A-Za-z] ®gö # Get the amount of unique characters, and convert it to that Base ₅B # And then convert that to Base-255 ®s # Push the string and swap so the compressed integer is at the top again "•ÿ•“ÿ“ÅвJ" # Insert it in the correct output format # `•<compressed_integer>•“<sorted_distinct_characters>“ÅвJ` "•ÿ•" # (after which the result is output implicitly with trailing newline) ``` [Answer] # Implicit `http://` When using `.w` to make requests to URLs, you may be tempted to prepend `žX` (the builtin for `"http://"`) to the URL. Don't do it! According to [line 239](https://github.com/Adriandmen/05AB1E/blob/master/lib/commands/gen_commands.ex#L239) of `gen_commands.ex` (general commands), if the URL does not start with `http`, it will automatically prepend `http://`. Not only that, but for URLs like `http://http-server.com`, while 05AB1E won't prepend `http://` to `http-server.com` as it starts with `http`, HTTPoison, 05AB1E's Elixir HTTP client, [will automatically prepend `http://`](https://github.com/edgurgel/httpoison/blob/main/lib/httpoison/base.ex#L691) ([following](https://github.com/edgurgel/httpoison/blob/main/lib/httpoison/base.ex#L689) [the](https://github.com/edgurgel/httpoison/blob/main/lib/httpoison/base.ex#L241) [function](https://github.com/edgurgel/httpoison/blob/main/lib/httpoison/base.ex#L240) [calls](https://github.com/edgurgel/httpoison/blob/main/lib/httpoison/base.ex#L245) [all](https://github.com/edgurgel/httpoison/blob/main/lib/httpoison/base.ex#L345) [the](https://github.com/edgurgel/httpoison/blob/main/lib/httpoison/base.ex#L334) [way](https://github.com/edgurgel/httpoison/blob/main/lib/httpoison/base.ex#L428) [down](https://github.com/edgurgel/httpoison/blob/main/lib/httpoison/base.ex#L427) [to](https://github.com/edgurgel/httpoison/blob/main/lib/httpoison/base.ex#L455) [05AB1E](https://github.com/Adriandmen/05AB1E/blob/master/lib/commands/gen_commands.ex#L239)). [Answer] # Conditionals and loops Loops and conditionals automatically receive closing brackets at the end of a program, so you only need to add them in the code if you need to something outside of the loop/conditional. For example, this (ungolfed) program creating a list of the first `n` prime numbers do not need closing brackets. [`[¹¾Q#NpiNˆ¼`](http://05ab1e.tryitonline.net/#code=W8K5wr5RI05waU7LhsK8&input=MTI) But if we wanted to perform some operation on the resulting list, for example taking delta's we'd need to close the loop first. [`[¹¾Q#NpiNˆ¼]¯¥`](http://05ab1e.tryitonline.net/#code=W8K5wr5RI05waU7LhsK8XcKvwqU&input=MTI) [Answer] # Automatic vectorization Note that some operators in 05AB1E vectorize automatically on arrays. For example, the code `5L3+`, which disassembles to the following pseudocode: ``` [1, 2, 3, 4, 5] + 3 ``` would become: ``` [4, 5, 6, 7, 8] ``` If it doesn't vectorize automatically, you can also use the `€` operator. It takes a single character command, and performs that (monadic) operator on each element. An example to split each element is the following code ([**try it here**](http://05ab1e.tryitonline.net/#code=4oKsUw&input=WyJhYmMiLCAiZGVmIiwgImdoaSJd)): ``` €S ``` Whereas the normal `S` operator would split each element in the array and flattens it into a single array ([**try it here**](http://05ab1e.tryitonline.net/#code=Uw&input=WyJhYmMiLCAiZGVmIiwgImdoaSJd)). [Answer] # Ordering of the Inputs The order that you take input can have a drastic effect on your code, and, oftentimes if you're using `s` to swap the top of the stack with the next highest thing on the stack, you're not thinking about the problem correctly. Try to reorder inputs and see if you can get rid of the need to swap by either swapping the inputs ahead of time, adding it to the stack earlier on or duplicating it somewhere. The most obvious I&O can be the least successful 05AB1E answer. [Answer] # Strings and ints are equal types Not something that everybody agrees with, but it works. Consider the following two programs: ``` 4 5+ "4""5"+ ``` They both result into **9**. That is because every value is first evaluated (with `ast.literal_eval`). Because of that, we can perform all string manipulation operators on ints and all int manipulation operators on strings. For example, `12345û` palindromizes the number `12345`, resulting in `123454321`. After that, we can do the regular math on this number. ``` 12345û50000- ``` This would result into: [**123404321**](http://05ab1e.tryitonline.net/#code=MTIzNDXDuzUwMDAwLQ&input=). [Answer] # Hidden loops and iterators 05AB1E has the following normal loops and iterators: * `F`, which iterates through **0 .. n-1**. * `G`, which iterates through **1 .. n-1**. * `ƒ`, which iterates through **0 .. n**. * `v`, which iterates over each element **s[0], s[1], .., s[n]**. * `ʒ`, which is not exactly a loop, but a *filter-by* command. We abuse this command for it's unintended behaviour of looping through each element. Using these loops, we can derive the following *hidden loops*: * Instead of `gF`, you can use `v` which also has an `N`-index that can be used. * The `vy -> ʒ` replacement is a bit more tricky: + You need to immediately print the results. This surpresses the automatic print from printing the top of the stack. + The code snippet is run on a **new temporary stack**. This means that stack-dependent snippets cannot be used. + Invoking `y` is not possible in these kind of loops. ]
[Question] [ For any positive integer \$k\$, let \$d(k)\$ denote the number of divisors of \$k\$. For example, \$d(6)\$ is \$4\$, because \$6\$ has \$4\$ divisors (namely \$1, 2, 3, 6\$). Given a positive integer \$N\$, display a "skyline" in ASCII art using a fixed character, such that the height of the "building" located at horizontal position \$k\$ is \$d(k)\$ for \$k = 1, ..., N\$. See test cases below. # Rules * Any non-whitespace character may consistently be used, not necessarily `#` as shown in the test cases. * The algorithm should theoretically work for arbitrarily high \$N\$. In practice, it is acceptable if the program is limited by time, memory, data-type size or screen size. * Horizontally or vertically leading or trailing spaces or newlines are allowed. * Input and output can be taken by any [reasonable means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). * [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](http://meta.codegolf.stackexchange.com/a/2073/36398). [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Shortest code in bytes wins. # Test cases `N = 10`: ``` # # # # # ### ######### ########## ``` `N = 50`: ``` # # # # # # # # # # # # # # # # # # # # # # # # # ## # # # # # # # # # # # # # ## # # # # # # ### # ### # ### # ##### ### # ### # # # # ### # ### # ### ##### # ##### ### # ### ### ################################################# ################################################## ``` `N = 200`: ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ## # # # # # # # # # ## # # # # # # # # # # # # # # # # # # ## # ## # # # # # # # # # # # # # # # # # # # # # # # ## # # # # # # # # # ## # # # # # # # # # # # # # # # # # # ## # ## # # # # # # # # # # # # ## # # # # # # ## # # # # ## # # # # # # # ### # ## # # # # ## # # # # # # ## # # # ## # ### # # # ## # ### ### # # # # ### # ## # # # # # # # # # # # # # ## # # # # # # ## # # # # ## # ## # # # # # ### # ## # # # # ## # # # # # # ## # # # ## # ### # # # ## # ### ### # # # # ### # ## # # # # # # ### # ### # ### # ##### ### # ### # ### ##### # ##### ### # ##### ### ##### ####### ### # ### # ### ####### ##### ### ##### # ######### # ##### ##### ### # ### ##### # ######### # ### # # # # ### # ### # ### ##### # ##### ### # ### ##### ##### # ##### ### # ##### ### ##### ####### ### # ### # ### ############# ### ##### # ######### # ##### ##### ### ##### ##### # ######### # ### # # ####################################################################################################################################################################################################### ######################################################################################################################################################################################################## ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes Uses `0` instead of `#`. ``` RÆD0ṁz⁶ṚY ``` [Try it online!](https://tio.run/nexus/jelly#@x90uM3F4OHOxqpHjdse7pwV@f//f1MDAA "Jelly – TIO Nexus") [Answer] # Octave, ~~41~~ ~~40~~ 32 bytes Thanks to @StewieGriffin saved 8 bytes. ``` @(N)" #"(sort(~mod(k=1:N,k'))+1) ``` [Try it online!](https://tio.run/nexus/octave#@@@g4aeppKCspFGcX1SiUZebn6KRbWto5aeTra6pqW2o@T8xr1jD0EDzPwA "Octave – TIO Nexus") Previous answers: ``` @(N)" #"(sort(~bsxfun(@mod,k=1:N,k')+1)) ``` [Try it online!](https://tio.run/nexus/octave#@@@g4aeprqCsrlGcX1SiUZdUXJFWmqfhkJufopNta2jlp5OtrqltqKn5PzGvWMPQQPM/AA "Octave – TIO Nexus") ``` @(N)" #"(sort(ismember((k=1:N)./k',k))+1) ``` [Try it online!](https://tio.run/nexus/octave#@@@g4aeprqCsrlGcX1SikVmcm5qblFqkoZFta2jlp6mnn62uk62pqW2o@T8xr1jD0EDzPwA "Octave – TIO Nexus") Explanation: ``` N=5; d = (1:N)./(1:N)' %divide each of numbers from 1 to N by 1 to N %a [N by N] matrix created d = 1.00 2.00 3.00 4.00 5.00 0.50 1.00 1.50 2.00 2.50 0.33 0.66 1.00 1.33 1.66 0.25 0.50 0.75 1.00 1.25 0.20 0.40 0.60 0.80 1.00 m = ismember(d,1:N) %find divisors of each number m = 1 1 1 1 1 0 1 0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 idx = sort(m) %sort the matrix idx = 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 1 1 1 1 1 1 1 " #"(idx+1) %replace 0 and 1 with ' ' and '#' respectively # #### ##### ``` [Answer] ## C, ~~99~~ ~~95~~ ~~92~~ ~~91~~ 90 bytes ``` c,l,i,j;f(n){for(j=n;j--;puts(""))for(i=0;i<n;c=!putchar(32|c>j))for(l=++i;l;c+=i%l--<1);} ``` See it [work here](https://tio.run/nexus/c-gcc#JclBCsIwEEDRtT1FLAgTkkCruJrGu4TR0AkxKbW6qT2262hw9eH9Qjpq1gE9JLn6PEOwCYMxOD2XB7StlBXZdshDQrL7n9PoZjgd33QJ/x2tUowRSVk@RGOGXuJWOC3i7jiBeGW@Ctmszc5D30msPddu5ZOyIUfj7Qs). [Answer] # [Haskell](https://www.haskell.org/), 71 bytes `f` takes an `Int` and returns a `String`. ``` f m|l<-[1..m]=unlines[[last$' ':drop(m-i)['#'|0<-mod n<$>l]|n<-l]|i<-l] ``` [Try it online!](https://tio.run/nexus/haskell#FcRBCsMgEADArwgVTA6KKfRS1n5EcpBqYMFdi1p68e82mcNQQHbIPdXw7nI5TE0hOoDV/EqNbR6CRgbtN2Nod1/OyKl5n0PrUgn1jLV8FtK4enVTw4KmEgWDfOV9MOhzvJ5zs@Jhxd3aPw "Haskell – TIO Nexus") * `m` is the `N` of the OP (Haskell variables must be lowercase.) * The abbreviation `l=[1..m]` is used in the nested list comprehensions for iterating through all of rows, columns, and potential divisors. This means some extra initial rows filled with whitespace. * `n` is column (also number checked), `i` is row. * `['#'|0<-mod n<$>l]` is a list of `'#'` characters with length the number of divisors of `n`. [Answer] # [Python 3](https://docs.python.org/3/), 111 bytes ``` lambda n:'\n'.join([*map(''.join,zip(*['#'*sum(x%-~i==0for i in range(x))+n*' 'for x in range(1,n+1)]))][::-1]) ``` [Try it online!](https://tio.run/nexus/python3#RcjBCgIhEADQXxEiZsbdjfUUCH6J68EoYyJnxS2QDv26ER06vpfc0u8xn85RiYVF4HBbWdDrHAvCT@OLC2oPO9DbM2PbT292bk5rVaxYVI1yvWAjGkSDgu@3/5tRBkOBKHhrJxOol8rywITHmah/AA "Python 3 – TIO Nexus") --- This produces some leading vertical whitespace [Answer] # Octave, 61 bytes ``` for i=1:input(''),p(1:nnz(~rem(i,1:i)),i)=35;end,[flip(p),''] ``` **Explanation:** ``` for i=1:input('') % Loop, for i from 1 to the input value p(1:nnz(~rem(i,1:i)),i)=35;end,[flip(p),''] % Breakdown: ~rem(i,1:i) % Return true if the remainder of i divided by any of the values % in the vector 1 - i nnz(~rem(i,1:i)) % Check how many of them are non-zero p(1:nnz(~rem(i,1:i)),i)=35;end % Assign the value 35 (ASCII for #) to rows 1 % to the number of divisors of i, in column i end, % End loop [flip(p),''] % Flip the matrix, and concatenate it with the empty string ``` --- A few things I wish to highlight * Takes the input directly into the loop + Doesn't assign the input value to any variable * Doesn't initialize any array + It creates it on the fly, adding columns and rows as necessary * Automatically casts ASCII-value 0 to whitespace (ASCII-32) --- What happens inside the loop (suppose input `6`) ``` p = 35 p = 35 35 0 35 p = 35 35 35 0 35 35 p = 35 35 35 35 0 35 35 35 0 0 0 35 p = 35 35 35 35 35 0 35 35 35 35 0 0 0 35 0 p = 35 35 35 35 35 35 0 35 35 35 35 35 0 0 0 35 0 35 0 0 0 0 0 35 ``` 1. Starts of as a single 35 2. Expands one column and one row, to make room for the two divisors of 2 3. Expands one column, to make room for 3 (only two divisors) 4. Expands one column and one row, to make room for the 3 divisors (`1,2,4`) 5. Expands one column, to make room for 5 6. Expands one column and one row, to make room for the 4 divisors (`1,2,3,6`) Finally we flip it, and converts it to a string, implicitly changing the `0` to `32`: ``` warning: implicit conversion from numeric to char ans = # # # ##### ###### ``` [Answer] ## Mathematica, ~~59~~ 57 bytes ``` Rotate[Grid@Map[X~Table~#&,0~DivisorSigma~Range@#],Pi/2]& ``` [![enter image description here](https://i.stack.imgur.com/nOnj2.png)](https://i.stack.imgur.com/nOnj2.png) [Answer] # C#, 333 281 Bytes ``` using System.Linq;using C=System.Console;class P{static void Main(){var n=int.Parse(C.ReadLine());var v=new int[n];for(var k=2;k<=n;k++)for(var i=1;i<k;i++)if(k%i==0)v[k-1]++;for(var i=0;i<v.Length;i++)for(var u=v.Max()-v[i];u<v.Max();u++){C.SetCursorPosition(i,u);C.Write("#");}}} ``` With line breaks: ``` using System.Linq; using C = System.Console; class P { static void Main() { var n = int.Parse(C.ReadLine()); var v = new int[n]; for (var k = 2; k <= n; k++) for (var i = 1; i < k; i++) if (k % i == 0) v[k - 1]++; for (var i = 0; i < v.Length; i++) for (var u = v.Max() - v[i]; u < v.Max(); u++) { C.SetCursorPosition(i, u); C.Write("#"); } } } ``` While I'm sure this is possible shorter as well, I hope we'll achieve a shorter solution together ;) *Saved 52 Bytes with the help of raznagul* [Answer] ## Mathematica, 99 bytes ``` {T=DivisorSigma[0,Range@#];Row[Column/@Table[Join[Table[,Max[T]-T[[i]]],$~Table~T[[i]]],{i,1,#}]]}& ``` for N=50 [![enter image description here](https://i.stack.imgur.com/IAd8z.jpg)](https://i.stack.imgur.com/IAd8z.jpg) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 19 bytes ``` ⊖⍉↑'#'⍴¨⍨+⌿0=∘.|⍨⍳⎕ ``` [Try it online!](https://tio.run/nexus/apl-dyalog#e9TR7pJZllmcXxScXZmTmZf6/1HXtEe9nY/aJqorqz/q3XJoxaPeFdqPevYb2D7qmKFXA@Q96t38qG/q/0cd7f9R9XIZGnChiZhiiBgZGAAA "APL (Dyalog Unicode) – TIO Nexus") `⎕` get evaluated input (*N*) `⍳` 1...*N* `∘.|⍨` division remainder table with 1...*N* both as vertical and as horizontal axis `0=` where equal to zero (i.e. it divides) `+⌿` sum the columns (i.e. gives count of divisors for each number) `'#'⍴¨⍨` use each number to reshape the hash character (gives list of strings) `↑` mix (list of strings into table of rows) `⍉` transpose `⊖` flip upside down [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~23~~ ~~22~~ 20 bytes ``` F…·¹N«Jι⁰Fι¿¬﹪ι⁺κ¹↑# ``` [Try it online!](https://tio.run/##RYxBCsIwFET3nuJTNz@QQrtwoyeo0FJEDxBjqsE0CWnSjXj2b5qNbzUMM0@@RJBOGKLJBcDOSpMWvaqLsE@FLYfO@hSHNN9VQMYYfHaQOafZXx1qDg07labcNSt5Q0@Ag4vYu0cyZTlmM745tFnz322MQduIx5vnUO2rLPwSHRqqV6oX8wM "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 1 byte by looping `k` from `0` to `i-1` and adding `1` inside the loop. Saved a further two bytes by not storing the input in a variable. Explanation: ``` F…·¹N for (i : InclusiveRange(1, InputNumber())) « { Jι⁰ JumpTo(i, 0); Fι for (k : Range(i)) ¿¬﹪ι⁺κ¹ if (!(i % (k + 1))) ↑# Print(:Up, "#"); } ``` Edit: This 18-byte "one-liner" (link is to verbose version of code) wouldn't have worked with the version of Charcoal at the time the question was submitted: [Try it online!](https://tio.run/##HYtBCsIwEAC/EuplF7agBy/6ggotRewDYgwaWDchbSq@fm28DcOMe9nsomXVMQdZ4DQlMr1N0InjMofVX608PRzIdJLKMpT33WdAJHOJQaCmgczNZ7H5C318FI7VjNtdL67ph0yza/6EiGfV417bVduZfw "Charcoal – Try It Online") ``` ↑E…·¹N⪫Eι⎇﹪ι⁺¹λω#ω ``` [Answer] # [Python 2](https://docs.python.org/2/), 101 bytes ``` N=input();r=range for i in r(N,0,-1):print''.join('# '[i>sum(x%-~p<1for p in r(x))]for x in r(1,1+N)) ``` [Try it online!](https://tio.run/nexus/python2#@@9nm5lXUFqioWldZFuUmJeeypWWX6SQqZCZp1Ck4adjoKNrqGlVUJSZV6KurpeVn5mnoa6soB6daVdcmqtRoapbV2BjCNJRANFRoakZC@JWQLiGOobafpqa//8bGgAA "Python 2 – TIO Nexus") This produces (a lot of) vertically leading whitespace. It prints a total of `N` lines, the great majority of which will [typically](https://en.wikipedia.org/wiki/Divisor_function#Growth_rate) be blank. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~34 33 16~~ 14 bytes *Saved 17 bytes thanks to @ETHproductions* ``` õ@'#pXâ l÷z w ``` [Try it online!](https://tio.run/nexus/japt#@394q4O6ckHE4UUKOYebD22vUij//9/QAAA "Japt – TIO Nexus") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 8 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ∫Λ⁄╗*}⁰H ``` [Try it here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMjJCJXUwMzlCJXUyMDQ0JXUyNTU3KiU3RCV1MjA3MEg_,inputs=NTA_,v=0.12) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes Code: ``` LÑ€g'#×.BøR» ``` Explanation: ``` L # Create the range 1 .. input Ñ # Get the list of divisors of each €g # Get the length of each element '# # Push a hash tag character × # String multiply .B # Squarify, make them all of equal length by adding spaces ø # Transpose R # Reverse the array » # Join by newlines ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@@9zeOKjpjXp6sqHp@s5Hd4RdGj3//@mBgA "05AB1E – TIO Nexus") [Answer] # R, ~~83~~ 82 bytes *-1 byte thanks to MickyT* ``` N=scan();m=matrix('#',N,N);for(i in 1:N)m[i,1:sum(i%%1:N>0)]=' ';write(m,'',N,,'') ``` Reads `N` from stdin. ``` N=scan() # read N m=matrix('#',N,N) # make an NxN matrix of '#' characters for(i in 1:N) # for each integer in the range m[i,1:sum(i%%1:N!=0)]=' ' # set the first n-d(n) columns of row i to ' ' write(m,'',N,,'') # print to console with appropriate formatting ``` [Try it online!](https://tio.run/##K/r/38@2ODkxT0PTOtc2N7GkKLNCQ11ZXcdPx0/TOi2/SCNTITNPwdDKTzM3OlPH0Kq4NFcjU1UVKGBnoBlrq66gbl1elFmSqpGrow7SBSQ1/5sa/AcA) [Answer] # PowerShell, 101 bytes ``` ((($d=1.."$args"|%{($x=$_)-(1..$_|?{$x%$_}).Count})|sort)[-1])..1|%{$l=$_;-join($d|%{' #'[$_-ge$l]})} ``` Less golfed test script: ``` $f = { $d=1.."$args"|%{ ($x=$_)-(1..$_|?{$x%$_}).Count } # $d is the Divisor count array $maxHeight=($d|sort)[-1] $maxHeight..1|%{ $l=$_ -join($d|%{' #'[$_-ge$l]}) } } @( ,(10, " # # #", " # # ###", " #########", "##########") ,(50, " # ", " # # ", " # # # # # # ", " # # # # # # ", " # # # # # # # # # # ## # #", " # # # # # # # # # # # ## # #", " # # # # ### # ### # ### # ##### ### # ### # #", " # # ### # ### # ### ##### # ##### ### # ### ###", " #################################################", "##################################################") ,(200, " # ", " # ", " # # # ", " # # # # ", " # # # # # ", " # # # # # ", " # # # # # # # # # # # # # # # # # # #", " # # # # # # # # # # # # # # # # # # #", " # # # # # # # # # # # # # # # # # # # # # # # #", " # # # # # # # # # # # # # # # # # # # # # # # # # # #", " # # # # # # # # # # # # # # # # # # # # ## # # # # # # # # # ## # # # # # # # # # # # # # # # # # # ## # ## # #", " # # # # # # # # # # # # # # # # # # # # # ## # # # # # # # # # ## # # # # # # # # # # # # # # # # # # ## # ## # #", " # # # # # # # # # # ## # # # # # # ## # # # # ## # # # # # # # ### # ## # # # # ## # # # # # # ## # # # ## # ### # # # ## # ### ### # # # # ### # ## # #", " # # # # # # # # # # # ## # # # # # # ## # # # # ## # ## # # # # # ### # ## # # # # ## # # # # # # ## # # # ## # ### # # # ## # ### ### # # # # ### # ## # #", " # # # # ### # ### # ### # ##### ### # ### # ### ##### # ##### ### # ##### ### ##### ####### ### # ### # ### ####### ##### ### ##### # ######### # ##### ##### ### # ### ##### # ######### # ### # #", " # # ### # ### # ### ##### # ##### ### # ### ##### ##### # ##### ### # ##### ### ##### ####### ### # ### # ### ############# ### ##### # ######### # ##### ##### ### ##### ##### # ######### # ### # #", " #######################################################################################################################################################################################################", "########################################################################################################################################################################################################") ) | % { $n,$expected = $_ $result = &$f $n "$result"-eq"$expected" #$result # uncomment this to enjoy the view of the Divisor skyline } ``` Output: ``` True True True ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~13~~ 11 bytes ``` ↔T' †K'#mḊḣ ``` [Try it online!](https://tio.run/##yygtzv7//1HblBB1hUcNC7zVlXMf7uh6uGPx////TQ0A "Husk – Try It Online") -2 bytes from Ko King(No, not JoKing). [Answer] ## [J](http://jsoftware.com/), 28 bytes ``` [:|:&.|.[('#',@$~1+_&q:)@-i. ``` Defines a monadic verb. [Try it online!](https://tio.run/nexus/j#@5@mYGulEG1VY6WmV6MXraGurK7joFJnqB2vVmil6aCbqfc/NTkjXyFNwdTgPwA "J – TIO Nexus") ## Explanation ``` [:|:&.|.[('#',@$~1+_&q:)@-i. Input is y. i. Range from 0 to y-1 [ - subtracted from y (gives range from y to 1). ( )@ For each of the numbers: _&q: Compute exponents in prime decomposition, 1+ add 1 to each, '#' $~ make char matrix of #s with those dimensions, ,@ and flatten into a string. The resulting 2D char matrix is padded with spaces. [:|:&.|. Reverse, transpose, reverse again. ``` [Answer] # PHP, 126 Bytes ``` for(;$n++<$argn;)for($c=$d=0;$d++<$n;)$n%$d?:$r[$n]=++$c;for($h=max($r);$h--;print" ")for($n=0;$n++<$argn;)echo$h<$r[$n]?:" "; ``` [Try it online!](https://tio.run/nexus/php#TcyxCsIwFEbhvU9Rwi@0hIIODvbmkgcpDiVRr4O3IXTw7WPTLq4fh@N8ktQ2mPNL@XK9UXkuuSOotW5H6isgMCKfCbH6htAToh@RJ@idrUWgvRP@zN8OuSfIMFDKb11NY46J1sPf@RFkgbhj4kfTGirlBw "PHP – TIO Nexus") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 34 bytes ``` ⟦fᵐlᵐgDh⌉⟦↔gᵐ;D↔z{z{>₁∧0ṫ|∧Ṣ}ᵐcẉ}ᵐ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9o/rK0h1sn5ABxukvGo55OoMCjtinpQL61C5BRVV1VbfeoqfFRx3KDhztX1wDphzsX1QKlkx/u6gTR//@bGgAA "Brachylog – TIO Nexus") [Answer] ## [Alice](https://github.com/m-ender/alice), 33 bytes ``` I.!.t&w?t!aot&wh.Bdt.?-ex' +o&;k@ ``` [Try it online!](https://tio.run/nexus/alice#@@@pp6hXolZuX6KYmA@kM/ScUkr07HVTK9QVtPPVrLMd/v9XAQA "Alice – TIO Nexus") Input is (unfortunately) [in the form of a code point](https://codegolf.meta.stackexchange.com/q/4708/8478). At least it reads a UTF-8 character, so you can use larger inputs than 255, but they're still limited and it's a pretty painful input format. For three additional bytes, we can read a decimal integer: ``` / ki@/.!.t&w?t!aot&wh.Bdt.?-ex' +o&; ``` [Try it online!](https://tio.run/nexus/alice#@6/PlZ3poK@nqFeiVm5fopiYD6Qz9JxSSvTsdVMr1BW089Ws//83NAAA "Alice – TIO Nexus") The non-whitespace character in the output is `!`. Note that the solution also prints a ton of leading whitespace (it always starts with an empty line and then prints an `NxN` grid so for larger `N`, there will be many lines of spaces before the first `!`s.) ### Explanation I've used and explained the `&w...k` construction before (for example [here](https://codegolf.stackexchange.com/a/116972/8478)). It's a neat little idiom that pops an integer **n** and then runs a piece of code **n+1** times (consequently, it's usually used as `t&w...k` to run a loop **n** times, with `t` decrementing the input value). This is done by working with the *return address stack* (RAS). `w` pushes the current IP address to the RAS, and if we repeat it with `&` then the address gets pushed **n** times. `k` pops one address from the RAS and jumps back there. If the RAS is empty, it does nothing at all and the loop is exited. You might notice that it's not trivially possible to nest these loops, because at the end of the inner loop, the stack isn't empty, so the `k` doesn't become a no-op. Instead, the IP would jump back to the beginning of the outer loop. The general way to fix this involves wrapping the inner loop in its own subroutine. But if we can arrange the nested loop such that the outer loop *ends* with the inner loop, we can actually make use of this behaviour and even save on one `k`! So this construction: ``` &wX&wYk ``` Is a working nested loop which runs the `XYYYXYYYXYYY...` (for some number of `Y`s in each iteration). It's pretty neat that we can end both loops with a single `k`, because it will consume an outer address from RAS each time the inner addresses have been depleted. This idiom is used in the program to run the loop over the output grid. ``` I Read a character and push its code point as input N. .! Store a copy on the tape. . Make another copy. t&w Run this outer loop N times. This loops over the lines of the output, so the current iteration corresponds to a divisor count no more than i (i counting down from N). ?t! Decrement the value on the tape. That means we'll actually have i-1 on the tape during the iteration. ao Print a linefeed. Doing this now leads to the weird leading linefeed, but it's necessary for the &w...&w...k pattern. t&w Remember that we still have a copy of N on the stack. We'll also ensure that this is the case after each loop iteration. So this also runs the inner loop N times. This iterates over the columns of the output grid so it's j that goes from 1 to N and corresponds to the number whose divisors we want to visualise. At this point the stack will always be empty. However, operating on an empty stack works with implicit zeros at the bottom of the stack. We'll use the top zero to keep track of j. h Increment j. .B Duplicate j and push all of its divisors. dt Push the stack depth minus 1, i.e. the divisor count of j. . Duplicate the divisor count. ?- Retrieve i-1 from the tape and subtract it. So we're computing d(j)-i+1. We want to output a non-whitespace character iff this value is positive (i.e. if i is no greater than d(j)). ex Extract the most significant bit of this value. This is 1 for all positive values and 0 for non-positive ones. It's the shortest way (I believe) to determine if a value is positive. ' + Add this to the code point of a space. This gives a 33, or '!', if the cell is part of the skyline. o Output the character. &; We still have all the divisors and the divisor count on the stack. We pop the divisor count to discard that many values (i.e. to get rid of the divisors again). k Return to the appropriate loop beginning to run the continue the nested loop. @ Terminate the program. ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 25 bytes ``` R♂÷♂l;M' *╗⌠'#*╜@+⌡M┬♂ΣRi ``` [Try it online!](https://tio.run/nexus/actually#@x/0aGbT4e1AIsfaV11B69HU6Y96FqgrAxlzHLQf9Sz0fTRlDVD23OKgzP//DQ0MAA) ## 22-byte version with a lot of leading newlines ``` ;╗R⌠÷l'#*╜' *@+⌡M┬♂ΣRi ``` [Try it online!](https://tio.run/nexus/actually#ASoA1f//O@KVl1LijKDDt2wnIyrilZwnICpAK@KMoU3ilKzimYLOo1Jp//8xMDA) [Answer] # SpecBAS - 149 bytes ``` 1 INPUT n: DIM h(n) 2 FOR i=1 TO n 3 FOR j=1 TO i 4 h(i)+=(i MOD j=0) 5 NEXT j 6 NEXT i 7 FOR i=1 TO n 8 FOR j=51-h(i) TO 50 9 ?AT j,i;"#" 10 NEXT j 11 NEXT i ``` An array keeps track of number of divisors, then prints the right number of characters down to screen position 50. [![enter image description here](https://i.stack.imgur.com/sNuLc.png)](https://i.stack.imgur.com/sNuLc.png) [Answer] # PHP, 99 bytes ``` for(;$d<$k?:$k++<$argn+$d=$n=0;)$k%++$d?:$r[--$n]=str_pad($r[$n],$k).H;ksort($r);echo join(" ",$r); ``` prints one leading space; run as pipe with `php -nr '<code>'` or [try it online](http://sandbox.onlinephpfunctions.com/code/a112e085d13e69ea94bdfc3a545d6fff9a6f2d81). **breakdown** ``` for(;$d<$k?: # inner: loop $d from 1 to $k $k++<$argn+$d=$n=0;) # outer: loop $k from 1 to $argn, reset $d and $n $k%++$d?: # if $d divides $k $r[--$n]=str_pad($r[$n],$k).H; # add one store to building $k ksort($r);echo join("\n",$r); # reverse and print resulting array ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~46~~ 44 bytes ``` Grid[PadLeft[0Divisors@Range@#-" "]+" "]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78r/HfvSgzJTogMcUnNa0k2sAlsyyzOL@o2CEoMS891UFZV0lBKfZ9f7s2iFb776BgbKr5/79uQVFmXgkA "Wolfram Language (Mathematica) – Try It Online") But maybe [try it online! with ColumnForm instead of Grid](https://tio.run/##y00syUjNTSzJTE78r/HfOT@nNDfPLb8oNzogMcUnNa0k2sAlsyyzOL@o2CEoMS891UFZV0lBKfZ9f7s2iFb776BgbKr5/79uQVFmXgkA "Wolfram Language (Mathematica) – Try It Online"), since `Grid` doesn't work in TIO. In Mathematica, it looks better: [![Mathematica output](https://i.stack.imgur.com/HE7hY.png)](https://i.stack.imgur.com/HE7hY.png) A third Mathematica solution... `Divisors@Range@#` finds all the divisors in the range we want, and then we multiply by `0` and subtract `" "`, making every divisor equal to `-" "`. `PadLeft` adds zeroes on the left, creating a sideways skyline, whose orientation we fix with ``=`\[Transpose]`. Finally, adding `" "` to everything makes all entries either `0` or `" "`. As an alternative, the 59-byte `""<>Riffle[PadLeft["X"-" "+0Divisors@Range@#]+" ","\n"]&` produces string output. [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 58 bytes ``` D,g,@,FL1+ D,k,@~,J L,R€gd"#"€*$dbM€_32C€*z£+bUBcB]bR€kbUn ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ13HQcfNx1Cby0UnW8ehTseLy0cn6FHTmvQUJWUlIK2lkpLkC6TjjY2cQdyqQ4u1k0Kdkp1ik0DKspNC8/7nWRkacHGp5CTmJqUkKhjaAXn@XB55yEKmmEKGBkCx//9NDQA "Add++ – Try It Online") ## How it works Our program consists of two helpers functions, `g` and `k`, and the main lambda function. `g` iterates over each integer, \$x\$, between \$1\$ and \$n\$ and returns \$d(x)\$ as defined in the challenge body, while `k` takes a list of characters and concatenates them into a single string. The main lambda function generates \$A = [d(1), d(2), d(3), ..., d(n)]\$, then repeats the `#` character for each element of \$A\$. We then take \$\max(A)\$, and subtract each element in \$A\$ from this maximum, before yielding this number of spaces for each element and concatenating the spaces to the repeated hashes. Next, we transpose and reverse the rows, before joining each line on newlines. Finally, we output the skyline. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LÑ_ζRJ» ``` Uses `0` (or `1`) instead of `#`. [Try it online.](https://tio.run/##yy9OTMpM/f/f5/DE@HPbgrwO7f7/39QAAA) **Explanation:** ``` L # Push a list in the range [1, (implicit) input] Ñ # Convert each value to a list of its divisors _ # Convert each inner integer to 0 ζ # Zip/transpose; swapping rows/columns, with space as default filler R # Reverse the list of lists J # Join each inner list together » # And then join the list of strings by newlines # (after which the result is output implicitly) ``` The `_` (==0) has some a few alternatives to get distinct values: `a` (is\_alphabetic); `Ā` (!=0); `d` (>=0): [try it online](https://tio.run/##yy9OTMpM/f9fySk1Lb8o1UpByd7n8ERbLiXHtJLUIoWE@ASQkEu8DlwkESKSiBA50gAROtKAEEsBC6Xo/P9vaAAA). [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), `L`, ~~6~~ 5 bytes ``` ƛKL×* ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=L&code=%C6%9BKL%5C%23*&inputs=10&header=&footer=) ## Explained ``` ƛKL×* ƛ # Over the range [1, input] do the following: KL # Push the length of the list of that number's divisors × # Push '*' * # And multiply the two together, repeating the "*" # Automatically close the map and then use the L flag to vertically join that list ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 16 bytes ``` j_.tm*\#/%LdSQ0S ``` [Try it online!](http://pyth.herokuapp.com/?code=j_.tm%2a%5C%23%2F%25LdSQ0S&input=50&debug=0) ]
[Question] [ Consider a piece of string (as in "rope", not as in "a bunch of characters"), which is folded back and forth on the real line. We can describe the shape of the string with a list of points it passes through (in order). For simplicity, we'll assume all of those points are integers. Take as an example `[-1, 3, 1, -2, 5, 2, 3, 4]` (note that not each entry implies a fold): ![enter image description here](https://i.stack.imgur.com/tLyo8.png) The string extending along the vertical direction is only for visualisation purposes. Imagine the string all flattened onto the real line. Now here is the question: what is the greatest number of pieces this string can be cut into with a single cut (which would have to be vertical in the above picture). In this case, the answer is *6* with a cut anywhere between `2` and `3`: ![enter image description here](https://i.stack.imgur.com/n640M.png) To avoid ambiguities, the cut *has* to be performed at a non-integer position. ## The Challenge Given a list of integer positions a string is folded through, you're to determine the greatest number of pieces the string can be cut into with a single cut at a non-integer position. You may write a full program or a function. You may take input via STDIN, command-line argument, prompt or function parameter. You may write output to STDOUT, display it in a dialog box or return it from the function. You may assume that the list is in any convenient list or string format. The list will contain at least **2** and no more than **100** entries. The entries will be integers, each in the range **-231 ≤ pi < 231**. You may assume that no two consecutive entries are identical. Your code must process any such input (including the test cases below) in less than 10 seconds on a reasonable desktop PC. ## Test Cases All test cases are simply input followed by output. ``` [0, 1] 2 [2147483647, -2147483648] 2 [0, 1, -1] 3 [1, 0, -1] 2 [-1, 3, 1, -2, 5, 2, 3, 4] 6 [-1122432493, -1297520062, 1893305528, 1165360246, -1888929223, 385040723, -80352673, 1372936505, 2115121074, -1856246962, 1501350808, -183583125, 2134014610, 720827868, -1915801069, -829434432, 444418495, -207928085, -764106377, -180766255, 429579526, -1887092002, -1139248992, -1967220622, -541417291, -1617463896, 517511661, -1781260846, -804604982, 834431625, 1800360467, 603678316, 557395424, -763031007, -1336769888, -1871888929, 1594598244, 1789292665, 962604079, -1185224024, 199953143, -1078097556, 1286821852, -1441858782, -1050367058, 956106641, -1792710927, -417329507, 1298074488, -2081642949, -1142130252, 2069006433, -889029611, 2083629927, 1621142867, -1340561463, 676558478, 78265900, -1317128172, 1763225513, 1783160195, 483383997, -1548533202, 2122113423, -1197641704, 319428736, -116274800, -888049925, -798148170, 1768740405, 473572890, -1931167061, -298056529, 1602950715, -412370479, -2044658831, -1165885212, -865307089, -969908936, 203868919, 278855174, -729662598, -1950547957, 679003141, 1423171080, 1870799802, 1978532600, 107162612, -1482878754, -1512232885, 1595639326, 1848766908, -321446009, -1491438272, 1619109855, 351277170, 1034981600, 421097157, 1072577364, -538901064] 53 [-2142140080, -2066313811, -2015945568, -2013211927, -1988504811, -1884073403, -1860777718, -1852780618, -1829202121, -1754543670, -1589422902, -1557970039, -1507704627, -1410033893, -1313864752, -1191655050, -1183729403, -1155076106, -1150685547, -1148162179, -1143013543, -1012615847, -914543424, -898063429, -831941836, -808337369, -807593292, -775755312, -682786953, -679343381, -657346098, -616936747, -545017823, -522339238, -501194053, -473081322, -376141541, -350526016, -344380659, -341195356, -303406389, -285611307, -282860017, -156809093, -127312384, -24161190, -420036, 50190256, 74000721, 84358785, 102958758, 124538981, 131053395, 280688418, 281444103, 303002802, 309255004, 360083648, 400920491, 429956579, 478710051, 500159683, 518335017, 559645553, 560041153, 638459051, 640161676, 643850364, 671996492, 733068514, 743285502, 1027514169, 1142193844, 1145750868, 1187862077, 1219366484, 1347996225, 1357239296, 1384342636, 1387532909, 1408330157, 1490584236, 1496234950, 1515355210, 1567464831, 1790076258, 1829519996, 1889752281, 1903484827, 1904323014, 1912488777, 1939200260, 2061174784, 2074677533, 2080731335, 2111876929, 2115658011, 2118089950, 2127342676, 2145430585] 2 ``` [Answer] # APL, ~~16~~ 14 bytes ``` 1+⌈/+/2≠/∘.≤⍨⎕ ``` Thanks to @ngn for saving 2 bytes. The `⎕` is actually a box character, not a missing-font error. You can try the program at [tryapl.org](http://tryapl.org/), but since `⎕` is not fully supported there, you have to replace it by the input value: ``` 1+⌈/+/2≠/∘.≤⍨ ¯1 3 1 ¯2 5 2 3 4 6 ``` ### Explanation The program is best explained with the example input `s = ¯1 3 1 ¯2 5 2 3 4`, which is taken from STDIN by `⎕`. First, we compute the `≤`-outer product of `s` with itself using `∘.≤⍨`. This results in a Boolean matrix whose `i`th row tells which elements of `s` are less than or equal to `s[i]`: ``` 1 1 1 0 1 1 1 1 0 1 0 0 1 0 1 1 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 1 0 0 0 0 1 0 0 1 1 1 1 0 1 0 0 1 0 1 1 0 0 0 0 1 0 0 1 ``` The occurrences of `0 1` and `1 0` on row `i` mark places where the string passes over the point `s[i] + 0.5`. We match on these on every row using `2≠/`, "reduce 2-sublists by `≠`": ``` 0 0 1 1 0 0 0 1 1 0 1 1 1 0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 1 0 1 0 0 0 1 1 0 1 1 1 0 0 0 0 1 1 0 1 ``` What remains is to take the sums of the rows with `+/` ``` 2 5 3 0 2 3 5 3 ``` and one plus the maximum of these with `1+⌈/`: ``` 6 ``` The result is automatically printed to STDOUT in most APL implementations. [Answer] # Python, ~~88~~ ~~75~~ 73 bytes ``` lambda x:max(sum((a+.5-m)*(a+.5-n)<0for m,n in zip(x,x[1:]))for a in x)+1 ``` Just a straightforward lambda --- Just to show another approach: # Pyth, ~~28~~ 27 bytes ``` heSmsmq@S+k(d)1dC,QtQm+b.5Q ``` This one's roughly equivalent to ``` lambda x:max(sum(a+.5==sorted(n+(a+.5,))[1]for n in zip(x,x[1:]))for a in x)+1 ``` applied to the input list from STDIN. Try it on the [online interpreter](https://pyth.herokuapp.com/). [Answer] # [Pyth](https://github.com/isaacg1/pyth): ~~31~~ ~~30~~ ~~29~~ ~~28~~ ~~24~~ 23 character (Python 68 chars) ``` heSmsm&<hSkdgeSkdC,tQQQ ``` Try it here: [Pyth Compiler/Executor](https://pyth.herokuapp.com/) It expects a list of integers as input `[-1, 3, 1, -2, 5, 2, 3, 4]` It's a straightforward translation of my Python program: ``` lambda s:1+max(sum(min(a)<i<=max(a)for a in zip(s,s[1:]))for i in s) ``` ## Old solution: Pyth 28 char Just for archiving reasons. ``` heSmsm<*-dhk-dek0C,tQQm+b.5Q ``` A corresponding Python code would be: ``` f=lambda x:1+max(sum((i-a)*(i-b)<0for a,b in zip(x,x[1:]))for i in [j+.5 for j in x]) ``` [Answer] # CJam, ~~36 34 33~~ 30 bytes ``` q~[__(+]zW<f{f{1$+$#1=}1b}$W=) ``` I believe that there is a better algorithm out there in the wild. Still, this works under the limit required for all test cases (even on the online compiler) Input is like ``` [-2142140080 -2066313811 -2015945568 -2013211927 -1988504811 -1884073403 -1860777718 -1852780618 -1829202121 -1754543670 -1589422902 -1557970039 -1507704627 -1410033893 -1313864752 -1191655050 -1183729403 -1155076106 -1150685547 -1148162179 -1143013543 -1012615847 -914543424 -898063429 -831941836 -808337369 -807593292 -775755312 -682786953 -679343381 -657346098 -616936747 -545017823 -522339238 -501194053 -473081322 -376141541 -350526016 -344380659 -341195356 -303406389 -285611307 -282860017 -156809093 -127312384 -24161190 -420036 50190256 74000721 84358785 102958758 124538981 131053395 280688418 281444103 303002802 309255004 360083648 400920491 429956579 478710051 500159683 518335017 559645553 560041153 638459051 640161676 643850364 671996492 733068514 743285502 1027514169 1142193844 1145750868 1187862077 1219366484 1347996225 1357239296 1384342636 1387532909 1408330157 1490584236 1496234950 1515355210 1567464831 1790076258 1829519996 1889752281 1903484827 1904323014 1912488777 1939200260 2061174784 2074677533 2080731335 2111876929 2115658011 2118089950 2127342676 2145430585] ``` Output (for above case) is ``` 2 ``` **How it works** ``` q~[__(+]zW<f{f{1$+$#1=}1b}$W=) q~ "Evaluate input string as array"; [__ "Put two copies of it in an array"; (+] "Shift first element of second copy to its end"; z "Zip together the two arrays. This creates"; "pair of adjacent elements of the input."; W< "Remove the last pair"; f{ } "For each element of input array, take the zipped"; "array and run the code block"; f{ } "For each element of the zipped array along with"; "the current element from input array, run this block"; 1$+ "Copy the current number and add it to the pair"; $# "Sort the pair and find index of current number";; 1= "check if index == 1 for a < I <= b check"; 1b "Get how many pairs have this number inside of them"; $W=) "Get the maximum parts the rope can be cut into"; ``` Now suppose the input array is `[-1 3 1 -2 5 2 3 4]`, the zipping steps look like: ``` [-1 3 1 -2 5 2 3 4] [[-1 3 1 -2 5 2 3 4] [-1 3 1 -2 5 2 3 4] [-1 3 1 -2 5 2 3 4] [[-1 3 1 -2 5 2 3 4] [3 1 -2 5 2 3 4 -1] [-1 3 1 -2 5 2 3 4] [[-1 3] [3 1] [1 -2] [-2 5] [5 2] [2 3] [3 4]]] ``` The second array on the last line is the folds of the string. Now we iterate over `[-1 3 1 -2 5 2 3 4]` and calculate the number of sets each of them lie in. Get the maximum out of that number, increment it and we have our answer. [Try it online here](http://cjam.aditsu.net/) [Answer] # Matlab (123)(97)(85) Yay, finally a use for *XNOR*=) I am sure it can be golfed down way more. But honestly I am a little embarassed that MatLab is becoming the language I know best =/ Approximate runtime is `O(n^2)`. **EDIT2:** ``` a=input();v=2:nnz(a);disp(max(arrayfun(@(e)sum(~xor(a(v-1)<e,e<a(v))),sort(a)-.5))+1) ``` **EDIT:** New more golfed version (including hints from @DennisJaheruddin, thanks!) ``` a=input();c=sort(a)-.5;n=0;v=2:nnz(c);for e=c;n=[n,sum(~xor(a(v-1)<e,e<a(v)))];end;disp(max(n)+1) ``` Old version: ``` a=input(); c=conv(sort(a),[.5,.5],'valid');' %find all cutting positions by taking the mean of two successive points k=numel(c); for e=1:k %iterate over all 'cuts' n(e)=sum(~xor(a(1:k)<c(e),c(e)<a(2:k+1)));%find the number of threads the cut cuts end disp(max(n)+1) %output the max ``` @MartinBüttner: I really enjoy your nice little just-before-I-go-to-bed-challenges! [Answer] # Mathematica ~~134 133~~ 104 Fun to solve, despite the size of the code. Further golfing can still be achieved by replacing the idea of `IntervalMemberQ[Interval[a,b],n]` with `a<n<b`. ``` n_~f~i_:=Count[IntervalMemberQ[#,n]&/@i,1>0]; g@l_:=Max[f[#,Interval/@Partition[l,2,1]]&/@(Union@l+.5)]+1 ``` --- ``` g[{-1, 3, 1, -2, 5, 2, 3, 4}] ``` > > 6 > > > --- ## Explanation `list1` is the given list of points `list2` is a shortened list that removes numbers that were not at folds; they are irrelevant. It's not necessary to do this, but it leads to a clearer and more efficient solution. ``` list1 = {-1, 3, 1, -2, 5, 2, 3, 4}; list2 = {-1, 3, 1, -2, 5,2, 3, 4} //. {beg___, a_, b_, c_, end___} /; (a <= b <= c) \[Or] (a >= b >= c) :> {beg, a, c, end} ``` The intervals in `list1` and `list2` are shown in the plots below: ``` NumberLinePlot[Interval /@ Partition[list1, 2, 1]] NumberLinePlot[intervalsArrangedVertically = Interval /@ Partition[list2, 2, 1]] ``` ![intervals](https://i.stack.imgur.com/65e42.png) --- We only need to test a single line in each interval determined by the fold points. The test lines are the dashed vertical lines in the plot. ``` delimitersLeftToRight = Union[list2] testLines = delimitersLeftToRight + .5 NumberLinePlot[ intervalsArrangedVertically = Interval /@ Partition[list2, 2, 1], GridLines -> {testLines, {}}, GridLinesStyle -> Directive[Gray, Dashed]] ``` ![test lines](https://i.stack.imgur.com/3Fj60.png) --- `f` finds the number of cuts or crossings of each test line. The line at x= 2.5 makes 5 crossings. That leaves 5 + 1 pieces of string. ``` f[num_, ints_] := Count[IntervalMemberQ[#, num] & /@ ints, True] f[#, intervalsArrangedVertically] & /@ testLines Max[%] + 1 ``` > > {2, 3, 5, 3, 2, 0} > > 6 > > > [Answer] # Pyth, 21 bytes ``` heSmsmq1xS+dSkdC,tQQQ ``` [Try it here.](https://pyth.herokuapp.com/) Give input as Python-style list, e.g. `[-1, 3, 1, -2, 5, 2, 3, 4]` Closely based off of @jakube's program, but with an improved central algorithm. Instead of doing a `>` check and a `>=` check, I do a `.index()` on the three numbers combined and make sure the index is 1, meaning it's greater than minimum and less than or equal to the maximum. [Answer] ## R, ~~86~~ 83 Was working through this and then realised that I had essentially come up with the same solution as Optimizer and others I suspect. Anyway here it is as a function that takes a vector ``` f=function(l)max(colSums(mapply(function(n)c(l[-1],NA,l)<=n&c(l,l[-1],NA)>=n,l),T)) ``` [Answer] ## GolfScript (43 bytes) ``` ~[.(;]zip);{$}%:x{0=:y;x{{y>}%2,=},,}%$-1=) ``` In terms of efficiency, this is O(n^2) assuming that comparisons take O(1) time. It breaks the input into line segments and for each starting point it counts the half-open line segments which cross it. [Online demo](http://golfscript.apphb.com/?c=OydbLTEgMyAxIC0yIDUgMiAzIDRdJwoKCn5bLig7XXppcCk7eyR9JTp4ezA9Onk7eHt7eT59JTIsPX0sLH0lJC0xPSk%3D) [Answer] # Python - 161 This can probably be golfed more. gnibbler helped golf this a lot. ``` l=input() d={} for i in zip(l,l[1:]):d[sum(i)/2.]=0 for i,k in zip(l,l[1:]): for j in[m for m in d.keys()if min(i,k)<m<max(i,k)]:d[j]+=1 print max(d.values())+1 ``` [Answer] # Ruby, 63 Similar to the Python solutions in concept. ``` ->a{a.map{|x|a.each_cons(2).count{|v|v.min<x&&x<=v.max}}.max+1} ``` Add 2 chars before the code e.g. `f=` if you want a named function. Thx to [MarkReed](https://codegolf.stackexchange.com/users/4133/mark-reed). [Answer] # C#, ~~73~~ 65 bytes ``` N=>1+N.Max(i=>N.Zip(N.Skip(1),(f,s)=>f<i+.5==i+.5<s).Count(b=>b)) ``` Reading the rules I thought a C# lambda should do pretty well. Edit: just found `Count` has a useful overload for filtering! You can test this by defining the appropriate `delegate` type: ``` delegate int solver(int[] l); ``` And then ``` var l = new int[] { -1, 3, 1, -2, 5, 2, 3, 4 }; solver s = N=>1+N.Max(i=>N.Zip(N.Skip(1),(f,s)=>f<i+.5==i+.5<s).Count(b=>b)); Console.WriteLine(s(l)); ``` [Answer] # Matlab (63 43) Input is given as a row vector passed to the function `f`. So for example `f([-1, 3, 1, -2, 5, 2, 3, 4])` returns `6`. ``` f=@(x)max(sum(diff(bsxfun(@le,2*x',x(1:end-1)+x(2:end)))~=0))+1 ``` Shorter version: ``` f=@(x)max(sum(diff(bsxfun(@lt,x',x))~=0))+1 ``` # Octave (31) In Octave `bsxfun` can be removed thanks to automatic broadcasting: ``` f=@(x)max(sum(diff(x'<x)~=0))+1 ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 17 bytes ``` {|/+/'~~':'x>/:x} ``` [Try it online!](https://tio.run/##PZY7jh5HDIRznWIyBdZCfDTZzRXgiwhK5cCAIgUGbOvq669aghcbEDM9TbJYVfz/fPn2x7e3t6@vf//z8beP73/8eP/6/q/fP77@9e/b18/2@Jd3Xz@Hr71O9trPy//x0RsOPC/3jD/2K3rxJ/U4nnqCcH159@67v764R6yMNcnBmF1h1vH4mUyrivO4d2VbrObEOWdiIvLJU7ZsE70cy4re3J87JruMHO7l4baXvqrm89G9ZZ5lx44eZ5300OFc5qvdnh12Yp/W@/E65tZDipiVi0KfxZ@fNUUvtie4inD34mDurWttd0fVs2JqD6XdwrcNvQWx58Q6M4qndwQdE9fy5TQg8Nr36jzTT/kuIGg93cej7QiJY6ttzYnnqC4nIaCZgdTq/TTBpjm@r51TK5aKTEs3U5HJ@x7gVG37F67AM6u4dK2HZEK6ux6Aa2E9qv0UA2Maj89MpS8NzvYxZlf9eIBd6BSPhVSdfRRbqSSr80wBdAOYOprYDjCURO8JYFQHD8BwLRXHOLwBct3ki0lZcDeQDURZqfGfsZh25ykcjNF1AKLjp2@zy8gJoA9NV521z0NVXdyh174pG@hpujMYnecn2Pnh1S@G5kwbeufJGd1X61RmMMyAvsxziYbuIxpsW0/6kHunJk8laEOJAJmRTYgvc3yR0pTy7AW8pNhZO@hGvEg@3KaxC43q0niQgRDyElyRpNJQwtbqOpR60xEVdZEP4di2w5HpGQIKCksmND4PND@0KoXAOlF2LuuRD9cWJNrgw4T9AUmBhG4g2YYJlARas8EBbvCUomCJ36kfWj@7pDw0GBnkEbWqczjOFesgkZEIE@uAyabxroFNqI@bG/HZUN6TXLH3RcoSwrvSwQP45tRI4qgN0mQrBCO9rk8YzneXw8SrvIl/U@0g1Z2exwWrXbZXX5Y5hfjloaMKrOWeQRfwHvpovKdt8@dXMgV6TOfGyMQA/PK5Vi3xXL0fSBBzJY8KZwOm2mSADK5vLlzD4NV1PxWGm17l0D5ERTNXcrK1nzVwEe5Cjze2BiH5r4tMMP6nRFfK5H4KE8NwER4KuEq7RnAYXxPK2ERVMlxLgeIgqae2i1HJofYuhJ2abF9nRPSEexLxHXpuDIYJijvtDcW2soGDoR7pAsNIHC85wDPSmW6A7Eg7ZXxJRwtRcRnejF8avvUiW6PMGoV8Vll6CglMzsjQsHW0JzsLKAcv/Iqz8SL7uU82deeh41hQyqWsFTLJh0qYDDeiPRyR4Z2V8iqYKpHBX1ZPLHGKLhkOVWOkD4bfsILJYxnaBcyFonB2SSLxMkYkC6CeuxEfEkAQyK2FgAigAu4SH16xITRl5VQjMvZJ7J4hCDqMexp6glVxFQgQ0Tj@rC@ahQXcu4m0CiWA3nhyL6a2WZ5wwxftIT8qCrXFJgEHfESSGO5aCpmvaeFBNMbLUpMD8xqLBjrMDbmzoABG9sQk2UpQVVzqvOHGBYAcmxCF7OpyUebBNlphB9KFzPgBY8SdFEIUMmBaLp/Z@A81IKbSZpFLHP0cCKE/TB3TkK@P0RE5tICYD3tV9U7e5dqmzeB42qZ0WmEXUlxqM6Bjtt79ZUCjrXWnHwmtHe8K4f@oyBBv6A1s42qGRupaSnx5@w8 "K (ngn/k) – Try It Online") Modeled after [Zgarb's APL answer](https://codegolf.stackexchange.com/a/44562/98547). * `x>/:x` build matrix storing whether or not each value of x is larger than each other value of x * `~~':'` for each "row", determine where the values change (i.e. `differ each`) * `+/'` take the sum of each row * `|/` take/return the maximum sum [Answer] # JavaScript (ES6) 80 ~~82~~ See comments - byte count does not include assign to F (that's still needed to test) ``` F=l=>Math.max(...l.map(v=>l.map(t=>(n+=t>u?v<t&v>=u:v>=t&v<u,u=t),n=1,u=l[0])&&n)) ``` **Test** In FireFox/FireBug console ``` ;[ F([0, 1]) ,F([2147483647, -2147483648]) ,F([0, 1, -1]) ,F([1, 0, -1]) ,F([-1, 3, 1, -2, 5, 2, 3, 4]) ,F([-1122432493, -1297520062, 1893305528, 1165360246, -1888929223, 385040723, -80352673, 1372936505, 2115121074, -1856246962, 1501350808, -183583125, 2134014610, 720827868, -1915801069, -829434432, 444418495, -207928085, -764106377, -180766255, 429579526, -1887092002, -1139248992, -1967220622, -541417291, -1617463896, 517511661, -1781260846, -804604982, 834431625, 1800360467, 603678316, 557395424, -763031007, -1336769888, -1871888929, 1594598244, 1789292665, 962604079, -1185224024, 199953143, -1078097556, 1286821852, -1441858782, -1050367058, 956106641, -1792710927, -417329507, 1298074488, -2081642949, -1142130252, 2069006433, -889029611, 2083629927, 1621142867, -1340561463, 676558478, 78265900, -1317128172, 1763225513, 1783160195, 483383997, -1548533202, 2122113423, -1197641704, 319428736, -116274800, -888049925, -798148170, 1768740405, 473572890, -1931167061, -298056529, 1602950715, -412370479, -2044658831, -1165885212, -865307089, -969908936, 203868919, 278855174, -729662598, -1950547957, 679003141, 1423171080, 1870799802, 1978532600, 107162612, -1482878754, -1512232885, 1595639326, 1848766908, -321446009, -1491438272, 1619109855, 351277170, 1034981600, 421097157, 1072577364, -538901064]) ,F([-2142140080, -2066313811, -2015945568, -2013211927, -1988504811, -1884073403, -1860777718, -1852780618, -1829202121, -1754543670, -1589422902, -1557970039, -1507704627, -1410033893, -1313864752, -1191655050, -1183729403, -1155076106, -1150685547, -1148162179, -1143013543, -1012615847, -914543424, -898063429, -831941836, -808337369, -807593292, -775755312, -682786953, -679343381, -657346098, -616936747, -545017823, -522339238, -501194053, -473081322, -376141541, -350526016, -344380659, -341195356, -303406389, -285611307, -282860017, -156809093, -127312384, -24161190, -420036, 50190256, 74000721, 84358785, 102958758, 124538981, 131053395, 280688418, 281444103, 303002802, 309255004, 360083648, 400920491, 429956579, 478710051, 500159683, 518335017, 559645553, 560041153, 638459051, 640161676, 643850364, 671996492, 733068514, 743285502, 1027514169, 1142193844, 1145750868, 1187862077, 1219366484, 1347996225, 1357239296, 1384342636, 1387532909, 1408330157, 1490584236, 1496234950, 1515355210, 1567464831, 1790076258, 1829519996, 1889752281, 1903484827, 1904323014, 1912488777, 1939200260, 2061174784, 2074677533, 2080731335, 2111876929, 2115658011, 2118089950, 2127342676, 2145430585]) ] ``` *Output* > > [2, 2, 3, 2, 6, 53, 2] > > > [Answer] # [Python 2](https://docs.python.org/2/), 63 bytes ``` lambda x:max(sum(a-m^a-n<0for m,n in zip(x,x[1:]))for a in x)+1 ``` [Try it online!](https://tio.run/##PZbdbh1HDoTv9ynOpYSVALL5000jeRKvA2ixa0RApBiOjSj78t6PHCG6UU@fniZZrCrOl7@@/fr76/rx@ed//fjt6eXf/3m6vX14eXq7@@P7y93T48svT4@vP8nn37/eXh5eb8@vt/89f7l7e3j7qB8@3d/3/lPvvt3/U3/8@evzb/@96YcvX59fv90@3z2/fvn@7e7@/sdHebjpp398XOrbj6Xvh9vj3w@HX/oAe32I//K@fGRt1y/r4RYPtzXPPj/pWm7Ly/rwqh1LJDmgp8wkYh3WmmEpy7MPnXNq1Vq8YSfEZffy8YjFyt2BbK@yDOlQqqFLZfu8GsklNfeHqIUcOfODxTFd84K5qKeS/V5y1j7JEc6UxhGVrA62ys1JnDL40@MVXZ7sWlzZ653OYdt77peduYJ9XxW7yHTuPGdLUfHqQ2q1/FTNQ@VeCyT6IVxdqWmwTd2edooLQneATc7@PrpSjs/FRzzF6/D26Tw1uzbSEHD0JKdktam5r4ltFb58sjYxFZmsjSNZ4H3lut@hb/DKg9udVwjc7cgkAMhmN6SmnBP0Vvparaow9Wmy7CP0OYisC3BXH@wfGsc4@8yDRCcoQewKupHAOWXW2gpmnSCgGHB2slAHjN2vXOmbJkj7lYjTVFkdBEQLfrkNY07JqlTtfSi8aq4Fq37l5IWBC@FBnHtBI@L4JgZZZnDVHNFNITSowUhb9FltgAFe0WYGCrFjVXNl@Amz1U2Hboto5kNh1WrWbAEy0yKHbUN5UkJkE40W0NhaQ7E66gSWCXy2gz37N98We1HdEMl4fcuQpEGKjGkhemroNAbIZUSdvi1xzzjkfkVmGWQ5rEKGsuX0scoqVp3fEqONpWyjlkP1ozYI25yvERihgvujmbfBDTJw/w2cGz1k2OzcMIcMG8faYASZep8k4ZVeHDmAcnaMnFH2snVabjAy0spGV8jxoLcabRsOhRhkqOAFCdF0h0gULXValMZNe19AiqEbncjwBqZqJ91ZrNj0oyMH@msrGAtbzS@XqQH0Mk3t6MAtI5RoA@kHUtGLuYqqsK7rGLJCMxBtOHBSNn/6LroAUpp3uRQ6E3pxCSE8vCUySBzYsuryEfRcG4inYlpMZ/OKiiMJRGyzHd7SN9@X@AADcqO6S7ptoe8JcR/uRbXXgySQjfVrkw@xvMvdrR3Vr7sFM9LWSlNFO9PLXw79TdZjos1xQuW4NwoB3dmXHXRyfHDvwCpsmp9jxhhJr3cZKj4NReJfdHiIlppwck9cABJEONLCigx7tT7DLoElJlO0glnY@KxRpiPPvpTZgElL@@NjOyhpR82al8Ni9uGKtBd3e5ktCHmMc0FSCKSX2hO7k/f5tqnETgOxHALqSNRX2zI@jFdgU6xQMhbcfT5ubYkxDESwUL8H4vKmYFdPF6nE2mSYPAmVmivYUY@lbiBJMl9GVYZv0syxF/Kbqd12IT2DvMcLjUFH0R3F5hCmhHZiTeQ81iOHPsWUFmxB7oYxuA1cegkcjIZ57ZZMUhqyqQjLPe3o3vpnHKR3ezcjHjqpd8komeRambKYa@DTNtXiKu70WUMGueYxHIUMDNwxf44wIBpYvBQTYW62KbQN0vWelXC9OZh2rTfuUu0JKJeK5F3kTuYHT@pDzi14QSsCp6Hl2OCsoRex2h@1rWxjct0T1Bk96PpdRgu6Wmc8rqAJjjSzpYQ6CTdDkTbyATAVlM1nQMrMKMVBd1dDfUxrkrWZUbgEQ/n6rKH@nGHcnzjZnyY6a5RUk/RqulFxw79GgtQWn/4P "Python 2 – Try It Online") I'm back 6 years in the future to golf the Python answers by [Sp3000](https://codegolf.stackexchange.com/a/44545/20260) and [Jakube](https://codegolf.stackexchange.com/a/44547/20260)! The improvement is shorten the core expression of `(a+.5-m)*(a+.5-n)<0` or `min(t)<a<=max(t)` with `t` for `m,n` to: ``` a-m^a-n<0 ``` This is parsed as `(a-m)^(a-n)<0`. Due the how XOR acts on the Python's bit representations of negative numbers, two the XOR of two numbers is negative if and only if exactly one of them is negative. So, this expression is equivalent to `(a-m<0)^(a-n<0)` or `(a<m)^(a<n)`. This expresses that exactly one of `m,n` is smaller than `a` while the other one isn't, which is equivalent to `min(m,n)<a<=max(m,n)`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` >þ`^ƝS$€Ṁ‘ ``` [Try it online!](https://tio.run/##RZY9si1FDoR9VnEMzPsi9F8lh02MSTxinHEm2MB4BA5bGGd2wAZwcF4E@xg2cvmkvsCxqutUl6RUZqr//a/vv//P@/s3X37953e//e8fX//@48///@WH33/47/uXn1i/v3/71ev1rby99PPbrEzjxPWK8/b69NfDff6cY2x/HGUpfz994tGf/@3tlW8v2@f48181C7don1esT5pIcUZvu0umXdZa6SUWNYfuvW1txht@U0LOLD9d8bQ6E8uPtVfKRFNNNZUT@2oWl/Ten6KecuXuH57X1fYFD9EopYZjcu3c4ghnWvOKSvUEsw4PEqcSfnqjcyqU08aVsz4VHPZz9n45VZbsh3WeJtO9894jTcU2h9Tb4nbvQ9cxA4l5yNBQalqQS0@U3@aC1JNgU7t/rlrJjb34SpREX96@k6fW1EYaAo5R5FSsDjXPNXm8Myw2axdXkc3aOVIN3k@u5wP6Aa8juT14hcDTjioCgGxNQ3rLuUlvZa7V7k7X2CbLuUKfk8hqgGtzcP4YHPOeuw@Sk6AksTvpRgHnltl2FMwmQUBx4JxkoQ4YRzy50jctkI4nkaCpYhMERBt@hS9jbot1qc4@dLbea8FqXrn1YBBCeBDnXtDIvHGIQZaVXLVH9FAIDRowyo0@qy8wwCs6zEAtfr17r8y46W7TdOhmRPNYCqv2sOYIkLk2ORxfypMSgttotIDGti3F@moQWDbwPQH27L/ieB6juiWS8/qRJcmAlJXbQvQ00GkukOZE3b6ZRFRecn8is0yyXFYhQzly51hXN6vJz8RpYyvbqOVS/aoNwg7newVGqOT@HOYdcIMM3P8C50EPGQ47D8whw8GxDxhBptknSXilD0cuoNyTK2eUbW535AYjs7x9dYUcL3rr1bbjVohBlgrRkBBNT4hC0dJ3ROncdM4DpDi60Y0Mb2CqTtKTheWhHxM50d9YwZ8uZkOxkC0DAKtc/eoiLquVHA@ZB7LRh7yKsHCv5xjKQjZwbWlwSw4//dBdgir9e4wKqQnteLSQkTEqWTAuhLF@rARJ9wHlLZou09x6omJKAhfHb5e6tC7Ooz/wgN8I71HvuOhHQtyHgVHw8yAFajsJdPiHXj4UHz6mGs/dgh/pyGXYopPpYzGXFhfr9dGhOaFqDRyRAPDuy0mauVZ4TuIWvv2v9WO8ZNanHSHfgaKwMJq8XCstaHk2LgAJOlx14UaOw/qcYZfAkpspcsEvfK3WKTNQ6FzKeMCnZSzy05goaWfvmpfTc/ehi4wdT3sZL2h5vdPgKRzSR/CF48nHiDtU4neAsICDuioNG2fGirELnIoVYsaFp883fFwxl4RoFvbPTLQYFk71dJFKfHyG4VNQabiCI81kmgaSJCNmheVYJ81chyG/HeLjGDJjKGbC0BiklNNRnA5tSuokNkSu6zN16FNuackW5B4Yk9vAZZbAwXTY117FMKUhh4pw3TumHmMBTISKae9hykMnjSkZMZPciFOM0QY@41QjrubO2DVkkGckw1HIwMxd/@cIM2KAxU7xEUbn@MI4IV2fcQnXh4Plz/pgMD22gHKpSD50HmR@saU5FNyCHYwiMBtajhPuGnoRayxSx80OPjc9QZ05s27eZbqgK7trcw1NMKUdLy3USbidi7SRb4CtoH2/BEp2TCkmeqYa6mNgk6zvmMIlmMvPlw31187j@cqp@TrRXaOk3qRt6EbFA7@tBKktP3/1@Q8 "Jelly – Try It Online") ## How it works ``` >þ`^ƝS$€Ṁ‘ - Main link. 1 argument e.g. [1, 0, -1] >þ` - Greater than outer product [[0, 0, 0], [1, 0, 0], [1, 1, 0]] $€ - Over each sublist: e.g. [1, 1, 0] Ɲ - Over each overlapping pair e.g. [1, 0] ^ - Perform XOR 1 S - Take the sums [0, 1, 1] Ṁ - Take the maximum 1 ‘ - Increment 2 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` ε@Ôg}à ``` [Try it online!](https://tio.run/##LVS9jZxZDGtlCpgF9C8xcx@GAx9wOFzkwLG7cAFuwhU4d0trSuON3rxPj6Qoar98/fzP//@@v//@@eHX9/@@/frx/v7xTdUs3AL@fLypodNEyp4PHbhLpg3PWuklFrVFMwODGV/4pIT0Ht9GPK2aR/U2eKXk82GqqabScU@zCILDT1FPGZn74Dmudg88RKNUno82GesplrAGmiMqhSUzhAeFPx/BP50A376ZNIyQe@4KFnv34UtXWfI@DNmg0sOcaQE7ti1Sh8UA9wPVZnRif2RoKHvS/VDaUT4gQGonvam771ErmTjgkSgJDF/P6tTa3ihD6GMUNRVPzZ4XJtuRYXGqXVxFTrWzpEC/X1r7r/VrHiKJHnxC4h1HFQnobO1AcO1McraysAogXeOGLD3COSeZ1WiubeF@WB9zeu6H5AqUJDeS0yjaeW3CWunZCqQpTjtXLKNDjyNeWjk3LTodLyHBoYotCR0F8xV@iRmIoVT3frwMB0uv9snUy4MQ0tNx4tKNzIkmB1VWEupKtNkIB7RmlBvnrH7G0F7RTUaM@zhwkBmT7rZDZ9yMbB4XYVVsalpomSuoof0iT0kdc2wcAQcLu4hhNEgsRzwd9J73j2jPNnZ3QXI@b7mQrElZeSPkPq11mmekOVlvbiYRlUPtL2YekyovVVxDaZktQwE8rT4T5xihvOa2DLu/bWNgN/O4BSNVEj83eU3fGAbiP@jzusc13HQ2k0OF6yOaHjFMe0@RzJW@MjI0ZTpvnbnZ5ja7bkxklsNvr7iOw33D7bYbg0Wgi0KAIeROL0VxowWzS@lE6n4ZKc690WNmbphUXdGrwrI5j2VO7t/@K4hPfwA "05AB1E – Try It Online") Explanation: ``` ε } # for each element of the input @ # is each element >= this one? (returns list of booleans) Ô # connected uniquified g # length à # maximum ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 71 bytes ``` a=>Math.max(...a.map(t=>a.map(u=>s+=(a[i++]-t-.5)*(u-t-.5)<0,s=i=1)|s)) ``` [Try it online!](https://tio.run/##TZbNbl03DIT3eYq7tBvbIMUfSWhvltn1CQIvLtKgdZHGQe0UXfTd3Y88TlGvJFlHJIczw/v75a/L08c/H74@3355/OXTy/vzy@X87ufL8293f1z@vrq7u7uw@Hr1fH53LL6d3z29PV9dPjy8fXt/@3x7F9c/XH07Fj/JzdP54azX/zxdX7/8@PHxy9Pj5093nx9/vfrw5vT@6oPcnPT@@s0Ny6E@fVn6vDnd/rdZr/@ti5x/v8xa/re9ZW/HjXFzipvT6L3fX59Orxd0DLfh2@qzsWcMkeSarm0mEWOx1gxLGZ51aa21xx6DL2yFuMxa3i6xGDkrnM2xLUMqoGroUJnen0byyO73Q9RClqz@h8UyHf2BuainUsccssZc2Ve2xhKV3BVrbDcnb2rhT5fvqBpl7sGLtZ7pXLY5@3mZmSM497FjbhI9KpmyqXfURm0PX3v3ZuccAxxqE66uVNQ4p05PW5vvQ2eATPb5XDpSViO0xFN8Lz5elaVmFUYSAoieZJSsJgXXKzFthw/vnE1MRTpn40puwO5M5yvsBdz24HHnC8JWKzJ5H1SzmrG7mBX0VepV3XuHqXeDZS6hx0FgHQA76mL9o0CMNVdvJCo/CULvoBMJll3kHlNBrPIDEgPLyhXaALB7p0rLNEHZjzycfsqoGMC5oZZbk2VtGTtV6xw@j92vglR9svJAwIXowA1gMyOWTyKQYwYv9Q2dlEFzCoq0QYvVGhawFS1SoBZbtne/GL7CbFTDB8Sn597cVd3FlyngZbrJYFozhITQWwcDf5q6R5NrL3XiSsdd0wGe85NPizmorTlkfD6l@VEIRUb3DyEVbhqN4jCidtOGuGcsUj8iswyyrNDIT6asurVzb1aV3hCjhVs5RiWL2ltlULXIvg/VoEKejyLdBDWIwPMnQC7skF8Rc8IaEiwU9wQhiFTn5Ain9ODHApM1o2WMooeNVTqDjZG2rQSFDBc62y1pw6qQgTQNfMM/pFwREiXLXiVG46E5DxjFUIx2YDgDSbVyJocRk2ZU3EB35QD@3d1G0culqwC@TFNb2nhLyyTyoKSSjR68VSSFaR3XEBWKgWdNgpUy@dNDcQGmNO/YIDKhF4cKwsNLHw3Fgi1jHxaClvcE466ZFtPZPILiRQIPy2WbtjTO56E84IDbSO7QbXnnaz68h29R8LGRBLSeAlrkQyqvWncrK/XjbcGHtKRSXNHK9PCWRYOTddtncZxQh1khEADuc5lBK9sC5wx8wrr72S6Mi9R6bkPDq6BIvIseN9NSE1LOjgtAggZbWviQ4axWdzglsERnilawCmuLNcp01FmPMhSwZylvvC33JO3YvebjsOhz2CJlw9VdhgpCbtMcsBQK6SH2xOvkdbBNKrFVQAyHgtoS9VGWjAdjFZgUK5SM/Vafl1v5YalaS7Bwvybh8GJhVU8XqcTKY5g5CZOKK7hRDaRqIEkyWlpWhmnSzLYX8usBXnYhNX68JguNQUhRHcXlUKaEVmLF41xW04Y@RZcWHMHtgjF4DVxqCRzMhf7slIxQGjKpCMNdZedeBsAsSK/2TmY7dFKvkpEyyZU2ZTDSwKdsqrS1edN7DRmkBzEbYElGbTs/V5gOBSxeioswMssVygbpeo1JuF4cTDvWE3vZ5QoIl4qkZc6GzBemVJecV3CDUgRWQ8uxwV5DL2KVP2p52cTlqieoM2rKtQWt@gkzVpvchiZ4Uk@WLdRJuJ6ItJHZ3xVs618AKT2hFAudVQ31MalJ1npCYRIM5OP3DPVnT@L6bZP1o0R7jZJ2Jz2KblRc8I@WILUFpnV//fIv "JavaScript (Node.js) – Try It Online") [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 27 bytes ``` D,w,@@,VbUG€<ÑBxs L~,A€wM1+ ``` [Try it online!](https://tio.run/##S0xJKSj4/99Fp1zHwUEnLCnU/VHTGpvDE50qirl86nQcgbxyX0NtoIISHQcrHcNYLi6VErtoAwVDBSMF41hOTk5rBSOwkK6hgjFQVNdIwRQkpWASC5IzA8sZKhgo6BpCVf8HAA "Add++ – Try It Online") Approach thanks to Zgarb for their [APL answer](https://codegolf.stackexchange.com/a/44562) The key part of this challenge is implementing an outer product command. Unfortunately, Add++ doesn't have a builtin to do so, not does it have any way of defining functions that take other functions as arguments. However, we can still make a generalised outer product function nonetheless. As the only way for a function to be accessed inside another function is via referencing an existing function, user defined or builtin, we have to create a 'builtin' that references such a function. A generalised "table" function would look something like this: ``` D,func,@@,+ D,iter,@@*, VbUG €{func} D,table,@@, $ bRbU @ €{iter} B] ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ600L1nHwUFHm4vLRSezJLUIyNHSUQhLCnVXeNS0phokXwuUKklMykkFKVRQUUgKSgpVcABLg3TUKjjF/lcBK7Czt7Pn8v//P9pQwUjBWMEk9n@0qYKZgrmCRSwA "Add++ – Try It Online") where `func` is a dyadic function that contains our operand. You can see faint similarities of this structure in the original submission, at the start of the **w** function, but here we want, primarily, a *monadic* outer product function - an outer product function that takes the same argument on both sides. The general **table** function takes advantage of how the `€`ach quick approaches dyadic functions. If the stack looks like ``` [a b c d e] ``` when `€{func}` is encountered, the `€` pops `e`, binds that as the left argument to the dyad, and maps that partial function over `a, b, c, d`. However, the `€` quick maps over the entire stack, rather than over lists. So we need to flatten the arrays passed as arguments first. The **table** function works overall like this ``` D,func,@@,+ D,iter, ; Define our helper function **iter** ; This takes an array as its left argument ; And a single integer as its right argument @@ ; Dyadic arguments - take two arguments and push to the stack *, ; After execution, return the entire stack, rather then just the top element ; ; Example arguments: [5 6 7 8] 1 ; VbUG ; Unpack the array; [5 6 7 8 1] ; €{func} ; Map **func** over the stack ; As **func** is dyadic, this pops the right argument ; and binds that to a monadic **func** ; This then maps the remaining elements, [5 6 7 8] ; over the monadic call of **func**, yielding [6 7 8 9] ; Now, as the **\*** flag was defined, we return the entire array ; rather than just the last element. ; We'd achieve the same behaviour by removing the flag and appending **B]** D,table, ; Define the main **table** function ; This takes two arrays as arguments ; Returns a single 2D array representing their outer product with **func** @@, ; Take the two arrays and push to the stack ; ; Example arguments: [[1 2 3 4] [5 6 7 8]] ; $ ; Swap; STACK = [[5 6 7 8] [1 2 3 4]] bR ; Reverse last; STACK = [[5 6 7 8] [4 3 2 1]] bU ; Unpack; STACK = [[5 6 7 8] 4 3 2 1] @ ; Reverse; STACK = [1 2 3 4 [5 6 7 8]] ; ; This allows us to place the stack so that each element of ; the first array is iterated over with the second array ; €{iter} ; Map **iter**; STACK = [[6 7 8 9] [7 8 9 10] [8 9 10 11] [9 10 11 12]] ; B] ; Return the whole stack; $table>?>? O ``` However, we can shorten this by quite a lot due to the fact that we need our outer table to be *monadic*, and only needs to apply to the argument passed. The `A` command pushes each argument to the stack individually, so we don't need to mess around with any stack manipulation. In short, if our argument is the array `[a b c d]`, we need to make the stack into ``` [a b c d [a b c d]] ``` The top value is, of course, the argument.You may have noticed from the general example that `bU` is the **unpack** command i.e. it splats the top array to the stack. So to make the above configuration, we can use the code ``` L,bUA ``` [Try it online!](https://tio.run/##S0xJKSj4/99HJynU8T@nUyyntYJHalGqQkm@QnFGfrlCSUaqQnFJYnI2F5dKTmJuUkqigqGdPZf////RhgpGCsYKJrEA "Add++ – Try It Online") However, this can be shortened by a byte. As an alias for `L,bU`, we can use the `~` flag, to splat the arguments to the stack beforehand, making our configuration example into ``` L~,A ``` [Try it online!](https://tio.run/##S0xJKSj4/9@nTsfxP6dTLKe1gkdqUapCSb5CcUZ@uUJJRqpCcUlicjYXl0pOYm5SSqKCoZ09l////9GGCkYKxgomsQA "Add++ – Try It Online") which is the start of the second line in the program. Now we've implemented monadic outer product, we just need to implement the rest of the algorithm. Once retrieving the result of **table** with `<` (less than), and count the number of `[0 1]` and `[1 0]` pairs in each row. Finally, we take the maximum of these counts, and increment it. The complete step for step walk through is ``` D,w, ; Define a function **w** ; This takes an array and an integer as arguments ; First, it produces the outer product with less than ; Then reduce overlapping pairs by XOR ; Finally, sum the rows @@, ; Take two arguments ; ; Example arguments: [[0 1 2 3] 0] ; VbUG€< ; Map **<** over the array; STACK = [0 1 1 1] ÑBx ; Equals [1 0]; STACK = [1 0 0] s ; Sum; STACK = [1] L ; Define a lambda function ; This takes one argument, an array ~, ; Splat the array to the stack before doing anything ; ; Example argument: [0 1 2 3] ; A€w ; Map with **w**; STACK = [1 1 1 0] M ; Maximum; STACK = [1] 1+ ; Increment; STACK = [2] ``` ]
[Question] [ ## Challenge Given a non-empty array of integers, e.g.: ``` [5, 2, 7, 6, 4, 1, 3] ``` First sever it into arrays where no item is larger than the previous (i.e. non-ascending arrays): ``` [5, 2] [7, 6, 4, 1] [3] ``` Next, reverse each array: ``` [2, 5] [1, 4, 6, 7] [3] ``` Finally, concatenate them all together: ``` [2, 5, 1, 4, 6, 7, 3] ``` This should be what your program outputs/function returns. Repeat this procedure enough times and the array will be fully sorted. ## Rules * Input and output may be given through any standard methods, and may be in any reasonable array format. * The input array will never be empty, but may contain negatives and/or duplicates. * The absolute value of each integer will always be less than 231. ## Test cases Hopefully these cover all edge cases: ``` [1] -> [1] [1, 1] -> [1, 1] [1, 2] -> [1, 2] [2, 1] -> [1, 2] [2, 3, 1] -> [2, 1, 3] [2, 1, 3] -> [1, 2, 3] [2, 1, 2] -> [1, 2, 2] [2, 1, 1] -> [1, 1, 2] [3, 1, 1, 2] -> [1, 1, 3, 2] [3, 2, 1, 2] -> [1, 2, 3, 2] [3, 1, 2, 2] -> [1, 3, 2, 2] [1, 3, 2, 2] -> [1, 2, 2, 3] [1, 0, 5, -234] -> [0, 1, -234, 5] [1, 0, 1, 0, 1] -> [0, 1, 0, 1, 1] [1, 2, 3, 4, 5] -> [1, 2, 3, 4, 5] [5, 4, 3, 2, 1] -> [1, 2, 3, 4, 5] [2, 1, 5, 4, 3] -> [1, 2, 3, 4, 5] [2, 3, 1, 5, 4] -> [2, 1, 3, 4, 5] [5, 1, 4, 2, 3] -> [1, 5, 2, 4, 3] [5, 2, 7, 6, 4, 1, 3] -> [2, 5, 1, 4, 6, 7, 3] [-5, -2, -7, -6, -4, -1, -3] -> [-5, -7, -2, -6, -4, -3, -1] [14, 5, 3, 8, 15, 7, 4, 19, 12, 0, 2, 18, 6, 11, 13, 1, 17, 16, 10, 9] -> [3, 5, 14, 8, 4, 7, 15, 0, 12, 19, 2, 6, 18, 11, 1, 13, 9, 10, 16, 17] ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest code in bytes wins.** [Answer] # JavaScript (ES6), 64 bytes ``` f=([n,...a],z=[],q=[n,...z])=>a+a?n<a[0]?[...q,...f(a)]:f(a,q):q ``` Recursion FTW! The basic algorithm in use here is to keep track of the current non-ascending run in an array, "returning" it whenever an ascending element is found. We do this recursively, continually concatenating the results, until we run out of items. By creating each run in reverse (`[n,...z]` instead of `[...z,n]`), we can avoid the lengthy `.reverse()` at no cost. ### Test snippet ``` f=([n,...a],z=[],q=[n,...z])=>a+a?n<a[0]?[...q,...f(a)]:f(a,q):q g=a=>console.log("Input:",`[${a}]`,"Output:",`[${f(a)}]`) g([1]) g([1,1]) g([1,2]) g([2,1]) g([3,2,1]) g([3,1,2]) g([3,1,1,2]) g([5,2,7,6,4,1,3]) ``` ``` <input id=I value="5, 2, 7, 6, 4, 1, 3"> <button onclick="g((I.value.match(/\d+/g)||[]).map(Number))">Run</button> ``` [Answer] # [Python 3](https://docs.python.org/3/), 63 bytes ``` f=lambda x,*p:x[:1]>p>()and p+f(x)or x and f(x[1:],x[0],*p)or p ``` [Try it online!](https://tio.run/nexus/python3#VVFBjoMwDDx3X@FbSetIdQItIC0fQRxYVUiVdtmo6iG/Z23XVbaHJOOZsTOEbfn8nn@@rjNkPKQ@jz1NQxoqN69XSMelyu73Dhmk5GKkfsI8niY2i5C2ReXbChWhQ9mB7AxyBqv5jAWyGgsMBaohPqEJXIW3ipQIdkt8q04IDYIPsS6E7a9U2lKzT4hGoV1RYhj9L/iTsxZSOZijUXhBOCv9@javQXix4lnyrHkWvapU60Qe3XJLo/3S3PEKGliStDqU5DXsUdhGQrGhc/3HLt1v66PKCHs/7FH@kXPbHw "Python 3 – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` Ṁ;<œṗ³UF ``` [Try it online!](https://tio.run/nexus/jelly#@/9wZ4O1zdHJD3dOP7Q51O3////RhiY6CqY6CsY6ChY6CoZAlrmOAlDI0BKIjXQUDHQUgKQhUM4MSBkCMVAliAIqMwQJARVYxgIA "Jelly – TIO Nexus") ## Explanation: ``` Ṁ; Prepend the list [a1, a2… an] with its maximum. < Elementwise compare this with the original list: [max(a) < a1, a1 < a2, …, a(n-1) < an, an] The first element is always 0. œṗ³ Partition the original list (³) at the indices of the non-zero values in the working list. (The spurious `an` at the end of the left argument, resulting from comparing lists of different sizes, is ignored by this operation, thankfully.) U Reverse each part. F Flatten. ``` [Answer] ## JavaScript (ES6), 70 bytes Sure, this is already beaten by [ETHproductions answer](https://codegolf.stackexchange.com/a/104135/58563), but that's the best I could come up with so far without using recursion. ``` a=>a.map((n,i)=>a[x=[...o,...r=[n,...r]],i+1]>n&&(o=x,r=[]),r=o=[])&&x ``` *Note:* Initializing both `r` and `o` to the exact same object with `r = o = []` may look like a hazardous idea. But it is safe to do so here because `r` is immediately assigned its own instance (containing the first element of `a`) on the first iteration with `r = [n, ...r]`. ### Test cases ``` let f = a=>a.map((n,i)=>a[x=[...o,...r=[n,...r]],i+1]>n&&(o=x,r=[]),r=o=[])&&x console.log(JSON.stringify(f([1]))); console.log(JSON.stringify(f([1, 1]))); console.log(JSON.stringify(f([1, 2]))); console.log(JSON.stringify(f([2, 1]))); console.log(JSON.stringify(f([2, 3, 1]))); console.log(JSON.stringify(f([2, 1, 3]))); console.log(JSON.stringify(f([2, 1, 2]))); console.log(JSON.stringify(f([2, 1, 1]))); console.log(JSON.stringify(f([3, 1, 1, 2]))); console.log(JSON.stringify(f([3, 2, 1, 2]))); console.log(JSON.stringify(f([3, 1, 2, 2]))); console.log(JSON.stringify(f([1, 3, 2, 2]))); console.log(JSON.stringify(f([1, 0, 5, -234]))); console.log(JSON.stringify(f([1, 0, 1, 0, 1]))); console.log(JSON.stringify(f([1, 2, 3, 4, 5]))); console.log(JSON.stringify(f([5, 4, 3, 2, 1]))); console.log(JSON.stringify(f([2, 1, 5, 4, 3]))); console.log(JSON.stringify(f([2, 3, 1, 5, 4]))); console.log(JSON.stringify(f([5, 1, 4, 2, 3]))); console.log(JSON.stringify(f([5, 2, 7, 6, 4, 1, 3]))); console.log(JSON.stringify(f([-5, -2, -7, -6, -4, -1, -3]))); console.log(JSON.stringify(f([14, 5, 3, 8, 15, 7, 4, 19, 12, 0, 2, 18, 6, 11, 13, 1, 17, 16, 10, 9]))); ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 15 bytes ``` lidO>vYsGhXSOZ) ``` Input is a column vector, with the format `[5; 2; 7; 6; 4; 1; 3]` (semicolon is the row separator). [Try it online!](https://tio.run/nexus/matl#@5@TmeJvVxZZ7J4REewfpfn/f7SptYKRtYK5tYKZtYKJtYKhtYJxLAA "MATL – TIO Nexus") Take input `[5; 2; 7; 6; 4; 1; 3]` as an example. ### Explanation ``` l % Push 1 % STACK: 1 i % Push input % STACK: 1, [5; 2; 7; 6; 4; 1; 3] d % Consecutive differences % STACK: 1, [-3; 5; -1; -2; -3; 2] O> % Test if greater than 0, element-wise % STACK: 1, [0; 1; 0; 0; 0; 1] v % Concatenate vertically % STACK: [1; 0; 1; 0; 0; 0; 1] Ys % Cumulative sum % STACK: [1; 1; 2; 2; 2; 2; 3] G % Push input again % STACK: [1; 1; 2; 2; 2; 2; 3], [5; 2; 7; 6; 4; 1; 3] h % Concatenate horizontally % STACK: [1 5; 1 2; 2 7; 2 6; 2 4; 2 1; 3 3] XS % Sort rows in lexicographical order % STACK: [1 2; 1 5; 2 1; 2 4; 2 6; 2 7; 3 3] OZ) % Get last column. Implicitly display % STACK: [2; 5; 1; 4; 6; 7; 3] ``` [Answer] # Mathematica, ~~30~~ 27 bytes *3 bytes saved due to [@Martin Ender](http://ppcg.lol/users/8478).* ``` Join@@Sort/@Split[#,#>#2&]& ``` Anonymous function. Takes a list of numbers as input and returns a list of numbers as output. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ ~~18~~ ~~16~~ 14 bytes Saved 2 bytes using [Luis Mendo's](https://codegolf.stackexchange.com/a/104123/47066) sorting trick ``` ü‹X¸ì.pO¹)ø{ø¤ ``` [Try it online!](https://tio.run/nexus/05ab1e#@394z6OGnRGHdhxeo1fgf2in5uEd1Yd3HFry/3@0oYmOgqmOgrGOgoWOgiGQZa6jABQytARiIx0FAx0FIGkIlDMDUoZADFQJooDKDEFCQAWWsQA "05AB1E – TIO Nexus") **Explanation** Example input `[5, 2, 7, 6, 4, 1, 3]` ``` ü‹ # pair-wise less-than # STACK: [0, 1, 0, 0, 0, 1] X¸ì # prepend a 1 # STACK: [1, 0, 1, 0, 0, 0, 1] .p # prefixes O # sum # STACK: [1, 1, 2, 2, 2, 2, 3] ¹ # push input # STACK: [1, 1, 2, 2, 2, 2, 3], [5, 2, 7, 6, 4, 1, 3] ) # wrap stack in list # STACK: [[1, 1, 2, 2, 2, 2, 3], [5, 2, 7, 6, 4, 1, 3]] ø # zip # STACK: [[1, 5], [1, 2], [2, 7], [2, 6], [2, 4], [2, 1], [3, 3]] { # sort # STACK: [[1, 2], [1, 5], [2, 1], [2, 4], [2, 6], [2, 7], [3, 3]] ø # zip # STACK: [[1, 1, 2, 2, 2, 2, 3], [2, 5, 1, 4, 6, 7, 3]] ¤ # tail # OUTPUT: [2, 5, 1, 4, 6, 7, 3] ``` **Previous 16 byte solution** ``` Dü‹X¸ì.pO.¡€g£í˜ ``` [Answer] # Python 2, 100 bytes A really terrible golf, but I wanted to post my solution [*(one does not simply outgolf Dennis)*](https://codegolf.stackexchange.com/a/104142/60919)... ``` d=input();L=[];x=0;d+=-~d[-1], for i in range(1,len(d)): if d[i]>d[i-1]:L+=d[x:i][::-1];x=i print L ``` [**Test on repl.it!**](https://repl.it/EvQM/0) Input should be given as a Python list literal, such as `[5, 3, 4, 2, 6, 1]`. The basic idea is to make heavy use of Python's slicing syntax, slicing each necessary section from the array, reversing it, and adding it to the new array. [Answer] ## Pyke, ~~11~~ 8 bytes ([old version](https://github.com/muddyfish/PYKE/commit/98f0079d7cb3d9e837dc1b36e9f7b4f5cd051f43)) ``` $0m<fm_s ``` [Try it here!](http://pyke.catbus.co.uk/?code=%240m%3C0R%2Bfm_s&input=%5B5%2C+2%2C+7%2C+6%2C+4%2C+1%2C+3%5D) (works on latest version) ``` $ - delta(input) 0m< - map(i<0 for i in ^) f - split_at(input, ^) m_ - map(reverse, ^) s - sum(^) ``` [Answer] # [Retina](https://github.com/m-ender/retina), 163 bytes Yes, I know how horrid this is. Supporting zeros and negatives was *super* fun. Byte count assumes ISO 8859-1 encoding. ``` \d+ $* (?<=-1*)1 x - x,1 x¶1 \b(1+),(1+\1)\b $1¶$2 ,,1 ,¶1 x,(¶|$) x¶¶ (?<=\b\1x+(?=,(x+))),\b ¶ O%$#`.(?=(.*)) $.1 +`¶ , \bx -x (\w+) $.1 ^, 0, ,$ ,0 ,, ,0, ^$ 0 ``` [**Try it online**](https://tio.run/nexus/retina#JY3RDcIwDET/bw2CFDeXKi4Ffqg6AgtEVVWxA/lgrgyQxYoLsnSy3tl3e34FuA5@fkxRO1EURKDQllYVefMahCZZJW9w2qobQPN5@IW@1Y@T47rVX0zespbg54m@BBGhvZn1PLvT2hv2fScC1yvCapzWYZ0FPr/Dny9EIujAZE2mxOKQ9v3KwSYx3hkH3jhSGS8GlOMX "Retina – TIO Nexus") **Explanation:** ``` \d+ # Convert to unary $* (?<=-1*)1 # Replace negatives with x's instead of 1's x - # Remove minus sign x,1 # Separate if negative before positive x¶1 \b(1+),(1+\1)\b # or greater positive follows a positive $1¶$2 ,,1 # or positive follows a zero ,¶1 x,(¶|$) # or zero follows a negative x¶¶ (?<=\b\1x+(?=,(x+))),\b # or negative follows a negative of greater magnitude. ¶ O%$#`.(?=(.*)) # Swear at the input, then reverse each line $.1 +`¶ # Remove breaks, putting commas back , \bx # Put the minus signs back -x (\w+) # Replace unary with length of match (decimal) $.1 ^, # Do a bunch of replacements to resurrect lost zeros 0, ,$ ,0 ,, ,0, ^$ 0 ``` [Answer] # JavaScript (ECMA 6), ~~121~~ ~~128~~ ~~125~~ ~~119~~ 108 bytes ``` f=a=>{p=a[0],c=[],b=[];for(e of a){e>p&&b.push(c.reverse(c=[]));c.push(p=e)}return[].concat.call([],...b,c)} ``` Lambda expression takes a single `Array` parameter, `a`. *Thanks to @ETHproductions for helping me see my first mistake.* [Answer] # Ruby, ~~60~~ 55 bytes ``` s=->x{x.slice_when{|p,q|p<q}.map{|z|z.reverse}.flatten} ``` Pretty much what the challenge asked for. I defined a lambda `s`, that takes an array `x`, and *sever* (slices) it into smaller pieces where the following element would be greater than. This gives back an enumerator, which we can call map on and *reverse* the order of the pieces, before finally bringing it all together with flatten, which *concatenates* the elements in the defined order into one array. Tests ``` p s[[1]]===[1] p s[[1, 1]]===[1, 1] p s[[1, 2]]===[1, 2] p s[[2, 1]]===[1, 2] p s[[2, 3, 1]]===[2, 1, 3] p s[[2, 1, 3]]===[1, 2, 3] p s[[2, 1, 2]]===[1, 2, 2] p s[[2, 1, 1]]===[1, 1, 2] p s[[3, 1, 1, 2]]===[1, 1, 3, 2] p s[[3, 2, 1, 2]]===[1, 2, 3, 2] p s[[3, 1, 2, 2]]===[1, 3, 2, 2] p s[[1, 3, 2, 2]]===[1, 2, 2, 3] p s[[1, 0, 5, -234]]===[0, 1, -234, 5] p s[[1, 0, 1, 0, 1]]===[0, 1, 0, 1, 1] p s[[1, 2, 3, 4, 5]]===[1, 2, 3, 4, 5] p s[[5, 4, 3, 2, 1]]===[1, 2, 3, 4, 5] p s[[2, 1, 5, 4, 3]]===[1, 2, 3, 4, 5] p s[[2, 3, 1, 5, 4]]===[2, 1, 3, 4, 5] p s[[5, 1, 4, 2, 3]]===[1, 5, 2, 4, 3] p s[[5, 2, 7, 6, 4, 1, 3]]===[2, 5, 1, 4, 6, 7, 3] p s[[-5, -2, -7, -6, -4, -1, -3]]===[-5, -7, -2, -6, -4, -3, -1] p s[[14, 5, 3, 8, 15, 7, 4, 19, 12, 0, 2, 18, 6, 11, 13, 1, 17, 16, 10, 9]]===[3, 5, 14, 8, 4, 7, 15, 0, 12, 19, 2, 6, 18, 11, 1, 13, 9, 10, 16, 17] ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 10 bytes ``` ~c:{>=r}ac ``` [Try it online!](http://brachylog.tryitonline.net/#code=fmM6ez49cn1hYw&input=WzU6Mjo3OjY6NDoxOjNd&args=Wg) ### Explanation ``` ~c Deconcatenate the Input :{>=r}a Each resulting sublist must be non-increasing, and then reverse it c Concatenate ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` ṁ↔ġ≤ ``` [Try it online!](https://tio.run/##PU@7DcIwEN0lVZCepZwd59MwAC1llBIJCVFFDBAKJHoWQMoStIhFyCLm@WJS2O/j872742U4hXO@f0/5LjPb7LAZ5usYvq9xvj0@z/k@hRC6Tnp0guW2vK1yC5dQ4BKmV/VdRHUc7MqIyvhnZQU8jHVlEnqWMBaV8OSeqG1SgOr/EFFpjdC16ntijYp6Gc7EBJgapoIpYQQm2sLu7NBAPMtZ3EIs4xnR8LdwA12jhlAVaPv@Bw "Husk – Try It Online") I've `ġ`ot `ṁ`yself the right tools for this job. ### Explanation `ġ` is "groupby": it divides a list into sublists where in each sublist the given function returns a truthy value for any pair of elements. Used with `≤`, this divides the list into non-increasing sequences. `ṁ` is "concatmap": it maps a function to each element of a list, and concatenates the results together. With `↔` (reverse), this performs the reverse-and-concatenate final part of the algorithm. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), ~~7~~ 15 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Requires `⎕ML←3`, which is default on many systems.\* ``` {∊⌽¨⍵⊂⍨1+⍵-⌊/⍵} ``` `∊` enlist (flatten) `⌽¨` each-reversed `⍵⊂⍨` the argument partitioned\* by cutting where each corresponding element is larger than its predecessor in `1+` one plus `⍵-` the argument minus `⌊/⍵` the smallest element of the argument --- Old 7 byte solution fails with non-positive integers: Requires `⎕ML←3`, which is default on many systems.\* ``` ∊⌽¨⊆⍨⎕ ``` `∊` enlist (flatten) the `⌽¨` each-reversed `⊂⍨` self-partitioned\* --- \* Partition (`⊂`) is a function which cuts its right argument where the corresponding left argument is larger than the preceding one. (Unfortunately it only accepts non-negative integers, and zero has special meaning.) From version 16, this functionality of `⊂` is available on all systems (even those where `⎕ML≠3`), using the glyph `⊆`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` <Ɲk$UF ``` [Try it online!](https://tio.run/##fZI9UsQwDIX7nMIzUNozsZxskhmGkhtQMDspaWAvQEtDT7UNN@AC1AzcAy5ipCfh9ZqfIrvW06cnWcnN9W53l/PZ@9Pt6eVFfn34vH9@e/x42fP/Vc7bbhtX705cOHd84si7SpAAGtUasUYNZ1qqZWFYMlpOdUGdoSZDJXM8jGaSZpqyiO6W/9021fXU5FPpXAXNWDozB713o3eB0lCQHq4ica5Q9ttQvd2tOwyGqh/jmteIk93rT0ovbex/VCpg@67qjhEBNV4jpEE3ocHk3QbS0TsmsGqyASQVAWvjh@PAcuBskL0dCoFMhn0jSTDZ1wBbDmc2H@ErnRd@CIuVm8xoGWXH9rEwFkViYCmdko44wGyAl1j26iWepEazmanfoj7wm9Zu/QI "Jelly – Try It Online") ## How it works ``` <Ɲk$UF - Main link. Takes an array A on the left $ - To A: Ɲ - For each overlapping pair of elements [a, b] in A: < - Is a < b? k - Partition A at the truthy elements U - Reverse each subarray F - Flatten ``` [Answer] ## Haskell, 49 bytes ``` (a:b)%l|any(<a)l=l++b%[a]|1<2=b%(a:l) _%l=l (%[]) ``` Usage example: `(%[]) [5,2,7,6,4,1,3]` -> `[2,5,1,4,6,7,3]`. Recursive approach. The function `%` takes the input list as its first parameter and an accumulator `l` which keeps track of the non-ascending chunk so far (in reverse order). The base case is reached when the input list is empty and then the result is the accumulator. If the input list is not empty and the first element `a` doesn't fit in the current chunk (`any(<a)l`), return the accumulator and append a recursive call on the rest of the list and `a` as the new accumulator (`l++b%[a]`). Else, make a recursive call on the rest of the list and `a` prepended to tha accumulator (`b%(a:l)`). The main function `(%[])` calls `%` with an empty accumulator. [Answer] ## [Retina](https://github.com/m-ender/retina), 98 bytes Byte count assumes ISO 8859-1 encoding. ``` $ -(\d+) $1$*-/ \d+ $* S-`(?<=(-+)/ )(?!\1)|(?=\b(1+))(?<!\2 ) O%`\S* ¶ ((-)|1)*/? $2$#1 $ ``` [Try it online!](https://tio.run/nexus/retina#LU5LrsIwDNz7FINekJJWVnHSUpBAXb4lC7ZZVIhjcC4OwMX6Jn4sPJ7xZ@x9/F23IBCN9dknCRY6HYRcQid3XeNyuUbt04AUl1219IrLtT6i9YmFy65mJLnt13rvIJ@3SIyaXpa6YYGEHH4MgiDbZmJokSUzZxRHQ3H0KiulIVVB/mYiM@e@@YAJmsvo1KOZsj1ikonoq27n6v9U4@waK9RkGTOOVO0BbY7QGXqEjlCDFjH6cfMEmzjKwTMs8xyNT9w0/unPzjCqA85/ "Retina – TIO Nexus") [Answer] ## R, 64 bytes ``` cat(unlist(lapply(split(x<-scan(),cumsum(c(F,diff(x)>0))),rev))) ``` Reads input from stdin. We split the input into a list of vectors using `split()` which requires a factor variable that groups the input. The factor is created by taking the cumulative sum of the the logical vector for which the difference is positive. Consider the vector: ``` x=c(5, 2, 7, 6, 4, 1, 3) ``` Now taking the difference and prepending `F` by running `y=c(F,diff(x)>0)` would produce the following logical vector: ``` [1] FALSE FALSE TRUE FALSE FALSE FALSE TRUE ``` Taking the cumulative sum `cumsum(y)` produces a vector where each group is represented by a unique factor upon which we can combine with the `split` function: ``` [1] 0 0 1 1 1 1 2 ``` [Answer] # Octave, ~~75~~ 44 bytes Based on [MATL answer](https://codegolf.stackexchange.com/a/104123/62451) of @LuisMendo ``` @(a)sortrows([cumsum([1;diff(a)>0]),a])(:,2) ``` [Try it Online!](https://tio.run/#bT0RW) Previous answer ``` @(a)[fliplr(mat2cell(f=fliplr(a),1,diff(find([1,diff(f)<0,numel(a)])))){:}] ``` [Try it Online!](https://tio.run/#RzUCx) reverse the array ``` f=fliplr(a) ``` take first difference of `f` ``` d = diff(f); ``` find position of where the next element is less than the previous element ``` p=find([1,diff(f)<0,numel(a)]) ``` first difference of the positions returns length of each sub array ``` len=diff(p) ``` use length of each sub array in `mat2cell` to split the array to nested list of arrays ``` nest = mat2cell(f,1,len); ``` reverse the nested list ``` rev_nest = fliplr(nest) ``` flatten the nested list ``` [rev_nest{:}] ``` [Answer] # [R](https://www.r-project.org/), 41 bytes ``` ave(x,diffinv(diff(x<-scan())>0),FUN=rev) ``` [Try it online!](https://tio.run/##K/r/P7EsVaNCJyUzLS0zr0wDRGtU2OgWJyfmaWhq2hlo6riF@tkWpZZp/jdVMFIwVzBTMFEwVDD@DwA "R – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes *Completely and utterly outgolfed [by Leo](https://codegolf.stackexchange.com/a/218911/95126) while I was typing in my answer...!* ``` ṁ↔CẊ-Θ:W<¹L¹ ``` [Try it online!](https://tio.run/##AS0A0v9odXNr///huYHihpRD4bqKLc6YOlc8wrlMwrn///9bNSwyLDcsNiw0LDEsM10 "Husk – Try It Online") ``` ṁ # map this function: ↔ # reverse # across all the elements of: C # cut the input into sublists given by Ẋ- # differences between elements of W<¹ # list of indices of the input that are less than their successor Θ: L¹ # prepended with zero and appended with the length of the input ``` [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 6 bytes ``` ᵃ>ṁƒVf ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLhtYM+4bmBxpJWZiIsIiIsIlsxLCAzLCAyLCAyXSAiLCIzLjQuMSJd) a weird quirk of "partition after truthy indices" means it matches lengths so it will never include the last value when getting booleans from comparing the overlapping pairs. By appending the reversed list we can always have a partition such that the last values are kept [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~17~~ 15 bytes ``` {,/|'x@=+\>':x} ``` [Try it online!](https://ngn.codeberg.page/k#eJx1U9tunDAQfecr5qFSWhUHbHO3GvU/tkhBGzaJkiwp0IpV2n575+IFb5U+eJk5c86ZGcMemrc4+XW1fP3y+dvNVbP8jqK5efuwO/0ZmwMALO52eHIfbw/d47Nb3MmNn1ri7GLtYt1ioEE7PBIaDA2FhlEfWkwQAOsrYKm2paxadeInqQXt6yg6Q5vEbizDkD37+FCMpZOGFHJQxmYuRQEFkJ8LfJx/rtugCXLcGhGcY8AzXMI0FJf+ha0U5AI2E42hYXaOz0xGpLCEAlO6IwNCKxDjsqLxQZWgClAZKFzCOgJLxgW0iPP42AobVqBz1KNjDdrgdjhHhZYat+TbLUFjlkLtLPXLUJGhAFUpCVBmiF6xgjQ1sUlTtlGURA/z/Do1SbIf7vr74flwPc3d/qlf9g/d8b6/3g8vyfcf/TQ/Dscp0WmmjU6m/mc/qmkYZ9UdVTeO3SmKdroFdQP4wDCGc0YRA2YF8A3vTMjwgF0xqsZ0aWu0UkPYhLBZ4aC1wFbgUKC5nS++42ZDpQmLdu0WJOEcMiEmaQx5zB+q1FM2ozymz8hT/G9ISf0a0TYMSy7n8y45R36L9ymynyf+l2JX1sVLCBtpTkzoknOeydKSlDEUDG1vzjBR5AUziK74evBgrhBWWFV0RV7F9dJzznUb8z8E/yDsiWmFzjmbUs8aj+E7pAUq7qfpOv1XgDRNEBJqaWNluIydMjYiv1SMyNCIS+WdxKwWEzYr279aDB9z) Chunks the input on indices where the value is greater than the previous value, reversing each chunk and concatenating back into a single array. * `>':x` check whether each element is larger than the prior element * `=+\` group the cumulative sum of this; elements in each run of equal or decreasing values get assigned their own index in the resulting dictionary * `x@` index back into the original input to retrieve the original values * `|'` reverse each chunk * `,/` flatten the chunks back into a single array [Answer] # Pyth - 15 bytes ``` s_McQf<@QtT@QTU ``` [Try it online here](http://pyth.herokuapp.com/?code=s_McQf%3C%40QtT%40QTU&input=%5B5%2C+2%2C+7%2C+6%2C+4%2C+1%2C+3%5D&debug=0). [Answer] # [Perl 6](http://perl6.org/), 59 bytes ``` {map |+«*.[0].reverse,m/:s([(\-?\d+)<?{[>=] $0}>] +)+/[0]} ``` Regex-based solution. Because this is ~~Sparta~~ Perl!! * `m/ /`: Stringify the input array, and match a regex against it. * `(\-? \d+)`: Match a number, and capture it as `$0`. * `<?{ [>=] $0 }>`: Zero-width assertion that only matches if all `$0` captured so far in the current sub-match are in non-ascending order. * `([ ] +)+`: Repeat the last two steps as often as possible, otherwise start a new sub-match. * `map , [0]`: Iterate over the sub-matches. * `|+«*.[0].reverse`: For each one, take the list of values matched by `$0`, reverse it, coerce the values to numbers (`+«`), and slip them into the outer list (`|`). # [Perl 6](http://perl6.org/), 63 bytes ``` sub f(\a){flat $_,f a[+$_..*]with first {[<=] $_},:end,[\R,] a} ``` Recursive list processing solution. More laborious than I had hoped. Even though the language has lots of convenient built-ins, there seem to be none for list partitioning (e.g. like Ruby's `slice_when` or Haskell's `takeWhile`). [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), noncompeting, 34 bytes Still constantly developing this language. ``` {e.b:e b last<}chunkby$revmap flat ``` Argument lies on TOS. [Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html) `chunkby` takes a function and collects arrays of contiguous data that satisfy the function. The function then is: ``` {e.b:e b last<} {e.b: } function with arguments [e, <unused>, b]--the element, <the index>, and the chunk being built e < check if e is less than b last the last element of b ``` This gives a strictly decreasing array. `$revmap` is basically `[rev]map` and reverses each item. `flat` finally flattens the array. --- Some fun for actually sorting the array: ``` [{e.b:e b last<}chunkby$revmap flat] @:sortstep [$sortstep periodloop] @:sort 10:> @arr arr out arr shuf @arr arr out arr sort out ``` This outputs (for example): ``` (0 1 2 3 4 5 6 7 8 9) (4 5 1 0 6 7 2 8 9 3) (0 1 2 3 4 5 6 7 8 9) ``` [Answer] # Python, ~~151~~ 139 Bytes *Saved 12 Bytes thanks to @Flp.Tkc!* Nowhere near @Flp.Tkc, let alone... ``` def s(l): r=[];i=j=0 while j<len(l)-1: if l[j+1]>l[j]:r+=l[i:j+1][::-1],;i=j+1 j+=1 r+=l[i:j+1][::-1],;return[i for s in r for i in s] ``` [Answer] # Python 2, 74 bytes ``` b=[];c=[];a+=9e9, for i in a[:-1]: b=[a.pop(0)]+b if b[0]<a[0]:c+=b;b=[] ``` Input in `a`, output in `c` [Answer] # Python 3, 191 Bytes ``` a=[int(i)for i in input().split()] while a!=sorted(a): b=[[]] for i,j in enumerate(a): if a[i-1]<j:b+=[[j]] else:b[-1]+=[j] a=[] for l in[k[::-1]for k in b]:a+=[k for k in l] print(a) ``` I'm not sure if using the `sorted` function to check is allowed here, but I couldn't think of a good reason against it, and it brought down my byte count by ~30 Bytes. ]
[Question] [ In [Wordle](https://powerlanguage.co.uk/wordle/), you try to guess a secret word, and some letters in your guess are highlighted to give you hints. If you guess a letter which matches the letter in the same position in the secret word, the letter will be highlighted green. For example, if the secret word is `LEMON` and you guess `BEACH`, then the `E` will be highlighted green. If you guess a letter which is present in the secret word, but not in the correct corresponding position, it will be highlighted yellow. If a letter appears more times in the guess than it does in the secret word, only upto as many occur in the secret may be highlighted. If any of the occurrences are in the same place, they should be preferentially highlighted green, leaving earlier letters unhighlighted if necessary. For example, with the secret `LEMON` and the guess `SCOOP`, the second `O` will be green, because it is in the right place, but the first `O` will be unhighlighted, because there is only one `O` in the secret, and one `O` has already been highlighted. Any of the remaining letters in the secret may be highlighted yellow if they match, as long as the right number are highlighted in total. For example, with the secret `LEMON` and the guess `GOOSE`, only one of the `O`s should be highlighted; it does not matter which. ## Task Given two five-letter strings, a secret and a guess, highlight the letters in the guess according to the rules above. You can "highlight" the letters using any reasonable output format. For example: * a length-`5` list of highlight values * a list of 5 pairs of `(letter, highlight value)` * a mapping from indices `0`-`4` or `1`-`5` to the highlight at that position You can choose any three distinct values to represent unhighlighted, yellow, and green. (For example, `0`/`1`/`-1`, or `""`/`"Y"`/`"G"`...) If in doubt about the "reasonable"ness of your output format, please ask. It must be unambiguous about the ordering of highlighting in case of double letters. ## Rules * You may assume the inputs are both of length 5 and contain only ASCII letters * You may choose whether to accept input in uppercase or lowercase * You may take input as a string, a list of character codes, or a list of alphabet indices (in \$ [0, 25] \$ or \$ [1, 26] \$) * You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447) * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins ## Test cases All using the secret word `HELLO`: \$ \require{color} \newcommand{\qG}[1]{\colorbox{##0f0}{$ \mathtt #1 $}} \newcommand{\qY}[1]{\colorbox{##ff0}{$ \mathtt #1 $}} \newcommand{\qW}[1]{\colorbox{ ##eee}{$ \mathtt #1 $}} \$ * `SCRAP` -> \$ \qW S \qW C \qW R \qW A \qW P \$ * `HELLO` -> \$ \qG H \qG E \qG L \qG L \qG O \$ * `EPOCH` -> \$ \qY E \qW P \qY O \qW C \qY H \$ * `CIVIL` -> \$ \qW C \qW I \qW V \qW I \qY L \$ * `BELCH` -> \$ \qW B \qG E \qG L \qW C \qY H \$ * `ZOOMS` -> \$ \qW Z \qY O \qW O \qW M \qW S \$ or \$ \qW Z \qW O \qY O \qW M \qW S \$ * `LLAMA` -> \$ \qY L \qY L \qW A \qW M \qW A \$ * `EERIE` -> \$ \qW E \qG E \qW R \qW I \qW E \$ * `HALAL` -> \$ \qG H \qW A \qG L \qW A \qY L \$ * `LLLXX` -> \$ \qY L \qW L \qG L \qW X \qW X \$ or \$ \qW L \qY L \qG L \qW X \qW X \$ * `LLLLL` -> \$ \qW L \qW L \qG L \qG L \qW L \$ [Copy and paste friendly format](https://ato.pxeger.com/run?1=NVBNawIxFKTX_IqHl160JDl5kEJcAi48WdG2SG-L-9wshF3YRKT9K14E8U_11zQfOiGQmfcyA3O5_Tpzvd5P_jib_728LhZv7MMQODqM5OE8jA10DiYrjVhN4DiMUFsL3pAj8OQ8HGpHjn26rm-Bp4VTb7rW2HA9NVMQSfwha4fzFOq-AZmUdiTq2a7Yqg3M3oFHsJQTqYxgelMVq0gFD4cV5VeJz2XBlhrzlEsZ6HdVrXeJijCGEMHjiyGqtUomUWdab0udf6VEhSp5Sh5NEHG_z4nyYSJkMgnI0SEs9_Wo7VnfPw) [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~19~~ 18 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) Improved after getting some new ideas from trying this in K. ``` =+5>≠{⊒⌾(∾𝕨⊸⊔)˝𝕩}≍ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=SnVkZ2Ug4oaQID0rNT7iiaB74oqS4oy+KOKIvvCdlajiirjiipQpy53wnZWpfeKJjQoKRuKGkCJIRUxMTyLiirhKdWRnZQoKPijiiqLii4jCtyjiiL7iipHin5wi4qyc77iPIuKAvyLwn5+oIuKAvyLwn5+pIsKoKeKKuOKLiEYpwqgg4p+oCiJTQ1JBUCIKIkhFTExPIgoiRVBPQ0giCiJDSVZJTCIKIkJFTENIIgoiWk9PTVMiCiJFRVJJRSIKIkxMTFhYIgoiTExMTEwiCuKfqQ==) --- # [BQN](https://mlochbaum.github.io/BQN/), ~~27~~ 24 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) Returns 0 for white, 1 for yellow and 2 for green. ``` +`⊸×∘≠⊏2∾(≠/⊣)(⊒<≠∘⊣)≠/⊢ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=SnVkZ2Ug4oaQICtg4oq4w5fiiJjiiaDiio8y4oi+KOKJoC/iiqMpKOKKkjziiaDiiJjiiqMp4omgL+KKogoKRuKGkCJIRUxMTyLiirhKdWRnZQoKPijiiqLii4jCtyjiiL7iipHin5wi4qyc77iPIuKAvyLwn5+oIuKAvyLwn5+pIsKoKeKKuOKLiEYpwqgg4p+oCiJTQ1JBUCIKIkhFTExPIgoiRVBPQ0giCiJDSVZJTCIKIkJFTENIIgoiWk9PTVMiCiJFRVJJRSIKIkxMTFhYIgoiTExMTEwiCuKfqQ==) This is a golfed version of my `Judge` function from the Wordle solver challenge, with an improvement suggested by Marshall. There might another approach more suitable for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). This is a tacit function taking the guess on the right and the secret on the left. `≠/⊢` / `≠/⊣` Remove fully correct letters from the guess / secret. `⊒` Progressive indices of the shortened guess inside the shortened secret. *Progressive* means that no index is output twice and if a value is not available, the length of the vector is returned. `<≠∘⊣` For each index, is this less than the length of the shortened secret? `2∾` Prepend a 2 to this boolean vector. `+`⊸×∘≠` 0s at the green positions, positive integers in increasing order at the other positions. `⊏` Index with that into the vector. The part `+`⊸×∘≠⊏2∾` is mostly there to invert the `≠/`, it would be nice if `≠/⁼` would work instead. ``` "HELLO" (≠/⊢) "LLLXX" # "LLXX" "HELLO" (≠/⊣) "LLLXX" # "HELO" "HELO" (⊒) "LLXX" # ⟨ 2 4 4 4 ⟩ "HELO" (⊒<≠∘⊣) "LLXX" # ⟨ 1 0 0 0 ⟩ "HELLO" (+`⊸×∘≠) "LLLXX" # ⟨ 1 2 0 3 4 ⟩ 1‿2‿0‿3‿4⊏2∾1‿0‿0‿0 # ⟨ 1 0 2 0 0 ⟩ ``` [Answer] # [Perl 5](https://www.perl.org/) + `-pF`, 57 bytes Returns `2` for green, `1` for yellow and leaves others as they were. This example pretty prints using ANSI escape codes! ``` $_=<>;s/./$F[pos]=~s!$&!#!?2:$&/ge;eval's/$F[$-++]/1/;'x5 ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJF89PD47cy8uLyRGW3Bvc109fnMhJCYhIyE/MjokJi9nZTtldmFsJ3MvJEZbJC0rK10vMS87J3g1IiwiaGVhZGVyIjoiIyB1c2VkIGxhdGVyIGZvciBwcmV0dHkgcHJpbnRpbmdcbiRzPSIsImZvb3RlciI6IjsjIHByZXR0eSBwcmludGluZywgcmVndWxhciBvdXRwdXQgaXMgSEVMTE8gPT4gMjIyMjIsIExMTExMID0+IExMMjJMXG5AbT0vLi9nO1xuJF89JHM7cy8uLyhcIiAkJiBcIixcIlxceDFiWzQzbSAkJiBcXHgxYlttXCIsXCJcXHgxYls0Mm0gJCYgXFx4MWJbbVwiKVskbVtwb3NdfDBdL2dlOyIsImFyZ3MiOiItcEYiLCJpbnB1dCI6IkhFTExPXG5MTFhMTCJ9) ## Explanation Initial (implicit via `-p`) input (the target word) is stored in `$_` and split into `@F` and the guess is then stored in `$_` instead. `s///`ubstitute each letter with: if `s///`ubstituting `$&` (the current match) with `#` is successful, `2`, otherwise itself. Then `s///`ubstitute each index of `@F` left in `$_` (`s///` works on `$_` by default) with 1. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` øDÆĀ*ø`0Kvy®.; ``` Input as a list of 1-based alphabet indices; modifies the list to change green to `0` and yellow to `-1` (grey values remain the same). [Try it online](https://tio.run/##yy9OTMpM/f//8A6Xw21HGrQO70gw8C6rPLROz/r//2gLHVMdQyMwMo3lijaCcI11LGIB) or [verify all test cases](https://tio.run/##yy9OTMpM/e9YWhycbRdadminvZKChpJ9hL2SpkJiXoqCkn0lRMSxtBKowgUk/qhtElA84v/hHS6H2440aB3ekWDgXVZ5aJ2e9f9aF4jyc1uVPsyfv/LRmtlAaoVSsd6hjYdX1HoBtSvp/Pdw9fHx54pWCnYOcgxQ0lEC84G0a4C/sweQdvYM8/QB0k6uPmB@lL@/bzCQ9vFx9HUEqXMN8nQF6XP0cfQBi/tEREBoHx@lWAA). **Explanation:** ``` ø # Zip the two (implicit) input-lists together, creating pairs D # Duplicate this list of pairs Æ # Reduce each inner pair by subtracting Ā # Check for each that it's NOT 0 (0 if 0; 1 otherwise) * # Multiply that to the pairs ø # Zip/transpose; swapping rows/columns ` # Pop and push both lists separated to the stack 0K # Remove all 0s from the top list v # Foreach `y` over the remaining values: y®.; # Replace the first `y` with -1 in the other list # (after which the result is output implicitly) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 45 bytes ``` +`(\w)(.{5})\1 +$2+ +`(\w)(.*,.*)\1 -$2- ,.* ``` [Try it online!](https://tio.run/##K0otycxL/P9fO0EjplxTQ6/atFYzxpBLW8VImwsmpqWjpwUS1FUx0uUCsrn@/w92DnIM0PFw9fHx5wKTULZrgL@zB5Tt7Bnm6QNlO7n6wMWj/P19g2HqXYM8XaFsHx@fiAgE2weqFwA "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input as two comma-separated words. Matching letters are changed to `+` and near-misses are changed to `-`. Explanation: ``` +`(\w)(.{5})\1 +$2+ ``` Change all matching letters to `+`s (in the secret word too, so that it doesn't match later.) ``` +`(\w)(.*,.*)\1 -$2- ``` Change all near misses to `-`s. ``` ,.* ``` Delete the secret word. [Answer] # [R](https://www.r-project.org/), ~~84~~ 80 bytes ``` function(s,g){e=s!=g;for(i in 1:5)s[x]=g[i]=1+is.na(x<-which(s*e==g[i])[1]);g*e} ``` [Try it online!](https://tio.run/##TZBRS8MwFIXf8ytifElmK01AELcIWgIrZHRsIsPSh1GaLi/paDIciL@9JiVW730797v3cO4wKrhKR3UxjdO9wTbpyFfL7Q3vlqofsIbaQPr0QGx1rXlX6ZrTO23vzRFfV@nnSTcnbBctn0akojVZdov2e3StdRZysDme8cWpx7e@MC5pMED7fPeyRcktTJ9hFgqgtZCyjBILBZDYlvk6SjTzDVBevBfy36KXXoWcqYyxIH2U5Wb/K1GPwX7wOA0@QuwKMeOTtZTycJh9WMQpizMpUfTz1wEhAISnhHDhL1NIAs@DNg6rv5w4JiLJhBAy/gA "R – Try It Online") My golfing skills are quite rusty after a long break, but here it goes anyway. Takes input as a vector of codepoints, outputs 0 for exact match, 1 for inexact match, 2 - for miss (the reverse of what is given in test cases). [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~32~~ 31 bytes ``` {g-(x~':x{x_x?y}\y@>g)@<>g:x=y} ``` [Try it online!](https://ngn.codeberg.page/k#eJxtj0ELgkAQhe/+imEvFbS061HK3GRBYUIxiIigk3qRgi7tIvrbc1srqmUYBubjvZlXBW1Np6qfBKpVZ7XW3UlHYT2LlmEdqJXuPG8BDOpbqefAzSwvc/BBl01zvQ+MhnY9YPrm7MWrKCCJRMyIx2Csng16HnFK4VSRXVyInHgcxvqmo9YHsx36m8o8i5OP8w+N032KhhrfP7qRaLW+66tjlm135q6TIoqtsM4OKmWRSpOIue4mAgXaRNzljIeDTfT8+o8ikgcP2GPD) Minor reordering and syntax change from the original answer below (and it returns the negation of the one below). --- # [K (ngn/k)](https://codeberg.org/ngn/k), 32 bytes ``` {(x~':x{x_x?y}\y@>g)[<>g]-g:x=y} ``` [Try it online!](https://ngn.codeberg.page/k#eJxtz10LgjAUBuB7f8VhNxUobV5KHy4ZKBwxEiL6oCv1Jgq6aUP0t+faKiwZY7CH855zyqAey3YUyFqe5VI1RxUuqslhtqhOXhXIuWocZwoUqnuhXGD6La4u+KCKy+X26IxZ8z5I31iGAYkFYkYcCva0tCtmIfPgWJI82vA1cRjY00Nb6YP+7G4PxTqL4m9sH6Nkm6BGHfqLK4Gm0h8YaJ9laa57DiEiT7mJ/UchNonQq9CBnjFHjmYVNhCLu51Z5TXvLyKSJ9MuYcE=) I saw the task being discussed in the arraylang discord, so I gave it a try myself. Returns an array where 1 represents gray, -1 green, and 0 yellow. ``` {(x~':x{x_x?y}\y@>g)[<>g]-g:x=y} x: correct answer, y: guess g:x=y g: green positions mask (1=green) y@>g reorder the guess so that greens come first x{ }\ seeded scan starting with x: for each char in y, x_x?y delete one copy of the char from x if it exists x~': for each position, test if the output is the same as input (1=gray, 0=green or yellow) ( )[<>g] reorder the result back to the original position (for permutation p, <p is the inverse permutation) - (1=gray, 0=other) - (1=green, 0=other) = (1=gray, 0=yellow, -1=green) ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 30 bytes Takes the guess as first argument and the secret as second. Returns a list with -1 for not highlighted, 0 for yellow and 1 for green. ``` {e-^(,/(=x@>e)@'<'=y)?<>e:x=y} ``` [Try it online!](https://ngn.codeberg.page/k#eJxFjsEKgkAQhu/7FMNeTFJyPZqWm6wojCgKEUXd1i5S0CVF7NlzXTOGuXzM989fe720bytrswracCfN0PCNoDP3/k56bdANhGxsBveX7CxwoJNN83xbMBH5ILHXO+ACC9m6vrRbmgjEnF4H4sA8n5hWUckLShjMMyJ9R1xQ9rgjEkUeJXQRFYrSY4oKKU2jg0B95S7x5zzPKpX1R4g841r8ISHKVKgSzpKVcOSoS7BFxNNJl5h+aoRIv1YVQ78=) ``` e:x=y booleans mask with 1s where the two words are equal "HALAL"="HELLO" -> 1 0 1 0 0 > grade down; this gives an order that would sort the equal indices to the front > 1 0 1 0 0 -> 0 2 1 3 4 < grade up; inverts this permutation < 0 2 1 3 4 -> 0 2 1 3 4 ( )? for each of those indices, find it in the list on the left Returns 0N (null) for indices that are not present in the list. (0 1 4 0N 0N 0N)?0 2 1 3 4 -> 0 0N 1 0N 2 ^ Is null? Returns a boolean mask which has 1s for non-higlighted positions. ^a?b is basically "b not in a" ^0 0N 1 0N 2 -> 0 1 0 1 0 ,/(=x@>e)@'<'=y inner part that generates a list of indices for yellow and green highlights, where the green highlights have been sorted to the front. =y group the secret word ="HELLO" -> "HELO"!(,0;,1;2 3;,4) <' grade up the indices of each group As the indices are sorted within each group, this converts each to a range from 0 to length-1. <'="Hello" -> "HELO"!(,0;,0;0 1;,0) x@>e sort matching values to the front in the guessed word. "HALAL"@>1 0 1 0 0 -> "HLAAL" = group this reordered string ="HLAAL" -> "HLA"!(,0;1 4;2 3) Now we have two dictionaries: - "char in secret!0 .. number of times that char appears-1", - "char in guess!indices of that char, when greens are sorted to the front" @' pair up matching keys in the two dicts, and apply @ between their values. @ performs indexing, where out of bounds indices return nulls. when a key is only present in one of the dicts, this will generate a new one with a list of nulls as value. ("HLA"!(,0;1 4;2 3))@"HELO"!(,0;,0;0 1;,0) -> "HLAEO"!(,0;1 4;,0N;,0N;,0N) ,/ flatten the values into a list ,/"HLAEO"!(,0;1 4;,0N;,0N;,0N) -> 0 1 4 0N 0N 0N ``` [Answer] # [Haskell](https://www.haskell.org/), 112 bytes ``` import Data.List f(x:y,z)=[0^x|elem x z]:f(y,delete x z) f _=[] x?z|x==z=(0,0)|1>0=(x,z) ((f.unzip).).zipWith(?) ``` [Try it online!](https://tio.run/##Hcu9CsMgFIbh3atw6HAEEdOfJXCapWP3DmKLUE0kPw2JBSO5d5uUb3h5hq8xc2u7Lmffj58p0JsJRtz9HIiDWC48MVTyGVfb2Z5GmnTpYOHvjcHuZsTRFypNYpXWiJgQJJdsLa4SIW53UiOAE98h@ZEJJrY8fGigYrk3fsBx8kM41FSd@L6CXzRVBT/@ddb5Bw "Haskell – Try It Online") Takes input as a list of integers on the range \$[1,26]\$. Outputs a list of `[]` for no match `[1]` for perfect match and `[0]` for imperfect match. This feels like it could be shorter. Having to import `delete` is costly. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~52~~ ~~46~~ 45 bytes ``` {@[g;&[#'(=x)^\:&g;#'y]#'y:(=y)^\:&g:x=y;2+]} ``` [Try it online!](https://ngn.codeberg.page/k#eJxFjlELgjAUhd/3K8YELRJSHyeCSwYKVyYKIZm9qS9S0EuOqN/e5ky5XC58nHPu6ek7bobQbixnF03725XaQ2g5slVLd5E0hE6RDIND+0HoiD08PDvpYl/f7u7iAMtuHB8v1MeUpBxAEOThZb49qZKSFQT5eBmFFlWgFPMqxAuRpJtRoyQ7Z6CRthl04mBUwRp/ESKvdNaGAFjOjPGPOC8zrkt4a1bKgIEp4a9GqGtTYv5pEAD5AU5RRXw=) -1 byte from ngn (thanks!). Starting with a list of positions showing letters that do (green `1`) and don't (grey `0`) match in the secret and guess, amend it as follows: Ignoring the positions that are green, take the first n positions of each letter in the guess (where n is the fewer of the frequency of that letter in the secret versus in the guess), and add `2` to those positions (yellow). [Answer] # [Python 3](https://docs.python.org/3/), 113 bytes ``` lambda g,w:[g[i]-w[i]and~((g[:i]+[a-b or b for a,b in zip(w,g)][i:]).count(g[i])<w.count(g[i]))for i in range(5)] ``` [Try it online!](https://tio.run/##TU67bsMwDNz5FUImsXW8FF2M5ksUDbQt2wRoSZDc2snQX3elqVkOdyTuER/bEvzHedzup9Daj6TmZu/MbNhe9wLkx1@tZ9OxfTd07VVIqldTQWp6xV49Oeq9mdEa7iy2Q/j2m652/NpfFVYPV0ciPzv9ifacbi@dhzZvK0Ud0ljjmn@1o0UAXmNIm8qPDFCzpGYV1eZtZN8mR6Owd1ljByomLsVSfqnsw2Z64ZfFiYQL4pmHRBFcDMMCA/@wQO@k8GcIawYp4wicS@xgISEpFzmOiiJ/ "Python 3 – Try It Online") Uses `-1` for gray, `-2` for yellow and `0` for green. A further 3 bytes can be saved if `-1` is replaced by False and `-2` by True, but I dislike this output format, since `False==0`. Input is a list of charcodes [Answer] # JavaScript, ~~76b~~   ~~72b~~   69b Solution found by @subzey and me while golfing the [MiniWordle](https://xem.github.io/MiniWordle/) project. Thanks to @emanresu for the further improvements ``` // a is the correct word (array of letters) // b is the guessed word (array of letters) a=>b=>b.map((s,i)=>s==a[i]?a[i]=0:s).map(s=>s?a[x=a.indexOf(s)]=~x:1) ``` Returns an array of 5 digits. 0 = black, 1 = green, anything else = yellow For example: `f([..."TEETH"])([..."EERIE"]) == [-3, 1, 0, 0, 0]` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 29 bytes ``` {u+^?/{x@&'x=,\x}'x*\:u:~=/x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxNjs0KgzAQhO8+hc2htrXgT28p0qYSUFiJKBRptUefQCEl6LPXTQLpLnv5mJmdkao5/NwiJe/7QGbnXi6BPPV0pmsWycXzJqq+62WXhOOBFBxAkKs8Lt70Jm3esJoMsW8XmVEMiW8XGa9FXpAh3TT6kOXlswTn1ezBAXWxdlr2EqJqkaXuBwCrGOb9Mc6bkhuv68KAAXaJXR4AdJ3pkri8bUwX/fkHNjdA5Q==) in: `("HELLO";guessedword)`, out: `0`=[bull](https://en.wikipedia.org/wiki/Bulls_and_Cows), `1`=cow, `2`=neither `{` `}` function with implicit argument `x` `~=/x` mask of where letters of the two words differ `u:` assign to `u` `x*\:` multiply by each left - zero out the matching letters `{` `}'` map `,\x` prefixes (of one of the words) `x=,\x` masks of where letter x[i] occurs in x[0...i] `&'x=,\x` where (masks -> lists of indices) `x@&'x=,\x` indexing of x with the above, i.e. for any letter `"a"`, the first occurrence turns into `,"a"` (a string of length 1), the second occurrence into `"aa"`, the third into `"aaa"`, etc. let's call the above *rep-letters* for "replicated letters" `?/` for each rep-letter of the guessed word, find its position among the rep-letters of the secret word; for "not found", use the special null value `0N` `^` mask of nulls `u+` add to `u` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` ⭆θ⎇⁼ι§ηκ+§.-‹№E…θκ⁻λ§ημι№Eη⁻λ§θμι ``` [Try it online!](https://tio.run/##bYxNCsIwFIT3niJk9YKpF3CloVAhRUEvEGIwoTG1@RF7@ph2EwQfDI8ZZj6phZejsDlfvHERrrG8Ry9eMFF0U94JP0M7JWEDGIoO8eTu6gOaooEQivAW1xDvmuK4CgHYmApswbBZWsX0uAKHMumNSwHsD@tJFpgpqkP9pzrV6nr7nI8tZ92mazk/5@Ztvw "Charcoal – Try It Online") Link is to verbose version of code. Outputs `+` for exact match, `-` for near miss and `.` for mismatch. Explanation: ``` θ Guessed word ⭆ Map over letters ι Current letter ⁼ Equal to η Secret word § Indexed by κ Current index ⎇ If true then + Literal string `+` else .- Literal string `.-` § Indexed by № Count of ι Current letter in θ Guessed word … Truncated to length κ Current index E Map over letters λ Inner letter ⁻ Remove match of η Secret word § Indexed by μ Inner index ‹ Is less than № Count of ι Current letter in η Secret word E Map over letters λ Inner letter ⁻ Remove match of θ Guessed word § Indexed by μ Inner index Implicitly print ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 63 bytes ``` s=>g=>g.map((u,i)=>s[i]-u&&s.some((v,j)=>g[j]==v|u-v?0:s[j]=1)) ``` [Try it online!](https://tio.run/##pZDNisIwFEb3PkVWJgEb1KVDKk4JYyFSURicKV2UWPuDGknazGbevZOMFlxHCOG7B869N2lyk2uh6lsbXOWx6E@01zQs7SGX/IZQN6kxDXVaZ0E3Hmui5aVAyEwaS8u0ySg1v11gltOFdtUM4/5HquM8VwpQ4CKgIUgJIS5n/01F5ZioiKhyFdmpqxZhPFJFOxeV02waLBvvknHEXpSCKVgC@AHB4lG3qisc@nIIAojfRkJetTwX5CxL9OiLTmjYDME14zyBGD@hfbRbbS2ym3jYA/Kz2TaJ1t52FH/G3Nt@Z/yF2d9Jstn7v5vtYuZtc84Ph1dsfv@1/g8 "JavaScript (Node.js) – Try It Online") Input array of code points, Output array of 0 = Green, true = Yellow, false = Unhighlighted. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~125~~ ~~122~~ 117 bytes ``` #define F for(i=5;i--;)g[i] i;f(s,g,p)char*s,*g,*p;{F==s[i]?s[i]=1,g[i]=2:0;F,(p=index(g,s[i]))?*p=3:0;F>3?g[i]=4:0;} ``` [Try it online!](https://tio.run/##tVPBbtpAEL3zFSOqBBuMGiA5FNfhUBV@oQisylnWy9LFtjxO6ybi10Nn7DUyhEq91Ah4O/Pe7Oy@sRgqIY7HDxsZ60TCHOI0d3Tw4Ovh0HfVSocd7ccOesrLXLGN8j56feX1M/91HgRI@Rn/BCOPucF4eufPPScLdLKRpaM8TrrurJ8FE049TmYV754Wh6NOCthHOnFceO0APSJNsIBqGygkFvgdVyEE8NrdSmPSrgf/Cxz8vzSgbAMo8ig7E8osFVsGQv/UhsGTNHXkJU33yMCYaB9VZJlrWckjE5k6ZcrSAmOuNSDLTIpCbmwHnAYWLPhhsAT6MOBMDRYLC5aWvGwALBo5WM6SQ7WcZNc6EFspfsjcNrAuv47X5acv9H1gWWs9adQ0PuCwr9UAkOzOt/AzoH6RaexYY92Pdt1vAj4MBhXXrUrVI3HZElLNZjQqcuhf5akTT73jZTl1GDtdlCKXxRTW3Rtc04nUs0RsljB85MtBCrutLag4PD3HMZXFIjcycZQLAxiF1zjYcPCSQ3GR/XbqSudbtFO0O7ZS8SlaC93rZ5d09tPwXB6ezcki5HsctSrza0@ZXW3Zju1a7UK2ZOe2rGgqsLX2GnY0HQGMYQa9RW96xmyeM@aEmct/Yd4zE3pT6H3r@Wd0e4Dq7/YWpBWUFyzr840gI8vWZR3ejQKQ5QmxmonnyqFVHDqH45uITaTwOPz1Bw "C (gcc) – Try It Online") *Saved 5 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)!!!* Inputs a secret and a guess as two strings. Returns the "highlights" as a list of \$2\$s, \$3\$s, and \$4\$s in the second input string. With \$2\$ for green, \$3\$ for yellow, and \$4\$ for unhighlighted. [Answer] # [J](http://jsoftware.com/), 39 31 bytes ``` =(+{.e.&(,.1#.%=%\)/@i.])=|"1,: ``` [Try it online!](https://tio.run/##ddH/a4JAFADw3/0rHm2lR3pmY78cnGTiKLhmNBhR@YO4qzlEh9lGLPrXnV82sXbzOJB3H997vnvLO1jeAiUggwoDIMXWMNgL9pBTpf@FOe4pKjZucJd2N0gfhdhD9NQxVJIDPI4xSAo9rZFC@yE@N9gk1CQb5NXak67ompTy/lYnI50gvWCqStSziCrlIWrzMiCk7QY86m1Qj5ikaQFJJU4O2fshIzAECruU81gFo3g98ihKPssBlGH/WNkdZKkf7yM/43sI4@I72CYpBEn8weOQxwEnlauPIp5lPN2Dppng74MwLOALl3YUw7an3PUOBEkSD14TkFn5yEV@eeIw5sp1eNAs0IrreLIX1vwPGjarQvXRNTKKHPWukDN37cm/5X6QPX2einoqSzVo7DBhJqPd@Mp1ZytBTxeIMWtmCcu1kOMspo5gBIN2TxOLWUw4gmG7HFsuhSOo/@8XXVxL/g0 "J – Try It Online") *-8 bytes thanks to Bubbler!* The above is Bubbler's excellent golf of the "alternate idea" I included in my original post: ``` (~:*[)(=+i.~e.&(,.1#.]=]\)&:>:]i.])~:*] ``` # [J](http://jsoftware.com/), 37 bytes ``` <@(~:*[)(_*])`i.`[} ::[~&.>/@,~~:<@*] ``` [Try it online!](https://tio.run/##ZZFvb9owEMbf51Oc9oIQBm7y1v2jpCgTkdxRUWmqilAw4QB3wYkSp4NJ46szGwhtQNZJlu93d89zft9/I/YC7inY0AUXqI4egf6I/djf@e0d7YyddtyZOFNBpuN/QOl41yIPN353t6N3fmeyd6yfjwSWoAouy5QrLCEawiIrIMnkB0qBMkEKQuaVghSVwqKEXu8BvJ6Qc9wAT/MVn6ECWa1nOkkAskoZ2lCVnGUbnJ@eiLW8JzCmcAuLVtv7Hpja@D1uCeJYByF6vgJeltVaC3FBlJBjscBEwZqrZAXtZYEonS7EhxwvlOBpndtimmZ/dJLLuY4t5FkplPjAkzZTIrPPTnzraLWRlp4Va56Kv3qmWiHwRFW668mGMhW/EXCTax1nL4C8FLqnThfI58Qy0o07wGSV@T1qfLY9Op2Yxet7RPTX@EhaLsQOLG/8iWUZFOxBwAJm60@wByFjQ9vyoD6Hfdgv/VHwrH@YngkX6nMkjs9fiVhXH@NIhM/D/qBB1DNqoh/9itgFYSZ8Eo8hu@oRN5S@DYdPbxc6mgRjwVNwNeUrEYajKLxw6zV0nBZ24dZtTGGvr1duj27OBGv02P8H "J – Try It Online") * Input: 1-indexed integers representing index within the alphabet. * Output: boxed list with the following scheme: + `0` = green + `_` = yellow + positive integers = gray ## idea * Turn perfect matches of both target and guess into 0 by multiplying by the "not-equal" vector `~:`. * Starting with the guess as our "previous value", reduce the letters of the target as follows: + If target letter not found in guess, return guess unaltered + If target letter found, update the first matching index of the guess to infinity `_`. This both "marks" the yellow partial match and ensures the same index won't be found again. + If letter found is a 0 (ie, already marked as a perfect match), update it to 0 (ie, leave it unchanged). Ensures that the reduction only touches yellow matches. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 78 bytes ``` a=>b=>b.map(y=(x,i)=>x-(c=a[i])&&(y[c]=-~y[c]*2,x)).map((x,i)=>x&&!(y[x]>>=1)) ``` [Try it online!](https://tio.run/##nZDBCoJAEIbvvUUX24lcqKusYLKSuKEoRCQetk3KKI2UWC@9um1FRN1cGBj4@L8ZZo78xmtxLS6NWVa7vPNIx4m9VYXP/IJaguSkAGJLEwnC0yIDw0BtKjJi3p9tPJtIgFf2kzSMoUrIzLbJFKCzAiIVxeLAr65a4TQIrIGoyro65fhU7ZGHUozxaEEZC0fZa1YA8IaJGzvRF/Yw/2APk0ahu9AyXX/lMy1zTpnmzk0YLhO9O2nsUy2TMbZe65rs50PdAw "JavaScript (Node.js) – Try It Online") Input charcode/[1,26], output `true`(no), `0`(green), `false`(yellow) # [JavaScript (Node.js)](https://nodejs.org), 82 bytes ``` a=>b=>b.map(y=(x,i)=>x!=(c=a[i])&&(y[c]=-~y[c],x)).map((x,i)=>x&&~~y[x]&&!!y[x]--) ``` [Try it online!](https://tio.run/##jc9RC4IwEAfw976FL3MDty8QE0omCouJQkjiw1oShjnJiPnSV1@a@D44OP7cj@PuIT9yVK92eONe3xobUytpeJ2LPOUAJwpN0CIaGo9CRWXV1ggAOFWqpvi7tMAg9KcbBOA7D0wNgOctHWNk9zul@1F3Den0HcawIoT4CeNc@DVaUxHlh2xOyMFuycWyTESJo43Sc8od7ZFx570XIU6F670sT5mj5ZyXpbvl62/2Bw "JavaScript (Node.js) – Try It Online") `0`(no match), `false`(green), `true`(yellow) [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 92 bytes Returns a list of `-1` for *Green*, `False` for *Yellow* and `True` for not highlighted. ``` lambda*r,c='':[-(a==b)or(c:=c+b).count(b)>sum(y!=x==b for x,y in zip(*r))for a,b in zip(*r)] ``` [Try it online!](https://tio.run/##TU9NSsQwGN3PKWI2ScY4GzdSiKAlMIVIhxmQwXEWTWy14jTlawut4hm8gDBbBQ/gebyA3qAmrQtX73s/8N5XdvWdLY5PSugzcd0/JDt9k0yBG0FIsDmiiRCaWaAmEOZQs5mxTVFTzU6rZke7A9E6H2UWUMs7lBfoMS/pFBjzUsL1P2nbV6mBtEYC4blUKsYTH7pt0qryMbwKl2cLzP9MjuUiDucOw@gyUg7PpRr4VRxfrLwvl5F0qJRar0dUCgcThMB1ZHSs40MBc2oJuZs@UE7I7N7mBcU/@/3b18fr9@eLu97xpt2O3/hFwHhG6BM8M8L6Xw "Python 3.8 (pre-release) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 bytes ``` o@= çW;œ-\⁻Ɲʋç@+= ``` [Try it online!](https://tio.run/##y0rNyan8/z/fwZbr8PJw66OTdWMeNe4@NvdU9@HlDtq2/x/u2ARkPGpaE/n/f7BzkGOAgoerj4@/gmuAv7OHgrNnmKePgpOrD5Ad5e/vG6zg4@Po66jg6hrk6arg4ejj6AMU8YmIAJE@Pv/BegE "Jelly – Try It Online") *-1 because there was a completely extraneous `ɗ`* Target on left, guess on right; `0` for gray, `1` for yellow, `2` for green. Absolutely dreadful... There ought to be some sort of `=þ`-based solution, but I've had no luck yet. ``` o@= Dyadic helper link: mask out exact matches = For each pair of corresponding elements, are they equal? o@ Replace 0s with elements from the left argument, leaving 1s unchanged. çW;œ-\⁻Ɲʋç@+= Main link ç Mask matches out of the target, ç@ mask matches out of the guess, ʋ and with those on the left and right: W; \ Scan across the guess, starting with the masked target, by œ- multiset difference; Ɲ for each pair of adjacent scan results, ⁻ are they not equal? += Add that to the mask of exact matches. ``` [Answer] # [Julia 1.6](https://julialang.org), 72 bytes ``` a\b=(* =.==;c=a*b;b[c]=a[c].=0;c-[sum(b[i]b[1:i])>sum(b[i]a) for i=1:5]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY5BSsNAFIb3c4rXWWVqOlixIA1TiGEggSkpLUhxOoskTWFKnEraQC7g2gMotJuCggfwKt16AT2CmUY3___e__g_3stxXRU6ORyO1W7VuzmFySJlThcYZczLWNJNvVRmiiWNUHbpZT25rR6cVGqVyv5QKzL63xMCq00JmvWHA0X-eE-dGhhI_PXx-v35jF38s9-_tfaO3Wt3oOTVRa0QstUatIEyT5aFNvnWIQgAynM95ELEmFKqFrK2Zk-PpTa7wji1CxjYCLAL6402Du2UxEY2KAnKzbJ95nDyZ8HUn6AzDfFJHIQoiO4igW65aOb7OB7PkBD-2EecTyOOQl_4oknEfG5ViJb0Cw) Fixed and improved version of [mbeltagy's answer](https://codegolf.stackexchange.com/a/242816/98541) Needs version 1.6+ for `(*) = (.==)`. [73 bytes in Julia 1.0](https://tio.run/##TYxBSgMxGIX3OcXfrCY4BkfspiWFOARmIGVKC1JMs8hMR0gZU0kt5BZeQOhWwQN4Hi@gNxgndePmvcf3eG937KzJQt@bTc2ShhnKWD2tVaOZGYSyq2lzqQ7Hx6RWVsdSZROryewfMgQe9h4syyZjTfpRAAYKf328fn@@4BT/nE5vf/aO05t0rNX1RdAIxU0A68C3ZttZ1x4SggDAn@eFkLLClFK9USFarJ68dc@dS0IKGNgMcAq7vXUJHXkSUQSeoNZt@1W@5At0fkFiUeUFysu7UqJbIYd8X1XzFZKSzzkSYlkKVHDJ5UDkeh1Vyl8 "Julia 1.0 – Try It Online") Inputs are vectors of characters, and the output is a vector with `1` for green, `0` for yellow, and `-1` for uncolored [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `t`, ~~24~~ ~~23~~ 21 bytes ``` Z⁰¹-ḃ*∩÷$£0o(¥nuøḞ£)¥ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJ0IiwiIiwiWuKBsMK5LeG4gyriiKnDtyTCozBvKMKlbnXDuOG4nsKjKcKlIiwiIiwiWzgsNSwxMiwxMiwxNV1cblsyLDUsMTIsMyw4XSJd) or [Run all the test cases](https://vyxal.pythonanywhere.com/#WyJ0UCIsIkBmOng6eXzihpB4OsKj4oaQeTrihpIiLCJawqXihpAt4biDKuKIqcO3JMKjMG8owqVudcO44biewqMpwqUiLCI7XG5cbkMgNjQtIOKBsEzhuosgJCBDIDY0LSBaIOKGkmFcbuKGkGEg4oaQYSDGmyDDtyBAZjsgOyBaIMabIMO3ICQgOiA2NCsgQyB24bmFIFogxpsgw7cgYCAoYCBKICQgUyBKIGApYCBKOyBgIGFuZCBgIGogJCA6IMabIDA9W2Dwn5+pYHx1PVtg8J+fqGB8YOKsm2BdXSA7IOG5hSAkIFMgYCAoYCBKICQgSiBgKWAgSiBcIiBgID0+IGAgaiA7IOKBiyIsIkhFTExPXG5bXCJTQ1JBUFwiLFwiSEVMTE9cIixcIkVQT0NIXCIsXCJDSVZJTFwiLFwiQkVMQ0hcIixcIlpPT01TXCIsXCJMTEFNQVwiLFwiRUVSSUVcIixcIkhBTEFMXCIsXCJMTExYWFwiLFwiTExMTExcIl0iXQ==) (it took me way longer to write the code to run the test cases than the program itself lol) Port of 05AB1E answer. Can probably be golfed down a ton. *-1 byte thanks to Aaroneous Miller* [Answer] # [Python 2](https://docs.python.org/2/), 95 bytes ``` lambda g,t:[not a or a in t and t.remove(a)for a in[a[a==b:]or t.remove(a)for a,b in zip(g,t)]] ``` [Try it online!](https://tio.run/##XU/BToQwEL3zFZN4aGsqB48kHJDUQNKVza4xG5FDyRZE2UKgmF2N345T2JNzmHmdN/Pmtb/Y987cz1X4NrfqVB4V1NwGueksKOgGTI0BxOYI1h/0qfvSVLHqyuQqV2FYBgW@/9O8dKvfTU9RkRXF/KkvgBHCz1NndEBuCX9U7YjojvDnYUJwQ379WlvPqgELjpJESJkRzynWkx5Hp0n28S7awkKB2GZxAnH6kkp4EBLxa5Zt9iBltIlAiF0qIIlkJLEjDweXpST@2LeNpSzwAAY9Tq07VtG2GS1d7jC@4NUIYzjWD425khzWPgdC/I@uMRT/Rs8MnM2zs7hqMjb/AQ "Python 2 – Try It Online") Loops over the guess twice, while removing characters from the target. Direct matches are removed in the first loop, indirect matches in the second. Requires two `list`s as input. Outputs a `list` containing 5 elements: `True` for direct match, `None` for indirect match and `False` for no match. ]
[Question] [ Out of all the years I've been making this challenge, 2017 is the first year that's been a prime number. So the question will be about prime numbers and their properties. Your task is to produce a program or function that will take an arbitrarily large positive integer as input, and output or return whether or not the number is *2,017-friable* — that is, whether the largest prime factor in that number is 2,017 or less. --- Some example inputs and their outputs: ``` 1 (has no prime factors) true 2 (= 2) true 80 (= 2 x 2 x 2 x 2 x 5) true 2017 (= 2017) true 2019 (= 3 x 673) true 2027 (= 2027) false 11111 (= 41 x 271) true 45183 (= 3 x 15061) false 102349 (= 13 x 7873) false 999999 (= 3 x 3 x 3 x 7 x 11 x 13 x 37) true 1234567 (= 127 x 9721) false 4068289 (= 2017 x 2017) true ``` Your program does not have to literally output `true` and `false` — any truthy or falsy values, and in fact any two different outputs that are consistent across true and false cases are fine. --- However, you may not use any *primes* in your source code. Primes come in two types: * Characters, or sequences of characters, that represent prime number literals. + The characters `2`, `3`, `5`, and `7` are illegal in languages where numbers are valid tokens. + The number `141` is illegal because it contains `41`, even though `1` and `4` are otherwise valid. + The characters `B` and `D` (or `b` and `d`) are illegal in languages where they are typically used as 11 and 13, such as CJam or Befunge. * Characters that have prime-valued Unicode values, or contain prime-valued bytes in their encoding. + The characters `%)+/5;=CGIOSYaegkmq` are illegal in ASCII, as well as the carriage return character. + The character `ó` is illegal in UTF-8 because its encoding has `0xb3` in it. However, in ISO-8859-1, its encoding is simply `0xf3`, which is composite and therefore okay. The shortest code to do the above in any language wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` 44‘²!*ḍ@ ``` [Try it online!](https://tio.run/nexus/jelly#@29i8qhhxqFNiloPd/Q6/P//38jAyBwA "Jelly – TIO Nexus") Note that test cases **11111** and above are a bit too much for TIO. ### Verification ``` $ source="34,34,fc,82,21,2a,d5,40" $ xxd -ps -r > 2017.jelly <<< $source $ xxd -g 1 2017.jelly 0000000: 34 34 fc 82 21 2a d5 40 44..!*.@ $ eval printf '"%d "' 0x{$source}; echo # Code points in decimal 52 52 252 130 33 42 213 64 $ test_cases="1 2 80 2017 2019 2027 11111 45183 102349 999999 1234567 4068289" $ for n in $test_cases; do printf "%11d: %d\n" $n $(jelly f 2017.jelly $n); done 1: 1 2: 1 80: 1 2017: 1 2019: 1 2027: 0 11111: 1 45183: 0 102349: 0 ``` Test case **999999** has been running for 13 hours. I'm pessimistic about computing **2025!4068289**... ### How it works ``` 44‘²!*ḍ@ Main link. Argument: n 44 Yield 44. ‘ Increment to yield 45. ² Square to yield 2025. Note that no integers in [2018, ..., 2025] are prime numbers. ! Take the factorial of 2025. * Raise it to the n-th power. This repeats all prime factors in 2025! at least n times, so the result will be divisible by n if (and only if) all of its prime factors fall in the range [1, ..., 2025]. ḍ@ Test the result for divisibility by n. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 characters, 14 bytes of UTF-8 ``` Æf½ṀḤ<90 ``` [Try it online!](https://tio.run/nexus/jelly#@3@4Le3Q3oc7Gx7uWGJjafD//38jA0NzAA "Jelly – TIO Nexus") Jelly normally uses its own codepage for programs. However, most of its prime-related builtins start with `Æ`, which is codepoint 13; not very helpful. Luckily, the interpreter also supports UTF-8, which has a friendlier encoding. ## Verification This program, in UTF-8, hexdumps like this: ``` 00000000: c386 66c2 bde1 b980 e1b8 a43c 3930 ..f........<90 ``` Verification that all the bytes are composite: ``` $ for x in c3 86 66 c2 bd e1 b9 80 e1 b8 a4 3c 39 30; do factor $((0x$x)); done 195: 3 5 13 134: 2 67 102: 2 3 17 194: 2 97 189: 3 3 3 7 225: 3 3 5 5 185: 5 37 128: 2 2 2 2 2 2 2 225: 3 3 5 5 184: 2 2 2 23 164: 2 2 41 60: 2 2 3 5 57: 3 19 48: 2 2 2 2 3 ``` Verification that all the Unicode codepoints are composite: ``` $ perl -Mutf8 -E '$a = ord, print `factor $a` for split //, "Æf½ṀḤ<90"' 198: 2 3 3 11 102: 2 3 17 189: 3 3 3 7 7744: 2 2 2 2 2 2 11 11 7716: 2 2 3 643 60: 2 2 3 5 57: 3 19 48: 2 2 2 2 3 ``` The only token parsed as a number is `90`. None of `9`, `0`, and `90` are prime. ## Explanation The main mathematical insight here is that 45² is 2025, which neatly falls between 2017 (the current year) and 2027 (the next prime). Thus, we can take the square root of every prime factor of the number, and see if any exceeds 45. Unfortunately, we can't write `45` due to the literal `5`, so we have to double it and compare to 90 instead. ``` Æf½ṀḤ<90 Æf In the list of prime factors, ½ taking the square root of each element Ṁ then taking the largest element Ḥ and doubling it <90 produces a result less than 90. ``` [Answer] # Mathematica, ~~62~~ ~~58~~ 55 bytes *The last three bytes saved are totally due to Martin Ender!* ``` #4<4||#<44*46&&#6[#^-1#4]&[Divisors[#][[6-4]],,,#,,#0]& ``` Unnamed function taking a positive integer argument and returning `True` or `False`. Recursive algorithm, with `#4<4` being the truthy base case (we only need it to return `True` on the imput 1, but the extra base cases are fine). Otherwise, we compute the second-smallest divisor (which is necessarily prime) of the input with `Divisors[#][[6-4]]`; if it's greater than 2024 (`44*46`) then we exit with `False`, otherwise we call the function recursively (using `#6` set to `#0`) on the input divided by this small prime factor `#` (which we have to express as `#^-1` times the input `#4`, since `/` is disallowed). Structurally, the first half `#4<4||#<44*46&&#6[#^-1#4]&` is an anonymous function of six arguments, being called with arguments `Divisors[#][[6-4]]`, `Null`, `Null`, `#`, `Null`, and `#0`; this is to get around the prohibition on the characters `2`, `3`, and `5`. Previous version, which saved four bytes by replacing `8018-6000` with `44*46`, inspired by [ais523's Jelly answer](https://codegolf.stackexchange.com/a/105250/56178) (Martin Ender also seemed inspired by an ais523 comment): ``` #<4||Divisors[#][[6-4]]<44*46&&#0[Divisors[#][[6-4]]^-1#]& ``` This was pretty nasty: I still don't know a way to actually set a variable in Mathematica under these restrictions! Both `=` and the `e` in `Set` are disallowed. Avoiding `+` and `)` was also an issue, but not too hard to work around at the expense of more bytes. [Answer] # Haskell, ~~48~~ 47 bytes ``` \n->[snd$[product[1..44*46]^n]!!0`divMod`n]<[1] ``` Basically a translation of [Dennis’ Jelly answer](https://codegolf.stackexchange.com/a/105253/3852). xnor saved a byte. Uses `[…]!!0` as parentheses because `)` is banned, and `snd` + `divMod` because the `m` in `mod` and `rem` is banned. [Answer] ## Pyke, ~~10~~ ~~8~~ ~~7~~ 9 bytes ``` P_Z|hwMX< ``` [Try it here!](http://pyke.catbus.co.uk/?code=P_Z%7ChwMX%3C&input=1) Saved 1 byte by using Dennis's way of generating 2025 ``` P - factors(input) _ - reversed(^) Z| - ^ or 0 h - ^[0] or 1 < - ^ < V wM - ⁴45 (ord("M")-32) X - ^**2 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~9~~ 10 bytes ``` *$ph$r*<90 ``` [Try it online!](https://tio.run/nexus/brachylog#@6@lUpChUqRlY2nw/78hAA) Basically using the same algorithm as my other answer. `$ph` finds the first (`h`) prime factor (`$p`); this is the largest prime factor, as Brachylog's prime factor lists go from largest to smallest. Then I take the square root (`$r`), double (`*`), and test to see if it's less than 90 (`<90`). I had to double the input first because 1 has no prime factors (and thus no first prime factor). This adds an extra prime factor of 2, which can't affect whether a number is 2017-friable, but prevents a failure when handling 1. [Answer] # [Actually](https://github.com/Mego/Seriously), 9 bytes ``` τyM:44u²≥ ``` Thanks to Dennis for lots of bytes! [Try it online!](https://tio.run/nexus/actually#@3@@pdLXysSk9NCmR51L//83BAA "Actually – TIO Nexus") Explanation: ``` τyM:44u²≥ τyM largest prime factor of 2*input (doubled to deal with edge case of n = 1) :44u² 2025 (2027 is the next prime after 2017, so any number in [2017, 2026] can be used here - 2025 is very convenient) ≥ is 2025 greater than or equal to largest prime factor? ``` [Answer] ## Mathematica, 66 74 bytes *Thanks to Dennis for pointing out that `U+F4A1` is prohibited.* ``` Fold[Function[{x,d},And[x,Tr[Divisors@d^0]>6-4||d<44*46]],0<1,Divisors@#]& ``` Explanation: `Divisors@#`: List of integer divisors of the first argument `#`. `0<1`: Golf for `True` (also avoids the use of the letter `e`). `Divisors@d^0`: List of the form `{1, 1, ..., 1}` with length equal to the number of divisors of `d`. `Tr`: For a flat list, `Tr` returns the sum of that list. Thus `Tr[Divisors@d^0]` returns the number of divisors of `d`. `Function[{x,d},And[x,Tr[Divisors@d^0]>6-4||d<44*46]]`: Anonymous function with two arguments `x` and `d`. The idea is that `d` is a divisor of `#` and we test to see if it is either composite or less than or equal to `2017` (inclusive). `2017`-friability is equivalent to all the divisors satisfying this condition. As [ais523](https://codegolf.stackexchange.com/a/105250/61980) discovered, being a prime less than or equal to `2017` is equivalent to being a prime less than `2025`. As [Greg Martin](https://codegolf.stackexchange.com/a/105248/61980) pointed out, it suffices to test whether it is less than `2024=44*46`. The argument `x` acts as an accumulator for whether all of the divisors encountered so far satisfy this property. We then left [`Fold`](http://reference.wolfram.com/language/ref/Fold.html?q=Fold) this function through all of the divisors of `#` with starting value `True`, since we have access to neither `Map` nor `/@`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` fθ46n99-›È ``` Returns 1 if true, 0 otherwise. [Try it online!](https://tio.run/##MzBNTDJM/f8/7dwOE7M8S0vdRw27Dnf8/29kYGgOAA "05AB1E – Try It Online") **Explanation** ``` f # Push the list of prime factors (ordered) θ # Get the last element 46n99- # Push 2017 (46² - 99) > # Push 1 if the last prime factor is greater than 2017, 0 otherwise È # Is the resulting number even ? Transforms 1 to 0 and 0 to 1. # Implicit display ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 15 bytes ``` t:\~ftZp*44QU<A ``` Outputs `0` for non-2017-friable or `1` for 2017-friable. [Try it online!](https://tio.run/nexus/matl#@19iFVOXVhJVoGViEhhq4/j/v6GRsYmpmTkA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#U3L4X2IVU5dWElWgZWISGGrj@P9/tKGCkYKFgYKRgaE5iLAEEkbmCoYgoGBiamhhrGBoYGRsYqlgCQYKhkCOqZl5LAA). [This program](https://tio.run/nexus/matl#@5@lAAKqCkGpiSkKOZl5qVxRBRARz2LdgqLM3FSFtNK85JLM/Lz//0usYurSSqIKtExMAkNtHAE) checks that all bytes are composite. ### Explanation ``` t % Implicit input n. Duplicate : % Range [1 2 ... n] \ % Modulo. Gives 0 for divisors of n ~f % Indices of zero values t % Duplicate Zp % Is-prime. Gives 1 for primes, 0 for composites * % Multiply 44QU % 44, add 1, square: 2025 < % Less than, element-wise A % True (1) if all entries are nonzero ``` [Answer] # Bash, 144 bytes ASCII encoding: ``` { printf '[ ' `tr D-Z _-z <<<KFH`tor $1|tr -d :|`tr B-Z _-z <<<JUH`p -o '[0-9]*$' printf ' -lt $[24*86-46] ]' }|tr \\n \ |`tr B-Z _-z <<<EDVK` ``` As usual for shell, the exit code indicates success (0) or failure (non-0). This is effectively a different spelling of ``` [ factor $1|tr -d :|grep -o '[0-9]*$' -lt 2018 ] ``` We get the largest factor with `factor $1|grep -o '[0-9]*$'`; the `tr -d :` is to special-case for input = `1`. The expression `$[6*6*69-466]` evaluates to 2018. It was tricky to use `tr` for the command names and still use command substitution - I couldn't use the nesting form `$( )`, so I ended up piping into another Bash to evaluate the result. Test results: ``` $ for i in 1 2 80 2017 2019 2027 11111 45183 102349 999999 1234567 4068289; do printf '%d %s\n' $i `./105241.sh $i && echo true || echo false`; done 1 true 2 true 80 true 2017 true 2019 true 2027 false 11111 true 45183 false 102349 false 999999 true 1234567 false 4068289 true ``` Confirmation of character codes: ``` $ grep -v '^#' ./105241.sh | perl -n -Mutf8 -E '$a = ord, print `factor $a` for split //, $_' | grep -v ': .* ' | wc -l 0 ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), ~~21~~ 19 bytes ``` ϼ↕1⦋91+₂⬠1+Đ1+⬠⇹₂-> ``` [Try it online!](https://tio.run/##K6gs@f///J5HbVMNHy3rtjTUftTU9GjNAkPtIxOA7DULHrXvBIro2v3/bwoA "Pyt – Try It Online") This uses [Pyt's custom encoding](https://github.com/mudkip201/pyt/wiki/Codepage), in which all of the characters used are non-prime bytes. It returns `false` if the number IS 2017-friable, and `true` if it is not. | code | action | | --- | --- | | `ϼ` | gets the unique prime factors of the input | | `↕1⦋` | gets the largest of those | | `91+₂⬠1+Đ1+⬠⇹₂-` | pushes 2017 | | `>` | is the largest prime factor greater than 2017?; implicit print | [Answer] # Pyth, 11 bytes ``` !s>R^h44h1P ``` [Try it online.](https://pyth.herokuapp.com/?code=%21s%3ER%5Eh44h1P&input=4068289&test_suite_input=1%0A2%0A80%0A2017%0A2019%0A2027%0A11111%0A45183%0A102349%0A999999%0A1234567%0A4068289&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=%21s%3ER%5Eh44h1P&input=4068289&test_suite=1&test_suite_input=1%0A2%0A80%0A2017%0A2019%0A2027%0A11111%0A45183%0A102349%0A999999%0A1234567%0A4068289&debug=0) Uses [Dennis's trick](https://codegolf.stackexchange.com/a/105253/30164) to get 2025, then checks if no prime factors of input are greater. [Answer] # [Julia 0.4](http://julialang.org/), ~~84~~ ~~38~~ 37 bytes ``` n->1^n:44*46|>prod|>t->t^n-t^n÷n*n<1 ``` Expects a *BigInt* as argument. [Try it online!](https://tio.run/nexus/julia#FcRBCsIwFEXRsV3Fp1BIyg80IVoVDe5D7UBiSiavJWbYfbkAFxbbC/cEuhYopwecrW3tYXFzmvzisnJ5gFr/fdHiokuYEoEi6BVHcdds@Nix6XS/cVoxPeutp6x2tzlF5CDqZu9JOWo@D9RMYAoCUlZv@PIH "Julia 0.4 – TIO Nexus") or [verify that no byte is prime](https://tio.run/nexus/julia#@5@bWKCRWVxQlJmbqqOQpJSna2cYl2dlYqJlYlZjV1CUn1JjV6JrVxKXpwvEh7fnaeXZGCppKtTYKRRn5Jf//w8A "Julia 0.4 – TIO Nexus"). [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` k æ¨44*46 ?0:1 ``` Returns 1 if true, 0 if false. Try it [here](http://ethproductions.github.io/japt/?v=1.4.3&code=ayDmqDQ0KjQ2ID8wOjE=&input=OTk5OTk5IA==). [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), 11 bytes [very non-competing] ``` VRp#ߢ-?0:1 ``` [Try it online!](https://tio.run/##SypKzMxLz89J@/8/LKhA@f4iXXsDK8P///8bGoABAA "Braingolf – Try It Online") Unreadable due to the `ߢ` which screws with the numbers, however still works in an interpreter. I didn't even notice the character restrictions when I wrote this, but all I had to do was change the weird unicode character from 2017 to 2018. Given 2018 is not a prime, any prime `<= 2018` is also `<= 2017` ### Explanation ``` VRp#ߢ-?0:1 Implicit input from command-line args VR Create stack2, return to stack1 p Split last item into prime factors, push each one to stack in asc order #ߢ Push 2018 - Subtract last 2 items (highest prime factor - 2017) ? If last item > 0.. 0 ..push 1 : Else.. 1 ..Push 1 Implicit output of last item on stack ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-!`](https://codegolf.meta.stackexchange.com/a/14339/), 12 [bytes](https://en.wikipedia.org/wiki/UTF-8) Japt gets jipped here 'cause `k` is our built-in for prime factors, and `#` converts characters to their codepoints. ``` â fj d¨44*46 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=4iBmaiBkqDQ0KjQ2&input=NDA2ODI4OQ) ]
[Question] [ Lots of people on this site use [esoteric languages](https://esolangs.org/wiki/Main_Page), and since these languages are unusual and hard to understand, they will frequently write an explanation in a certain format. For example, if the code was ``` abcdefghijklmnop ``` And this languages uses `#` for comments, they would write an explanation like this: ``` a #Explanation of what 'a' does bc #Bc d #d e #Explanation of e fgh #foobar ij #hello world k #etc. l #so on mn #and op #so forth ``` I frequently do this too, but every time I do this, I feel like creating the layout of text is really obnoxious and time-consuming. So I want you to create a "Esolang-Comment-Template-Generator" for me. For example, if we ignore the comments, the previous code has this template: ``` a # bc # d # e # fgh # ij # k # l # mn # op # ``` # The Challenge: You must write a program or function that takes two strings as input, and outputs this "Esolang-Comment-Template". The first input will be the code, but with bars (`|`) inserted where the newlines go. The second input is what we will use for comments. So our last example would have this for input: ``` "a|bc|d|e|fgh|ij|k|l|mn|op", "#" ``` Unfortunately this excludes bars from being part of the code input, but that's OK. You can assume that the comment input will be a single character. For simplicity's sake, the comment char will not be a bar. The code input will only contain printable ASCII, and it will not contain any newlines. Hopefully you can infer what to do from the testcases, but I'll try to clarify some things. You must split the code input up into "code-sections" on every bar. Then, each section of code is output on its own line and left-padded with the length of all the previous code (not including the bars). Then, each line is right-padded with enough spaces so that the last two characters on every line are "One additional space" + "The comment character". One trailing newline is allowed. Here is another example. For the input ``` "Hello|World", "/" ``` The first *section* of code is "Hello" and the second is "World". So it should give the output: ``` Hello / World / ``` Here are some more samples: ``` Input: "a|b|c|d|e|f|g", "," Output: a , b , c , d , e , f , g , Input: "abcdefg", ":" Output: abcdefg : Input: "4|8|15|16|23|42", "%" Output: 4 % 8 % 15 % 16 % 23 % 42 % Input: "E|ac|h s|ecti|on is| one c|haracte|r longer| than the| last!", "!" Output: E ! ac ! h s ! ecti ! on is ! one c ! haracte ! r longer ! than the ! last! ! Input: "This|Code|has||empty||sections", "@" Output: This @ Code @ has @ @ empty @ @ sections @ ``` # Rules: You may take these inputs and outputs in any reasonable format. For example, reading/writing a file, STDIN/STOUT, function arguments/return value, etc. As usual, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to make your code as short as possible and you win if you can get the shortest solution in your language! I will also select the shortest solution as the overall winner. [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are banned. [Answer] ## [Retina](http://github.com/mbuettner/retina), ~~35~~ 34 bytes Byte count assumes ISO 8859-1 encoding. ``` \| ·$'¶$`± T0-2`·±|p`___ `.+±.|·.+ ``` The two input strings are separated by a space (which is unambiguous since we know that the comment delimiter is always a single character). [Try it online!](http://retina.tryitonline.net/#code=XHwKwrckJ8K2JGDCsQpUMC0yYMK3wrF8cGBfX18gYC4rwrEufMK3Lis&input=RXxhY3xoIHN8ZWN0aXxvbiBpc3wgb25lIGN8aGFyYWN0ZXxyIGxvbmdlcnwgdGhhbiB0aGV8IGxhc3QhICE) [Answer] # Java 11, ~~189~~ ~~159~~ 136 bytes ``` s->c->{int p=0;for(var a:s.split("\\|"))System.out.println(" ".repeat(p)+a+" ".repeat(s.replace("|","").length()-(p+=a.length())+1)+c);} ``` -30 bytes converting Java 7 to Java 10 and optimizing the loops. -23 bytes converting Java 10 to Java 11, so `String#repeat` builtin can be used. [Try it online.](https://tio.run/##bVLBbhshEL37KyZbVQHtmtZJWlVxbFWyWuXSUyr1kPQwZtldHBYQYEtWxt/uYnvVxlUuCHhv3vDmscINjlf1814ajBF@oLYvI4CYMGkJq4yKddJGNGsrk3ZWfB82dw8paNtWb3EWzsZ1r8LdosOAMqkwn0MDs30cz@V4/qJtAj/7OG1cYBsMgLdRRG90YsXTExWcP2xjUr1w6yR87pKMZQUUIiivMDHPSyxfneNhY1AqVlBRFQUXRtk2dYyPmS9n@PfIywkvJZ/u9tNRNunXS5NNDl43TtfQZ//s5OzxNyA/zAIgqZifhrSUVJOipu1Ir@iZDPWWnC@qy3eXfPqKeq@McfTLBVNn8MM5mHVoEKI2w9V/8FLWqjkAt@fADX2hySeafKara7q5yoT354RvhJI6iKRyDOQs6EjgrIJ8e8qBAhhnWxUIUoc2L4ogB58ustrFudrPLpcvXK1ycSRSvU9boqiOEcfM/3ri70b//stxhsfy0wwhVjK3BjkMEhqB3psti1yglMonJoem8Ebmg/5u/wc) **Explanation:** ``` s->c->{ // Method with String & char parameters and no return-type int p=0; // Position-integer, starting at 0 for(var a:s.split("\\|")) // Loop over the parts split by "|": System.out.println( // Print with trailing newline: " ".repeat(p) // `p` amount of spaces +a // plus the current part " ".repeat(s.replace("|","").length()-(p+=a.length())+1) // plus the correct trailing amount of spaces // (and add the length of the current part to `p` at the // same time) +c);} // plus the current comment character ``` [Answer] # Pyth - ~~28~~ ~~27~~ ~~24~~ 23 bytes ~~Might be able to golf a little off.~~ A lot off, apparently! ``` jt+R+;zC.t.u+*lNdYcQ\|k ``` [Try it online here](http://pyth.herokuapp.com/?code=jt%2BR%2B%3BzC.t.u%2B%2alNdYcQ%5C%7Ck&input=%22a%7Cbc%7Cd%7Ce%7Cfgh%7Cij%7Ck%7Cl%7Cmn%7Cop%22%0A%23&debug=0). [Answer] ## Pyke, ~~31~~ ~~28~~ 24 bytes ``` \|cDslF2l-hd*Q+Zi:il?+ZK ``` [Try it here!](http://pyke.catbus.co.uk/?code=%5C%7CcDslF2l-hd%2aQ%2BZi%3Ail%3F%2BZK&input=%23%0Aa%7Cbc%7Cd%7Ce%7Cfgh%7Cij%7Ck%7Cl%7Cmn%7Cop) [Answer] ## JavaScript (ES6), 92 bytes ``` f= (s,c)=>s.split`|`.map((_,i,a)=>a.map((e,j)=>i-j?e.replace(/./g,` `):e).join``+` `+c).join` ` ; ``` ``` <div oninput=o.textContent=f(s.value,c.value)><input id=s placeholder=Code><input id=c size=1 maxlength=1 value=#><pre id=o> ``` [Answer] # GNU sed (85 + 1 for -r) 86 ``` :s;h;:;s,\|( *)[^ \|](.),|\1 \2,;t;s,\|,,g p;g;:l;s,^( *)[^ \|],\1 ,;tl;s,\|,,;/\S/bs ``` The inputs are strings separated by a space. **Tests:** input.txt: ``` a|b|c|d|e|f|g , abcdefg : 4|8|15|16|23|42 % E|ac|h s|ecti|on is| one c|haracte|r longer| than the| last! ! This|Code|has||empty||sections @ ``` Output: ``` $ cat input.txt | sed -rf template a , b , c , d , e , f , g , abcdefg : 4 % 8 % 15 % 16 % 23 % 42 % E ! ac ! h s ! ecti ! on is ! one c ! haracte ! r longer ! than the ! last! ! This @ Code @ has @ @ empty @ @ sections @ ``` [Answer] # Python 2, ~~107~~ ~~105~~ ~~102~~ 99 bytes Tested with all test cases above **EDIT** Golfed off 2 bytes by changing d=a.split("|");i=0 to d,i=a.split("|"),0 Not sure how I missed that one. Thanks @Oliver Ni Another 3 bytes gone. Thanks again. Suggestion from @Jonathan actually saves 3 bytes and takes it down to the magic 99. Thanks. ``` def c(a,b): d,i=a.split("|"),0 for e in d:j=i+len(e);print" "*i+e+" "*(len("".join(d))-j+1)+b;i=j ``` [Answer] # Haskell, ~~139~~ 135 bytes ``` s#p=j$foldl g("",0)s where g(a,n)c|c=='|'=(j(a,n)++"\n"++q n,n)|1>0=(a++[c],n+1);q m=' '<$[1..m];j(a,n)=a++q(sum[1|c<-s,c/='|']-n+1)++p ``` Saved 4 bytes by inlining a definition. **Ungolfed:** ``` template :: String -> String -> String template code comment = format $ foldl g ("", 0) code where g (acc, n) c | c == '|' = (format (acc, n) ++ "\n" ++ spaces n, n) | otherwise = (acc ++ [c], n+1) l = length $ filter (/= '|') code spaces n = replicate n ' ' format (acc, n) = acc ++ spaces (l-n+1) ++ comment ``` [Answer] # Groovy, ~~120~~ ~~113~~ 111 Bytes ``` def m(s,c){s.split(/\|/).inject(0,{e,t->println((' '*e+t).padRight(s.replace('|','').size()+1)+c);e+t.size()})} ``` **ungolfed\*** ``` def m(s,c){ s.split(/\|/).inject(0, { e, t -> println((' '*e+t).padRight(s.replace('|','').size())+' '+c) e+t.size() }) } ``` # (First Draft with 120 Bytes) ``` def m(s,c){def l=0;s.split(/\|/).collect{l+=it.size();it.padLeft(l).padRight(s.replace('|','').size())+' '+c}.join('\n')} ``` **ungolfed\*** ``` def m(s,c){ def l=0 // minimized version needs a semicolon here s.split(/\|/).collect{ l+=it.size() // minimized version needs a semicolon here it.padLeft(l).padRight(s.replace('|','').size())+' '+c }.join('\n') } ``` **Tests** ``` %> m('a|bc|d|e|fgh|ij|k|l|mn|op', '#') a # bc # d # e # fgh # ij # k # l # mn # op # %> m('Hello|World', '/') Hello / World / %> m('a|b|c|d|e|f|g', ',') a , b , c , d , e , f , g , %> m('abcdefg', ':') abcdefg : %> m('4|8|15|16|23|42', '%') 4 % 8 % 15 % 16 % 23 % 42 % %> m('E|ac|h s|ecti|on is| one c|haracte|r longer| than the| last!', '!') E ! ac ! h s ! ecti ! on is ! one c ! haracte ! r longer ! than the ! last! ! %> m('This|Code|has||empty||sections', '@') This @ Code @ has @ @ empty @ @ sections @ ``` [Answer] # Python 2, ~~125 124~~ 132 bytes -1 byte thanks to @TuukkaX (missed golfing the space from `i, v`) ``` def g(s,c):x=s.split('|');print((' '+c+'\n').join(' '*len(''.join(x[:i]))+v+' '*len(''.join(x[i+1:]))for i,v in enumerate(x))+' '+c) ``` All test cases on [**ideone**](http://ideone.com/MWZ0Lx) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~29~~ ~~38~~ ~~31~~ 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '|„ǝʒ:'ǝ¡'ʒмεD®>úsg®+©s}.Bεð²J, ``` Can definitely be golfed, but at least its working now.. +9 bytes because `¡` (split) removes empty items automatically, so I had to add `'|„ǝʒ:'ǝ¡'ʒм`.. [Try it online.](https://tio.run/##AUYAuf8wNWFiMWX//yd84oCex53Kkjonx53CoSfKktC8zrVEwq4@w7pzZ8KuK8Kpc30uQs61w7DCskos//9hYmN8ZHxlfHxmZwoh) **Explanation:** ``` '|¶: # Take the first input, and replace every "|" with "¶" # i.e. "abc|d|e||fg" → "abc¶d¶e¶¶fg" (¶ are new-lines in 05AB1E) .B # Box all the items (appending trailing whitespace to make it a rectangle) # i.e. "abc¶d¶e¶¶fg" → ['abc','d ','e ',' ','fg '] εðÜ} # Remove all trailing spaces from each item # i.e. ['abc','d ','e ',' ','fg '] → ['abc','d,'e','','fg'] # NOTE: `'|¡` would have resulted in ['abc','d','e','fd'], hence the use of # Box which implicitly splits on new-lines to keep empty items ε # For-each: D # Duplicate the current item ®>ú # Prepend global_variable + 1 amount of spaces # (+1 because the global_variable is -1 by default) # i.e. "e" and 3+1 → " e" sg # Swap so the duplicated item is at the top, and take its length ®+ # Sum it with the global_variable # i.e. "e" (→ 1) and 4 → 5 © # And store it as new global_variable s # Then swap so the space appended item is at the end again } # And end the for-each loop .B # Box all the items (appending the appropriate amount of spaces) # i.e. ['abc',' d',' e',' ',' fg'] # → ['abc ',' d ',' e ',' ',' fg'] ε # For-each again: ð # A space character I # The second input-character J # Join both together with the current item , # And print the current row with trailing new-line ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) There's a byte to be saved here, *at least*, I just can't quite see it. ``` q| ËùT±DÊÃú Ë+ViS ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=cXwgy/lUsUTKw/ogyytWaVM&input=ImF8YmN8ZHxlfGZnaHxpanxrfGx8bW58b3AiCiIjIg) ``` q| ËùT±DÊÃú Ë+ViS :Implicit input of strings U=programme & V=character q| :Split U on | Ë :Map each D ù : Left pad with spaces to length T± : Increment T (initially 0) by DÊ : Length of D à :End map ú :Right pad each with spaces to length of longest Ë :Map + : Append Vi : V prepended with S : Space :Implicit output joined with newlines ``` [Answer] ## PowerShell v2+, ~~103~~ 99 bytes ``` param($a,$b)$a-split'\|'|%{" "*$l+$_+" "*(($a-replace'\|').length+1-$_.length-$l)+$b;$l+=$_.Length} ``` Takes input as two strings, `-split`s the first on literal pipe (since split uses regex syntax), and feeds the elements into a loop `|%{...}`. Each iteration, we construct a string as being a number of spaces defined by `$l` concatenated with the current element. For the first loop, `$l` initializes to `$null`, which gets evaluate here as `0`. That string is further concatenated with another number of spaces (defined by how long `$a` would be if we `-replace`d every pipe with nothing, plus `1` for the additional padding between code and comments, minus the `.length` of the current element, minus `$l` which is how many spaces we padded left on this iteration), concatenated with our comment character `$b`. That's left on the pipeline. We then update `$l` for the next iteration. The resultant strings are all left on the pipeline, and output via implicit `Write-Output` happens at program execution, with a newline between them by default. ### Examples ``` PS C:\Tools\Scripts\golfing> .\esolang-comment-template-generator.ps1 "This|Code|has||empty||sections" "@" This @ Code @ has @ @ empty @ @ sections @ PS C:\Tools\Scripts\golfing> .\esolang-comment-template-generator.ps1 "a|bc|def|ghi|h" "|" a | bc | def | ghi | h | ``` [Answer] # Vim, ~~39~~ 38 keystrokes -1 byte thanks to DJMcMayhem Expects as input a buffer (e.g. a file) whose first character is the comment delimiter, followed by the code, e.g. `#foo|bar|baz`. ``` "cxqaf|m`Yp<Ctrl+o>v$r jv0r x@aq@a$p<Ctrl+v>gg$C <Ctrl+r>c<Esc> ``` ## Explanation ("`_`" denotes a literal space.) ``` "cx " Delete the first character (the comment delimiter) and store in register 'c' qa " Start recording macro 'a' f|m` " Advance to the first '|' on the line and set mark Yp<Ctrl+o> " Duplicate this line and return to mark v$r_ " Replace everything after the cursor on this line (inclusive) with spaces jv0r_x " Go down a line and replace everything before the cursor on this line (inclusive) with " spaces, then delete one space @a " Call macro recursively q@a " Stop recording and immediately call the macro $p " Paste the deleted space at the end of the last line <Ctrl+v>gg$ " Highlight the column where the comment delimiters will go and all trailing spaces C_<Ctrl+r>c<Esc> " Replace the highlighted text on each line with a space and the contents of " register 'c' (the comment delimiter) ``` [Answer] # [Floroid](https://github.com/TuukkaX/Floroid) - 94 bytes ``` Ah(a,b):c=a.fn("|");z(" "+b+"\n".y(' '*Z("".y(c[:j]))+l+" "*Z("".y(c[j+1:]))Kj,lIai(c))+' '+b) ``` Uses an approach similar to @[JonathanAllan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)s' Python solution. ## Testcases ``` Call: h("a|bc|d|e|fgh|ij|k|l|mn|op", "#") Output: a # bc # d # e # fgh # ij # k # l # mn # op # ``` [Answer] # C# 176 167 154 bytes ``` string f(string s,char x){var c=s.Split('|');var d="";int i=0;foreach(var b in c)d+=b.PadLeft(i+=b.Length).PadRight(s.Length+2-c.Length)+x+"\n";return d;} ``` UnGolfed ``` string f(string s, char x) { var c = s.Split('|'); var d = ""; int i = 0; foreach (var b in c) d += b.PadLeft(i += b.Length).PadRight(s.Length + 2 - c.Length) + x + "\n"; return d; } ``` A LINQ solution would have been 146 but needed `using System.Linq;` bringing it back up to 164: ``` string f(string s,char x){var c=s.Split('|');int i=0;return c.Aggregate("",(g,b)=>g+b.PadLeft(i+=b.Length).PadRight(s.Length+2-c.Length)+x+"\n");} ``` Old solutions: 167 bytes: ``` string f(string s,char x){var c=s.Split('|');var d="";int i=0;foreach(var b in c){d+=b.PadLeft(i+b.Length).PadRight(s.Length+2-c.Length)+x+"\n";i+=b.Length;}return d;} ``` 176 bytes using string interpolation ``` string f(string s,char x){var c=s.Split('|');var d="";int i=0;foreach(var b in c){d+=string.Format($"{{1,{i}}}{{0,-{s.Length+2-c.Length-i}}}{x}\n",b,"");i+=b.Length;}return d;} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ṣ”|⁶ṁ;ɗ\pG ``` [Try it online!](https://tio.run/##AT8AwP9qZWxsef//4bmj4oCdfOKBtuG5gTvJl1xwR////1RoaXN8Q29kZXxoYXN8fGVtcHR5fHxzZWN0aW9uc/8nQCc "Jelly – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 107 104 103 bytes ``` w=2-(n=split($1,p,"|"))+gsub(t=".",FS,$1){for(;s++<n;gsub(t,FS,b))y=y substr((b=b p[s])$1,1,w)$2RS}$0=y ``` [Try it online!](https://tio.run/##JczRCsIgFIDhVxnihYdZ5G6XEAQ9QOsuupi1mlQqO4ZIp2e3RZc/H/x9upeSdLMQTmN42Ci4kkEyYgD1DV9GRM2WTO46yRW8r34SLdb12rV//IEByDpXc2OchDDaVOGIJ5hPSibgzb778JXOpRxGi7T1l4HGHomGZ4iZCIdztN5htfkC "AWK – Try It Online") *Thanks to Pedro Maimere for helping shave off more 3 chars* One interesting thing about this challenge... I found a quirk about the TIO AWK setup. I can't figure out way to specify input where a positional argument can contain a space. Meaning setup a TIO test that behaves like this commandline, ``` echo "this is the first parameter" second | gawk '{ print $1 }' ``` In TIO, the first parameter will be `"this` not the whole string. That means while it works in a terminal window, I can't show that it handle the second test for this challenge in TIO. Here's how the code works... The test associated with the codeblock is always truthy, so the code always runs. It's only a test (rather then code) to avoid needing a `;` character. It does a couple of things by using AWK's willingness to combine multiple expressions into one "line" of code. ``` w=2-(n=split($1,p,"|"))+gsub(t=".",FS,$1) ``` First is splits the first parameter into in array of strings using the pipe character as the delimeter with `n=split($1,p,"|")`. It also saves the number of substrings generated in `n`. Then it changes all the characters in the first parameter to spaces with `gsub(t=".",FS,$1)` setting convenience constants `t` and `n` in the process. Finally the value of `w` is set to the number of non-pipe characters in the first parameter by subtracting the number of sub-strings from the total number of characters in the original. The associated code block is one statement, a `for` loop, that processes each substring. ``` for(;s++<n;gsub(t,FS,b))y=y substr((b=b p[s])$1,1,w)$2RS ``` The iteration check is simple `s++<n`. The end of loop statement converts all the characters in the previous output line to blanks `gsub(t,FS,b)`, which turns it into the prefix for the next line. The body of the loop constructs and appends the next line of output to an accumulator `y`. That string is a concatenation of the previous string, plus the current string (code fragment) with a bunch of blanks appended (meaning `$1`) `(b=b p[s])$1`. That mess is truncated to the length we want `w` and the comment delimiter and LF are appended with `y=y substr(...,w)$2RS`. Once all the code substrings have been processes, assigning `$0` to the accumulator takes care if printing out the results. ``` $0=y ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 74 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 9.25 bytes ``` \|/:¦↳:t↲Ḋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJqPSIsIiIsIlxcfC86wqbihrM6dOKGsuG4iiIsIiIsIlwidGhlfGZpdG5lc3N8Z3JhbXx8cGFjZXJ8dGVzdFwiXG5cIi8tLVwiIl0=) Bitstring: ``` 01101010100010101110000101000000110001011111111110001111111100110011110001 ``` ## Explained ``` \|/:¦↳:t↲Ḋ­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢⁢​‎‏​⁢⁠⁢‌­ \|/ # ‎⁡Split on "|"s :¦ # ‎⁢Push the cumulative sums without popping. This acts as the space length before each section ↳ # ‎⁣Pad each item right with spaces to length in ^ :t↲ # ‎⁤And pad each item left with spaces to length of tail of ^ Ḋ # ‎⁢⁡Append " {comment char}" to each ‎⁢⁢Implicitly join on newlines 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire) and not this challenge. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 79 bytes ``` c=>s=>s.split`|`.map((_,i,a)=>a.map(y=>i--?y.replace(/./g,' '):y).join``+' '+c) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LYxBDsIgFAWvYnBRSAt1aUygR_AIghQqlQKRumjyb-KmMXoob2OjTSZ5mcWbxyvE1sxPy9_30dL956i5yAssJ-9GCZINKmF8qlylCBfqpxMXjtJmYjeTvNIG16zuqmJTkMNEWB9dkLJctNRkze50DDl6w3zssMVoiwhGCs4aWjBguwu4Hq7gYQgQEyLrb57_-wU) +4 to add an extra space before `#` [Answer] # PHP, ~~120~~ ~~117~~ ~~116~~ ~~110~~ 109 bytes ``` foreach($a=split('\|',$argv[1])as$i=>$t){$c=preg_replace('#.#',' ',$a);$c[$i]=$t;echo join($c)," $argv[2] ";} ``` or ``` foreach($a=split('\|',$argv[1])as$t){$c=preg_replace('#.#',' ',$a);$c[$i++|0]=$t;echo join($c)," $argv[2] ";} ``` [Answer] # [MATL](http://github.com/lmendo/MATL), ~~33~~ 31 bytes ``` '\|'0'|'hYXo8M&YbY:&YdtaZ)0ihYc ``` [Try it online!](http://matl.tryitonline.net/#code=J1x8JzAnfCdoWVhvOE0mWWJZOiZZZHRhWikwaWhZYw&input=J1RoaXN8Q29kZXxoYXN8fGVtcHR5fHxzZWN0aW9ucycKJyMn) ### Explanation The builtin function `Yd` (`blkdiag`), which builds a block-diagonal matrix from its inputs, does most of the work. The fill values in the matrix are 0, and char 0 is treated as a space for displaying purposes. The code would simply split on `|`, build a matrix from the resulting blocks, convert to char, and append two columns with space and comment symbol. However, the possibility of empty sections in the input string ~~complicates~~ makes the problem more interesting: the resulting block would be empty and thus wouldn't show in the resulting matrix. To solve this, we introduce a char 0 before each `|`, so no block will be empty; and then in the resulting char matrix we remove columns that are formed by char 0 only. A non-empty code section will have some printable ASCII char, and thus the columns it spans will survive. An empty section will contribute a row, but won't introduce an extra column. ``` '\|' % Push this string: source for regexp matching. It's just | escaped 0'|'h % Push a string formed by char 0 followed by | (no escaping needed) YX % Input string implicitly. Replace first of the above string by the second o % Convert from chars to code points. Gives a numeric vector 8M % Push '|' again &Yb % Split numeric vector at occurences of | (the latter is automatically % converted to its code point). This gives a cell array of numeric vectors Y: % Unbox cell array: pushes the numeric vectors it contains &Yd % Form a block-diagonal matrix from those vectors ta % Duplicate. Compute vector that equals true for columns that have some % nonzero value Z) % Used that as a logical index (mask) for the columns of the matrix. % This removes columns that contain only zeros 0ih % Input comment symbol and prepend char 0 (which will be displayed as space) Yc % Append that to each row of the matrix. The matrix is automatically % converted from code points to chars % Display implicitly ``` [Answer] # Ruby, ~~96~~ 80 bytes ``` ->s,c{s.gsub(/(^|\|)([^|]*)/){" "*$`.count(t="^|")+$2+" "*(1+$'.count(t))+c+$/}} ``` See it on eval.in: <https://eval.in/639012> I really ought to just learn Retina. [Answer] # Pyth, 30 bytes ``` VJcE\|s[*ZdN*h--lsJZlNdQ)=+ZlN ``` or ``` jm+dQ.t.t+MC,.u*l+NYdJc+Ed\|kJ ``` Both are full programs that take input on STDIN of the comment string, and then the program string, newline-separated. [Try the first version online](https://pyth.herokuapp.com/?code=VJcE%5C%7Cs%5B%2aZdN%2ah--lsJZlNdQ%29%3D%2BZlN&test_suite=1&test_suite_input=%27%23%27%0A%22a%7Cbc%7Cd%7Ce%7Cfgh%7Cij%7Ck%7Cl%7Cmn%7Cop%22%0A%22%2F%22%0A%22Hello%7CWorld%22%0A%22%2C%22%0A%22a%7Cb%7Cc%7Cd%7Ce%7Cf%7Cg%22%0A%22%3A%22%0A%22abcdefg%22%0A%27%25%27%0A%224%7C8%7C15%7C16%7C23%7C42%22%0A%22%21%22%0A%22E%7Cac%7Ch+s%7Cecti%7Con+is%7C+one+c%7Characte%7Cr+longer%7C+than+the%7C+last%21%22%0A%22%40%22%0A%22This%7CCode%7Chas%7C%7Cempty%7C%7Csections%22&debug=0&input_size=2) [Try the second version online](https://pyth.herokuapp.com/?code=jm%2BdQ.t.t%2BMC%2C.u%2al%2BNYdJc%2BEd%5C%7CkJ&test_suite=1&test_suite_input=%27%23%27%0A%22a%7Cbc%7Cd%7Ce%7Cfgh%7Cij%7Ck%7Cl%7Cmn%7Cop%22%0A%22%2F%22%0A%22Hello%7CWorld%22%0A%22%2C%22%0A%22a%7Cb%7Cc%7Cd%7Ce%7Cf%7Cg%22%0A%22%3A%22%0A%22abcdefg%22%0A%27%25%27%0A%224%7C8%7C15%7C16%7C23%7C42%22%0A%22%21%22%0A%22E%7Cac%7Ch+s%7Cecti%7Con+is%7C+one+c%7Characte%7Cr+longer%7C+than+the%7C+last%21%22%0A%22%40%22%0A%22This%7CCode%7Chas%7C%7Cempty%7C%7Csections%22&debug=0&input_size=2) **How they work** ``` VJcE\|s[*ZdN*h--lsJZlNdQ)=+ZlN Program. Inputs: E, Q cE\| Split E on "|" J Assign to J Implicit Z=0 V For N in that: [ ) Create a list with elements: *Zd Z spaces N N -lsJZ len(concatenate(J))-Z - lN -len(N) h +1 * d spaces Q Q s Concatenate the list Implicitly print =+ZlN Z=Z+len(N) jm+dQ.t.t+MC,.u*l+NYdJc+Ed\|kJ Program. Inputs: E, Q +Ed Add a trailing space to E c \| Split that on "|" J Assign to J .u Cumulatively reduce J with: k starting value empty string and function N, Y -> l+NY len(N+Y) * d spaces , J Two-element list of that and J C Transpose +M Map concatenation over that .t Transpose, padding with spaces .t Transpose again m+dQ Map concatenation with Q over that j Join on newlines Implicitly print ``` [Answer] # Perl, 63 bytes Includes +5 for `-Xpi` Run with input on STDIN and comment character after -i: ``` perl -Xpi% esolang.pl <<< "Ab|Cd||ef" ``` `esolang.pl`: ``` s/ /|/;s%(.*?)\|%$"x$`=~y/|//c.$1.$"x$'=~y/|//c." $^I "%eg ``` Totally boring straightforward solution [Answer] # [Turtlèd](https://github.com/Destructible-Watermelon/turtl-d/), 35 bytes (noncompeting) Takes one input, the last character is the comment character. Does not work with comment character as space, but I assume that isn't necessary. ``` !' [*.+(|' dl)r_]' r[*+.(|u)_][ .d] ``` Explanation: ``` ! take input into string variable ' write space over current cell [* ] while cell is not * .+ write pointed char of string, stringpointer+1 (starts 0) (| ) if current cell is | ' dl write space (over |), move down, left r_ move right, write * if pointed char is last char, else space ' r write space, move right [* ] while cell is not * +. increment pointer and write pointed char (|u) if cell is |, move up _ write * if the pointed char is the last char [ ] while cell is not space .d write the pointed char from string, move down ``` [Answer] # GolfScript, 85 bytes ``` {(;);}:r;", "%(r\(r n+:c;;.,\'|'%.,@\-)):l;0:m;{.,0>}{" "m*\(.,m+:m l\-" "\*+c@}while ``` [Try it online](http://golfscript.tryitonline.net/#code=eyg7KTt9OnI7IiwgIiUoclwociBuKzpjOzsuLFwnfCclLixAXC0pKTpsOzA6bTt7LiwwPn17IiAibSpcKC4sbSs6bSBsXC0iICJcKitjQH13aGlsZQ&input=IkhlbGxvLHxXb3JsZCF8VGhpc3xpc3xHb2xmU2NyaXB0IiwgIiMi&debug=on) # 2017 Update - [GolfScript](https://tio.run/##FccxDsIwDADAnVdYZrCgbgJrIiT@QRhooMU00ArY6ubroUyn64bUfuJbxm8pxEA2Zxd93lvDwUykdJiZj6HeuORPS89258RPhqVyAgmkJqBtrMIfXGGYbSl40SbqVW/adneVh/aa9PnSYUQGXOMP) - 71 bytes ``` ', '/~~:c;~1/.,\.{'|'=},,@\-):l;['|']/0:i;{.,i+:i l i-' '*c+\' '*" "\}/ ``` ### Explanation ``` ', '/~~:c;~1/ # Parses input .,\.{'|'=},,@\-):l; # Computes string length without '|' ['|']/ # Splits the array 0:i; # Counter {., # Length of the substring i+:i # Counter update l i-' '*c+\ # Adds spaces after the substring ' '*"\n"\ # Adds spaces before the next substring }/ # ...For each substring ``` [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), 89 bytes ``` s=>c=>{y=0forn inl=s::split"|"print((v=" "::rep)(y)+l[n]+v((#l::reduce@++1)-y+=#l[n])+c)} ``` [Try it online!](https://tio.run/##dVDdasIwFL62T3GMCA3twDo3RiUiyN7AO@lFTE@1rKZdE4XS02fvUlc2mCwXB/L9JefLrvqj6TPRG7FRYtM2YpGVtYZcF8LEsamK3DJiVZ1r6/s3wYDFcY0V9xseFAedBDffnxUDll4VboMg4k9NIGYDxwPFu36Pxu6kQQMCWm/SMklHUpQSUkYnFgILWRfeiaNKMbtD8Qit6I2iF4peaflMq@VAzUfqnaSiMxhCZXMq3Z8NQakRHCprqSxSDUWpT1gT2LPUbiBBIY2dDjnTMWd/dsZdmaKzGSK8VLYhMkNqqc2g3LLO6zzPFQO5awZ@N2o9GM93Q2z@6fpxwou0/o/skCeHRcLD/9ko4XztTbIHz4Ns/edF/nDv@i8 "Funky – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 108 bytes ``` s,c=input().split("|"),input() i,S=0,len("".join(s)) for l in s:L=len(l);print(" "*i+l+" "*(S-L-i+1)+c);i+=L ``` [Try it online!](https://tio.run/##LYtBCsIwEADvfUXIKWvSonizBApee6sfkBrpStyEbjwU9u/RgqeBGSZvZUl0rpXd7JHypxjoOEcsRosG91cNuskfXQxktO5eCckwQPNMq4oKSfFl9HuM0OcV6TcrfUAb7U4ztWOL9gR2hh6tH2u9LchyTY8gy51FwjuXTYTDXDARN8MX) Simple solution -- keep track of how many spaces we have (i) and accumulate. [Answer] # Python 3.8 (pre-release), 99 bytes Different approach: ``` def f(c,d,i=0): for y in(x:=c.split('|')):z=[' '*len(e)for e in x];z[i]=y;print(''.join(z),d);i+=1 ``` [Try it online!](https://tio.run/##ZZHNasMwEITvfoqNS5GVuCF/LcHBUCh9g97SUBR5HSu1JWPpEId9d1eqQy657GH2m9EyantXGb3ett0wFFhCmci0SFW@4FkEpemgB6WTS5bLuW1r5RJGjPPsmu8ZsGmNOkEeMPQYXA67614d8n7Xdkp7ls3PxtuvPC34Ts3y5eDQOiksWshhHyWxoKOkgpDKU0XqTL9UU6PJtHEK8VPM05GhG0SnoKc3/Sj9yf9KNiob2tLylZZvtFrTZhU2z@Pmk4SkCiyhdIqMBmUJjEbwquiEdEgd1EafsCNwldB@IEEtrJuEmMkY81V534cp0LssETat64lsCDXaBvA95tEhikIn0nOpn02D2v1I/04o6d6AL/hW0wubbhcz9q0Zj8IPPPj4HWV8@AM "Python 3.8 (pre-release) – Try It Online") Ungolfed with explanation: ``` def f(c,d,i=0): x=c.split('|') # break string by '|' for y in x: # for each element of list z=[' '*len(e) for e in x] # create a list of blank strings z[i]=y # insert element we care about into otherwise blank list print(''.join(z),d) # print line i+=1 # increment ``` ]
[Question] [ As part of its compression algorithm, the JPEG standard unrolls a matrix into a vector along antidiagonals of alternating direction: [![enter image description here](https://i.stack.imgur.com/I8Pu2.png)](https://i.stack.imgur.com/I8Pu2.png) Your task is to take a matrix (not necessarily square) and return it in unrolled form. As an example: ``` [1 2 3 4 5 6 7 8 9 1 2 3] ``` should yield ``` [1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3] ``` ## Rules You may assume that the matrix elements are positive integers less than `10`. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. The input matrix may be given in any convenient, unambiguous, nested list or string format, or as a flat list along with both matrix dimensions. (Or, of course, as a matrix type if your language has those.) The output vector may be in any convenient, unambiguous, flat list or string format. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## Test Cases ``` [[1]] => [1] [[1 2] [3 1]] => [1 2 3 1] [[1 2 3 1]] => [1 2 3 1] [[1 2 3] [5 6 4] [9 7 8] [1 2 3]] => [1 2 5 9 6 3 4 7 1 2 8 3] [[1 2 3 4] [5 6 7 8] [9 1 2 3]] => [1 2 5 9 6 3 4 7 1 2 8 3] [[1 2 6 3 1 2] [5 9 4 7 8 3]] => [1 2 5 9 6 3 4 7 1 2 8 3] [[1 2 5 9 6 3 4 7 1 2 8 3]] => [1 2 5 9 6 3 4 7 1 2 8 3] [[1] [2] [5] [9] [6] [3] [4] [7] [1] [2] [8] [3]] => [1 2 5 9 6 3 4 7 1 2 8 3] ``` ## Related Challenges * [Reconstruct a zigzagified matrix](https://codegolf.stackexchange.com/q/75588/8478) (the somewhat trickier inverse transformation) * [Rotate the anti-diagonals](https://codegolf.stackexchange.com/q/63755/8478) [Answer] # J, 31 30 14 12 11 bytes ``` [:;<@|.`</. ``` [Ych](https://en.wiktionary.org/wiki/ych_a_fi). Too big. Takes a matrix as input. **Explanation** J has an advantage here. There's a command called [oblique](http://jsoftware.com/help/dictionary/d421.htm) (`/.`) which takes the oblique lines in turn and applies a verb to them. In this case I'm using a gerund to apply two verbs alternately: `<` ([box](http://jsoftware.com/help/dictionary/d010.htm)) and `<@|.` ([reverse](http://jsoftware.com/help/dictionary/d231.htm) and box). Then it's just a matter of unboxing everything using `;` ([raze](http://jsoftware.com/help/dictionary/d330.htm)). [Answer] # Jelly, ~~24~~ ~~19~~ ~~15~~ ~~13~~ 11 bytes ``` pS€żị"¥pỤị⁵ ``` Takes number of rows, number of columns and a flat list as separate command-line arguments. [Try it online!](http://jelly.tryitonline.net/#code=cFPigqzFvOG7iyLCpXDhu6Thu4vigbU&input=&args=NA+Mw+WzEsIDIsIDMsIDUsIDYsIDQsIDksIDcsIDgsIDEsIDIsIDNd) ### How it works ``` pS€żị"¥pỤị⁵ Main link. Argument: m (rows), n (columns), A (list, flat) p Compute the Cartesian product [1, ..., m] × [1, ..., n]. This yields the indices of the matrix M, i.e., [[1, 1], [1, 2], ..., [m, n]]. S€ Compute the sums of all index pairs. p Yield the Cartesian product. ¥ Dyadic chain. Arguments: Sums, Cartesian product. ị" For each index pair in the Cartesian product, retrieve the coordinate at the index of its sum, i.e., map [i, j] to i if i + j is odd and to j if i + j is even. ż Zip the sums with the retrieved indices. Ụ Sort [1, ..., mn] by the corresponding item in the resulting list. ị⁵ Retrieve the corresponding items from A. ``` [Answer] ## Pyth, ~~24~~ ~~23~~ ~~21~~ ~~20~~ ~~19~~ ~~18~~ 17 bytes ``` ssm_W=!Td.T+LaYkQ ``` Alternate 17-byte version: `ssuL_G=!T.T+LaYkQ` ``` Q input +L prepend to each subarray... aYk (Y += ''). Y is initialized to [], so this prepends [''] to the first subarray, ['', ''] to the second, etc. ['' 1 2 3 4 '' '' 5 6 7 8 '' '' '' 9 1 2 3] .T transpose, giving us ['' '' '' 1 '' '' 2 5 '' 3 6 9 4 7 1 8 2 3] m_W=!Td black magic s join subarrays together s join *everything* on empty string (which means ''s used for padding disappear) ``` Thanks to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for a byte, [@Jakube](https://codegolf.stackexchange.com/users/29577/jakube) for 2 bytes, and [@isaacg](https://codegolf.stackexchange.com/users/20080/isaacg) for a byte! Explanation of "black magic" alluded to above: `m_W=!Td` essentially reverses every other subarray. It does this by mapping `_W=!T` over each subarray; `W` is conditional application, so it `_`s (reverses) all subarrays where `=!T` is true. `T` is a variable preinitialized to ten (truthy), and `=!T` means `(T = !T)`. So it toggles the value of a variable that starts out truthy and returns the new value, which means that it will alternate between returning falsy, truthy, falsy, truthy... (credit to Jakube for this idea) [Test suite here](https://pyth.herokuapp.com/?code=ssm_W%3D%21Td.T%2BLaYkQ&test_suite=1&test_suite_input=%5B%5B1%5D%5D%0A%5B%5B1%2C2%5D%2C%5B3%2C1%5D%5D%0A%5B%5B1%2C2%2C3%2C1%5D%5D%0A%5B%5B1%2C2%2C3%5D%2C%5B5%2C6%2C4%5D%2C%5B9%2C7%2C8%5D%2C%5B1%2C2%2C3%5D%5D%0A%5B%5B1%2C2%2C3%2C4%5D%2C%5B5%2C6%2C7%2C8%5D%2C%5B9%2C1%2C2%2C3%5D%5D%0A%5B%5B1%2C2%2C6%2C3%2C1%2C2%5D%2C%5B5%2C9%2C4%2C7%2C8%2C3%5D%5D%0A%5B%5B1%2C2%2C5%2C9%2C6%2C3%2C4%2C7%2C1%2C2%2C8%2C3%5D%5D%0A%5B%5B1%5D%2C%5B2%5D%2C%5B5%5D%2C%5B9%5D%2C%5B6%5D%2C%5B3%5D%2C%5B4%5D%2C%5B7%5D%2C%5B1%5D%2C%5B2%5D%2C%5B8%5D%2C%5B3%5D%5D&debug=0). [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~28~~ 27 bytes ``` tZyZ}:w:!+-1y^7MGn/*-X:K#S) ``` Adapted from my answer [here](https://stackoverflow.com/a/28375839/2586922). The general idea is to create a 2D array of the same size as the input, filled with values that increase in the same order as the zig-zag path. Then the linearized (flattened) version of that array is sorted, and the *indices* of that sorting are kept. Those are the indices that need to be applied to the input in order to produce the zig-zag path. Input is in the form ``` [1 2 3; 5 6 4; 9 7 8; 1 2 3] ``` ### Explanation [**Try it online!**](http://matl.tryitonline.net/#code=dFp5Wn06dzohKy0xeV43TUduLyotWDpLI1Mp&input=WzEgMiAzOyA1IDYgNDsgOSA3IDg7IDEgMiAzXQ) ``` t % input 2D array. Duplicate ZyZ} % get size as length-2 vector. Split into two numbers: r, c : % range [1,2,...,c] as a row vector w:! % swap, range [1;2;...;r] as a column vector + % add with broadcast. Gives a 2D array -1 % push -1 y^ % duplicate previous 2D array. Compute -1 raised to that 7M % push [1;2;...;r] again Gn/ % divide by input matrix size, that is, r*c * % multiply - % subtract X: % linearize 2D array into column array K#S % sort and push the indices of the sorting. Gives a column vector ) % index input matrix with that column vector ``` [Answer] # Matlab, 134 bytes I just tried my best to shorten my code in Matlab, like telegraphing it. ``` function V=z(M) [m,n]=size(M); a=(1:m)'*ones(1,n); b=ones(m,1)*(1:n); A=a+b-1; B=a-b; C=(A.^2+(-1).^A.*B+1); [~,I]=sort(C(:)); V=M(:); V=V(I)'; ``` Notes: 1. `M` is an `m×n` matrix. 2. `a` and `b` are both matrices same size of `M`, each row of `a` consists of numbers equal to its row number, while each column of `b` is equal to its column number. Thus, `a`+`b` is a matrix whose element equals to sum of its row and column number, i.e., `matrix(p,q)=p+q`. 3. Thus, `A(p,q)=p+q-1`; and `B(p,q)=p-q`. 4. `C` is mathematically stated as equation below. [![Zigzagifiedly increasing matrix](https://i.stack.imgur.com/JtqIN.png)](https://i.stack.imgur.com/JtqIN.png) with the equation, a zigzagifiedly increasing matrix can be made like shown below. > > > ``` > C = > 1 2 6 7 > 3 5 8 14 > 4 9 13 18 > 10 12 19 25 > > ``` > > 5. `C` indicates the order of elements of M in zigzagified results. Then, `[~,I]=sort(C(:));`returns the order, i.e., `I`, thus, `V=V(I)'` is the result. [Answer] # JavaScript (SpiderMonkey 30+), 99 bytes ``` x=>[for(y of[...x,...x[0]].keys())for(z of Array(y+1).keys())if(a=x[y%2?z:y-z])if(b=a[y%2?y-z:z])b] ``` Tested in Firefox 44. Takes input as a 2D array. [Answer] ## Python 2, 84 bytes ``` lambda N,w,h:[N[i*w+s-i]for s in range(w+h+1)for i in range(h)[::s%2*2-1]if-1<s-i<w] ``` Porting [nimi's answer](https://codegolf.stackexchange.com/a/75609/20260). Takes a flat array with given width and height. xsot saved a byte. --- **88 bytes:** ``` lambda M,w,h:[M[i]for i in sorted(range(w*h),key=lambda i:(i/w+i%w,-i*(-1)**(i/w+i%w)))] ``` Takes a flat array with given width and height. Sorts the corresponding 2D coordinates `(i/w,i%w)` in zigzag order of increasing sum to get diagonals, tiebroken by either increasing or decreasing row value, based on whether the row plus column is odd or even. [Answer] ## Haskell, ~~79~~ ~~78~~ 73 bytes ``` (m#h)w=[m!!(y*w+x-y)|x<-[0..h+w],y<-g!!x$[0..x],y<h,x-y<w] g=reverse:id:g ``` The input is a flat list with the number of rows and columns, e.g. `( [1,2,6,3,1,2,5,9,4,7,8,3] # 2) 6` -> `[1,2,5,9,6,3,4,7,1,2,8,3]`. How it works: walk through the x and y coordinates of the matrix (`h` rows, `w` columns) in two nested loops: ``` | 0 1 2 3 4 5 6 7 8 outer loop Index is y*w+x-y, i.e. --+------------------ x from 0 to h+w the elements are accessed 0 | 1 2 6 3 1 2 in the following order: 1 | 5 9 4 7 8 3 2 | 1 2 4 6 8 10 3 | 3 5 7 9 11 12 4 | 5 | 6 | 7 | inner loop: 8 | y from 0 to x ``` i.e. from top/right to down/left, skipping out of bound indices (`y` and `x` must satisfy `y<h` and `x-y<w`). When `x` is even, the order of the inner loop is reversed: `y` goes from `x` to `0`. I do this by picking a modifying function for the y-range `[0..x]` which is the `x`th element of `[reverse,id,reverse,id,...]`. Edit: @xnor re-arranged the loops and saved 5 bytes. Thanks! [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` Σz*İ_∂ ``` [Try it online!](https://tio.run/##yygtzv7//9ziKq0jG@IfdTT9//8/OtpQx0jHWMckVifaVMdMx1zHAsiy1AGLxsYCAA "Husk – Try It Online") Same idea as [Zgarb's Boustrophedonize solution.](https://codegolf.stackexchange.com/questions/150117/boustrophedonise/150135#comment499944_150135) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~50~~ 41 bytes -9 Can use odometer directly ``` {(,/x)@,/((#c)#(|:;::))@'c:.=+/!#'(x;*x)} ``` [Try it online!](https://ngn.codeberg.page/k#eJy1jksKwkAQRPd9ipIsplsHhzEfzQxCNt4gNwjkDAE/Z7d7RCGgS3fV7zVFzenKPiwy+MBcTVLxLeWURAY3pf15FzaV4yVvF7kTjYm9jwSOOOQaUQheIzS+IOrcokOTexxxyoXIWyk2aaLHSnXWoJUtejT2UFSpNmTasN2q1LgfSoguulHXfGatwte2/wub9ZjdSPQE7uY+jg==) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` Þ`⁽ṘẆf ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLDnmDigb3huZjhuoZmIiwiIiwiW1sxLDIsMyw0XSxbNSw2LDcsOF0sWzksMSwyLDNdXSJd) ``` Þ` # Antidiagonals ⁽ Ẇ # To every other item Ṙ # Reverse f # Flatten ``` [Answer] # [Julia 0.7](http://julialang.org/), ~~114~~ 85 bytes ``` ^ =size ~A=[[i%2<1?reverse(x):x for(i,x)=pairs(-A^2:A^1.|>x->diag(rotl90(A),x))]...;] ``` [Try it online!](https://tio.run/##pZNdT8IwFIav7a84Xph0SVncGAyoRUn8F00hC6taXYCsU6sx@@vYM74S8AO0yS76tu@zc96cPj4XJkuXyzEIa941qUdCSnMRX0XXpX7RpdXUBQMHd/OSGuYCschMaWlrNI4Ho3EUfgxda5ib7J6W86roX9JR4G8FKgxDrpY39mH@CrWMIIY2JATWqwNdSKG33fehuaFACJARg5hBh0GfQZdBm0HCIGWw0nteUYTkIODWTCtKzmSk5IANFPy6xNDTFUMLxNxXFKmjLM2PfR1bL1r5n7286T/hvm0fAt/0/o33xyB29SR8kyrfxfkvZhe7xJw6Hpgg@RB5KhNRyEUc7r9CnsTkTYG@ZQ5djtH6HFIfaaP7KNrr2TiaGRCSFcWk0rayk0VmrcZR8xKVUDsc0Fw6he8BHJgZPOk3S/MAVEAOtGa@zR36zgVQ7RZ6WulcIGF9imv1Stzevt4XNvZG1rOc4Lc62q@YkOUn "Julia 0.7 – Try It Online") Takes the antidiagonals (rotates and takes the main diagonals), reverses every other one, and flattens the list. -29 bytes thanks to MarcMush: * replace `A[end:-1:1,1:end]` with `rotl90(A)` to rotate the matrix * rewrite with `pairs` instead of `eachindex` * to flatten a vector of vectors `Q`, use `[Q...;]` instead of `vcat[Q...]` [Answer] # Python 2 + NumPy, 122 bytes I admit it. I worked ahead. Unfortunately, this same method cannot be easily modified to solve the other 2 related challenges... ``` import numpy def f(m):w=len(m);print sum([list(m[::-1,:].diagonal(i)[::(i+w+1)%2*-2+1])for i in range(-w,w+len(m[0]))],[]) ``` Takes a numpy array as input. Outputs a list. [**Try it online**](http://ideone.com/okHH7F) ### Explanation: ``` def f(m): w=len(m) # the height of the matrix, (at one point I thought it was the width) # get the anti-diagonals of the matrix. Reverse them if odd by mapping odd to -1 d=[list(m[::-1,:].diagonal(i)[::(i+w+1)%2*-2+1])for i in range(-w,w+len(m[0]))] # w+len(m[0]) accounts for the width of the matrix. Works if it's too large. print sum(d,[]) # join the lists ``` A lambda is the same length: ``` import numpy lambda m:sum([list(m[::-1,:].diagonal(i)[::(i+len(m)+1)%2*-2+1])for i in range(-len(m),len(m)+len(m[0]))],[]) ``` [Answer] ## Python 3, ~~131~~ ~~118~~ ~~115~~ 107 bytes Based on the same principe as my [answer](https://codegolf.stackexchange.com/a/75350/49289) of [Deusovi's challenge](https://codegolf.stackexchange.com/q/75334/49289) I assume we can't have zero in the input matrice ``` e=enumerate lambda s:[k for j,i in e(zip(*[([0]*n+i+[0]*len(s))for n,i in e(s)]))for k in i[::j%2*2-1]if k] ``` ## Explanation how it works : ``` pad with 0 transpose remove 0 reverse line concatenate with even index 1 2 3 1 2 3 0 0 1 0 0 1 1 4 5 6 --> 0 4 5 6 0 --> 2 4 0 --> 2 4 --> 2 4 --> 1 2 4 7 5 3 6 8 9 7 8 9 0 0 7 8 9 3 5 7 3 5 7 7 5 3 0 6 8 6 8 6 8 0 0 9 9 9 ``` ## Results ``` >>> [print([i,f(i)]) for i in [[[1]], [[1, 2], [3, 1]], [[1, 2, 3, 1]], [[1, 2, 3], [5, 6, 4], [9, 7, 8], [1, 2, 3]], [[1, 2, 3, 4], [5, 6, 7, 8], [9, 1, 2, 3]], [[1, 2, 6, 3, 1, 2], [5, 9, 4, 7, 8, 3]], [[1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]], [[1], [2], [5], [9], [6], [3], [4], [7], [1], [2], [8], [3]]]] # [input, output] [[[1]], [1]] [[[1, 2], [3, 1]], [1, 2, 3, 1]] [[[1, 2, 3, 1]], [1, 2, 3, 1]] [[[1, 2, 3], [5, 6, 4], [9, 7, 8], [1, 2, 3]], [1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]] [[[1, 2, 3, 4], [5, 6, 7, 8], [9, 1, 2, 3]], [1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]] [[[1, 2, 6, 3, 1, 2], [5, 9, 4, 7, 8, 3]], [1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]] [[[1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]], [1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]] [[[1], [2], [5], [9], [6], [3], [4], [7], [1], [2], [8], [3]], [1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΣN²‰ÐOŠO<è‚ ``` Inputs as `flattened_list, width, height` (even though I ignore the `height` input). [Try it online](https://tio.run/##yy9OTMpM/f//3GK/Q5seNWw4PMH/6AJ/m8MrHjXM@v8/2lDHSMdYx0THVMdMx1zHQsdSBywSy2XCZQwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JhcUpqYo5CZV1BaUmyloGRfmVBsr6SQmJeiUG57eL@SDpdSQFFqSUmlbkFRZl5JagpEKVClTmXC4S2HdgMV@JeWQISAmkP/n1vsF/GoYcPhCf5HF/jbHF7xqGHW/1qdQ9vs/0dHRxvG6gARkNYx0jEGMY1QeCYInqmOmY6JjqWOuY6FDlgkFoRgsiZgeZCcJUwWrtcMZBaQNgXKmYDVAGXNYLIgUTOwCeZgVWBZQyP80rGxAA). **Explanation:** The actual sorting algorithm is a direct port of [my 05AB1E answer](https://codegolf.stackexchange.com/a/254393/52210) for the [*Traverse a rectangle's antidiagonals* challenge](https://codegolf.stackexchange.com/questions/254367/traverse-a-rectangles-antidiagonals/). Even though the actual path over the matrix is different for both challenges, that linked challenge uses \$y,x\$ as coordinates, whereas I use \$x,y\$ here, so the actual sorting implementation is basically the exact same. ``` Σ # Sort the first (implicit) input-list by: N # Push the 0-based sort-index ²‰ # Divmod it by the second input-width Ð # Triplicate this coordinate O # Sum the top pair together Š # Tripleswap from pair,pair,sum to sum,pair,pair O # Sum the top pair together again < # Decrease it by 1 è # Modular 0-based index this sum-1 into the pair ‚ # Pair it together with the other sum # (after which the sorted list is output implicitly) ``` Just like in my linked answer, there are a few equal-bytes alternatives for `ÐOŠO<è‚` (not as many as in the linked answer, since we don't have access to the pair as variable `y` here, since we've just created the pair manually with `N²‰`): ``` RDODŠè‚ ÐO<è‚€O ... ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 89 bytes ``` a=>a.flatMap((b,i)=>b.map((c,j)=>({c,k:++i-j/(-2)**i}))).sort((p,q)=>p.k-q.k).map(x=>x.c) ``` [Try it online!](https://tio.run/##lZLNboMwDIDvfQqOSWuCRmkLq@DY254AcUizUvGzJgVUVZr27MwO3U6MFaQosuPvizGU8iZb1RSmcy/6/dQf4l7GiRR5Lbs3aRg7QsHj5Cg@KFBQYsA@FVSvq1Xhlh5zfb5cFl@cc9HqpmPMwBVrjKjcq6i45e5xcheK9/tcN8wYR@dOukjTlywDZ97jeQ5ixIKfQbqGGQ7Lgg8EDQaYxY8bsIsNbCHAPYIdhLgP@VHvj2EDEUJrCBChOETgt6fg4RxsEUz4njJSepgXFVFB@LfvKePY0cQc/zNiZ7Y7eltcW/qyuGgOO5rn4zy0eXvPpDHjC6Uvra5PotZndsBfjvP@Gw "JavaScript (Node.js) – Try It Online") ]
[Question] [ ## Introduction We all know the cool S (also known as Superman S, Stüssy S, Super S, Skater S, Pointy S, Graffiti S etc. etc.): billions of schoolchildren around the world drew this S and immediately felt proud of themselves. In case you've forgotten or had a *completely uncool childhood*, here is an image of said cool S: ![](https://upload.wikimedia.org/wikipedia/commons/thumb/7/79/%22Cool_S%22.svg/57px-%22Cool_S%22.svg.png) Given a scale factor `n` as input (where \$1\leq n\leq 20\$), output the Cool S in ASCII art. ## How to Draw It From the [Wikipedia page](https://en.wikipedia.org/wiki/Cool_S) on the Cool S: ![](https://upload.wikimedia.org/wikipedia/commons/thumb/6/67/%22Cool_S%22_Drawing_Instructions.svg/430px-%22Cool_S%22_Drawing_Instructions.svg.png) ## Output The Cool S when `n` = 1 is: ``` ^ / \ / \ / \ | | | | | | \ \ / \ \/ /\ \ / \ \ | | | | | | \ / \ / \ / v ``` And for different values of `n`, you simply make the output `n` times bigger. For example, `n`=2: ``` ^ / \ / \ / \ / \ / \ | | | | | | | | | | | | \ \ / \ \ / \ \/ /\ \ / \ \ / \ \ | | | | | | | | | | | | \ / \ / \ / \ / \ / v ``` Note that the vertical sections are two times longer and the spacing between the vertical lines is two times wider. And when `n`=3: ``` ^ / \ / \ / \ / \ / \ / \ / \ | | | | | | | | | | | | | | | | | | \ \ / \ \ / \ \ / \ \/ /\ \ / \ \ / \ \ / \ \ | | | | | | | | | | | | | | | | | | \ / \ / \ / \ / \ / \ / \ / v ``` ***Note:*** Although not required, your code may also be able to support `n`=0: ``` ^ / \ \\/ /\\ \ / v ``` ## Winning The shortest program in bytes wins. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 58 53 47 43 41 bytes ``` Nθ≔⊕⊗θδ↗θ/⊗θ↘δ^‖B↓‖M← vMδ⁰⊗θ↗⊕θM⁰δ↗θ/⊗θ⟲T ``` [Try it online!](https://tio.run/##jY9PC4JAEMXvfYrwtAtG0TFPhRejIqSugX9GXVh3dZwt@vRbWqmHiE4zzLwf772kiDDRkbQ2UJWhgyljQFZzb7JuGpErFqgEoQRFkDJfm1g@Z825mz4lRxSK2OpchSIvyJ3W/c2ZO/0@onrE1zf1hlL@YS4tE0ImIaGNIQLM5P2lHR57gaiRrXaQ0WA3vbbs1pQVS93FT@s@7bhZJ@jwxbdmfxQLNUUEJ4xUk2ksGfesXdrZVT4A "Charcoal – Try It Online") I just wanted to try another approach, this draws the outside via reflections (thanks to Neil for expanding the idea) and then draws the inside part. As Charcoal has `:Left` as default direction to draw lines, I make use of that direction as much as possible to save some bytes by drawing the S horizontally, like this: ``` /----\ /----\ / \ / \ / \/ \ / / \ / / \ v ----/ /---- ^ \ / / \ / / \ /\ / \ / \ / \----/ \----/ ``` And then I just need to rotate the canvas 90 degrees counterclockwise. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~47~~ ~~42~~ 41 bytes ``` Fv^«↓⊗θ↘⊗⊕θ←↓⊗θ↙⊕⊗θ↖ι↖⊕⊗θ→↑⊗θ↗⊕θMθ⁺⊗θ⊕θ⟲⁴ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBQ6ksTklToZqLM6AoM69Ew8olvzxPR8ElvzQpJzVFo1BT0xpFKigzPaMEIe@Zl1yUmpuaVwJRC1Lsm1@WqmHlk5pWgqYVj6kg1ToKyIYhKUVSG1oAUZmJRQyPboiTwE5H0YjDRaEFUF@i@Q5mUqGOQkBOaTGSLRhKQWqD8ksSS1I1TIDs2v//Df/rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Draws the following lines in order: ``` ^ / \ / \ / \ | 1 | | 1 | \ 2 / \ 2/ 8\ 2 8 \ 2 7 | 3 7 9 3 6 4 6 4 6 4 5 ``` Where `5` is the current character of the string `v^`. At the end of the first loop the cursor is then positioned at point `9`. The entire canvas is then rotated so that the other half of the Cool S can be drawn. (The canvas actually gets rotated twice, but this is just an implementation detail.) Charcoal doesn't support `RotateCopy(:Up, 4)` but if it did then this would work for 33 bytes: ``` ↖^↖⊕⊗θ→↑⊗θ↗⊕θ‖BM↓↙⊗θ→↓⊗θ⟲C↑⁴J⁰¦⁰v ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~255~~ ~~249~~ ~~248~~ 209 bytes -6 bytes thanks to Kevin Cruijssen -1 byte thanks to Kevin Cruijssen -39 bytes thanks to Rod and Jo King ``` n=int(input()) m=2*n a,b,q,c,l='\ \n/|' f=m*b s=q+q.join([f[d:]+c+b*2*d+b+a+f[d:]for d in range(m+1)]+[l+f+l+f+l]*m+[d*b+a+f+a+f[d*2:]+c+d*b for d in range(n)]+[n*b+a+f+a+c+n*b]) print(f,'^'+s+q+s[::-1]+f,'v') ``` [Try it online!](https://tio.run/##XY7LCsIwEEX3@Yrs8pioWHeFfEkaoWmMVppp01ZB8N9jW8GFi4HL4Z7LDK/51uMpZ9QtzrzF4TFzIUjUhURSK6eSalSnWUUrPLwZCTpKRyadIO3vfYvcBONLCw04WUgPDmrYSOhH6mmLdKzxeuERjsKC6SDAdlZGMF5u9a8ii21mYfTPxdXEX7eBJVtBhnF9OSh2ZjBBgsmU5e5oYSFPJnIuPg "Python 3 – Try It Online") It now handles n=0. [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~36~~ ~~32~~ 29 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` «|*‼l├/L1^╋;╶╵\∔∔│α╶«├:╵╋:↔↕∔ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JUFCJTdDJXVGRjBBJXUyMDNDJXVGRjRDJXUyNTFDJXVGRjBGJXVGRjJDJXVGRjExJTVFJXUyNTRCJXVGRjFCJXUyNTc2JXUyNTc1JXVGRjNDJXUyMjE0JXUyMjE0JXUyNTAyJXUwM0IxJXUyNTc2JUFCJXUyNTFDJXVGRjFBJXUyNTc1JXUyNTRCJXVGRjFBJXUyMTk0JXUyMTk1JXUyMjE0,i=MQ__,v=4) A whole lot of stack manipulation. (outdated) explanation: ``` «|* an array of input*2 "|"s ‼ cast to a 2D object (needed because bug) : duplicate that (saved for the center line) l├ height+2 / create a diagonal that long L1^╋ and in it, at (width; 1) insert "^" ;∔ append the vertical bars ^ / so far done: / / | | ⁸╵ input+1 \ antidiagonal with that size ∔ appended to the above │ mirror horizontally ^ / \ / \ / \ current: | | | | \ / \ / | α get the 2nd to last popped thing - the antidiagonal | └∔ append it to the vertical line copied way before: \ ⁸«├ input/2 + 2 \ :╵ duplicate + 1 ╋ at (input/2 + 2; input/2 + 3) in the big part insert ^ :↔↕∔ mirror a copy vertically & horizontally and append that to the original ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~260~~ 254 bytes -6 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` f(n){int s=2*n++,t=s+1,I[]={1,t,s,n,n,s,t,1},A[]={s,1,1,1,2*t,1,t,t,1,t,1,n,t,t,1,t,t,1,1,1,t,s,1,1},x;for(s=8;s--;)for(n=0;n<I[s];n++,puts(""))for(t=3;t--;)x=s*3+t,printf("%*c",n*("AAAA?BAAAAC@?ABAAACA@AAA"[x]-65)+A[x],"w!!!0]}}}]]00]]}}}]!0_!!"[x]-1);} ``` [Try it online!](https://tio.run/##bY/dSsQwEIWv3afYBIT8TKBpUYQYduNe7TPUIFKo7IVx2YlYKHn2OunqlWbgcPLlDDMZzNswLMsokpxPKW/RtyppDdmjtnDso58tZEBIVEjOFgiVIti1WkWM@FUtpX59/knUblv7Jjd@XAT6B4fGOFkvyTcuPR57jK5OPX9mFJzL9S37zuUanDyqTmc4X2jDUfBbNXBISvBAZ/dU9bDfhWoOYU/K@yma@zupAxngX4yxJpZSYmyauBrWvDC2xqx0Zak/f389JSE38@ZmFAS3112ekzGGS1dp@y/t/tKyfAM "C (gcc) – Try It Online") ## Rundown We can divide the shape into parts: ``` ^ Top cap / \ Top slope ||| Sides \\/ Twist, part 1 /\\ Twist, part 2 ||| Sides \ / Bottom slope v Bottom cap ``` Each part could be described by a number of lines, three chars, and three relationships to certain values that decides the field-width at each line. A first iteration came to be: ``` #define g(x,s,A,B,C)for(i=0;i<x;i++)printf("%*c%*c%*c\n",A,*s,B,s[1],C,s[2]); f(n) { int s=2*n++,t=s+1,i; g(1, " ^", 1, 1, t-1) g(t, "/ \\",t-i, 1,2*i+1) g(s, "|||", 1, t, t) g(n,"\\\\/",i+1, t,t-2*i) g(n,"/\\\\",n-i, 2*i+1, t) g(s, "|||", 1, t, t) g(t, "\\/ ",i+1,2*t-2*i, 1) g(1, " v", 1, 1, t-1) } ``` The calls to the `g()` macro looks very much like a table could be constructed and looped over. Field-widths are sometimes related to the index counter, and sometimes not. We can generalise the field-width to be `F * i + A`, where F is some factor to multiply `i` with, and A is some value to add to the width. So the last width of the fourth call above would be `-2 * i + t`, for example. Thus we get: ``` f(n){int s=2*n++,t=s+1, s = size of "side" parts, t = size of top and bottom slopes I[]={1,t,s,n,n,s,t,1}, The number of lines per part. A[]={...},x; A[] holds the values to add to each field-width. for(s=8;s--;) Loop through the parts. for(n=0;n<I[s];n++,puts("")) I[s] decides how many lines to the part. Ends with newline. for(t=3;t--;) Go through the three chars of each line. x=s*3+t, Calculate offset. printf("%*c", Print the char. n*("..."[x]-65)+A[x], Build field-width. The string holds the index factor, A[] holds the offset part. "..."[x]-1);} The char itself is grabbed from the string. Shifted by 1 to eliminated double backspaces. ``` In the end it was not much shorter than a tightened version of the `g()` calling one, but shorter is shorter. [Answer] # [Python 2](https://docs.python.org/2/), ~~227~~ ~~208~~ ~~207~~ ~~202~~ ~~196~~ 181 bytes ``` I=n=2*input() R,L,S,P='/\ |' k=n*[2*(P+S*n)+P] exec"k=[R+S+2*S*I+L]+k+-~I%2*[L+S*n+L+S*I+R];I-=1;"*-~n print'\n'.join(t.center(2*n+3)for t in['^']+k+[a[::-1]for a in k[::-1]]+['v']) ``` [Try it online!](https://tio.run/##JU/BasMwFDv3fYUJDCd20i3uTik@dmAILCS7uS5kmUczj5dg3G2F0V/PYnYRepJ4SPM1nCcUyzC9WSKJT5JkURKlYCPOl5Bm0OZ13uWNpPdH8kvBSWRasLThHcOMNwbsjx0SJ3XLOy5YxxSvDXe8uKk7wXQdczyi4q3Zq0KW@4QVN4TZjxjoEen2YxoxDdvBYrA@FWt@l71PngQyoqYnGt/pXldVUZqo96tO3P9tuKZf1GTL2hy@z@OnJS/@YivYBH9dcRPrkTgPVjrYOZDD89PB@8lH99Xb3sHyACUI2MHj8gc "Python 2 – Try It Online") Thks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) for 1 byte; and then another 5 bytes total (via `n => 2*n`). Works for `n=0` as well. [Answer] # [C (gcc)](https://gcc.gnu.org/), 379 353 344 334 bytes I used a couple of `#define`s for subexpression elimination and several globals to communicate between the internal functions. The main loop goes {0,1,2,3,3,2,1,0} to construct the S. Thanks to Jonathan Frech for the suggestions. ``` #define z(a,b...)printf("%*c%*c%*c\n"+a,b);} #define y(a){for(i=~-a*t;v*i<v*a*!t+t;i+=v) i,n,p,r,t,u,v;a(){z(6,r+2,94+t*24)b()y(-~r)z(3,-i-~r,47+u,i*2+2,92-u)c()y(r)z(0,~r,124,~r,124,~r,124)d()y(-~n)z(0,i+1,92-u,2*(n-t*i)+1,92,2*(n-!t*i)+1,47+u)(*x[])()={a,b,c,d};f(s){r=2*s;for(p=0;p<8;x[7*t-p++*(2*t-1)](n=s))t=p>3,v=2*!t-1,u=t*45;} ``` [Try it online!](https://tio.run/##VZDRbsIgFIbvfYqqWXIOnDZr7eYWxBdxXiC1SuKwaWmjNvXVO9DtYgkJ//n/7wAHHR@0HufG6lNb7KNV44qT2SXH9Tgv9qWx@@gGinZJkmBVG@tKmL0w/VxfdsZ9hmKY/MFXUNiX5xqMvMeKOdExs@qYYlPHnTBcdjgxZKmimhy11AkF2N/gnWqe0WfOHcty3AFeIb7XeIMFxcYrype8JcOyQGVxizogAXgln6ZZ/n/D4nmEfRCGp48uyhjY2DGDD@NZTn/rcAMCu2y2CCh7PxhpKgZRQoN9LTPWiDBYJV9FtfoQl82SubjinEHmRYpbsLJBdLJaL6jz/NS71ErH8jcxjP7vom9lLASh6oMmfVR1xJjXHUb9JIpC0shUBFlCYNYpeke5swllt0m3GNLwJDEZxnHxAw "C (gcc) – Try It Online") [Answer] # [PHP](https://php.net/), ~~378~~ ~~374~~ ~~378~~ ~~377~~ ~~376~~ ~~335~~ ~~331~~ 328 bytes -3 bytes, thanks to manatwork -4 bytes, used str\_pad instead of str\_repeat -41 bytes, thanks to manatworks' suggestions -1 byte, merged two increments into a +=2 -1 byte, removed superfluous \ ~~-4 bytes by echoing once.~~ Forgot I needed to pass the string into the function so this is more bytes Works for n = 0 as well. ``` function s($b){return str_pad($w,$b);}echo s($i=1+$a=2*$argv[1]).'^ ';for(;$i;$j++,$y=$z.$y)echo$z=s(--$i).'/'.s(++$j).'\ ';for(;$k<$a;$k++)$x.='|'.s($a).'|'.s($a).'| ';echo$x;for(;$l<=$a/2;)echo s($m++).$c='\\',s($a).$c.s($a-$l++*2).'/ ';for(;$m;$n+=2)echo s(--$m).'/'.s($n).$c.s($a).'\ ';echo$x.strtr($y,'/\\','\/').s($a+1).v; ``` [Try it online!](https://tio.run/##TZDLboMwEEX3/YourmQ7A0awNVY/pKSVS5OGJDxkyIO0/XY6kIC6GY2tc3yv3OyaIX1peG5PVd4VdfXcSnyob7/pTp4PnX9v3KfEJeBb87vJd/VIFDYmOJus4PzX@TVeKy3enoTZ1l4aFAZ7ogC9xU2jV6OFm21lGKJgMhK6lUTY854t1iGF40mkcNVW/IwQHCP/Noanx64P55hauCgxai5Wsq6RW5FlIrhbyCc9xJFolYzxS2RpUJFNZpvrlXM9VIv5aHkP1vwlnZfoAxGNGSKLhJowipU@m2EY4j8 "PHP – Try It Online") [Answer] # Java, 435 bytes The function itself takes 435 bytes. There is certainly room for improvement, "high level" by analyzing the rules about where to place which character (in the end the S is point-symmetric), and "low-level", by classical golfing (maybe pulling out another variable or combining two of the `for`-loops). But it's a first shot with this rather ungolfy language: ``` import static java.util.Arrays.*; import static java.lang.System.*; public class CoolS { public static void main(String[] args) { print(1); print(2); print(3); } static void print(int n){int i,r,d=3+6*n,w=3+n*4,h=6+n*10,m=n+n,v=w/2,k=h-1,j=w-1;char t[],S='/',B='\\',P='|',s[][]=new char[h][w];for(char x[]:s)fill(x,' ');s[0][v]='^';s[k][v]='v';for(i=0;i<1+m;i++){r=i+1;t=s[r];t[v-r]=S;t[v+r]=B;t=s[k-r];t[v-r]=B;t[v+r]=S;}for(i=0;i<m;i++){r=2+m+i;t=s[r];t[0]=t[v]=t[j]=P;t=s[k-r];t[0]=t[v]=t[j]=P;}for(i=0;i<1+n;i++){r=2+m+m+i;t=s[r];t[i]=t[i+1+m]=B;t[j-i]=S;t=s[d-i];t[i]=S;t[v-i]=t[j-i]=B;}for(char x[]:s)out.println(x);} } ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 1024 bytes ``` i'0'-i1+:?!v1-'0'-$a*+1v v < < >~ :1-2*3+ >1-' 'v v oa&0~~~< v&1:oa*2:~o'^'^?:o < >~'/'o$:v <^ < >>' 'o1-: ?v v >@ '\'o$v v -1o< > v >:?vv^ -1< ^ < :^ < ~ ~> \:>:?v v >'/'v^o' '^!?:-1<:< > ' 'o^ >'\'o:1-?v^ - vo' '<:&o'/' < < ^^?:o' '\ \ >' '/'\'\~$^ > o:?v~1>$ :?v$^ ~! oa $+2$-1 < ^1\1-:?^~'\'oao v / \-1<:@@~o/o1- v^a< >1+^v:$-2<vo'\'< ^@~<v < v^?:+1v!?:-1&+2/ / / \ \' '^!?:< < >$@@:>1-' 'o:?v^ >~'\'o$v^ oa< > ^ /-1 /-1 / \ \ \:0:< ^ < v -1< :v o' '<^ +1$-2 < v -1< >~&~1& >:2*:1->'|'o1>@@:>' 'o1-:?^~@'|'o:?^~ao: ?^~&?^ 1+2*0 >:>:?!^' 'o^ >>1-: ?^~'/'o:2-?^@@2*ao>' 'o:?^'v'o ; ``` Takes one number `1-99` as input and draws the Cool S. The program uses only one stack to store the number of spaces. It is almost not golfed, coded just for practice and fun :D [Try it online!](https://tio.run/##jVOxjoMwDN35CleKiASKaNLNh5J8CLLEcrpOGU7KdMqv9@yQtrTccBnAgO33/Pz4vH5/3W5XfdbmakcMp2yNPKh1GG3uMjzODLu486UGaI0bLiN4rgJ9z95V/eOktT@XUuYOcm8xrYPDkjRpCpheYf9xfNGTTgorhZl2hD0TTNYghPw3RR9BL1yb60dj0x7aP8MMHkPOxClbBjUIpBexyhGitDYLSounWp5JZ0rMkE4BuS/OAimMiT8yKxY6ZOoMZMmasU9cwjAHeUhk45SFUUBmnrh8KYr7QGLQYr3ivYWshG051QUAqNEpY7ldR3ZhlQIVgV3TUanpHixCNMaSJta1TkKr8LYjZVTGzcx10Y0hxTK/tpKFM1m2WZ25H930DvOEegRNo/nNl17FiJsLZUp6uKFulDafMeL7NrfEiUffrn8g3u94xqPaexZtPLEF@6/uiWC0rMTDxrkldEytL7Z/@gvdwDv2@odN6mWWZldeRJSXEqwJAfjeBzpYy45uOLdWbK4TNfP4anmqvwU6EyhGN6zJb0KRzjrBx@12ufwC "><> – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~321~~ 307 bytes Thanks to @EsolangingFruit for saving 14 bytes ``` n=int(input()) b,f='\/' c,l=4*n+3,10*n+6 r=range h=c//2 L=[c*[' ']for _ in r(l)] L[0][h],L[-1][h]='^v' for i in r(h):a=L[h-i];a[i],a[c+~i]=f,b for i in r(2*n):L[h-~i][0::h]='|'*3 for i in r(n+1):a=L[h+h+i];a[c+~i],a[i:c-1:h]=f,b*2 for i in r(1,l//2):L[l+~i]=L[i][::-1] print('\n'.join(''.join(i)for i in L)) ``` [Try it online!](https://tio.run/##TZBdaoUwEEbfswrfxvxYjZY@pGQH2UFuWryh3qTIKMEWCqVbt4m9FJ9mIOc7mZn1awsLDvuOOuJWR1w/tppSchWThksLxItZPzLkg5BdLk8k6TTi7Y0E7du2J0ZbzyxU4KYlVa9VxCrVM3XE2M7Z4ISxjSyNhpdPIAWKf1CgatTGhia659FGJ0br@U90ehLXM9czpKpw@c12ShXVN7DhzCCXdxsP/PAdqqyMyjeyZLKV9eeMFHNeoKjn41uTZ7BK5WnJmsox4ILw8L5ErOFeI/3PG0r3XQ6/ "Python 3 – Try It Online") # [Python 2](https://docs.python.org/2/), 303 bytes ``` n=int(input()) b,f='\/' c,l,r=4*n+3,10*n+6,range h=c/2 L=[c*[' ']for _ in r(l)] L[0][h],L[-1][h]='^v' for i in r(h):a=L[h-i];a[i],a[c+~i]=f,b for i in r(2*n):L[h-~i][0::h]='|'*3 for i in r(n+1):a=L[h+h+i];a[c+~i],a[i:c-1:h]=f,b*2 for i in r(1,l/2):L[l+~1]=L[i][::-1] print'\n'.join(''.join(i)for i in L) ``` [Try it online!](https://tio.run/##TZBNasMwEEb3OoV3Y/24tuTShYJuoBsoanFMXamYsRFOoVBydVdKQ/HqG5j3PYZZv7ewoNp3NBG3OuJ63WpKyUVMBs4tkFHMIplnhrwXssvxItKAH@8kmLFVxBo3MgcV@GlJ1VsVsUr1TD2xrvMueGFdI8tg4PULSIHiHxSoHox1oYn@NLjoxeBGfoveTOJy5BRDqguXd67Tuqh@gPVHBrl82Hjgd99dlZVRj40snWxl6tiRYm5VMc/8Jn3uZr3W@ViypvwKOCM8fS4Ra3hkpP9tS/dd9r8 "Python 2 – Try It Online") [Answer] # [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate), 180 bytes ``` ( {2*$~1}) ^\n(( {#3-1}|$1)/( $4| )\\\n){#1+1}((\|$1\|$1\|\n){#1})(( $8|)(\\$1\\)( {#10-2}|$1)/\n){$~1+1}(( {#12-1}|$8)/( $13|)$9\n){$~1+1}$5(( $15|)\\( {#16-2}|$4)/\n){#1+1}$1 v ``` Takes input as a command-line argument. [Try it here!](https://replit.com/@dloscutoff/regenerate) ### Explanation Hoo boy, this is long. It's not actually super-complicated, though; once you get a few basic principles of golfing in Regenerate, this just uses the same techniques over and over. ``` ( {2*$~1}) ``` Group 1: Take the command-line argument (`$~1`), multiply it by 2, and add that many spaces. ``` ^\n ``` Complete the first line with one more space, `^`, and a newline. ``` (...){#1+1} ``` Group 2 generates one line of the `/ \` section. Repeat it (length of group 1, plus 1) times. It contains groups 3 and 4. ``` ( {#3-1}|$1)/ ``` Group 3: Add spaces, one fewer than the last time we matched group 3; or, if group 3 hasn't been matched before, start with the contents of group 1 (arg \* 2 spaces) instead. After group 3, add a forward slash. ``` ( $4| )\\\n ``` Group 4: Add spaces, two more than the last time we matched group 4; or, if group 4 hasn't been matched before, start with one space instead. After group 4, add a backslash and a newline. ``` ((\|$1\|$1\|\n){#1}) ``` Group 5 is the whole vertical lines section, which we're capturing because we can reuse it verbatim later. Specifically, this is (length of group 1) repetitions of group 6, which consists of: pipe, group 1, pipe, group 1, pipe, newline. ``` (...){$~1+1} ``` Group 7 generates one line of the `\ \/` section. Repeat it (argument plus 1) times. It contains groups 8, 9, and 10. ``` ( $8|) ``` Group 8: Add spaces, one more than the last time we matched group 8; or, if group 8 hasn't been matched before, start with empty string instead. ``` (\\$1\\) ``` Group 9: backslash, group 1, backslash (capture for reuse later). ``` ( {#10-2}|$1)/\n ``` Group 10: Add spaces, two fewer than the last time we matched group 10; or, if group 10 hasn't been matched before, start with the contents of group 1 instead. After group 10, add a forward slash and a newline. ``` (...){$~1+1} ``` Group 11 generates one line of the `/\ \` section. Repeat it (argument plus 1) times. It contains groups 12 and 13. ``` ( {#12-1}|$8)/ ``` Group 12: Add spaces, one fewer than the last time we matched group 12; or, if group 12 hasn't been matched before, start with the most recent contents of group 8 instead. After group 12, add a forward slash. ``` ( $13|)$9\n ``` Group 13: Add spaces, two more than the last time we matched group 13; or, if group 13 hasn't been matched before, start with empty string instead. After group 13, add the contents of group 9 (two backslashes with some spaces in between) and a newline. ``` $5 ``` Add the contents of group 5 again (vertical pipes section). ``` (...){#1+1} ``` Group 14 generates one line of the `\ /` section. Repeat it (length of group 1, plus 1) times. It contains groups 15 and 16. ``` ( $15|)\\ ``` Group 15: Add spaces, one more than the last time we matched group 15; or, if group 15 hasn't been matched before, start with empty string instead. After group 15, add a backslash. ``` ( {#16-2}|$4)/\n ``` Group 16: Add spaces, two fewer than the last time we matched group 16; or, if group 16 hasn't been matched before, start with the most recent contents of group 4 instead. After group 16, add a forward slash and a newline. ``` $1 v ``` For the last line, add the contents of group 1, a space, and `v`. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~271~~ ~~261~~ ~~253~~ 230 bytes -10 bytes by moving `2*` inside `S` macro -8 bytes by placing `u,d` in the global scope and replacing `(n-u)` with `d` -23 bytes by abusing the C preprocessor, thanks to @ceilingcat ``` #define S(i,c)printf("%*s"#c,2*i,""); #define R(m)}for(u=0,d=n*m+1;d--;u++){S(0+ #define V(x,y)S(x,\\\n)R(2-1)0,|)S(n,|)S(n,|\n)R(y)u,\\)S( u,d;f(n){{S(n+1,^\n)R(2)d,/)V(u+1,1)n,\\)S(d,/\n)R(1)d,/)S(u,\\)V(n,2)d+1,/\n)}S(n+1,v\n)} ``` [Try it online!](https://tio.run/##PZDBasMwDIbP8VOYlIKUOCwuO9XLSzSQkxkMuxk6RBvtPFayPHumJGQXyf7/Tz9IoXoPYZ4P8doTX3ULZAJ@3oi/esiPxT0/BHMqyOQ5OrVTFxhw6j9ukJraxIaLobQuVpVLZYljC3X5j3bwYx7YSvXeM17gVFmsza9IvNdVf2ASRASVTHQ9MI6SxKU1r9scRvOEHSRRLPLGirSadjVbWCM6yRRauMWctpDv5TnLWnp4IwbUo8qWHzmVySYaSDe6dpr0i36WJossSLafwvORzp4950aTnCLLelj7pKb5Dw "C (gcc) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `C`, 49 bytes ``` \^?d›(\/n꘍øM)\|?꘍m∞?dḊ?›(\\?꘍m?›n-d꘍\/J)W:ṘRJṪ\vJ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJDIiwiIiwiXFxeP2TigLooXFwvbuqYjcO4TSlcXHw/6piNbeKInj9k4biKP+KAuihcXFxcP+qYjW0/4oC6bi1k6piNXFwvSilXOuG5mFJK4bmqXFx2SiIsIiIsIjMiXQ==) Will add explanation tomorrow. ]
[Question] [ This challenge is inspired by [Fortran](https://gcc.gnu.org/fortran/)'s idiosyncratic implicit typing rules. Your task will be to determine the data type of the object `GOD` according to the implicit typing rules explained below. ## Background Fortran 77 has six data types: `CHARACTER`, `COMPLEX`, `DOUBLE PRECISION`, `INTEGER`, `LOGICAL`, and `REAL`. Any object not explicitly declared to have one of these types is *implicitly* assigned a type by the compiler, as determined by the first letter of the object's name. The default implicit types are: ``` ---------------------------- First letter | Implicit type -------------+-------------- A-H | REAL I-N | INTEGER O-Z | REAL ---------------------------- ``` For example, the object called `NUMBER` (first letter N) has implied type `INTEGER` whereas the object called `DUMBER` (first letter D) has implied type `REAL`. These rules lead to the [old joke](https://ell.stackexchange.com/questions/163171/god-is-real-unless-declared-integer) that `GOD` is `REAL` . . . unless declared `INTEGER`. The default implicit types can be overridden using `IMPLICIT` statements. For example, ``` IMPLICIT DOUBLE PRECISION (D,X-Z), INTEGER (N-P) ``` means that all objects whose names start with D, X, Y, or Z now have implied type `DOUBLE PRECISION` and those starting with N, O, or P have implied type `INTEGER`. Objects whose names start with any other letter retain their default implied types (in this example, `REAL` for A–C, E–H, and Q–W and `INTEGER` for I–M). For the purposes of this challenge, we will adopt a more concise syntax: the `IMPLICIT` keyword (redundant here) will be dropped and we will use the single-character identifiers `C`, `D`, `I`, `L`, `R`, and `X` to represent the six data types (`X` represents `COMPLEX`). Thus, the example `IMPLICIT` statement given above becomes ``` D(D,X-Z), I(N-P) ``` i.e. a series of identifier–range pairs. ## The challenge Assume that the object `GOD` exists in a Fortran 77 program and does not have an explicitly declared type. Write a program or function that returns the implied type of `GOD`, given a compact `IMPLICIT` statement as input. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the shortest submission (in bytes) in each language wins. ## Input * Input is either empty or otherwise consists of 1 to 26 identifier–range pairs. * Input may be taken in any reasonable format (e.g. one long string, list of identifier–range pairs). If you divide the input into identifier–range pairs, each pair may either be taken as is, e.g. `'D(D,X-Z)'`, or split, e.g. `['D', '(D,X-Z)']`. * In ranges, letters appear in alphabetical order and are separated either by commas (for single letters) or dashes (indicating a span of letters). One-letter spans, e.g. `G-G`, are valid. The outer parentheses must be included, but may be replaced with other paired delimiters (e.g. `[]` or `{}`) if desired. * `IMPLICIT` statements are guaranteed not to overlap. That is, no letter has its implied type specified more than once. * Alphabetic characters must be uppercase. ## Output The uppercase identifier, `C`, `D`, `I`, `L`, `R`, or `X`, that represents the implied type of the object `GOD`. If the input is empty, your code must return `R` (the default type of `GOD`). ## Test cases Input -> Output ``` '' -> R I(M-Z) -> R I(A-Z) -> I I(G) -> I I(G-G) -> I L(A,B,D-H,M-X,Z) -> L D(D,X-Z), I(N-P) -> R L(B,D,F,H,J,L,N,P,R,T,V,X,Z), C(A,C,E,G,I,K,M,O,Q,S,U,W,Y) -> C D(S-Z), D(J-Q), D(A-H) -> D I(I-K,M,R-T), R(N-P,U-Z), D(D-F,H), X(C,G), C(A,B,Q), L(L) -> X I(F), X(N), R(P-P), I(C-C), C(A-A), I(J-J), R(V), D(H-H), X(O), L(B-B), C(R), L(Q-Q), I(D), L(X), R(S-S), C(Y), L(T-T), L(Z), X(U), D(K-K), R(G), X(W-W), D(I), C(L-L), R(E), I(M) -> R ``` Note: In the first test case, single quotes denote string boundaries. ## Bonus imaginary internet points! Awarded to answers that only use characters from the standard Fortran 77 character set: the 26 uppercase letters `A-Z`, the 10 digits `0-9`, the space , and the 12 characters `+-*/=().,’:$` [Answer] # FORTRAN IV (Compiled with [gfortran -ffixed-form](https://gcc.gnu.org/fortran/)), ~~309~~ ~~291~~ ~~290~~ ~~280~~ ~~398~~ ~~393~~ ~~392~~ ~~334~~ ~~237~~ 231 bytes + Bonus imaginary Internet points --- **This should now be a proper FORTRAN IV program, with no anachronisms!** --- ``` REALS(200) DATAG,R,H,A/1HG,1HR,1H-,1H(/ READ 9,S 9 FORMAT(200A1) DO1 I=1,200 C=S(I) IF(C.NE.A)GOTO2 T=S(I-1) GOTO1 2 IF(C.LT.G.AND.S(I+1).EQ.H.AND.S(I+2).GE.G.OR.C.EQ.G)GOTO8 1 CONTINUE T=R 8 PRINT 9,T END ``` [Try it online!](https://tio.run/##PVDJbsMgED3DV/gI6jMJPiWHHCgm2K0DCSbdblFbR5W6SGkP/fq64EhBGol5m2Zm@Dr9nA6f5XE4f8aRBKO6nlXzOaekVlFZBDRQM9lYyCakKlOxGc3Kuliip0V6S7L2YaNidiqZvV4W7Uoi9ZToVc/aBLZrpoUzQnHro68oiZkosz4DcoqqzrIuCiuUq0VSXEkuzE40l77iwprE@yB0ZuwUuJj8kmjvYuv2JueHCVuQbWhdTONGSoyrx7Fj16ixTrvdoIPDNu0ZcYcHPHEUmiloGFi0uMUGHjv02OMej/zveXg/HL/Hchjefl9fynS7j38 "Fortran (GFortran) – Try It Online") Here's [the same code embedded in a loop that runs through the entire test suite](https://tio.run/##PVLNTuMwED4nT5Gjo50xdU9w4ODaqePWSVrHpYUbAoKQdkFi97BPv9nxBHFwxvP9zSTK9PH55/PxHV@n5TLPRWx0GMV6tarLwuqkHURoQV@p1oFqIx2kI67KqlKrVZbb6gZGaqvqptgOsdMp27XKAYOq/K0C6svC3I7CE@i3wsi@kbp2QxrWZZEygVmfAcVR60UWknRS91aS4oeqZXOU7Xe/rqVriB@iNJlxHHjNflWYoU@@PzU5PzJ2XRyi7xOtm5ZR@Q3KountPJdedPhQU9FLcfxAKkFo2IDFFjq8AJFWWLiQCiovejxkBfGwpe@0gwA9HOibJbiDrIbKkN9AAw487KGDAY4wwgnOcJ@zRk6yYodHrhrbPNpj1kZMBMY8Bk5fQos0iW4XYcB95W8gm4MI2bplsmfjgfbLexo0ixQ19zvcMX/HkS0ugQOHbHDD2sjdkffywnJ3YdeIIyvuGUu8ZBAPnHHixD3uWekYO@OZUc@ugIG5hnO7@t/T9PPx9feM0/T29@UZ6Wf89R8). I don't think this can be done with TIO's header and footer. --- *18 bytes off thanks to @JonathanAllan, who pointed out that one IF statement wasn't needed.* *1 more byte off by eliminating a stray space between `CHARACTER` and `S` at the top.* *And 10 more bytes by rearranging the spaghetti code a bit.* *Added 118 bytes to put it in proper FORTRAN IV fixed-column punch-card formatting. (This is for historical accuracy -- it isn't necessary for proper functioning under gfortran.)* *Shaved off 5 more bytes: Cleaned up the GOTOs a bit, and changed the treatment of characters so it's actually correct for FORTRAN IV.* *1 more byte off from removing an unneeded space in the `DATA` statement.* *58 bytes off by streamlining the flow of control through the various IF statements.* *97 more bytes off by: (1) eliminating variable `P`; and (2) replacing the spaces required at the beginning of a line with a tab character, which I found is allowed, according to an old FORTRAN IV manual. (I was thinking of punch card machines, which, as I recall, didn't have a horizontal tab, but I forgot about teletype machines, which did have a tab key.)* *Thanks to @Dingus for 6 more bytes (from removing the `B` in the `DATA` statement which was no longer needed after `P` was eliminated).* --- I've limited myself to FORTRAN IV constructs here. This should now be a correct FORTRAN IV program, without such things as the `CHARACTER` data type and quote-delimited strings, which were only introduced later. Characters in FORTRAN IV needed to be entered as Hollerith constants, and they could be stored in variables of type REAL (and probably other types sometimes too, but there was no CHARACTER type originally). (As I recall, a real could hold 5 ASCII characters from what we now call a string. I think they were padded with spaces if there were fewer than 5 characters in a grouping. The single characters I use are each stored as a real, padded with extra space characters in the real.) Input is on stdin, on one line, just like the OP's test cases. Output is on stdout. --- *FORTRAN IV was my introduction to computer programming -- it was the first programming language I ever learned. When I was a boy, I read through my dad's textbooks when he took a class in it at NYU, which was required by his musicology graduate program. Computer programming (as well as FORTRAN itself) has changed quite a bit since then :) .* --- [Answer] # [Python 3](https://docs.python.org/3/), 61 bytes ``` lambda i:[a for a,b in i if re.match(b,'G')]or['R'] import re ``` [Try it online!](https://tio.run/##hc0/C8IwEIfhPZ/itstJ6uImdBCqhY5OxZghVUOvtU0JWfz0sXTyHzjeezz8pkds/bhJLj@nux2aqwXeagvOB7CqAR6BgR2E23qw8dLKRmGJZHzQeEQjeJh8iPM7cS6FxgIVoC5UnZ0MGjWXeil7tcuqpZCYAo9RrpxkItFBDv/g4RN2M@zfYPkDVt@LPb0ciETpCQ "Python 3 – Try It Online") **Input** a list of lists of the form `["<type char>", "[<var letters/ranges separated by commas>]"]` (*eg* `[['D','[D,X-Z]'],['X','[E,A-J]']]`). **Output** a list of of one string of type char. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṪḊṣ”,Om2r/71eƲƇµƇȯ”R ``` A full program accepting a list of pairs as defined in the specification (each being `[type_character, ranges_string]`) which prints the appropriate type character. **[Try it online!](https://tio.run/##y0rNyan8///hzlUPd3Q93Ln4UcNcHf9coyJ9c8PUY5uOtR/aeqz9xHqgaND///@jo9U91XUU1DU8db11fHWCdEM01WN1FKLVg8CifroBOqG6UVAxF7CYi66bjgdUJAIs4qzjDuU7g/mOOk46gVARH7CID5AXCwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##ZVG7SsNgFN59im5R@A6ii3OTtLnfmyZpyNhF6uLmJi4B38HJTQRBEOyqEHyN9kVimls9v@P5znf7z3@93mzu6nq3fdl9Pu62z/v7J3g3l7fnVxfr6r0qvz6q8uetQcP6u9w/vGZ1nefFCfJcMiRMpFOHVmdS8ReZ/kM0caYjYncayFBJh0Mpjmq13alIW0dMBr1LvqBv1JhDhwkbLnyEWGCJzuugU/oUBTNoMGDBgYcAEWIkyITEaMzrZpMCNk9JF15k0MExpEXPC4eeiAUvlZqePZK2iAJNaCljyOteZwtpc6Z3Wabf3uZ4K4UU7k5TtjfJZPola6sT7@qxXjLJzDtk22C8Wpeksm3KUiOKmFPGuIvxrt28Yp1i1tgiizlrjJtQwtgGS7XJZtoZ6@@0v1D8Ag "Jelly – Try It Online"). ### How? ``` ṪḊṣ”,Om2r/71eƲƇµƇȯ”R - Main Link: list of pairs, [[type_char, range_str],...] µƇ - filter keep those for which: Ṫ - tail & yield (removes the range_str which we now process ...leaving [type_char] as what the filter might keep) Ḋ - dequeue - remove the leading '(' ṣ”, - split at commas (e.g. 'A,F-H,K-K)' -> ['A', 'F-H', 'K-K)'] O - to ordinal (vectorises) -> [[65], [70,45,72], [75,45,75]] Ƈ - filter keep those for which: Ʋ - last four links as a monad: m2 - modulo-2 slice -> [65] [70,72] [75,75] / - reduce by: r - inclusive range -> [65] [70,71,72] [75] 71 - 71 e - exists in? -> 0 1 0 - }--> -> [[70,45,72]] (non-empty is truthy) - }--> [[type_char]] or [] ȯ”R - logical or with 'R' (i.e. 'R' if empty) - implicit, smashing print ``` [Answer] # [sed](https://www.gnu.org/software/sed/) -E, ~~50~~ ~~45~~ 44 bytes *1 byte off thanks to @user41805.* ``` s/^/R(G/;s/(.)*\([^)]*(G|[A-F]-[H-Z]).*/\1/; ``` [Try it online!](https://tio.run/##LY47c8JADIT7/ApKmVnhSU3lB36ewdgYm2eVTCYNZMZJl98e526hOZ203640vr/px@1nmkb/6jeS@svRl4U3P8vp6l3mkv6eAk0uesr0ePEWc//86i@n6SWXSo@eLcGjpHzUFiMBQsSaodIBVowlxmApzHJZa@0IqyNBhgIGa9RosMMejsYssv4IK6TIUaLCBlu06NDj4LJaJsVS6JY10MytztWxje7ssHFr0D3BWO0m@xskQvrMD@HMRoyzJhTXNNb2PndnpNED1YB9oQX1PSMzfQRuGBJqSLZht@VducTsBrpabUkcONvxSCNHZnRMLLUkmXLWa89pTpdRQ23F3Mr7u399f95v46Srfw "sed – Try It Online") This takes input on stdin formatted on one line just as in the OP's test cases, and output is on stdout. [Answer] # JavaScript (ES6), 39 bytes Takes input as an array of `['type','[patterns]']`. ``` a=>(a.find(a=>'G'.match(a[1]))||'R')[0] ``` [Try it online!](https://tio.run/##dZNPb4JAEMXvfoq9LSRvTHttg42CIor/UCst4bBRbG2sGDVND353iyvoaNsLYfbN/N7bCXyoL7WdbhbrHa3SWXKYWwdlVQxVni9WMyN7la4sf6rd9N1Q0X1smvu9DKQZ3cWHx6gkRBTFENlJDF1E0pOQUYdeYxn/pVTPinejuP@d0x@Kr1mowaEmOhSioPqXHufY4yDUjshpXer/TqZpGQsNNNGCjy76CDDCM07kbNo@Odqow4WHNjroYYAhxpjgJWfaN@7DwltXLRqwqkrNfMq5ubFHR3pAo1N3kOfG@IrmUJb2VIfH2oZ7lbSG3E3fzs@9whuvBiN0mV9f76nYmk02Z1OVaS1qsblnlrBJPF@PpalRjfECpgyKHWm2w5SQuQxpyOZfWNeo2JquXpn/mCVrU5vRXNY1oQnr85iLTz6bqbOUncsXVYpL5Xm6qavsfzEiBZF8r5PpLpnFprAqYpqutukyKS/TN2NuKBPi@BSWde4TT0L22lI8CNmoen7dkaZ5@AE "JavaScript (Node.js) – Try It Online") ### Commented ``` a => ( // a[] = input array of [type, pattern] a.find(a => // find in a[]: 'G'.match(a[1]) // an entry whose pattern is matching 'G' ) // end of find() || 'R' // find() returns undefined if nothing is found, // in which case we use the string 'R' instead )[0] // extract either the type of the entry that was found // or the first (and only) character of 'R' ``` [Answer] ## Ruby, 37 bytes ``` ->x{(x.find{|_,r|/#{r}/=~?G}||?R)[0]} ``` [Try it online!](https://tio.run/##XVJdT@pAEH3vr9jEh26TM1V/ABpotRQWhPJVbZob7gUiiSIBTGoo/nWcnVZNbh/aM3M@ZtLd3fvfj/Oqcaab4qgLf7XeLI7lH@zKy4vj7nTZ@LyNTmV5m3jZVX46H5b7w141lOvEukdPnqIblTBu1jhmHP0i@sZGN9FCSG30KEWlNU6oQ6TshIp1nwZ1mtGsxD3a6MCgjwESjDGF9UEFnBTgDhFidNHDA4YYYYIZHsUfcOpIMkPdoaF8m9QWLuSdYrKuhMbMJHYqJrU6JJ7JKNUBonpSCzbBaCP@lP33ouiLe8A7290DCio9NaXuUEf4qeS2qUp9kKQWtUSbSDWUDWMdSpWKa0QjUTxKbyybGv0kGRNJ7FJXlJH0ZjSTbiwuQ0a4O8nt1f/U9V/Wm@U@u/Z9us4dR87RX87/PavFmyptWTqKH4ug5ht7yBb7@@3L@qBdG@N6P5L/WDDnv863x7IoVVbwVYEq6mH@Yadd7VlNlrtefpKQagK/WetIZyuJFXznS7bKbJ3/NljsLDeL8xc) Takes input as pairs with brackets, and interprets the second element of each pair as a regexp. [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=pairgrep -ap`, ~~53~~ 30 bytes ``` $_=(pairgrep{G=~/$b/}@F)[0]||R ``` [Try it online!](https://tio.run/##NU/dS4NQHH33r/gxjCmcO@1hL4q1pfNj6dbutlZdJGyMkCQvTgbR6k/vJkYv58D5giMPTTVW@t6TtZyE7h8q/dkzZFE2r81Bfkbet6W/WF@T0BR2fj5z5R6Lj8GJBiPD0vfWNU@ieOPs@HIRma528eYZpqs33nDoKp9EytKcOIlZTgmJLCd2RVxLSdwgQIgYc6RY4A4cG9zjAU85dbUpfMwQIcEtMiyxwhpb7PDYD/haIGjNumhAYs5WPU9Z3JvBTy3bsn4/Kpal5bF1nG1bVt7/oU4dj@xLW7FCVr8 "Perl 5 – Try It Online") **Input**: A single line, with literal square brackets: `type [letter|range...] ...` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~37~~ 36 bytes ``` $ R(G 1!`.(?=\([^)]*(G|[A-F]-[H-Z])) ``` [Try it online!](https://tio.run/##LY5PT4NAEMXvfIqaaDKYNyZ@AGOALcvSpX@gLRSsqQcPXjwYj3533H0tB2Zn3u@9mZ/P36/vj/lB7GW@T1qxyfPd5UleX95kek/Pj2L/pkzLs06Vjuc0nedkEb/ESaNjGkp2LZY/DcVLhhxGKzQ6IIhGDIZAYeFkrdtIBB0lKtTwWGOLFnscEWksiuAvsISFwwoNNtihwwE9TjGrY5KRWnesmVZxtdPItroPwzauweEGGg2bwmuQAvaWnyOavfhoLSmuadyG@@KdhRZXVDP2tdbUj4ys9Bq4YUiuOdmW3Y53OTHsBro67UicONvzSC8jMw5MXOmKpOWs155TR5dXT23J3Cb9Bw "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 1 byte thanks to @MitchellSpector. Explanation: ``` $ R(G ``` Default to Real. ``` .(?=\([^)]*(G|[A-F]-[H-Z])) ``` Match a letter that's followed by a `(` and then any non-`(` characters including a `G` or a range that includes a `G`. ``` 1` ``` Only output the first match, in case the default is a duplicate. ``` !` ``` Print the match rather than the count of matches. [Answer] # [Ruby](https://www.ruby-lang.org/) `-pl`, 47 bytes Takes space-separated arguments from STDIN. ``` t=?R gsub(/(\w)(\S+)/){t=$1if"G".tr!$2,''} $_=t ``` [Try it online!](https://tio.run/##JY5LawJBEITv/oqNCM6Q6khyl7AP3Yez6r7cVYSAhwQhRNGVEEL@etYpvUz3dH1V3afL7qfr2vFr3vs4X3ZqpLbfWm2LRz3Sv@148Lx/74f9p/b0MHjBcPjXG7yN267rxSqVjbbFvZfw9ogtRrnwEEiEVBpYMVABGks5sZrLkoCVMUWEBAZzLJGjxAqEHd@6fUwQIsYMKRbIUKBCjTWTCuYEKpGMxZWIa2MhmUupnZwrUN2pQOwS7TTKR3hP9mB9Rhm6plTmtCztVfY4X/wbJS5/iSTUVgyK5BazoNcTj1TOPuMZsQrYN6QLKSiuOSh5j1EbOiumzGRGJuSglpqjmLQRw/mEUan@Pxzb/eHr3Mnx8wo "Ruby – Try It Online") [Answer] # Java 10, 63 bytes ``` m->{var r="R";for(var p:m)r="G".matches(p[1])?p[0]:r;return r;} ``` Input as an array of String-pairs in the format `["type", "[declaration]"]`. [Try it online.](https://tio.run/##nZVfb6JQEMXf@ylueMJ0hnRfJd2NYot/wCpotSU83EW6iytILlebxvDZXUBjTcM80BfDZTxzf@cwyaz5nuN69e8YbHiWMZtHyeGGsSiRoXjjQcjG5ZExV4oo@cMC9fTg@Z7P4pZe1PKb4ieTXEYBG7OE3bNjjD8Pey6YuFccRX/bCrU8pe24VbwxFS3mMvgbZmrq/fBbv1Lvzm8LXYRyJxIm9Pyoly3T3e9N0fLceb@NViwu6C4AjLdOaDLMpJqE7@wT7ZBXaPW16@NBGSigeDa@@kreUNT5jsj8hgSbiawKDrrQwz7YuIRmmL1S3oNl5Q5YDdAYJ82BChx4hD4MwYIxTMCBGTzDCe7rLcbJgQEPYMIARmDDE0zBhTks4KW5G7fWS1Ua4pQqdbDf/GMNsKR1cFbT1TmHB3Oap4dFSDXFZVk0wKTT6kKdkyp7q7mPR4phTBmbVFNROzAGGiQ3dijVEIfUXc9UfH0kw3ui0ulil6JzKM20dmwq7B6lWVJuXHQpgBeq2ax2wqrSK5XAnEpthCOKzaSaLXBBtRtQbiy0qHseqDjty@xeL5pqHVSjfLWPyrPBs/C8F9yPTIaxtt1JLS3@IzeJui62nbaT0UbrCME/Mm0Vhulse@qhXvS3Spspt4kWfL46E@TH/w) **Explanation:** ``` m->{ // Method with String-matrix as input and String return-type var r="R"; // Result-String, starting at "R" as default for(var p:m) // Loop over each pair `p` r= // Set the result to: "G".matches(p[1])? // If "G" regex-matches the second part of the pair p[0] // Set the result to the first part of the pair : // Else: r; // Leave the result unchanged return r;} // After the loop: return the result-String ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 38 bytes `+` to [@Noodle9](https://codegolf.stackexchange.com/a/201787/68224) ``` $r=$args|?{'G'-match$_[1]} "R$r"[!!$r] ``` Expects input via [splatting](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting). [Try it online!](https://tio.run/##XZLRbtpAEEXf/RUbtK2hvSM1TaW@1E3AToxhIWAgOFkshJADkWhK7UiJRPh2ujvGatInz9yZe2bWmu3v5ywv1tlmc5D3whO7g8w9uchXxev5zg1d@rV4Wq7lXJ@me6cWy7ymT05knh72jrzfrDy9XC/y9MvL1@/flhD/stMzp@66EG7sNmDCSPfoLn0nNI9CVAnhfym9E5RuooWA2uhRgtKqylKgAySGBhHpPg3ejlHaeHCFNjpQ6GOAGGPcwBIgfMP0cYkQEbro4RpDjDDBFLcM8Sv@iOmB7tCQv01qc0NQLRuR9cc0NuXYLoHJ0RKQmW6iRPsIjzNbsBilFUOSCnLFbX1GDMw77Ht88ksTNTnvUIfrNwxvU4m@ZlyLWtwbczbkXSMdcJawa0Qj7rhlbczrKn3HjAkTu9TlzpC1KU1ZjdilSHHtkrm96j@LV/Fh5wgh88cVhMxetuaQ5NwqD482vqjbkqBiu3l4Em79/Ic3SxuYFZ9c9grU5fxN2ZvphsHuGwzNCoP4KMx5XhickWol7Wc5qvbZHqLmmLI/bEid/eEv) [Answer] # [Perl 5](https://www.perl.org/) with `-apF'(?=\[)'`, 25 bytes Accepts input as: ``` A [A-F,H-M] B [N-Z] ``` ``` $\||=$_ x"G "=~<>}{$\||=R ``` [Try it online!](https://tio.run/##K0gtyjH9/18lpqbGViVeoULJnUvJts7GrrYaLBT0/78nV7SnrreOr06QbkgsVxBXtJ9ugE6oblQslwtXtIuum45HLFcEV7SzjnsslzNXtKOOk05gLJcPV7RP7L/8gpLM/Lzi/7qJBW7qGva2MdGa6gA "Perl 5 – Try It Online") [Verify all test cases.](https://tio.run/##jZBbb9pAEIXf@RUTy5IXaQbUvnJpwQ5gMIRrIAFUUXu5qJaxbEhThfSvu@uxCS@t1KednTnnm7P7fRPvE@nuj0ABGIm@ulxq@jd41doFrfa7Wn9/49Y4MaAOu6NHh5giufHpHPgyjsmTrr@JpOoHJ7mTUSn0K4XC9hiBfwgkHALQ9K9aBbxjAdQtPJ9qutj8/AHUMoDqYIDxFkbKrH96N6BarSp96tSKFWWQr6F0T9L7l@fzXzzuMXiRUWYKZeQDhRKMX2VRxPJyXfYqcRku4ktttSyWV0F5dyVwuAwRyfjsnz78m7BlZAbjP78gR35ESbHpc/J/1oxsG79Gvz6yVCqBlq4/bGG5BD1LAXe1mwTW6wqc9jJQqhyntRq2A3SVM0D6sbwpJmfXVTnvVGd7KHjHQBaSxBZ9ei6m@8eqbuS1rer2raJr7YgGNtGiDvZpgZnWSSxh4UI5EWwxoGFOc4RSYgs72EUHBzjEMU7xEVMfgqlIJt5jG23sYR8fcIQTnOEcn9hvKuqEmZbo0ojPBnV4ZqlMNqWuMU3VZJxuxVmutkjtVNVCmNjONzUxJTjCYf9C@VusGLB7qDKn2U0yMz01@N6lLs8fmduhjPrApCY1WTvm24gT2sLi24JdE5qw4ol7U07qiGdmzJjYox4r29yb05y7Nrsccnh2z9x@9qd/AA) *Note*: the empty test case is missing from the verify all link because my test suite is bad and I should feel bad, but [it works when tested in isolation](https://tio.run/##K0gtyjH9/18lpqbGViVeoULJnUvJts7GrrYaLBT0//@//IKSzPy84v@6iQVu6hr2tjHRmuoA "Perl 5 – Try It Online"). [Answer] # [Pip](https://github.com/dloscutoff/pip), 18 bytes ``` @@Y'G~``.@>_FIg|'R ``` Takes each identifier–range pair as a separate command-line argument, in the format `D[D,X-Z]`. [Try it online!](https://tio.run/##K8gs@P/fwSFS3b0uIUHPwS7ezTO9Rj3o////LtEuOhG6UbH/PaP9dANi/ztHu@l6xAIA "Pip – Try It Online") ### Explanation ``` g The list of cmdline args FI Filter on this function: @>_ Everything after the first character ``. Convert to Pattern (regex) by concatenating with an empty Pattern 'G~ Match against the string "G" We now have either a list containing the pair that matched, or empty list |'R Logical OR with "R": if no pair matched, use "R" instead Y Yank (to get the operator precedence to cooperate) @ Take first element: the pair that matched, or "R" @ First element of that: the identifier from the pair, or "R" Autoprint ``` [Answer] # [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), 271 bytes ``` mod G is pr LIST{String}+ LEXICAL . op g : String ~> Qid . var A B C D :[Qid]. var X Y :[String]. ceq g(X Y)= A if A '`( B C D '`) := tokenize(Y)/\ C == 'G or substr(string(C),0,1)< "H" and substr(string(C),2,1)> "F" . eq g(X S:String)= g(X)[owise]. eq g(nil)= 'R . endm ``` The result is obtained by reducing the `g` function with a Maude list of strings of the form `"A(B,C-D)"`. The result will be a quoted identifier of the letter for the type of `GOD`, e.g., `'R`. ### Example Session ``` \||||||||||||||||||/ --- Welcome to Maude --- /||||||||||||||||||\ Maude 3.1 built: Oct 12 2020 20:12:31 Copyright 1997-2020 SRI International Thu Oct 21 00:28:50 2021 Maude> mod G is pr LIST{String}+ LEXICAL . op g : String ~> Qid . var A B C D > :[Qid]. var X Y :[String]. ceq g(X Y)= A if A '`( B C D '`) := tokenize(Y)/\ > C == 'G or substr(string(C),0,1)< "H" and substr(string(C),2,1)> "F" . eq g(X > S:String)= g(X)[owise]. eq g(nil)= 'R . endm Maude> red g(nil) . result Qid: 'R Maude> red g("I(M-Z)") . result Qid: 'R Maude> red g("I(A-Z)") . result Qid: 'I Maude> red g("I(G)") . result Qid: 'I Maude> red g("I(G-G)") . result Qid: 'I Maude> red g("L(A,B,D-H,M-X,Z)") . result Qid: 'L Maude> red g("D(D,X-Z)" "I(N-P)") . result Qid: 'R Maude> red g("L(B,D,F,H,J,L,N,P,R,T,V,X,Z)" "C(A,C,E,G,I,K,M,O,Q,S,U,W,Y)") . result Qid: 'C Maude> red g("D(S-Z)" "D(J-Q)" "D(A-H)") . result Qid: 'D Maude> red g("I(I-K,M,R-T)" "R(N-P,U-Z)" "D(D-F,H)" "X(C,G)" "C(A,B,Q)" "L(L)") . result Qid: 'X Maude> red g("I(F)" "X(N)" "R(P-P)" "I(C-C)" "C(A-A)" "I(J-J)" "R(V)" "D(H-H)" "X(O)" > "L(B-B)" "C(R)" "L(Q-Q)" "I(D)" "L(X)" "R(S-S)" "C(Y)" "L(T-T)" "L(Z)" > "X(U)" "D(K-K)" "R(G)" "X(W-W)" "D(I)" "C(L-L)" "R(E)" "I(M)") . result Qid: 'R ``` ### Ungolfed ``` mod G is pr LIST{String} + LEXICAL . op g : String ~> Qid . var A B C D : [Qid] . var X Y : [String] . ceq g(X Y) = A if A '`( B C D '`) := tokenize(Y) /\ C == 'G or substr(string(C), 0, 1) < "H" and substr(string(C), 2, 1) > "F" . eq g(X S:String) = g(X) [owise] . eq g(nil) = 'R . endm ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` k@'GrXÌÃΪ'R ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=a0AnR3JYzMPOqidS&input=W1snRCcsJ1tELFgtWl0nXSxbJ1gnLCdbRSxBLUpdJ11d) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ ~~21~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ʒθ',¡εáÇŸ}˜71å}˜'Rªн ``` Input as a list of pairs in the format `["type","(declaration)"]`. [Try it online](https://tio.run/##yy9OTMpM/f//1KRzO9R1Di08t/XwwsPtR3fUnp5jbnh4KZBSDzq06sLe//@jo5U8lXSUNDx1vXV8dYJ0QzSVYnWilYJAYn66ATqhulEQEReQiIuum44HhB8B4jvruEN4ziCeo46TTiCE7wPi@wDZsQA) or [verify all test cases](https://tio.run/##XVC5TsNAEP2VyE1AelNQUUY@Et@Oz8RJ5AIkCioKJKQUtNCnpklBQ4@UhiYWDUhRvoEfMfbaVmZT7b6ZecfMw@PN7f1d9bQeKYO/l81AGa2rn81hN8R@e/gst@Xr9@759@36qnyvn2G8/zh@VahWq5WiQFGKAoP6a9f/C5@Wl1JBPS@YZ5BOBU8QoMEgCz7lOFGNpmUgF2rouAGFMrdmYgILDjwECBEjxQytTk3SW30dY5iw4cLHFBESZJhjIXslvZNADkUMqWTJS9jUaMWUtkNxFw6ZJGJQna3FeYN1mFIuDZ2J2MWTLSaMGDCbUNygv4hOOpcklfUcchhvxoJZxGNNWQiNNKYXs07UX0RoG6yTM5eEEsZfsKm0P5ZAS@afsWQuuUzNZFNzmrM5m7l45DHOmKX0m5MW/w). **Explanation:** ``` ʒ # Filter the (implicit) list of pairs by: θ # Pop and push the last value of the pair # i.e. ["I","(I-K,M,R-T)"] → "(I-K,M,R-T)" ',¡ '# Split it by "," # → ["(I-K","M","R-T)"] ε # Map each inner range to: á # Remove the "(", "-", and ")" by only leaving the letters # → ["IK","M","RT"] Ç # Convert each letter to its codepoint integer # → [[73,75],[77],[82,84]] Ÿ # And then convert it to a range # → [[73,74,75],[77],[82,83,84]] }˜ # After the map: flatten the list of lists of integers # → [73,74,75,77,82,83,84] 71å # Check if 71 is in this list (the codepoint for "G") # → 0 (falsey) }˜ # After the filter: flatten the remaining list of pairs (potentially empty) # i.e. [["X","(C,G)"]] → ["X","(C,G)"] 'Rª '# Append an "R" to this list # → ["X","(C,G)","R"] н # Pop and only leave the first item of this list # → "X" # (after which it is output implicitly as result) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~38~~ 37 bytes ``` ($args+'RG'|?{'G'-like"[$_ ]"})[0][0] ``` [Try it online!](https://tio.run/##ZVNdT@JAFH3vr7jBup3Ge5N93mSzQKulUBAKSNUYU9lZaazAtuO6BvntOC130F2TPsycc8/Hbdr16lkW5ULm@c7@Bd9hsxN2WtyXJ04cOK8/Nk7gUJ49yMa1fQs3ja17/fVGP7utZTWFZaFwYgcBwHHcD5dQ9OnK3UOhgVqfoeATQAaK9lAkWthGnzrYpwSNAcf4wsekcsVKO6Ah057RaiWeYQe7GOEAhxjjBC@w9tEST3t7eIoBhtjDPp7jCMc4xRlespFvcsac4osujfjUog6PJaZ@SJVPTJN6JK4q4fQg9Ul3qc@J8DA4dGjj3jISkfvfazzj8QEbDqsd62098owBtRjrUpfnLjiyQybwnCPa1GZdzMiINwqFz0jCLmMa8@wlMxNeLRJX7DvlpB71WBUwM6MZcyG7RBTxzCkn9quFLRde4XhjAdjy71rOlfyJYJcqVfJRLlWpP0v7tmL/gZriw90FOIJYlmpVSFALCWlRpC8Id3KePpUShofPHLLHdZ7NM5W/wHy1/CML7ZYu9wJ4ztQCUiiz5X0uQea1O6hVNcG3qkghy6dc6RJfQP81zfcemmzYwvAkf7@v5H4zuoa13b0B "PowerShell – Try It Online") Takes strings as is, e.g. `'D(D,X-Z)'`. ]
[Question] [ There are quite a large number of prime generating functions. Pretty much all of them are constructed and are based on the sieve of Eratosthenes, the Möbius function or the Wilson's theorem and are generally infeasible to compute in practice. But there are also generators, that have a very easy structure and were found by accident. In 2003 Stephen Wolfram explored a class of nested recurrence equations in a live computer experiment at the NKS Summer School. A group of people around Matthew Frank followed up with additional experiments and discovered an interesting property of the simply recurrence ``` a(n) = a(n-1) + gcd(n,a(n-1)) ``` with the start value of `a(1) = 7`. The difference `a(n) - a(n-1) = gcd(n,a(n-1))` always seemed to be 1 or a prime. The first few differences are ([OEIS A132199](https://oeis.org/A132199)): ``` 1, 1, 1, 5, 3, 1, 1, 1, 1, 11, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 23, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 47, 3, 1, 5, 3, ... ``` If we only omit the 1s we get the following sequence ([OEIS A137613](https://oeis.org/A137613)): ``` 5, 3, 11, 3, 23, 3, 47, 3, 5, 3, 101, 3, 7, 11, 3, 13, 233, 3, 467, 3, 5, 3, 941, 3, 7, 1889, 3, 3779, 3, 7559, 3, 13, 15131, 3, 53, 3, 7, 30323, 3, ... ``` [Eric S. Rowland](https://cs.uwaterloo.ca/journals/JIS/VOL11/Rowland/rowland21.pdf) proved the primeness of each element in this list a few years later. As you can see, the primes are mixed and some of them appear multiple times. It also has been proven, that the sequence includes infinitely many distinct primes. Furthermore it is conjectured, that all odd primes appear. Because this prime generator was not constructed but simply found by accident, the prime generator is called "naturally occurring". But notice that in practice this generator is also quite infeasible to compute. As it turns out, a prime p appears only after `(p–3)/2` consecutive 1s. Nevertheless implementing this prime generator will be your task. # Challenge: Write a function or a program that prints the first `n` elements of the sequence `A137613` (the sequence without the 1s). You can read the input number `n >= 0` via STDIN, command-line argument, prompt or function argument. Output the first `n` elements in any readable format to STDOUT, or return an array or a list with these values. This is code-golf. Therefore the shortest code wins. # Leaderboard: Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` ``` var QUESTION_ID=55272;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/; ``` ``` 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] # Pyth, 14 13 bytes ``` meaYhP+sY-5dQ ``` Uses `a(n) = Lpf(6 - n + sum(a(i) for i in range(1, n))` where `Lpf` means least prime factor. [Try it here online.](http://pyth.herokuapp.com/?code=meaYhP%2BsY-5dQ&input=20&debug=0) [Answer] # Python 3.5.0b1+, ~~95~~ 93 bytes Link to [Python 3.5.0b1+ release](https://www.python.org/downloads/release/python-350b1/) ``` import math def f(k,n=2,a=7,L=[]):x=math.gcd(n,a);return k and f(k-1%x,n+1,a+x,L+1%x*[x])or L ``` A direct implementation of the recurrence, featuring: * Our good friend `1%x`, and * [`math.gcd`](https://bugs.python.org/issue22486), as opposed to `fractions.gcd`. [Answer] # Julia, 110 bytes ``` n->(a(n)=(n≥1&&(n==1?7:a(n-1)+gcd(n,a(n-1))));i=2;j=0;while j<n x=a(i)-a(i-1);x>1&&(j+=1;println(x));i+=1end) ``` Ungolfed: ``` function a(n::Int) n ≥ 1 && (n == 1 ? 7 : a(n-1) + gcd(n, a(n-1))) end function f(n::Int) i = 2; j = 0; while j < n x = a(i) - a(i-1) if x > 1 j += 1 println(x) end i += 1 end end ``` [Answer] # PHP, ~~101~~ ~~96~~ ~~99~~ ~~98~~ ~~77~~ 72 bytes ``` <?for(;2>$t=gmp_strval(gmp_gcd(~++$i,7+$e+=$t))or$argv[1]-=print"$t ";); ``` **Usage:** Call the Script with an argument: `php -d error_reporting=0 script.php 30` If you want to test it you need to uncomment `;extension=php_gmp.dll` in your php.ini --> `extension=php_gmp.dll` Should I add the extension to my byte count? Any thoughts? **Log:** Saved 3 bytes thanks to Ismael Miguel. Saved 26 bytes thanks to primo. [Answer] # Haskell, 51 bytes ``` d=zipWith gcd[2..]$scanl(+)7d f=($filter(>1)d).take ``` Note that `f` is a function that will return the first *n* elements. Rather than computing the `a(n)` and then working out the differences, we compute the differences `d(n)` and sum them together to get `a(n)`. (Those unfamiliar with Haskell may protest that we need `a(n)` first in order to get `d(n)`, but of course lazy evaluation gets us around this problem!) Ungolfed: ``` a = scanl (+) 7 d -- yielding a(n) = 7 + d(1) + d(2) + ... + d(n-1) d = zipWith gcd [2..] a -- yielding d(n) = gcd(n+1, a(n)) f n = take n $ filter (> 1) d -- get rid of 1s and take the first n ``` [Answer] # Pyth, 30 bytes Very badly golfed, can be considerably reduced. Defines recursive function at front, filters `.f`irst-n, and then maps the difference. ``` L?tb+KytbibK7m-yhdyd.ft-yhZyZQ ``` [Try it here online](http://pyth.herokuapp.com/?code=L%3Ftb%2BKytbibK7m-yhdyd.ft-yhZyZQ&input=20&debug=0). [Answer] # Julia, ~~69~~ 67 bytes ``` n->(i=1;a=7;while n>0 x=gcd(i+=1,a);a+=x;x>1&&(n-=1;println(x))end) ``` This is a simple iterative solution to the problem. `x` is the difference (which is the `gcd`), and then I update `a` by adding `x`. [Answer] # JavaScript (ES6), 91 Recursive gcd, iterative main function. Not so fast. Usual note: test running the snippet on any EcmaScript 6 compliant browser (notably not Chrome not MSIE. I tested on Firefox, Safari 9 could go) ``` F=m=>{ for(G=(a,b)=>b?G(b,a%b):a,o=[],p=7,n=1;m;d>1&&(o.push(d),--m)) p+=d=G(++n,p); return o } O.innerHTML=F(+I.value) ``` ``` <input id=I value=10><button onclick='O.innerHTML=F(+I.value)'>-></button> <pre id=O></pre> ``` [Answer] # Haskell, 74 71 66 bytes ``` f=($filter(>1)$tail>>=zipWith(-)$scanl(\x->(x+).gcd x)7[2..]).take ``` Used the trick here: <https://codegolf.stackexchange.com/a/39730/43318>, and made point-free. (Previous: 71 bytes) ``` a=scanl(\x->(x+).gcd x)7[2..] f m=take m$filter(>1)$zipWith(-)(tail a)a ``` First make the sequence of a's, and then take the differences. (Previous: 74 bytes) ``` f m=take m$filter(>1)$map snd$scanl(\(x,d)->(\y->(x+y,y)).gcd x)(7,1)[2..] ``` Standard list functions, plus clever use of lambda function. Note this is 1 byte shorter than the more obvious ``` g m=take m$filter(>1)$map snd$scanl(\(x,d)n->(x+gcd x n,gcd x n))(7,1)[2..] ``` If we don't count imports, I can get this down to 66. ``` import Data.List h m=take m$filter(>1)$snd$mapAccumL(\x->(\y->(x+y,y)).gcd x)7[2..] ``` [Answer] ## PARI/GP, 60 bytes ``` a(n)=a=7;i=1;while(n,if(1<d=gcd(i+=1,a),n-=1;print(d));a+=d) ``` Taken more or less straight from the definition ***a(n) - a(n-1) = gcd(n, a(n-1))*** Output for `a(20)`: ``` 5 3 11 3 23 3 47 3 5 3 101 3 7 11 3 13 233 3 467 3 ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 24 bytes ``` {⍵<2:5⋄⊃⍭6-⍵-+/∇¨⍳⍵-1}¨⍳ ``` `{⍵<2:5⋄⊃⍭6-⍵-+/∇¨⍳⍵-1}` dfn to calculate the nth element `⍵<2:5` if ⍵<2 return 5 `⋄` else `∇¨⍳⍵-1` recursively find the first ⍵-1 terms `+/` sum them `6-⍵-s` in APL is 6-(⍵-s) = 6-⍵+s, as APL is evaluated right to left `⊃⍭` take the first (least) prime factor `¨⍳` apply the function to the first n numbers, to find the first n elements [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR71YbIyvTR90tj7qaH/WuNdMFiuhq6z/qaD@04lHvZhDPsBbM/J/2qG3Co94@sMI1j3q3HFpv/Kht4qO@qcFBzkAyxMMz@H@agiFXmoIREBsDsQkQmwKxGQA "APL (Dyalog Extended) – Try It Online") Old answer: 46 bytes ``` {l←⍵⋄{l≡≢r←1~⍨2-⍨/⍵:r⋄∇⍵,(+/(0,1+≢)∨1↑⌽)⍵}7 8} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/vzrnUduER71bH3W3AJmdCx91LioCihjWPepdYaQLJPSBklZFQOlHHe1Apo6Gtr6GgY6hNlCh5qOOFYaP2iY@6tmrCZSqNVewqP2fBjav71FX86PeNY96txxabwxS0jc1OMgZSIZ4eAb/T1Mw5EpTMAJiYyA2AWJTAA "APL (Dyalog Extended) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 10 bytes ``` ’ßS_+6ÆfḢ) ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw8zD84Pjtc0Ot6U93LFI8////4amAA "Jelly – Try It Online") *Edit: I decided to revisit my oldest answer and found out that it can be very trivially golfed by 3 bytes. I sure have improved…* Uses the formula `a(n) = Lpf(6-n+sum{i=1,...,n-1}a(i))`. ## Explanation ``` ’ßS_+6ÆfḢ) Main monadic link ) Map over the range [1..n]: ’ Decrement ß Recursively apply this link S Sum _ Subtract n +6 Add 6 Æf Prime factorization Ḣ First element ``` [Answer] # C++, ~~193~~ ~~182~~ ~~180~~ 172 bytes Thanks @Jakube - saved 8 bytes on output. ``` int g(int a,int b){return a==b?a:a>b?g(b,a-b):g(a,b-a);}void f(int *r,int n){int m=1,i=0,a=7,b;while(i<n){b=g(a,++m);if(b>1){r[i]=b;++i;}a+=b;}}int main(){int r[6];f(r,6);} ``` [Answer] # Mathematica, 59 bytes ``` For[i=j=1;a=7,i<=#,,d=GCD[++j,a];If[d>1,Print@d;i++];a+=d]& ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` ↑¡ö▼p+6§-LΣ;5 ``` [Try it online!](https://tio.run/##ASAA3/9odXNr///ihpHCocO24pa8cCs2wqctTM6jOzX///8xMg "Husk – Try It Online") Uses Shevelev's formula from [A137613](https://oeis.org/A137613): `a(n) = Lpf(6-n+sum{i=1,...,n-1}a(i))`. ``` ↑ # input-th element of ¡ # list of repeated application of ö # 4 functions: ▼ # minimum of p # prime factors of +6 # 6+ Σ # sum of list so far §-L # minus length of list so far ;5 # starting with 5 ``` # [Husk](https://github.com/barbuz/Husk), 18 bytes ``` ↑f←Ẋ-¡λS+ȯ⌋→L¹→);7 ``` [Try it online!](https://tio.run/##yygtzv7//1HbxLRHbRMe7urSPbTw3O5g7RPrH/V0P2qb5HNoJ5DUtDb///@/oREA "Husk – Try It Online") Alternative derivation (following the story of the question): difference between adjacent elements of `a(n) = a(n-1) + gcd(n,a(n-1))` with `a(1)=7`, ignoring `1`s. ``` ↑ # input-th element of f← # (without 1s) Ẋ- # differences between adjacent elements of ¡ # list of repeated application of λ ) # this function: S+ → # sum of last element of list so far, plus ȯ⌋ # gcd of → # last element of list so far, and L¹ # length of list so far ;7 # starting with 7 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` n6+UÆßXÃÅx)k ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=bjYrVcbfWMPFeClr&input=Mzg) Uses the LPF formula from the OEIS entry with a little bit of Japt trickery: when reducing a 2D-array by addition Japt just grabs the first element of each sub-array\*. ``` n6+UÆßXÃÅx)k :Implicit input of integer U n :Subtract U from 6+ : 6 plus UÆ : Map each X in the range [0,U) ßX : Recursive call with argument U=X Ã : End map Å : Slice off the first element x : Reduce by addition (of first elements) ) :End subtraction k :Prime factors of result :Implicit output of first element of final array ``` \*Or, for those interested, what actually happens is that each sub-array is run through JavaScript's `parseFloat` function coercing them to comma delimited strings and then `parseFloat` parses that string to an integer until it hits an illegal character, i.e. the first comma. ]
[Question] [ # The Challenge Write a program that can break down an input chemical formula (see below), and output its respective atoms in the form `element: atom-count`. --- # Input Sample input: ``` H2O ``` Your input will always contain at least one element, but no more than ten. Your program should accept inputs that contain parentheses, which may be nested. Elements in the strings will always match `[A-Z][a-z]*`, meaning they will always start with an uppercase letter. Numbers will always be single digits. --- # Output Sample output (for the above input): ``` H: 2 O: 1 ``` Your output can be optionally followed by a newline. --- # Breaking Down Molecules Numbers to the right of a set of parentheses are distributed to each element inside: ``` Mg(OH)2 ``` Should output: ``` Mg: 1 O: 2 H: 2 ``` --- The same principle applies to individual atoms: ``` O2 ``` Should output: ``` O: 2 ``` --- And also chaining: ``` Ba(NO2)2 ``` Should output: ``` Ba: 1 N: 2 O: 4 ``` --- # Testcases ``` Ba(PO3)2 -> Ba: 1 P: 2 O: 6 C13H18O2 -> C: 13 H: 18 O: 2 K4(ON(SO3)2)2 -> K: 4 O: 14 N: 2 S: 4 (CH3)3COOC(CH3)3 -> C: 8 H: 18 O: 2 (C2H5)2NH -> C: 4 H: 11 N: 1 Co3(Fe(CN)6)2 -> Co: 3 Fe: 2 C: 12 N: 12 ``` # Scoreboard For your score to appear on the board, it should be in this format: ``` # Language, Score ``` Or if you earned a bonus: ``` # Language, Score (Bytes - Bonus%) ``` ``` function getURL(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 getAnswers(){$.ajax({url:getURL(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){var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),useData(answers)}})}function getOwnerName(e){return e.owner.display_name}function useData(e){var s=[];e.forEach(function(e){var a=e.body.replace(/<s>.*<\/s>/,"").replace(/<strike>.*<\/strike>/,"");console.log(a),VALID_HEAD.test(a)&&s.push({user:getOwnerName(e),language:a.match(VALID_HEAD)[1],score:+a.match(VALID_HEAD)[2],link:e.share_link})}),s.sort(function(e,s){var a=e.score,r=s.score;return a-r}),s.forEach(function(e,s){var a=$("#score-template").html();a=a.replace("{{RANK}}",s+1+"").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SCORE}}",e.score),a=$(a),$("#scores").append(a)})}var QUESTION_ID=58469,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],answer_ids,answers_hash,answer_page=1;getAnswers();var VALID_HEAD=/<h\d>([^\n,]*)[, ]*(\d+).*<\/h\d>/; ``` ``` body{text-align:left!important}table thead{font-weight:700}table td{padding:10px 0 0 30px}#scores-cont{padding:10px;width:600px}#scores tr td:first-of-type{padding-left:0} ``` ``` <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="scores-cont"><h2>Scores</h2><table class="score-table"><thead> <tr><td></td><td>User</td><td>Language</td><td>Score</td></tr></thead> <tbody id="scores"></tbody></table></div><table style="display: none"> <tbody id="score-template"><tr><td>{{RANK}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SCORE}}</td></tr></tbody></table> ``` **Edit:** Square brackets are no longer a part of the question. Any answers posted before 3AM UTC time, September 23, are safe and will not be affected by this change. [Answer] # CJam, ~~59~~ 57 bytes ``` q{:Ci32/")("C#-"[ ] aC~* Ca C+"S/=~}%`La`-S%$e`{~": "@N}/ ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q%7B%3ACi32%2F%22)(%22C%23-%22%5B%20%5D%20aC~*%20Ca%20C%2B%22S%2F%3D~%7D%25%60La%60-S%25%24e%60%7B~%22%3A%20%22%40N%7D%2F&input=Co3(Fe(CN)6)2). ### How it works ``` q e# Read all input from STDIN. { e# For each character: :Ci e# Save it in C and cast to integer. 32/ e# Divide the code point by 32. This pushes e# 2 for uppercase, 3 for lowercase and 1 for non-letters. ")("C# e# Find the index of C in that string. (-1 if not found.) - e# Subtract. This pushes 0 for (, 1 for ), 2 for digits, e# 3 for uppercase letters and 4 for lowercase letters. "[ ] aC~* Ca C+" S/ e# Split it at spaces into ["[" "]" "aC~*" "Ca" "C+"]. =~ e# Select and evaluate the corresponding chunk. e# ( : [ : Begin an array. e# ) : ] : End an array. e# 0-9 : aC~* : Wrap the top of the stack into an array e# and repeat that array eval(C) times. e# A-Z : Ca : Push "C". e# a-z : C+ : Append C to the string on top of the stack. }% e# ` e# Push a string representation of the resulting array. e# For input (Au(CH)2)2, this pushes the string e# [[["Au" [["C" "H"] ["C" "H"]]] ["Au" [["C" "H"].["C" "H"]]]]] La` e# Push the string [""]. - e# Remove square brackets and double quotes from the first string. S% e# Split the result at runs of spaces. $e` e# Sort and perform run-length encoding. { e# For each pair [run-length string]: ~ e# Dump both on the stack. ": " e# Push that string. @N e# Rotate the run-length on top and push a linefeed. }/ e# ``` [Answer] # [Python 3](https://docs.python.org/3/), 157 154 bytes ``` import re s=re.sub f=s("[()',]",'',str(eval(s(',?(\d+)',r'*\1,',s('([A-Z][a-z]*)',r'("\1",),',input()))))).split() for c in set(f):print(c+":",f.count(c)) ``` [Try it online!](https://tio.run/##HclBC4IwGIDhu79i7LLv0ymY0EGQCKFjPyD1YLbRwLaxzaD@/Fq@t5fHfsLT6CZG9bLGBeJE5jsnKr/dM9l5oAMg4xPljHEfHIj3vIIHxk8wPopEjuVjzRMCg@Fc3qZhLr9TvgvQsaYckypttwC4V3m7qjSZNI4sRGniRQCJrXVKB1gK2lIuq8Vs/0OMsTcNXAT0Vzzi4Qc "Python 3 – Try It Online") Only supports input using regular brackets. Before creating the golfed solution using `eval` above I created this reference solution, which I found very elegant: ``` import re, collections parts = filter(bool, re.split('([A-Z][a-z]*|\(|\))', input())) stack = [[]] for part in parts: if part == '(': stack.append([]) elif part == ')': stack[-2].append(stack.pop()) elif part.isdigit(): stack[-1].append(int(part) * stack[-1].pop()) else: stack[-1].append([part]) count = collections.Counter() while stack: if isinstance(stack[-1], list): stack.extend(stack.pop()) else: count[stack.pop()] += 1 for e, i in count.items(): print("{}: {}".format(e, i)) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 66 65 bytes ``` VrSc-`v::z"([A-Z][a-z]*)""('\\1',),"",?(\d+)""*\\1,"`(k))8j": "_N ``` [Try it online!](https://tio.run/##K6gsyfj/P6woOFk3oczKqkpJI9pRNyo2OlG3KlZLU0lJQz0mxlBdR1NHSUnHXiMmRRsopgUU0lFK0MjW1LTIUrJSUIr3@//fOd9Ywy1Vw9lP00zTCAA "Pyth – Try It Online") Port of my Python answer. Only supports input using regular brackets. [Answer] # JavaScript ES6, 366 bytes ``` function f(i){function g(a,b,c){b=b.replace(/[[(]([^[(\])]+?)[\])](\d*)/g,g).replace(/([A-Z][a-z]?)(\d*)/g,function(x,y,z){return y+((z||1)*(c||1))});return(b.search(/[[(]/)<0)?b:g(0,b)}return JSON.stringify(g(0,i).split(/(\d+)/).reduce(function(q,r,s,t){(s%2)&&(q[t[s-1]]=+r+(q[t[s-1]]||0));return q},{})).replace(/["{}]/g,'').replace(/:/g,': ').replace(/,/g,'\n')} ``` JS Fiddle: <https://jsfiddle.net/32tunzkr/1/> I'm pretty sure this can be shortened, but I need to get back to work. ;-) [Answer] # [SageMath](https://en.wikipedia.org/wiki/SageMath), ~~156~~ 148 bytes ``` import re i=input() g=re.sub var(re.findall("[A-Z][a-z]?",i)) print g("(\d+).(\S+)\D*",r"\2: \1\n",`eval(g("(\d+)",r"*\1",g("([A-Z(])",r"+\1",i)))`) ``` Try it online [here](https://cloud.sagemath.com/projects/f313957c-5f64-4f65-9c4d-b95b3ca2952e/files/2015-09-22-223459.sagews) (hopefully link will work, might need an online account) Note: If trying online, you will need to replace `input()` with the string (e.g. `"(CH3)3COOC(CH3)3"`) ### Explanation Sage allows you to simplify algebraic expressions, providing they are in the right format (see 'symbolic manipulation' of [this](http://doc.sagemath.org/html/en/constructions/polynomials.html) link). The regexes inside the eval() basically serve to get the input string into the right format, for example something like: ``` +(+C+H*3)*3+C+O+O+C+(+C+H*3)*3 ``` `eval()` will then simplify this to: `8*C + 18*H + 2*O`, and then it's just a matter of formatting the output with another regex substitution. [Answer] # [Python 3](https://docs.python.org/3/), 414 bytes I hope that the order of the result doesn't count. ``` import re t=input().replace("[", '(').replace("]", ')') d={} p,q="(\([^\(\)]*\))(\d*)","([A-Z][a-z]*)(\d*)" for i in re.findall(q,t):t = t.replace(i[0]+i[1],i[0]*(1if i[1]==''else int(i[1]))) r=re.findall(p,t) while len(r)>0:t=t.replace(r[0][0]+r[0][1],r[0][0][1:-1]*(1if r[0][1]==''else int(r[0][1])));r=re.findall(p,t) for i in re.findall(q[:-5], t):d[i]=d[i]+1if i in d else 1 for i in d:print(i+': '+str(d[i])) ``` [Try it online!](https://tio.run/##bY9dS8MwFIbv@ytCb3JOm47VoReRCDLw0h9gGmEsKQvENssiouJvr0kpbqI3@XiT8zy8/j0exmEzTfbFjyGSYIoo7OBfI@AqGO92ewOlLBmhQC8SlROkWGjx@VV4dhQldCCfO@hQVR0idLrCkpUg75snJXfNh6qWsOjHQCyxQ7KtejvonXNwZBF5JILEH4mVa1Vb2SqWTxW0tif5KgSlxp1MIkTIASIWQVzAfIIVbwfrDHFmgIB3ax7FmRwSL8PnPfGXu2x50y6i5emXa8mS7vav7t9SkjfXipFUTUurRF7quUb@qMlMbs@jmvswl6opJ7Q@xQB5BHGatuMGHgxsH/EGr74B "Python 3 – Try It Online") [Answer] # Javascript (ES6), ~~286~~ 284 Not that much shorter than the other ES6 one but I gave it my best. Note: this will error out if you give it an empty string or most invalid inputs. Also expects all groups to have a count of more than 1 (ie, no `CO[OH]`). If this breaks any challenge rules, let me know. ``` a=>(b=[],c={},a.replace(/([A-Z][a-z]*)(?![0-9a-z])/g, "$11").match(/[A-Z][a-z]*|[0-9]+|[\[\(]/g).reverse().map(d=>(d*1==d&&b.push(d*1),d.match(/\(|\[/)&&b.pop(),d.match(/[A-Z]/)&&eval('e=b.reduce((f,g)=>f*g,1),c[d]=c[d]?c[d]+e:e,b.pop()'))),eval('g="";for(x in c)g+=x+`: ${c[x]}\n`')) ``` Uses a stack-based approach. First, it preprocesses the string to add `1` to any element without a number, ie `Co3(Fe(CN)6)2` becomes `Co3(Fe1(C1N1)6)2`. Then it loops through in reverse order and accumulates element counts. ``` a=>( // b: stack, c: accumulator b=[], c={}, // adds the 1 to every element that doesn't have a count a.replace(/([A-Z][a-z]*)(?![0-9a-z])/g, "$11") // gathers a list of all the elements, counts, and grouping chars .match(/[A-Z][a-z]*|[0-9]+|[\[\(]/g) // loops in reverse order .reverse().map(d=>( // d*1 is shorthand here for parseInt(d) // d*1==d: true only if d is a number // if it's a number, add it to the stack d * 1 == d && b.push(d * 1), // if there's an opening grouping character, pop the last item // the item being popped is that group's count which isn't needed anymore d.match(/\(|\[/) && b.pop(), // if it's an element, update the accumulator d.match(/[A-Z]/) && eval(' // multiplies out the current stack e = b.reduce((f, g)=> f * g, 1), // if the element exists, add to it, otherwise create an index for it c[d] = c[d] ? c[d] + e : e, // pops this element's count to get ready for the next element b.pop() ') )), // turns the accumulator into an output string and returns the string eval(' g=""; // loops through each item of the accumulator and adds it to the string // for loops in eval always return the last statement in the for loop // which in this case evaluates to g for(x in c) g+=x+`: ${c[x]}\n` ') ) ``` [Fiddle](http://jsfiddle.net/5dp3ng0e/) [Answer] # Perl, ~~177~~ 172 bytes 171 bytes code + 1 byte command line parameter Ok, so I may have got a *little* carried away with regex on this one... ``` s/(?>[A-Z][a-z]?)(?!\d)/$&1/g;while(s/\(([A-Z][a-z]?)(\d+)(?=\w*\W(\d+))/$2.($3*$4).$1/e||s/([A-Z][a-z]?)(\d*)(\w*)\1(\d*)/$1.($2+$4).$3/e||s/\(\)\d+//g){};s/\d+/: $&\n/g ``` Usage example: ``` echo "(CH3)3COOC(CH3)3" | perl -p entry.pl ``` [Answer] ## Mathematica, 152 bytes ``` f=TableForm@Cases[PowerExpand@Log@ToExpression@StringReplace[#,{a:(_?UpperCaseQ~~___?LowerCaseQ):>"\""<>a<>"\"",b__?DigitQ:>"^"<>b}],a_. Log[b_]:>{b,a}]& ``` The above defines a function `f` which takes a string as input. The function takes the string and wraps each element name into quotes and adds an infix exponentiation operator before each number, then interprets the string as an expression: ``` "YBa2Cu3O7" -> ""Y""Ba"^2"Cu"^3"O"^7" -> "Y" "Ba"^2 "Cu"^3 "O"^7 ``` Then it takes the logarithm of that and expands it out (mathematica doesn't care, what to take the logarithm of :)): ``` Log["Y" "Ba"^2 "Cu"^3 "O"^7] -> Log["Y"] + 2 Log["Ba"] + 3 Log["Cu"] + 7 Log["O"] ``` and then it finds all occurrences of multiplication of a `Log` by a number and parses it into the form of `{log-argument, number}` and outputs those in a table. Some examples: ``` f@"K4(ON(SO3)2)2" K 4 N 2 O 14 S 4 f@"(CH3)3COOC(CH3)3" C 8 H 18 O 2 f@"Co3(Fe(CN)6)2" C 12 Co 3 Fe 2 N 12 ``` [Answer] # Java, 827 bytes ``` import java.util.*;class C{String[]x=new String[10];public static void main(String[]a){new C(a[0]);}C(String c){I p=new I();int[]d=d(c,p);for(int i=0;i<10;i++)if(x[i]!=null)System.out.println(x[i]+": "+d[i]);}int[]d(String c,I p){int[]f;int i,j;Vector<int[]>s=new Vector();while(p.v<c.length()){char q=c.charAt(p.v);if(q=='(')s.add(d(c,p.i()));if(q==')')break;if(q>='A'&&q<='Z'){f=new int[10];char[]d=new char[]{c.charAt(p.v),0};i=1;if(c.length()-1>p.v){d[1]=c.charAt(p.v+1);if(d[1]>='a'&&d[1]<='z'){i++;p.i();}}String h=new String(d,0,i);i=0;for(String k:x){if(k==null){x[i]=h;break;}if(k.equals(h))break;i++;}f[i]++;s.add(f);}if(q>='0'&&q<='9'){j=c.charAt(p.v)-'0';f=s.get(s.size()-1);for(i=0;i<10;)f[i++]*=j;}p.i();}f=new int[10];for(int[]w:s){j=0;for(int k:w)f[j++]+=k;}return f;}class I{int v=0;I i(){v++;return this;}}} ``` [Git repository w/ ungolfed source](https://github.com/ProgrammerDan/molecules-golf "Git repository") (not perfect parity, ungolfed supports multi-character numbers). Been a while, figured I'd give Java some representation. Definitely not going to win any awards :). [Answer] ## ES6, 198 bytes ``` f=s=>(t=s.replace(/(([A-Z][a-z]?)|\(([A-Za-z]+)\))(\d+)/,(a,b,x,y,z)=>(x||y).repeat(z)))!=s?f(t):(m=new Map,s.match(/[A-Z][a-z]?/g).map(x=>m.set(x,-~m.get(x))),[...m].map(([x,y])=>x+": "+y).join`\n`) ``` Where `\n` is a literal newline character. Ungolfed: ``` function f(str) { // replace all multiple elements with individual copies // then replace all groups with copies working outwards while (/([A-Z][a-z]?)(\d+)/.test(str) || /\(([A-Za-z]+)\)(\d+)/.test(str)) { str = RegExp.leftContext + RegExp.$1.repeat(RegExp.$2) + RegExp.rightContext; } // count the number of each element in the expansion map = new Map; str.match(/[A-Z][a-z]?/g).forEach(function(x) { if (!map.has(x)) map.set(x, 1); else map.set(x, map.get(x) + 1); } // convert to string res = ""; map.forEach(function(value, key) { res += key + ": " + value + "\n"; } return res; } ``` [Answer] # [Pip](http://github.com/dloscutoff/pip), ~~85~~ 77 + 1 = 78 bytes **Non-competing answer** because it uses language features that are newer than the challenge. Takes the formula as a command-line argument, and uses the `-n` flag for proper output formatting. ``` Y(VaRl:`([A-Z][a-z]*)``"&"`R`\d+``X&`R`(?<=\d|")[("]``.&`l)u:UQyu.": ".Y_NyMu ``` [Try it online!](http://pip.tryitonline.net/#code=dTpVUSBZKFZhUmw6YChbQS1aXVthLXpdKilgYCImImBSYFxkK2BgWCZgUmAoPzw9XGR8IilbKCJdYGAuJmBsKXUuIjogIi5ZX055TXU&input=&args=Q28zKEZlKENOKTYpMg+LW4) The main trick is to transform the formula via regex replacements into a Pip expression. This, when eval'd, will do the repetition and resolve parentheses for us. We then post-process a bit to get the atom counts and format everything correctly. Ungolfed, with comments: ``` a is command-line arg (implicit) l:`([A-Z][a-z]*)` Regex matching element symbols aR:l `"&"` Replace each symbol in a with symbol wrapped in quotes aR:`\d+` `X&` Add X before each number aR:`(?<=\d|")[("]` `.&` Add . before ( or " if it's preceded by a digit or " Y (Va)@l Eval result, findall matches of l, and yank resulting list into y u:UQy Remove duplicates and store in u u.": ".(_Ny M u) Map function {a IN y} to u, returning list of element counts; append this (with colon & space) itemwise to list of symbols Print that list, newline-separated (implicit, -n flag) ``` Here's how the input `Co3(Fe(CN)6)2` is transformed: ``` Co3(Fe(CN)6)2 "Co"3("Fe"("C""N")6)2 "Co"X3("Fe"("C""N")X6)X2 "Co"X3.("Fe".("C"."N")X6)X2 CoCoCoFeCNCNCNCNCNCNFeCNCNCNCNCNCN ``` Then: ``` ["Co" "Co" "Co" "Fe" "C" "N" "C" "N" "C" "N" "C" "N" "C" "N" "C" "N" "Fe" "C" "N" "C" "N" "C" "N" "C" "N" "C" "N" "C" "N"] ["Co" "Fe" "C" "N"] [3 2 12 12] ["Co: 3" "Fe: 2" "C: 12" "N: 12"] ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=pairmap -n`, 94 bytes ``` s/\(([^()]+?)\)(\d)/$1x$2/e&&redo;s/([A-Z][a-z]*)(\d?)/$k{$1}+=$2||1/ge;pairmap{say"$a: $b"}%k ``` [Try it online!](https://tio.run/##LcxNC4IwHIDxrxKy5L9kza28KCKde/EQXVKDhSOGpsN5qNSv3iro9Fx@PFp2dWCtoTlAdgFceAnOMeQlpog9EKfSdTtZtpGhkG3IucgEeRWLn0i@pBoQm7wY8XFk9CYjLVR3F3ow4ukgEc7Q1ZnmlbXbNaQHOKYrzDF/t7pXbWMs2QdLn/nf7pTpw/DUqzr@LyxpPg "Perl 5 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 133 bytes ``` x=>x.replace(/[A-Z][a-z]*|\d+|./g,c=>d=[c<'/'?c<')'?'}':'{':+c?`for(_ in"${Array(-~c)}")`:`o.${c}=-~o.${c};`]+d,d='',o={})+eval(d)&&o ``` [Try it online!](https://tio.run/##TY/daoNAEIXvfQqRkN2pf0TTUkw3kgpFCGigd7FSt7trSBAnmBLSGvPqNiY3vRk@5sycw9nxIz@IZrv/tmuUql8xgfUBK@VUuNFK1p/Y/OQ0al9xoaibLex1nnH7N384f0jz7LgbS7C5ZJl4IS4JrxNISDoSkJYEpgiLEhv6qW9rY9Qumob/UPsioDOgCAp0Rq3omH25w6zITWlJRoiFrO3AVEdeUQnjMfYzbfDBr52OpZ4Zr5yuUh88wzKiiR9PntMBl1OaJvR9EG4SjWIf/ChNozvdVl78CF4SD5/o0zdFowSeruc5aP@a03IIA@j/AA "JavaScript (Node.js) – Try It Online") Would remain shorter than the existing ones using same old ECMAscript ]
[Question] [ Write a single line program two or more characters long that contains no [line terminators](https://en.wikipedia.org/wiki/Newline#Unicode) and takes no input. For example, your program might be: ``` MyProgram ``` When your program is arranged into the shapes a clock's hands make at 12, 3, 6, and 9 o'clock, it needs to output the corresponding hour number. No other times need be supported. Specifically: * When your program is arranged like clock hands at 12 o'clock (üïõ) ``` m a r g o r P y M ``` running it should output `12`. * When your program is arranged like clock hands at 3 o'clock (üïí) ``` m a r g o r P y MyProgram ``` running it should output `3`. * When your program is arranged like clock hands at 6 o'clock (üïï) ``` m a r g o r P y M y P r o g r a m ``` running it should output `6`. * When your program is arranged like clock hands at 9 o'clock (üïò) ``` ........m ........a ........r ........g ........o ........r ........P ........y margorPyM ``` running it should output `9`. # Notes * The first character in your program is always placed at the center of the clock. (Note how there is only one `M` in the 6 o'clock example.) * Any one non-newline character may be used to indent the program for the 9 o'clock arrangement. In the examples `.` is used, but space or `/` or `#` would be just as valid. * For the 3 o'clock arrangement, no characters should be in the empty upper right region. (i.e. keep it empty, don't fill it with spaces.) * The initial program arrangement (`MyProgram` as is) does not need to do anything. Only the 12, 3, 6, and 9 o'clock arrangements need to have correct, well-defined output. * Code that only works as a function or REPL command is not allowed. Each of the four arrangements should be ready to run as full programs as is. **The shortest program in bytes wins.** e.g. `MyProgram` has a length of 9 bytes. [Answer] # GolfScript, ~~11~~ 10 bytes ``` 21;;3#9];6 ``` Uses `#` as padding character. ## 12 o'clock ``` 6 ; ] 9 # 3 ; ; 1 2 ``` [Try it online!](http://golfscript.tryitonline.net/#code=Ngo7Cl0KOQojCjMKOwo7CjEKMg&input=) ### How it works. * `6` is pushed on the stack, `;` discards it. * `]` wraps the stack in an array (does not affect output). * `9` and `3` are pushed on the stack, `;` and `;` discard them. * Finally, `1` and `2` are pushed on the stack, and implicitly printed without separation. ## 3 o'clock ``` 6 ; ] 9 # 3 ; ; 1 21;;3#9];6 ``` [Try it online!](http://golfscript.tryitonline.net/#code=Ngo7Cl0KOQojCjMKOwo7CjEKMjE7OzMjOV07Ng&input=) ### How it works * `6` is pushed on the stack, `;` discards it. * `]` wraps the stack in an array (does not affect output). * `9` and `3` are pushed on the stack, `;` and `;` discard them. * `1` and `21` are pushed on the stack, `;;` discards them. * `3` is pushed on the stack. * `#` begins a comment until the end of the line. ## 6 o'clock ``` 6 ; ] 9 # 3 ; ; 1 2 1 ; ; 3 # 9 ] ; 6 ``` [Try it online!](http://golfscript.tryitonline.net/#code=Ngo7Cl0KOQojCjMKOwo7CjEKMgoxCjsKOwozCiMKOQpdCjsKNg&input=) ### How it works * `6` is pushed on the stack, `;` discards it. * `]` wraps the stack in an array (does not affect output). * `9` and `3` are pushed on the stack, `;` and `;` discard them. * `1`, `2` and `1` are pushed on the stack. * `;` and `;` discard the last `1` and `2`. * `3` and `9` are pushed on the stack. * `]` and `;` wrap the stack in an array and discard it, clearing the stack. * `6` is pushed on the stack. ## 9 o'clock ``` #########6 #########; #########] #########9 ########## #########3 #########; #########; #########1 6;]9#3;;12 ``` [Try it online!](http://golfscript.tryitonline.net/#code=IyMjIyMjIyMjNgojIyMjIyMjIyM7CiMjIyMjIyMjI10KIyMjIyMjIyMjOQojIyMjIyMjIyMjCiMjIyMjIyMjIzMKIyMjIyMjIyMjOwojIyMjIyMjIyM7CiMjIyMjIyMjIzEKNjtdOSMzOzsxMg&input=) ### How it works * All lines but the last are comments. * `6` is pushed on the stack, `;` discards it. * `]` wraps the stack in an array (does not affect output). * `9` is pushed on the stack. * `#` begins a comment until the end of the line. [Answer] ## [><>](http://esolangs.org/wiki/Fish), 20 bytes ``` X n-+g+aa0g+9a2c!v ``` There's unprintables in there, namely: * After the `X` is `\x06\t` * After the `c` is `\x03` The same part of source code is run each time, using `g` on two parts of the source code to determine what to subtract from 12. ``` v Make IP move downwards !\x03 Jump over the \x03 c Push 12 2a9+g Get the char at position (2, 19), i.e. the \t for 3 o'clock, the \x03 for 9 o'clock, 0 otherwise 0aa+g Get the char at position (0, 20), i.e. first char on the line after the X, \x06 for 6 o'clock + Add - Subtract from the 12 n Output as number \t Unrecognised instruction - errors out ``` [12 o'clock](http://fish.tryitonline.net/#code=dgohCgMKYwoyCmEKOQorCmcKMAphCmEKKwpnCisKLQpuCgkKBgpY&input=) | [3 o'clock](http://fish.tryitonline.net/#code=dgohCgMKYwoyCmEKOQorCmcKMAphCmEKKwpnCisKLQpuCgkKBgpYBgluLStnK2FhMGcrOWEyYwMhdg&input=) | [6 o'clock](http://fish.tryitonline.net/#code=dgohCgMKYwoyCmEKOQorCmcKMAphCmEKKwpnCisKLQpuCgkKBgpYCgYKCQpuCi0KKwpnCisKYQphCjAKZworCjkKYQoyCmMKAwohCnY&input=) | [9 o'clock](http://fish.tryitonline.net/#code=ICAgICAgICAgICAgICAgICAgIHYKICAgICAgICAgICAgICAgICAgICEKICAgICAgICAgICAgICAgICAgIAMKICAgICAgICAgICAgICAgICAgIGMKICAgICAgICAgICAgICAgICAgIDIKICAgICAgICAgICAgICAgICAgIGEKICAgICAgICAgICAgICAgICAgIDkKICAgICAgICAgICAgICAgICAgICsKICAgICAgICAgICAgICAgICAgIGcKICAgICAgICAgICAgICAgICAgIDAKICAgICAgICAgICAgICAgICAgIGEKICAgICAgICAgICAgICAgICAgIGEKICAgICAgICAgICAgICAgICAgICsKICAgICAgICAgICAgICAgICAgIGcKICAgICAgICAgICAgICAgICAgICsKICAgICAgICAgICAgICAgICAgIC0KICAgICAgICAgICAgICAgICAgIG4KICAgICAgICAgICAgICAgICAgIAkKICAgICAgICAgICAgICAgICAgIAYKdiEDYzJhOStnMGFhK2crLW4JBlg&input=) (looks misaligned due to the tab) [Answer] ## [ROOP](http://esolangs.org/wiki/ROOP), 54 bytes ``` OW 3#H V 1#1 H#6 WO#H V>V1#OW V>V9#OW 2#OW 1 ``` Uses `<` as padding character. [12 o'clock](https://tio.run/##K8rPL/j/35BLAQzDufy5lLmMUHiWXGFcdkAM4xvC@R5Anj9QFKTWDMj2ALMMwWpALJgaY6h5YBP@/wcA) | [3 o'clock](https://tio.run/##VYw9CsAwCIV3T/HAE5hAIUtmt2zJMVJ6f7DGNoUq8n748JrzNBNC7KBGTOmXCnWqfjvLl9VT83axh3sNJ8Est5n8/osPAz6ZFR0QFkD5AEZbTe3CDrgWDjA9ImY3) | [6 o'clock](https://tio.run/##K8rPL/j/35BLAQzDufy5lLmMUHiWXGFcdkAM4xvC@R5Anj9QFKTWDMj2ALMMwWpALJgaY6h5EBPC4TxjqJ4wNH0gPWZILoCoAdlpCLcRwrdEcoEC0N3IPMP//wE) | [9 o'clock](https://tio.run/##7ZYxCsAgDEX3nuJDThAFQSjObm56DEvvD7a2W8cMKYpZPkgewv9GPWs9WtslxZsIwwhYkWFJhpEMMyuAfwPwMizLsKC628y58crtW1E1gKR6uHRvLqfqZBzBEh5hunUtmXm67cT/EvGzyABKIvOKzyF35a6RUgEcRYDp7usrFk9jaxc) ## 12 o'clock The `1` and the `2` that are near the top fall for 3 cycles. When they reach the `W` operator, the operator places the number in `O`, which represents the output. The `1` in this part ``` 1 V H ``` fell for 2 cycles, the `V` operator moves it below and at the next cycle activates the `H` operator that ends the program. ## 3 o'clock `O` are also objects that move and fall. Since the code now has a line with more than one character, all other lines are filled with empty spaces. All `O` moves to the right and fall, causing the `W` operators to have no place to send the `1` and `2`. The only `O` that does not move is the one that is trapped in the center. The `3` above falls for 4 cycles to the `W`. Then the numbers that fall are filling the 4 spaces between the `W` and`3`. When it is filled, another number can pass over all of them and reach the `H` operator that ends the program. ## 6 o'clock ``` 1 H # 6 W O ``` Very similar to the 12, the `6` falls to the `W` and the `1` to the `H`. This occurs in 2 cycles, ending the program before the 12 case occurs. ## 9 o'clock ``` <9 <V <> <V < <W <O <# <1 <V <> <V < <H ``` (I show a single column of `<` because the others do nothing). The `V` picks up the `9` and moves it to the pipe below, which deflects the object to the left. The pipe `<` moves the object down and the next one to the right. The `V` operator put the `9` in the space below and then it is sent to the output. The `1` makes equal movements and reaches the `H`, which ends the program. As the pipes move objects in the same cycle, all this takes a single cycle. ]
[Question] [ # Single moves The board is an infinite 2 dimensional square grid, like a limitless chess board. A piece with value N (an ***N-mover***) can move to any square that is a distance of exactly the square root of N from its current square (Euclidean distance measured centre to centre). For example: * A 1-mover can move to any square that is horizontally or vertically adjacent * A 2-mover can move to any square that is diagonally adjacent * A 5-mover moves like a chess knight Note that not all N-movers can move. A 3-mover can never leave its current square because none of the squares on the board are a distance of exactly root 3 from the current square. # Multiple moves If allowed to move repeatedly, some pieces can reach any square on the board. For example, a 1-mover and a 5-mover can both do this. A 2-mover can only move diagonally and can only reach half of the squares. A piece that cannot move, like a 3-mover, cannot reach any of the squares *(the starting square is not counted as "reached" if no movement occurs)*. [![1-mover](https://i.stack.imgur.com/VJHUqs.png "1-mover. Proportion reachable: 1")](https://i.stack.imgur.com/VJHUq.png) [![2-mover](https://i.stack.imgur.com/DQZNgs.png "2-mover. Proportion reachable: 1/2")](https://i.stack.imgur.com/DQZNg.png) [![3-mover](https://i.stack.imgur.com/Irb9Xs.png "3-mover. Proportion reachable: 0")](https://i.stack.imgur.com/Irb9X.png) [![4-mover](https://i.stack.imgur.com/8eFbps.png "4-mover. Proportion reachable: 1/4")](https://i.stack.imgur.com/8eFbp.png) [![5-mover](https://i.stack.imgur.com/2mAWYs.png "5-mover. Proportion reachable: 1")](https://i.stack.imgur.com/2mAWY.png) [![8-mover](https://i.stack.imgur.com/Ia6Dys.png "8-mover. Proportion reachable: 1/8")](https://i.stack.imgur.com/Ia6Dy.png) [![9-mover](https://i.stack.imgur.com/ph92ss.png "9-mover. Proportion reachable: 1/9")](https://i.stack.imgur.com/ph92s.png) [![10-mover](https://i.stack.imgur.com/1NlwDs.png "10-mover. Proportion reachable: 1/2")](https://i.stack.imgur.com/1NlwD.png) [![20-mover](https://i.stack.imgur.com/RreHys.png "20-mover. Proportion reachable: 1/4")](https://i.stack.imgur.com/RreHy.png) [![25-mover](https://i.stack.imgur.com/NIB1Ss.png "25-mover. Proportion reachable: 1")](https://i.stack.imgur.com/NIB1S.png) [![40-mover](https://i.stack.imgur.com/KKdlDs.png "40-mover. Proportion reachable: 1/8")](https://i.stack.imgur.com/KKdlD.png) [![64-mover](https://i.stack.imgur.com/JZ7r5s.png "64-mover. Proportion reachable: 1/64")](https://i.stack.imgur.com/JZ7r5.png) [![65-mover](https://i.stack.imgur.com/wnPYrs.png "65-mover. Proportion reachable: 1")](https://i.stack.imgur.com/wnPYr.png) [![68-mover](https://i.stack.imgur.com/idHbJs.png "68-mover. Proportion reachable: 1/4")](https://i.stack.imgur.com/idHbJ.png) The images show which squares can be reached. More details on hover. Click for larger image. * Squares reachable in 1 or more moves are marked in black * Squares reachable in exactly 1 move are shown by red pieces *(apart from the 3-mover, which cannot move)* What proportion of the board can a given N-mover reach? # Input * A positive integer N # Output * The proportion of the board that an N-mover can reach * This is a number from 0 to 1 (both inclusive) * For this challenge, output as a fraction in lowest terms, like 1/4, is allowed So for input `10`, both `1/2` and `0.5` are acceptable outputs. Output as separate numerator and denominator is also acceptable, to be inclusive of languages that support neither floats nor fractions. For example, `1 2` or `[1, 2]`. For the integer outputs (0 and 1), any of the following are acceptable formats: * For 0: `0`, `0.0`, `0/1`, `0 1`, `[0, 1]` * for 1: `1`, `1.0`, `1/1`, `1 1`, `[1, 1]` # Scoring This is code golf. The score is the length of the code in bytes. For each language, the shortest code wins. # Test cases In the format `input : output as fraction : output as decimal` ``` 1 : 1 : 1 2 : 1/2 : 0.5 3 : 0 : 0 4 : 1/4 : 0.25 5 : 1 : 1 6 : 0 : 0 7 : 0 : 0 8 : 1/8 : 0.125 9 : 1/9 : 0.1111111111111111111111111111 10 : 1/2 : 0.5 13 : 1 : 1 16 : 1/16 : 0.0625 18 : 1/18 : 0.05555555555555555555555555556 20 : 1/4 : 0.25 25 : 1 : 1 26 : 1/2 : 0.5 64 : 1/64 : 0.015625 65 : 1 : 1 72 : 1/72 : 0.01388888888888888888888888889 73 : 1 : 1 74 : 1/2 : 0.5 80 : 1/16 : 0.0625 81 : 1/81 : 0.01234567901234567901234567901 82 : 1/2 : 0.5 144 : 1/144 : 0.006944444444444444444444444444 145 : 1 : 1 146 : 1/2 : 0.5 148 : 1/4 : 0.25 153 : 1/9 : 0.1111111111111111111111111111 160 : 1/32 : 0.03125 161 : 0 : 0 162 : 1/162 : 0.006172839506172839506172839506 163 : 0 : 0 164 : 1/4 : 0.25 241 : 1 : 1 242 : 1/242 : 0.004132231404958677685950413223 244 : 1/4 : 0.25 245 : 1/49 : 0.02040816326530612244897959184 260 : 1/4 : 0.25 261 : 1/9 : 0.1111111111111111111111111111 288 : 1/288 : 0.003472222222222222222222222222 290 : 1/2 : 0.5 292 : 1/4 : 0.25 293 : 1 : 1 324 : 1/324 : 0.003086419753086419753086419753 325 : 1 : 1 326 : 0 : 0 360 : 1/72 : 0.01388888888888888888888888889 361 : 1/361 : 0.002770083102493074792243767313 362 : 1/2 : 0.5 369 : 1/9 : 0.1111111111111111111111111111 370 : 1/2 : 0.5 449 : 1 : 1 450 : 1/18 : 0.05555555555555555555555555556 488 : 1/8 : 0.125 489 : 0 : 0 490 : 1/98 : 0.01020408163265306122448979592 520 : 1/8 : 0.125 521 : 1 : 1 522 : 1/18 : 0.05555555555555555555555555556 544 : 1/32 : 0.03125 548 : 1/4 : 0.25 549 : 1/9 : 0.1111111111111111111111111111 584 : 1/8 : 0.125 585 : 1/9 : 0.1111111111111111111111111111 586 : 1/2 : 0.5 592 : 1/16 : 0.0625 593 : 1 : 1 596 : 1/4 : 0.25 605 : 1/121 : 0.008264462809917355371900826446 610 : 1/2 : 0.5 611 : 0 : 0 612 : 1/36 : 0.02777777777777777777777777778 613 : 1 : 1 624 : 0 : 0 625 : 1 : 1 ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~144~~ ~~138~~ ~~125~~ ~~74~~ ~~73~~ 70 bytes ``` f=(x,n=2,c=0)=>x%n?x-!c?f(x,n+1)/(n%4>2?n/=~c&1:n%4)**c:1:f(x/n,n,c+1) ``` [Try it online!](https://tio.run/##FYpBDoMgEEX3nmK6sAHBAqYr7ehZzFQaGjMYbIyrXp3S1fvv573nY94phe3TcnwuOXsUp2bsNKGVOJ41T2d7ocn/b@WkEVzfx25ig1@6ur6YbBrqXV8Kw5o1lSoPlY8JxDEnCIDghoIHOGttWUrJCijyHtfltsaXCBq8CFLmHw "JavaScript (Node.js) – Try It Online") **-4 byte thanks @Arnauld!** ### Original approach, 125 bytes ``` a=>(F=(x,n=2)=>n*n>x?[x,0]:x%n?F(x,n+1):[n,...F(x/n,n)])(a).map(y=>r-y?(z*=[,1,.5,p%2?0:1/r][r%4]**p,r=y,p=1):p++,z=r=p=1)&&z ``` [Try it online!](https://tio.run/##FYzBDoIwEAXvfEUvkJYupTV6ARdu/ATh0CAYDG6bagzw8wineZOXzMv@7KcPk/9m5B7DPuJuseIN8gUILwIrSqla6nYB3RVLTHVzPtKIoiVQSh2aE5DoBLdCva3nK1YhW2u@pdiCAXUDH19qXZg8dG2Ir12aegi4gsej4qWEDQOekiTbXkajC4z/bGATQ2bKA3dmtNbHklJErHf0cfOgZvfkE7CRT0Lsfw "JavaScript (Node.js) – Try It Online") Inspired by the video [Pi hiding in prime regularities](https://www.youtube.com/watch?v=NaL_Cb42WyY) by 3Blue1Brown. For each prime factor \$p^n\$ in the factorization of the number, calculate \$f(p^n)\$: * If \$n\$ is odd and \$p\equiv 3\text{ (mod 4)}\$ - \$f(p^n)=0\$. Because there is no place to go. * If \$n\$ is even and \$p\equiv 3\text{ (mod 4)}\$ - \$f(p^n)=\frac{1}{p^n}\$. * If \$p=2\$ - \$f(2^n)=\frac{1}{2^n}\$. * If \$p\equiv 1\text{ (mod 4)}\$ - \$f(p^n)=1\$. Multiply all those function values, there we are. ### Update Thanks to the effort of contributors from Math.SE, the algorithm is now [backed by a proof](https://math.stackexchange.com/questions/3108324/how-much-of-an-infinite-board-can-a-n-mover-reach/3108647#3108647) [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~189~~ ~~185~~ ~~172~~ 171 bytes ``` import StdEnv $n#r=[~n..n] #p=[[x,y]\\x<-r,y<-r|x^2+y^2==n] =sum[1.0\\_<-iter n(\q=removeDup[k\\[a,b]<-[[0,0]:p],[u,v]<-q,k<-[[a+u,b+v]]|all(\e=n>=e&&e>0)k])p]/toReal(n^2) ``` [Try it online!](https://tio.run/##NY3BbsIwEETP5CtWgFCi2KmTFlRVMSd6qNRTOdpOZcBtI2InJE5EJNRPrzGtenirndHuzL5S0jhdH/pKgZalcaVu6tbC1h6ezRDMzayl7NskiRHBrKGMndEoOD/nuEWjH5dzkcVjkVHqD2jXa5YmhPP3HJdWtWBCfqKt0vWgNn3DjpwziXYix4wRRMRTIxDr0eCNEzreXBn3aBcPQlxkVYVcUbOmarFQaxIdRdSIO1u/KVmFpsgit7WytcFkBlZ1tgMKoW9PUiIgjoGl9wjSlecRQUY8S4/XqwfPUkTBhAILb68IptxSmCKY/0szjYDz32DI8V@BcD/7j0p@dg6/vLrNaKQu9158uSUh2uGdw51f9RU "Clean – Try It Online") Finds every position reachable in the `n`-side-length square cornered on the origin in the first quadrant, then divides by `n^2` to get the portion of all cells reachable. This works because: * The entire reachable plane can be considered as overlapping copies of this `n`-side-length square, each cornered on a reachable point from the origin as if it were the origin. * All movements come in groups of four with signs `++ +- -+ --`, allowing the overlapping tiling to be extended through the other three quadrants by mirroring and rotation. [Answer] # Mathematica, 80 bytes ``` d[n_]:=If[#=={},0,1/Det@LatticeReduce@#]&@Select[Tuples[Range[-n,n],2],#.#==n&]; ``` This code is mostly reliant on a mathematical theorem. The basic idea is that the code asks for the density of a lattice given some generating set. More precisely, we are given some collection of vectors - namely, those whose length squared is N - and asked to compute the density of the set of possible sums of these vectors, compared to all integer vectors. The math at play is that we can always find two vectors (and their opposite) that "generate" (i.e. whose sums are) the same set as the original collection. LatticeReduce does exactly that. If you have just two vectors, you can imagine drawing an identical parallelogram centered at each reachable point, but whose edge lengths are the given vectors, such that the plane is completely tiled by these parallelograms. (Imagine, for instance, a lattice of "diamond" shapes for n=2). The area of each parallelogram is the determinant of the two generating vectors. The desired proportion of the plane is the reciprocal of this area, since each parallelogram has just one reachable point in it. The code is a fairly straightforward implementation: Generate the vectors, use LatticeReduce, take the determinant, then take the reciprocal. (It can probably be better golfed, though) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~126~~ 82 bytes ``` .+ $* +`^(1(1111)+)(?<!^\3+(11+))(\1)*$ 1$#4$* ^(?!((^1|11\2)+)\1?$)1+ 0 11+ 1/$.& ``` [Try it online!](https://tio.run/##RY8xTsVADET7uQYBbbJSWHttZ1cRovyXiPifSBQ0FIiSu4cJFBRPsdfjmfjz7ev94/W4T5fbMWcME/LtJYnkMW0y5m3HIKsMd8rJtgsn8vcsbNPZj3lcN/kVXgfBPP2/b/s8oeCKla7bRdLz0zytiebj9yp54AoYBXkc5ofjECgqDI7AgoYOKZAKCUiDFqhDA2EIx6JYKhZDK2iCphAz4oR6axA/V@kQTAnO4@wNagwyJWd9WtKZGm0M6aw7Z72iqhEngUpNpabSp0ZHXQrMOsz55Z411tx1PRGicPo7/8Op88a6OQk4/Z3@3nlL4bG8MkSIkopgbqj/AA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` .+ $* ``` Convert to unary. ``` +`^(1(1111)+)(?<!^\3+(11+))(\1)*$ 1$#4$* ``` Repeatedly divide by prime factors of the form `4k+1`. ``` ^(?!((^1|11\2)+)\1?$)1+ 0 ``` If the result is neither a square nor twice a square then the result is zero. ``` 11+ 1/$.& ``` Compute the reciprocal as a decimal fraction. [Answer] # Regex (ECMAScript, reciprocal out), ~~256~~ ~~163~~ ~~157~~ ~~94~~ ~~83~~ 82 bytes *-93 bytes [thanks to Neil](https://chat.stackexchange.com/transcript/message/49175336#49175336)* *-6 bytes [thanks again to Neil](https://chat.stackexchange.com/transcript/message/49177733#49177733)* This uses the same mathematics as [Shieru Asakoto's JavaScript answer](https://codegolf.stackexchange.com/a/179760/52210). The input is in unary. Since a pure regex can only return as output a substring from the input (i.e. a natural number less than or equal to the input), or "no match", this regex returns the reciprocal of the proportion of the board that an N-mover can reach. Since the reciprocal of 0 is infinity, it returns "no match" in that case. **SPOILER WARNING**: For the square root, this regex uses a variant of the generalized multiplication algorithm, which is non-obvious and could be a rewarding puzzle to work out on your own. For more information, see an explanation for this form of the algorithm in [Find a Rocco number](https://codegolf.stackexchange.com/questions/179239/find-a-rocco-number/179420#179420). This regex first goes into loop identifying all prime factors \$p\$ such that \$p\equiv 1\text{ (mod 4)}\$, and divides the input number by each one as many times as it can. Let \$m\$ be the end result of this. Then, it indirectly tests to see if the prime factorization of \$m\$ (and therefore also the input number) includes any primes \$\equiv 3\text{ (mod 4)}\$ raised to an odd power, by testing to see if \$m\$ or \$m/2\$ is a perfect square. If not, then \$m\$ did include such a prime raised to an odd power, and the regex returns "no match"; otherwise, it returns \$m\$. (It's now a bit more complicated than that. Due to a golf optimization in the reciprocal-output version, it tests not only \$m\$ and \$m/2\$ for being a square, but also the intermediate result before the division of each \$p\$, if the first test fails. This doesn't change the end result, because if the first perfect square test failed, at least one odd power of a prime \$\equiv 3\text{ (mod 4)}\$ will still be present in the number at every step, and it can't be a square.) ``` ^(?=((?=(x+)(?!(\2+)(\2\3)+$)((\2{4})+$))\5|((xx?)(\8*))(?=(\7*)\9+$)\7*$\10)+$)\1 ``` [Try it online!](https://tio.run/##XZDPTsJAEIdfpRBCZ1pbWgRU6sLJAxcOerSabGAoq8vS7C5Q@XP1AXxEXwS3iSbEw2Z@2W8n8@288S03My1KG5lSzEmv1uqdPs6aKdp5j1Q8VCXAno06wfkVxgzqU4UI4wbkXVfzbn6NYQvBpUPvVEfM@0eAqho7ehsg1i35TYD5nYMutPI0qd/l6Tno7DG26yerhSoAYyPFjGBwFfUQM8OSbLcUkgAk08TnUigCxAZTGynxUDAZm1IKC37kYyYWAIoVsSRV2CWOusejMFM@BcFKrg1NlIXiOXlB/AN0CdQoHafDGqNd6vWuOVFbLsXc01wVNPSaocwWaw2ZuGeUiTDEg2m3SyduoXZNa4EVa1bNWFNJ3ILAeMXtbAkasdxYYzWI0Pe@P788P4SVU/l1dZP9tOOHF1dDP/XdCkga8v71Ju6vp9M5iQbd/g8 "JavaScript (SpiderMonkey) – Try It Online") [Try it online!](https://tio.run/##XZBBbtswEEX3PIViBNHQKh2SImnJquxVF9lk0S6rFhBsRmYrywLFxG5sb3uAHrEXcUdACwRdEG/AP/Pnk9/ql3pYe9cHNvRuY/1u3323P66@7Owh@mibD8ce4LVc3k@vX2FVwniOCYXVDVQSWckqpcktBaxO6jKWtNJngONxhWo2pXQcqeZTWuUoYnFbCT72VeI6vX@ls7D/FLzrGqCzoXVrC@YdU5QWQ8mLw9a1FqAtva03ressUHpTds9tS09N2c6GvnUBYhbTwj0BdGUza23XhC1dyvPZDY/1I7iyr/1gH7oAzWf@hdJ/gn0rdEuxEotRpmHr94fJQ/dSt24T@bpr7CKaJG3xtPdQuPelLVyS0NNwd9dj8ABjVjEG2JWT42TmbW/rAI7OdnVYb8FT2j@HIXhwSRz9/vkrihPYYZS/WXFzLO7j5M3VIhYxfoFtBxv9N8vxrZfLVTDBiUiJMERkRHIiNZOGGMWMJnPJ5opknGWSCKWYUBqJnSojQo9DnAmjiFSCSSWRCqmJxHtpBJEZWubomUsm85SkUrEU3VPUUyOROUvnnCiVM6WRWcYU9mvJmZaSaKXwZEyrnOhMMZ0ZotFLo5fOMSXXxAjOjBBIiUyJwR1G6j8 "JavaScript (SpiderMonkey) – Try It Online") (just the test cases) ``` ^ (?= ( # Capture return value, which will just be the value # matched by the last iteration of this loop. # Divide tail by every one of its prime factors that's ≡1 mod 4, as many times as # possible. (?= (x+) # \2 = quotient (?!(\2+)(\2\3)+$) # Assert divisor is prime ((\2{4})+$) # Assert divisor ≡1 mod 4; \5 = tool to make tail = \2 )\5 # tail = \2 | # When the above alternative has been done as many times as possible: # Test if tail or tail/2 is a perfect square. If this test fails, the regex engine # will backtrack into the division loop above, and run the same perfect square # test on every previous number (effectively "multiplying" it by each previous P # in reverse, one at a time). This will not cause a failure of the test to change # into a success, however, because the odd power of a prime ≡3 mod 4 will see be # present in the number at every step. Allowing this backtracking to happen is a # golf optimization, and it does make the regex slower. # Failure of this perfect square test results in returning "no match" and indicates # a return value of zero. ( # \7 = \8 * sqrt(tail / \8) (xx?) # \8 = control whether to take sqrt(tail) # or 2*sqrt(tail/2) (\8*) # \9 = \7 - \8 ) (?= (\7*)\9+$ # Iff \8 * (\7 / \8)^2 == our number, then the first match # here must result in \10==0 ) \7*$\10 # Test for divisibility by \7 and for \10==0 # simultaneously )+ $ # Require that the last iteration of the above loop was # the perfect square test. Since the first alternative, # the division, always leaves >=1 in tail, this guarantees # that the last step is a successful perfect square test, # or else the result will be "no match". ) \1 # Return value (which is a reciprocal) ``` ## Regex (ECMAScript+`(?*)`, reciprocal output), ~~207~~ ~~138~~ ~~132~~ bytes Obsoleted by doing division without capturing the divisor (i.e. is now identical to the above). ## Regex (ECMAScript 2018, reciprocal output), ~~212~~ ~~140~~ ~~134~~ bytes Obsoleted by doing division without capturing the divisor (i.e. is now identical to the above). # Regex (ECMAScript, fraction output), 80 bytes In this version, the numerator is returned in `\10` (zero if unset/NPCG) and the denominator in `\7`. Unlike the reciprocal output version: * An input of zero is not correctly dealt with (it returns "no match" just like that version, but unlike it, that does not correspond to an output value of zero). * If the perfect square test fails, it does not backtrack into the division loop, so this version is more efficient in execution time. The big downside of an output specification like this is that it isn't contained in the program itself. ``` ((?=(x+)(?!(\2+)(\2\3)+$)((\2{4})+$))\5)*((((x)x?)(\9*))(?=(\8*)\11+$)\8*$\12|x) ``` [Try it online!](https://tio.run/##TU/LcsIwDPyVwDBEiktIUqAtqcmpBy4c2iPh4AET3BqTsQ2kPK79gH5if4Q6nTKDDtJKuxqt3tmOmbkWpe2YUiy4Xm/UB/@8aKr43nvlxUtVAhzoqBtcADIKFUHIGpAnruZJfo@kheDQsXeuIeZ9DMBFhVXmFE8BYr2WPwaYx7FTONTK4@RU4SXoHjC0mzerhSoAQyPFnMPgrtNDTA2N0v1KSA4gqeZsIYXigNigaislHgsqQ1NKYcHv@JiKJYCiRSi5KuwKR8npJMyETUDQkmnDx8pCMY1miFeC3xJqFGfxsKbRrvRm3xyrHZNi4WmmCj70mkSmy42GVDxTngpC0B1c02bVDDUvObMgMFwzO1@BRjyadrt0T1mo/4jTcmuN1SCI7/18fXs@AVhP42iW/eV/z8MIiRs/XHtK48z3h37XJzdTZzA9ny9RZ5D0fwE "JavaScript (SpiderMonkey) – Try It Online") [Try it online!](https://tio.run/##TU/BctowEL3rKwiTiXdxBZYsCRtXcOohlxzaY5yDBxSj1hiP7QQ3wLUf0E/sj9Cl08xEM9Jb7Xv7dvd78Vp069Y3Pe8av3Htbl//cD8vra3dYfTVlV@GBuDNLmeTC8DKwhAirG4gl4S5zGMMbxEoOqrzNcRc4wToDDisSJFOEK9leTLBXAhSUHSbC3ka8DKZveG033/rW1@XgNOu8msH5hNXiFlno@yw9ZUDqGzrik3laweIN7Z@qSo8lraadk3lewh4gJl/BqhtOa1cXfZbXMrTyXcPxQN42xRt5@7rHsrH6AnxnXAfiXopVmJxpbHftvvD@L5@LSq/GbVFXbrFaBxW2fO@hcx/ti7zYYjUcGfHw3jausYVPXic7op@vYUW8djd3TW0VA/XPUTWvPRd34IPg9GfX79HQQiwexTR0@rf@3/mRYQhpefvf2vFKggWwSwIP2RpwOx8vgguIiZiJgwTCZMRk5pLw4ziRrO55HPFkognkgmluFCakJQqYUJfiyIujGJSCS6VJFSEmknKSyOYTMgyJc9UcpnGLJaKx@QeEx8bSZjyeB4xpVKuNGGScEV6LSOupWRaKboJ1yplOlFcJ4Zp8tLkpVOaMtLMiIgbIQglYcwM9TBS/wU "JavaScript (SpiderMonkey) – Try It Online") (just the test cases) ``` # No need to anchor, since we return a match for all inputs in the domain. # Divide tail by every one of its prime factors that's ≡1 mod 4 ( (?= (x+) # \2 = quotient (?!(\2+)(\2\3)+$) # Assert divisor is prime ((\2{4})+$) # Assert divisor ≡1 mod 4; \5 = tool to make tail = \2 )\5 # tail = \2 )* # Test if tail or tail/2 is a perfect square. If this test succeeds, return tail as # the denominator and 1 as the numerator. ( # \7 = denominator output ( # \8 = \9 * sqrt(tail / \9) ((x)x?) # \9 = control whether to take sqrt(tail) or 2*sqrt(tail/2); # \10 = numerator output (NPCG to represent zero) (\9*) # \11 = \8 - \9 ) (?= (\8*)\11+$ # Iff \9 * (\8 / \9)^2 == our number, then the first match # here must result in \12==0 ) \8*$\12 # Test for divisibility by \8 and for \12==0 # simultaneously | # Failure of the perfect square test results in returning 0/1 as the answer, so here # we return a denominator of 1. x ) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆFµ%4,2CḄ:3+2Ịị,*/ʋ÷*/)P ``` A monadic link using the prime factor route. **[Try it online!](https://tio.run/##AS4A0f9qZWxsef//w4ZGwrUlNCwyQ@G4hDozKzLhu4rhu4ssKi/Ki8O3Ki8pUP///zgx "Jelly – Try It Online")** ### How? ``` ÆFµ%4,2CḄ:3+2Ịị,*/ʋ÷*/)P - Link: integer, n e.g. 11250 ÆF - prime factor, exponent pairs [[2,1], [3,2], [5,4]] µ ) - for each pair [F,E]: 4,2 - literal list [4,2] % - modulo (vectorises) [2,1] [3,0] [1,0] C - complement (1-x) [-1,0] [-2,1] [0,1] Ḅ - from base 2 -2 -3 1 :3 - integer divide by three -1 -1 0 +2 - add two (call this v) 1 1 3 ʋ - last four links as a dyad, f(v, [F,E]) Ị - insignificant? (abs(x)<=1 ? 1 : 0) 1 1 0 */ - reduce by exponentiation (i.e. F^E) 2 9 625 , - pair v with that [1,2] [1,9] [3,625] ị - left (Ị) index into right (that) 1 1 625 */ - reduce by exponentiation (i.e. F^E) 2 9 625 ÷ - divide 1/2 1/9 625/625 P - product 1/18 = 0.05555555555555555 ``` --- Previous 25 was: ``` ŒRp`²S⁼ɗƇ⁸+€`Ẏ;Ɗ%³QƊÐLL÷² ``` Full program brute forcer~~; possibly~~ longer code ~~than the prime factor route (I might attempt that later).~~ [Try it online!](https://tio.run/##ATcAyP9qZWxsef//xZJScGDCslPigbzJl8aH4oG4K@KCrGDhuo47xoolwrNRxorDkExMw7fCsv///zgx "Jelly – Try It Online") Starts by creating single moves as coordinates then repeatedly moves from all reached locations accumulating the results, taking modulo `n` of each coordinate (to restrict to an `n` by `n` quadrant) and keeping those which are distinct until a fixed point is reached; then finally divides the count by `n^2` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~27~~ ~~26~~ 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÓεNØ©<iozë®4%D≠iyÈ®ymz*]P ``` Port of [*@ShieruAsakoto*'s JavaScript answer](https://codegolf.stackexchange.com/a/179760/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##AS8A0P9vc2FiaWX//8OTzrVOw5jCqTxpb3rDq8KuNCVE4omgaXnDiMKueW16Kl1Q//8xOA) or [verify all test cases](https://tio.run/##FYytCsJgFIZvRQYWecPO2fl@BGHFLBaTGBQMC7IgCN9gVbSJFqNVhDVvYF/3InYj8yw84eXlecrjdlfs@1PIk1F3vo@SPMTbqo@P33cRn@17VpRV/LSNjOfd9VWEeGmbcKgmdV0ve/RrAiODwMDCwWMKSkEZyII8OAUbsIUQrMAaOIbL4AQ@hSd4BokoRlFFPMgMtkYsKfrbYQtYGyysyOYP). **Explanation:** ``` Ó # Get all prime exponent's of the (implicit) input's prime factorization # i.e. 6 → [1,1] (6 → 2**1 * 3**1) # i.e. 18 → [1,2] (18 → 2**1 * 3**2) # i.e. 20 → [2,0,1] (20 → 2**2 * 3**0 * 5**1) # i.e. 25 → [0,0,2] (25 → 2**0 * 3**0 * 5**2) ε # Map each value `n` to: NØ # Get the prime `p` at the map-index # i.e. map-index=0,1,2,3,4,5 → 2,3,5,7,11,13 © # Store it in the register (without popping) <i # If `p` is exactly 2: oz # Calculate 1/(2**`n`) # i.e. `n`=0,1,2 → 1,0.5,0.25 ë # Else: ®4% # Calculate `p` modulo-4 # i.e. `p`=3,5,7,11,13 → 3,1,3,3,1 D # Duplicate the result (the 1 if the following check is falsey) ≠i # If `p` modulo-4 is NOT 1 (in which case it is 3): yÈ # Check if `n` is even (1 if truthy; 0 if falsey) # i.e. `n`=0,1,2,3,4 → 1,0,1,0,1 ®ymz # Calculate 1/(`p`**`n`) # i.e. `p`=3 & `n`=2 → 0.1111111111111111 (1/9) # i.e. `p`=7 & `n`=1 → 0.14285714285714285 (1/7) * # Multiply both with each other # i.e. 1 * 0.1111111111111111 → 0.1111111111111111 # i.e. 0 * 0.14285714285714285 → 0 ] # Close both if-statements and the map # i.e. [1,1] → [0.5,0.0] # i.e. [1,2] → [0.5,0.1111111111111111] # i.e. [2,0,1] → [0.25,1.0,1] # i.e. [0,0,2] → [1.0,1.0,1] P # Take the product of all mapped values # i.e. [0.5,0.0] → 0.0 # i.e. [0.5,0.1111111111111111] → 0.05555555555555555 # i.e. [0.25,1.0,1] → 0.25 # i.e. [1.0,1.0,1] → 1.0 # (and output implicitly as result) ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 21 bytes This program uses the prime factor route. I am indebted to Adám, dzaima, H.PWiz, J.Sallé, and ngn. [The APL Orchard](https://chat.stackexchange.com/rooms/52405/the-apl-orchard) is a great place to learn APL and they are always willing to help ``` (×/÷,3≠4|*∘≢⌸)⍭*1≠4|⍭ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@PwdP3D23WMH3UuMKnRetQx41Hnokc9OzQf9a7VMgQLAln/0x61TXjU2/eob6qn/6Ou5kPrjR@1TQTygoOcgWSIh2fw/zQFcyMA "APL (Dyalog Extended) – Try It Online") **Ungolfing** Part 2 of this code is the same as in the Dyalog Unicode version below, and so in this explanation, I will focus on `⍭*1≠4|⍭` ``` ⍭*1≠4|⍭ ⍭ Gives us a list of the prime factors of our input. Example for 45: 3 3 5 1≠4| Checks if each prime is of the form 4k+1. ⍭* Takes each prime to the power of 1 or 0, turning all the 4k+1 primes into 1s. Example for 45: 3 3 1 ``` --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~41~~ ~~40~~ ~~36~~ 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") This program uses the prime factor route. Learned a few tricks while writing this and I am deeply indebted to Adám, dzaima, H.PWiz, J.Sallé, and ngn. [The APL Orchard](https://chat.stackexchange.com/rooms/52405/the-apl-orchard) is a great place to learn APL and they are always willing to help (or this post never would have got off the ground :) Edit: -1 byte from ngn. -2 bytes from Adám and -2 more from ngn. -1 byte from ngn. ``` {(×/÷,3≠4|*∘≢⌸)p*1≠4|p←¯2÷/∪∧\⍵∨⍳⍵} ``` [Try it online!](https://tio.run/##jVS9blMxFN7vU2QLVND6/NpmZaETEmVkiYSCEJEaVV1Q6QSqEiAVDAhGYKFi6YBQEWPzJn6RcHJtJx2SEA/xyfF3/r9ze8PB3acve4PDZ7PZya3p573p1R1K46/8aieNvqTx9/T@z@3hDrSqYTr7cH2J06u9NPqZRj@epMnvNLpIk18mnM769pwm5@n80/7D9Pb19SWls4/27@DRfft9/GD/YHZskJO51fjbkYn9NPl7r3v4opveven2e88HXVPY89Fp0@lA57gDdqPdbldMorlkN7canKukgLQ8@XKHFgItJmZ5w2k64GoUoOwSWpe7Tuc@IPtzsv5o00G3SAxLYqjVL5bUNGfvQFrPWoAei5rCuhMNVZLzXN0GdyPNAMUJEov6uEowVO0ocMnFaeS1x2A5R2BdGIZaKQj9v72gJUuaTwS0TdNurOHBY6AoqwSDUYEv5o6cyYFcPTAQIgE7jhLUew1ixllrsBuWki3QsQvmGlXIoqFhQvRRIgRuUBeTxJzs5vowFH44Yo/rToOxsgwjLgLEPFPCOgxyQRmilxWCwaTAM@WJc3eotngjgahU4xx671wgcMiRnGcfrQXk1RNYEK0UId1ie8jXuphjmx2L22JhOCzX1Lrf1sGx1rF@RNhIWbW5pWAmgyBuEVMq51sqypLIwltUKoGXcYNsY1B3RsrI202VMnSJWuOrK8x0AZVZMbgYwZMIeYhV2@jiS6WQ18g6Uyjt155gqBxRM83sbnn0Dw "APL (Dyalog Unicode) – Try It Online") **Ungolfing** This is a program in two parts: ``` p*1≠4|p←¯2÷/∪∧\⍵∨⍳⍵ Part 1 p← We can define variables mid-dfn (a function in {} brackets). ⍵∨⍳⍵ We take the GCD of our input with every member of range(1, input). ∪∧\ This returns all the unique LCMs of every prefix of our list of GCDs. Example for 31500: 1 2 6 12 60 420 1260 6300 31500 ¯2÷/ We divide pairwise (and in reverse) by using a filter window of negative two (¯2). Example for 31500: 2 3 2 5 7 3 5 5 1≠4|p Check if the primes are 1 modulo 4 or not p* And take each prime to the power of the result (1 or 0), turning the 4k+3 primes into 1s and leaving any 2s and 4k+3 primes. Example for 31500: 2 3 2 1 7 3 1 1 (×/÷,3≠4|*∘≢⌸) Part 2 ( ) We apply all this to the filtered array of primes. *∘≢⌸ This takes all of our primes to their exponents (the number of times those primes appear in the factorization). Example for 31500: 4 9 1 7 3≠4| Then we take each prime modulo 4 and check if not equal to 3. We will only get a falsey if any 4k+3 primes, as an even number of 4k+3 primes multiplied together will result in some 4m+1. Example for 31500: 1 1 1 0 ÷, We append the results of the above condition check to the reciprocals of the primes in p. Example for 31500: (1/2) (1/3) (1/2) 1 (1/7) (1/3) 1 1 1 1 1 0 ×/ We multiply it all together, resulting in a positive fraction or 0 depending on our condition check. Example for 31500: 0 We return the results of all our checks implicitly. ``` ]
[Question] [ Implement the Fast Fourier Transform in the fewest possible characters. Rules: * Shortest solution wins * It can be assumed that the input is a 1D array whose length is a power of two. * You may use the algorithm of your choice, but the solution must actually be a Fast Fourier Transform, not just a naive Discrete Fourier Transform (that is, it must have asymptotic computation cost of \$O(N \log N)\$) * the code should implement the standard forward Fast Fourier Transform, the form of which can be seen in equation (3) of [this Wolfram article](http://mathworld.wolfram.com/DiscreteFourierTransform.html), $$F\_n = \sum\_{k=0}^{N-1}f\_ke^{-2\pi ink/N}$$ * Using an FFT function from a pre-existing standard library or statistics package is not allowed. The challenge here is to succinctly *implement* the FFT algorithm itself. [Answer] # Mathematica, 95 bytes Another implementation of the Cooley–Tukey FFT with help from @[chyaong](https://codegolf.stackexchange.com/users/7254/chyaong). ``` {n=Length@#}~With~If[n>1,Join[+##,#-#2]&[#0@#[[;;;;2]],#0@#[[2;;;;2]]I^Array[-4#/n&,n/2,0]],#]& ``` ### Ungolfed ``` FFT[x_] := With[{N = Length[x]}, If[N > 1, With[{a = FFT[ x[[1 ;; N ;; 2]] ], b = FFT[ x[[2 ;; N ;; 2]] ] * Table[E^(-2*I*Pi*k/N), {k, 0, N/2 - 1}]}, Join[a + b, a - b]], x]] ``` [Answer] # J, 37 bytes ``` _2&(0((+,-)]%_1^i.@#%#)&$:/@|:]\)~1<# ``` An improvement after a few years. Still uses the Cooley-Tukey FFT algorithm. Saved 4 bytes using *e**πi* = -1, thanks to @[Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun). [Try it online!](https://tio.run/##HYu7DoJAFAV7vuJE5BXxuu9lN2qwsrewEimMRG0saCjEX1/BnEwmU5xX6LHzYJgIrUhzluercl00ScuvT6rjJC7Spd/UH99cii/fxqGIFoSsm28ZSowefTTMJTASDqfjObrfHm90KS0o3WMIgeO/yQISKmgSyggDSY5ZNdsKKTU0WaWEgyLrKomKpOKWT6mMrTQYWcO4dD8) ## Usage ``` f =: _2&(0((+,-)]%_1^i.@#%#)&$:/@|:]\)~1<# f 1 1 1 1 4 0 0 0 f 1 2 3 4 10 _2j2 _2 _2j_2 f 5.24626 3.90746 3.72335 5.74429 4.7983 8.34171 4.46785 0.760139 36.9894 _6.21186j0.355661 1.85336j_5.74474 7.10778j_1.13334 _0.517839 7.10778j1.13334 1.85336j5.74474 _6.21186j_0.355661 ``` ## Explanation ``` _2&(0((+,-)]%_1^i.@#%#)&$:/@|:]\)~1<# Input: array A # Length 1< Greater than one? _2&( )~ Execute this if true, else return A _2 ]\ Get non-overlapping sublists of size 2 0 |: Move axis 0 to the end, equivalent to transpose /@ Reduce [even-indexed, odd-indexed] &$: Call recursively on each # Get the length of the odd list i.@ Range from 0 to that length exclusive %# Divide each by the odd length _1^ Compute (-1)^x for each x ] Get the odd list % Divide each in that by the previous + Add the even values and modified odd values - Subtract the even values and modified odd values , Join the two lists and return ``` [Answer] # Python, 166 151 150 characters This uses the radix-2 Cooley-Tukey FFT algorithm ``` from math import* def F(x):N=len(x);t=N<2or(F(x[::2]),F(x[1::2]));return N<2and x or[ a+s*b/e**(2j*pi*n/N)for s in[1,-1]for(n,a,b)in zip(range(N),*t)] ``` Testing the result ``` >>> import numpy as np >>> x = np.random.random(512) >>> np.allclose(F(x), np.fft.fft(x)) True ``` [Answer] ## Python 3: 140 134 113 characters Short version - short and sweet, fits in a tweet (with thanks to [miles](https://codegolf.stackexchange.com/users/6710/miles)): ``` from math import* def f(v): n=len(v) if n<2:return v a,b=f(v[::2])*2,f(v[1::2])*2;return[a[i]+b[i]/1j**(i*4/n)for i in range(n)] ``` (In Python 2, `/` is truncating division when both sides are integers. So we replace `(i*4/n)` by `(i*4.0/n)`, which bumps the length to 115 chars.) Long version - more clarity into the internals of the classic Cooley-Tukey FFT: ``` import cmath def transform_radix2(vector): n = len(vector) if n <= 1: # Base case return vector elif n % 2 != 0: raise ValueError("Length is not a power of 2") else: k = n // 2 even = transform_radix2(vector[0 : : 2]) odd = transform_radix2(vector[1 : : 2]) return [even[i % k] + odd[i % k] * cmath.exp(i * -2j * cmath.pi / n) for i in range(n)] ``` [Answer] ### R: 142 ~~133~~ ~~99~~ 95 bytes Thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312) for helping me shaving down ~~32~~ 36 bytes! ``` f=function(x,n=sum(x|1),y=1:(n/2)*2)`if`(n>1,f(x[-y])+c(b<-f(x[y]),-b)*exp(-2i*(y/2-1)*pi/n),x) ``` An additional trick here is to use the main function default arguments to instantiate some variables. Usage is still the same: ``` x = c(1,1,1,1) f(x) [1] 4+0i 0+0i 0+0i 0+0i ``` **4-year old version at 133 bytes:** ``` f=function(x){n=length(x);if(n>1){a=Recall(x[seq(1,n,2)]);b=Recall(x[seq(2,n,2)]);t=exp(-2i*(1:(n/2)-1)*pi/n);c(a+b*t,a-b*t)}else{x}} ``` With indentations: ``` f=function(x){ n=length(x) if(n>1){ a=Recall(x[seq(1,n,2)]) b=Recall(x[seq(2,n,2)]) t=exp(-2i*(1:(n/2)-1)*pi/n) c(a+b*t,a-b*t) }else{x} } ``` It uses also Cooley-Tukey algorithm. The only tricks here are the use of function `Recall` that allows recursivity and the use of R vectorization that shorten greatly the actual computation. Usage: ``` x = c(1,1,1,1) f(x) [1] 4+0i 0+0i 0+0i 0+0i ``` [Answer] ## Python, 134 This borrows heavily from jakevdp's solution, so I've set this one to a community wiki. ``` from math import* F=lambda x:x*(len(x)<2)or[a+s*b/e**(2j*pi*n/len(x))for s in(1,-1)for n,(a,b)in enumerate(zip(F(x[::2]),F(x[1::2])))] ``` Changes: -12 chars: kill `t`. ``` def F(x):N=len(x);t=N<2or(F(x[::2]),F(x[1::2]));return ... in zip(range(N),*t)] def F(x):N=len(x);return ... in zip(range(N),F(x[::2]),F(x[1::2]))] ``` -1 char: exponent trick, `x*y**-z == x/y**z` (this could help some others) ``` ...[a+s*b*e**(-2j*pi*n/N)... ...[a+s*b/e**(2j*pi*n/N)... ``` -2 char: replace `and` with `*` ``` ...return N<2and x or[ ...return x*(N<2)or[ ``` +1 char: `lambda`ize, killing `N` ``` def F(x):N=len(x);return x*(N<2)or[a+s*b/e**(2j*pi*n/N) ... zip(range(N) ... F=lambda x:x*(len(x)<2)or[a+s*b/e**(2j*pi*n/len(x)) ... zip(range(len(x)) ... ``` -2 char: use `enumerate` instead of `zip(range(len(` ``` ...for(n,a,b)in zip(range(len(x)),F(x[::2]),F(x[1::2]))] ...for n,(a,b)in enumerate(zip(F(x[::2]),F(x[1::2])))] ``` [Answer] # C, 259 ``` typedef double complex cplx; void fft(cplx buf[],cplx out[],int n,int step){ if(step < n){ fft(out, buf,n, step * 2); fft(out+step,buf+step,n,step*2); for(int i=0;i<n;i+=2*step){ cplx t=cexp(-I*M_PI*i/n)*out[i+step]; buf[i/2]=out[i]+t; buf[(i+n)/2]=out[i]-t; }}} ``` The problem is, such implementations are useless, and straightforward algorithm is MUCH faster. [Answer] # Matlab, ~~128~~ ~~118~~ ~~107~~ ~~102~~ ~~101~~ ~~94~~ 93 bytes EDIT6: thanks @algmyr for another byte! ``` function Y=f(Y); n=numel(Y); k=2:2:n; if k; c=f(Y(k-1)); d=f(Y(k)).*i.^(2*(2-k)/n); Y=[c+d;c-d]; end ``` EDIT5: Still getting shorter:) thanks to @sanchises ``` function Y=f(Y) n=numel(Y); k=2:2:n; if k; c=f(Y(k-1)); d=f(Y(k)).*(-1).^((2-k)/n); Y=[c+d;c-d]; end ``` EDIT4: Yay, -1 character more (could aslo have done without the `k`): ``` function Y=f(Y) n=numel(Y); if n>1; k=2:2:n; c=f(Y(k-1)); d=f(Y(k)).*(-1).^((k/2-1)*2/n)'; Y=[c+d;c-d]; end ``` EDIT2/3: Thanks for @sanchises for further improvements! ``` function Y=f(Y) n=numel(Y); if n>1; c=f(Y(1:2:n)); d=f(Y(2:2:n)).*(-1).^(-(0:n/2-1)*2/n).'; Y=[c+d;c-d]; end ``` EDIT: Could make some improvements, and noticed that the scaling constant is not required. This is the expanded version, character count is valid if you remove the newlines/spaces. (Works only for column vectors.) ``` function y=f(Y) n=numel(Y); y=Y; if n>1; c=f(Y(1:2:n)); d=f(Y(2:2:n)); n=n/2; d=d.*exp(-pi*i*(0:n-1)/n).'; y=[c+d;c-d]; end ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~188 186 184~~ 183 bytes ``` #define d(a,b,c)f(a,b,c,1,0) f(a,b,c,n,k)_Complex*a,*b;{_Complex z[c];*b=*a;if(n<c)for(f(a,z,c,n*2),f(a+n,z+n,c,n*2);k<c;k+=n*2)b[k+c>>1]=z[k]*2-(b[k/2]=z[k]+z[k+n]/cpow(1i,2.*k/c));} ``` [Try it online!](https://tio.run/##rVDBasMwDL33K0RHwY7dNUnDKLjuZZ@RmWG7cTFJnNB0bKT015fZzVo22NihO0jPT5b0JOn5TuthuNsWxroCtkhSRTU2I9KExnhyIY6W@PmxqduqeIskjRQ7Xij0uRYsUjySzBrk1r5Fs0ehsg@VUYqpJ8TR3tsYYOVas5Lw8FZ5SfRmkwje56WI0jnykUU6UuIdcWKh2@YVJZam91G50Biz03DVl3kSCza5cjVy6w5QS@sQPk7AJ8WC@8zg0uCWgifMf4RZIeRa4BAzD2vIPBACGEIlQLv3/wbBdGbIzFiYUtD7QlZI5lZgT2wtdyMBHHqevLUvhw5Np2e@RSApKAoZvlVSfZVUP0k@uVH0c1m/Z8zO2yfsvHrqIRN86eFB8Cyk1kXdFQcUJowpdLYvGgPq11lX/3ce@H6f1c2af98nXOc0vGtTyV03zKv6Aw "C (gcc) – Try It Online") Slightly golfed less ``` #define d(a,b,c)f(a,b,c,1,0) f(a,b,c,n,k)_Complex*a,*b;{ _Complex z[c]; *b=*a; if(n<c) for(f(a,z,c,n*2),f(a+n,z+n,c,n*2);k<c;k+=n*2) b[k+c>>1]=z[k]*2-(b[k/2]=z[k]+z[k+n]/cpow(1i,2.*k/c)); } ``` [Answer] # Jelly, ~~31~~ ~~30~~ ~~28~~ 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` LḶ÷$N-*×,N$+ḷF s2Z߀ç/µ¹Ṗ? ``` This uses the Cooley-Tukey radix-2 recursive algorithm. For an un-golfed version, see my [answer](https://codegolf.stackexchange.com/a/12429/6710) in Mathematica. [Try it online](http://jelly.tryitonline.net/#code=TOG4tsO3JE4tKsOXLE4kK-G4t0YKczJaw5_igqzDpy_CtcK54bmWPw&input=&args=WzEsIDIsIDMsIDRd) or [Verify multiple test cases](http://jelly.tryitonline.net/#code=TOG4tsO3JE4tKsOXLE4kK-G4t0YKczJaw5_igqzDpy_CtcK54bmWPwrDh8WS4bmYJOKCrGrigbc&input=&args=W1sxLCAxLCAxLCAxXSwKIFsxLCAyLCAzLCA0XSwKIFs1LjI0NjI2LCAzLjkwNzQ2LCAzLjcyMzM1LCA1Ljc0NDI5LCA0Ljc5ODMsIDguMzQxNzEsIDQuNDY3ODUsIDAuNzYwMTM5XV0). ## Explanation ``` LḶ÷$N-*×,N$+ḷF Helper link. Input: lists A and B L Get the length of A $ Operate on that length Ḷ Make a range [0, 1, ..., length-1] ÷ Divide each by length N Negate each - The constant -1 * Compute -1^(x) for each x in that range × Multiply elementwise between that range and B, call it B' $ Operate on that B' N Negate each , Make a list [B', -B'] ḷ Get A + Add vectorized, [B', -B'] + A = [A+B', A-B'] F Flatten that and return s2Z߀ç/µ¹Ṗ? Main link. Input: list X Ṗ Curtail - Make a copy of X with the last value removed ? If that list is truthy (empty lists are falsey) µ Parse to the left as a monad s2 Split X into sublists of length 2 Z Transpose them to get [even-index, odd-index] ߀ Call the main link recursively on each sublist ç/ Call the helper link as a dyad on the sublists and return Else ¹ Identity function on X and return ``` [Answer] # Pari/GP, 76 characters ``` X(v)=my(t=-2*Pi*I/#v,s);vector(#v,k,s=t*(k-1);sum(n=0,#v-1,v[n+1]*exp(s*n))) ``` Usage ``` X([1,1,1,1]) %2 = [4.000000000000000000000000000, 0.E-27 + 0.E-28*I, 0.E-28 + 0.E-27*I, 0.E-27 + 0.E-28*I] ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~109 103 101~~ 100 bytes ``` f(f=@(f)@(x,n=rows(x)){@(d=f(f)(x(k=2:2:n)).*i.^((k*2-4)/n)')[d+(c=f(f)(x(k-1)));c-d],x}{1+(n<2)}()) ``` [Try it online!](https://tio.run/##TY3BCsIwGIPvPkVv@7N1da3zMi30PUYF2SzIoAMVLYw9ey0diAS@QBLIPLyu71t0WggRHTltyMFQ4F4/5s@TArAYGnWqQIEmrTrVeUCUd3EhmkpVt9h7FOjHiobfrpYATkM9Wh7WRVbkzworAemkt9glHjeTrPmXLbaUs4YzlXnIbHku4xc "Octave – Try It Online") Ooooo do my eyes bleed from this ~~recursive~~ accursed lambda. Large parts of this were lifted from @flawr's answer. ``` f( % lambda function f=@(f) % defined in its own argument list, % accepts itself as parameter (for recursion) @(x,n=rows(x)){ % calls another lambda, % 2nd parameter is just to define a variable @(d=f(f)(x(k=2:2:n)).*i.^((k*2-4)/n)')% 1/4 of FFT (argument just defines a variable) [d+(c=f(f)(x(k-1))); % 2/4 of FFT c-d % 4/4 of FFT ], % This is in a @()[] to inhibit evaluation % unless actually called x % FFT of length 1 }{1+(n<2)} % if len(x)==1, return x % else return [d+c;c-d] () % this is probably important too ) ``` [Answer] # APL(NARS), 58 chars, 116 bytes ``` {1≥k←≢⍵:⍵⋄(∇⍵[y∼⍨⍳k])(+,-)(∇⍵[y←2×⍳t])×0J1*t÷⍨2-2×⍳t←⌊k÷2} ``` test ``` f←{1≥k←≢⍵:⍵⋄(∇⍵[y∼⍨⍳k])(+,-)(∇⍵[y←2×⍳t])×0J1*t÷⍨2-2×⍳t←⌊k÷2} f 1 1 1 1 4J0 0J0 0J0 0J0 f 1 2 3 4 10J0 ¯2J2 ¯2J0 ¯2J¯2 f 1J1 2 ¯2J1 9 10J2 3J7 ¯12J2 3J¯7 f 5.24626,3.90746,3.72335,5.74429,4.7983,8.34171,4.46785,0.760139 36.989359J0 ¯6.211855215J0.3556612739 1.85336J¯5.744741 7.107775215J¯1.133338726 ¯0.517839J0 7.107775215J1.133338726 1.85336J5.744741 ¯6.211855215J¯0.3556612739 ``` [Answer] # Axiom, ~~259~~, ~~193~~, ~~181~~, 179 bytes ``` L(g,n,f)==>[g for i in 1..n|f] h(a)==(n:=#a;n=1=>a;c:=h(L(a.i,n,odd? i));d:=h(L(a.i,n,even? i));n:=n/2;t:=1>0;v:=L(d.i*%i^(-2*(i-1)/n),n,t);append(L(c.i+v.i,n,t),L(c.i-v.i,n,t))) ``` Even if h(a) could pass all the test and would be ok as entry for this 'competition' one has to call h() or hlp() thru fft() below, for *checking arguments*. I don't know if this software can be ok because i only had seen what other wrote, and search the way it could run in Axiom for return some possible right result. Below ungolfed code with few comments: ``` -- L(g,n,f)==>[g for i in 1..n|f] -- this macro L, build one List from other list, where in g, there is the generic element of index i -- (as a.i, or a.i*b.i or a.i*4), n build 1..n that is the range of i, f is the condition -- for insert the element in the list result. hlp(a)== n:=#a;n=1=>a -- L(a.i,n,odd? i) it means build a list getting "even indices i of a.i as starting from index 0" [so even is odd and odd is even] -- L(a.i,n,even? i) it means build a list getting "odd indices i of a.i as starting from index 0" c:=hlp(L(a.i,n,odd? i));d:=hlp(L(a.i,n,even? i)) n:=n/2;t:=1>0 v:=L(d.i*%i^(-2*(i-1)/n),n,t) append(L(c.i+v.i,n,t),L(c.i-v.i,n,t)) -- Return Fast Fourier transform of list a, in the case #a=2^n fft(a)==(n:=#a;n=0 or gcd(n,2^30)~=n=>[];hlp(a)) (5) -> h([1,1,1,1]) (5) [4,0,0,0] Type: List Expression Complex Integer (6) -> h([1,2,3,4]) (6) [10,- 2 + 2%i,- 2,- 2 - 2%i] Type: List Expression Complex Integer (7) -> h([5.24626,3.90746,3.72335,5.74429,4.7983,8.34171,4.46785,0.760139]) (7) [36.989359, - 6.2118552150 341603904 + 0.3556612739 187363298 %i, 1.85336 - 5.744741 %i, 7.1077752150 341603904 - 1.1333387260 812636702 %i, - 0.517839, 7.1077752150 341603904 + 1.1333387260 812636702 %i, 1.85336 + 5.744741 %i, - 6.2118552150 341603904 - 0.3556612739 187363298 %i] Type: List Expression Complex Float (8) -> h([%i+1,2,%i-2,9]) (8) [10 + 2%i,3 + 7%i,- 12 + 2%i,3 - 7%i] Type: List Expression Complex Integer ``` in the few i had seen h() or fft() would return exact solution, but if the simplification is not good as in: ``` (13) -> h([1,2,3,4,5,6,7,8]) (13) +--+ +--+ (- 4 + 4%i)\|%i - 4 + 4%i (- 4 - 4%i)\|%i - 4 + 4%i [36, --------------------------, - 4 + 4%i, --------------------------, - 4, +--+ +--+ \|%i \|%i +--+ +--+ (- 4 + 4%i)\|%i + 4 - 4%i (- 4 - 4%i)\|%i + 4 - 4%i --------------------------, - 4 - 4%i, --------------------------] +--+ +--+ \|%i \|%i Type: List Expression Complex Integer ``` than it is enought change the type of only one element of list, as in below writing 8. (Float) for find the approximate solution: ``` (14) -> h([1,2,3,4,5,6,7,8.]) (14) [36.0, - 4.0000000000 000000001 + 9.6568542494 923801953 %i, - 4.0 + 4.0 %i, - 4.0 + 1.6568542494 92380195 %i, - 4.0, - 4.0 - 1.6568542494 92380195 %i, - 4.0 - 4.0 %i, - 4.0 - 9.6568542494 923801953 %i] Type: List Expression Complex Float ``` I wrote it, seen all other answers because in the link, the page it was too much difficult so I don't know if this code can be right. I'm not one fft expert so all this can (it is probable) be wrong. ]
[Question] [ *(based on [this](https://codegolf.meta.stackexchange.com/a/12146/42963) post and the [ensuing discussion](http://chat.stackexchange.com/transcript/message/36815472#36815472) on chat -- also, much thanks to Dennis for TIO!)* ## The Challenge Choose a language that's currently available on the [TryItOnline site](https://tio.run/), for example [PowerShell](https://tio.run/#powershell). Write code in that language on that page, that doesn't take any input, such that when the *Run* button is clicked, the output on that page is the *exact same* as what is in the "Plain URL" field when the *Save/Store* button is clicked instead. For a fictitious example, suppose that `aaa` was the code for a solution to this in PowerShell. Then, the result of clicking *Run* with `aaa` as the code on `https://tio.run/#powershell` should output `https://tio.run/##K8gvTy0qzkjNyfn/PzEx8f9/AA`, which is also the "Plain URL" field when the *Save/Store* button is clicked. ## Scoring The *resulting URL* is your submission to this challenge. The winner is the shortest URL measured in bytes. For the example above, the URL `https://tio.run/##K8gvTy0qzkjNyfn/PzEx8f9/AA` is the submission to the challenge, at **44 bytes**. The shortest URL that fulfills the rest of this challenge wins the challenge and earns brownie points (points not redeemable). Given that there is a distinct minimum possible length, if two submissions tie in length, the earlier submission wins. ## URL Generation [This](https://github.com/TryItOnline/tryitonline/blob/master/usr/share/tio.run/frontend.js#L391) is the start of the URL generation algorithm in the repository. You can see how the main code area is taken, any extra elements are appended, the string is deflated and Base64 converted, and then `##` prepended, etc. I won't go into full detail here; part of the challenge is to parse and understand how the URLs are generated in order to exploit any potential quirks in said algorithm. ## Rules / Clarifications * The actual code should take no input and produce only the quine-URL as output. -- This means the only text fields that should be populated when clicking into the URL are the `Code`, `Header`, `Footer` or corresponding "Compiler Flag" fields; the `Input` and `Arguments` fields are forbidden and must remain empty/unused. Clicking the *Run* button should only change the `Output` field. For this challenge, the `Debug` field is ignored in all situations. * Usual quine rules apply to the code to the extent possible (for example, the code cannot read its own source code via `.code.tio`). * Please include a description of how the code works in your submission. * Submitting a "cheaty" quine by submitting a Git pull request to the TIO repository to create a "trick" URL or shortcut or the like is not allowed. * Similarly, submitting a pull request to update a particular language to produce a "trick" URL is not allowed. * Please be nice to Dennis' servers and don't abuse them or attempt exploits for the sake of this challenge. [Answer] # [Python 2](https://docs.python.org/2/), URL length = 170 bytes ``` https://tio.run/##K6gsycjPM/r/v9hWqQDCjqlISwPhYlvVIuvM3IL8ohKFpMTiVDMT64KizLwS9YySkoJiK339ksx8vaLSPH1lZXVtiAK9JDOT1Lzk/JRUDY1iVdViTT0YT70qJzNJXVMz2shK1yRWE2aHEkUW4Db//38A ``` ``` s="python2\xff\xffs=%r;import base64;print'https://tio.run/##'+base64.b64encode((s%%s).encode(('zlib'))[2:-4])\xff\xff";import base64;print'https://tio.run/##'+base64.b64encode((s%s).encode(('zlib'))[2:-4]) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9hWqQDCjqlISwPhYlvVIuvM3IL8ohKFpMTiVDMT64KizLwS9YySkoJiK339ksx8vaLSPH1lZXVtiAK9JDOT1Lzk/JRUDY1iVdViTT0YT70qJzNJXVMz2shK1yRWE2aHEkUW4Db//38A "Python 2 – Try It Online") This relies on three coincidences: 1. The default zlib level 6 happens to give the same results as zlib level 9 for this string, modulo the header that I strip. 2. The compressed length is divisible by 3, so base64 does not generate any `=` padding characters. 3. The base64 output does not contain any `+` characters. [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~174~~ ~~166~~ ~~165~~ 157 bytes ``` https://tio.run/##S0oszvj/v6QosUBBV1dBvaAoM68kTSGjpKSg2EpfvyQzP0avqDRPX1lZRQMqp6RaHFORlgbCSgpJQO0KSgkg/QlKNelVmQU1JYmZOQq6ydqGhjVA2VQzEwXdckNjS011BdcIz5D//wE ``` This encodes the following Bash program. ``` trap -- 'printf https://tio\.run/##$(printf "%s\xff\xff" bash "`trap`"|gzip|tail -c+11|base64 -w139)' EXIT ``` [Try it online!](https://tio.run/##S0oszvj/v6QosUBBV1dBvaAoM68kTSGjpKSg2EpfvyQzP0avqDRPX1lZRQMqp6RaHFORlgbCSgpJQO0KSgkg/QlKNelVmQU1JYmZOQq6ydqGhjVA2VQzEwXdckNjS011BdcIz5D//wE "Bash – Try It Online") *Thanks to @jimmy23013 for golfing 8 bytes off my original approach, for an approach that saved another byte, and for golfing another 8 bytes off that approach!* [Answer] # [Pyth](https://github.com/isaacg1/pyth), URL length = 134 bytes ``` https://tio.run/##K6gsyfj/X68syy/ZS6lYmyujpKSg2EpfvyQzX6@oNE9fWZnLwae4OLrI3dA9NITLQZ9LM8vZxqSkRC@qOJqrAKiby9vZyNTUmwtiBpefl7e3ppnJ//8A ``` Code: ``` .vjNcJ"s+ https://tio.run/## @Lss[rG1GUT @/ )jC<4tt.Zs[ pyth KC255K .vjNcJ NJKK)64 ``` [Try it online!](https://tio.run/##K6gsyfj/X68syy/ZS6lYmyujpKSg2EpfvyQzX6@oNE9fWZnLwae4OLrI3dA9NITLQZ9LM8vZxqSkRC@qOJqrAKiby9vZyNTUmwtiBpefl7e3ppnJ//8A "Pyth – Try It Online") Uses Pyth’s zlib builtin (`.Z`), and an inline implementation of base64. ### How it works The outer stage: ``` .vjNcJ"… "… take this 75-byte string J assign it to J c split on whitespace jN join on N = '"' .v evaluate as Pyth code ``` The inner stage, obtained by replacing whitespace in the string `J` with double quotes: ``` s+"https://tio.run/##"@Lss[rG1GUT"@/")jC<4tt.Zs["pyth"KC255K".vjNcJ"NJKK)64 [ begin a list: "pyth" string, C255 character 255 K assign that to K, K K again, ".vjNcJ" string, N '"', J J (the 75-byte string), K K again, K K again ) end list s concatenate .Z compress with zlib t remove first character t remove first character <4 remove last 4 characters C convert from base 256 j 64 convert to base 64 digits @L map d ↦ the following indexed at d: [ begin a list: G alphabet ("abcdefghijklmnopqrstuvwxyz") r 1 uppercase, G alphabet again, UT unary range of length T = 10: [0, …, 9], "@/" string, ) end list s concatenate s concatenate (we now have the base64 alphabet) +"https://tio.run/##" prepend string s concatenate ``` (It’s too bad the “Input” field is disallowed, or I’d have a [118 byte solution](https://tio.run/##K6gsyfj/v1hbKaOkpKDYSl@/JDNfr6g0T19ZWcnBp7g4usjd0D00RMlBX0kzy9nGpKREL0pbqQCoS0nLSFvLyNnI1LTKzIQKRgAA "Pyth – Try It Online").) [Answer] # PowerShell, 274 bytes ``` https://tio.run/##TY/rCsIwDIVfZaiYFV2HooIbgu8xBrYzboXSljYq3p59VkHZjxAOJydf4uwVfehQ676fphO5e1TK8pPSWBfF1StCobW8EYYUJMyrphO@qmtw/xzMluv1t37maJoePpsm8sVGP5eV7V25JDslsozmgOJRHAcQ3t6BldARuVDkOcVBfzb5eAwRYM0FPcUQWSkCblaBvDJtPLxaLDmPnTf2bCjbsppxj06LBlPYwRxgoGdR74E9vw9mnQ2UZObF@v4N ``` It's all thanks to the following snippet: ``` &($b={[io.file]::writeallbytes('b',[char[]]'powershell'+255+255+[char[]]"&(`$b={$b})"+255+255);gzip -f b;$b=[io.file]::readallbytes('b.gz');'https://tio.run/##'+[convert]::tobase64string($b[12..($b.count-9)]).replace('=','').replace('+','@')|write-host -n}) ``` [Try it online!](https://tio.run/##TY/rCsIwDIVfZaiYFV2HooIbgu8xBrYzboXSljYq3p59VkHZjxAOJydf4uwVfehQ676fphO5e1TK8pPSWBfF1StCobW8EYYUJMyrphO@qmtw/xzMluv1t37maJoePpsm8sVGP5eV7V25JDslsozmgOJRHAcQ3t6BldARuVDkOcVBfzb5eAwRYM0FPcUQWSkCblaBvDJtPLxaLDmPnTf2bCjbsppxj06LBlPYwRxgoGdR74E9vw9mnQ2UZObF@v4N) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 214 bytes ``` v=()=>console.log('https://tio.run/##'+require(`zlib`).deflateRawSync(Buffer.from(`javascript-node\xff\xffv=`+v+`;v()\xff\xff`,`ascii`)).toString("base64"));v() ``` [Try it online!](https://tio.run/##VY07EoIwFADvAgXJoKFxLHSw8AjSWrwALxgmJPgS4ufyUQoLi212dmZHGaXvSM9ha12PKcWa8frUOeudQWHcwIpbCLM/VFXQTtBiqzwvSsL7ogkZvI1ugYselZEBL/LRvGzHzotSSEKRmxiM/4/rU6mVWEMZSzhGxn8KNvAttQbORXBNIG0HlrXS436Xcb6mKX0A "JavaScript (Node.js) – Try It Online") ]
[Question] [ In many fonts (specifically in the [Consolas font](https://en.wikipedia.org/wiki/Consolas)), 5 out of the 10 decimal digits have "holes" in them. We will call these holy digits: ``` 46890 ``` The 5 unholy digits are thus: ``` 12357 ``` An integer may thus be classified as "holy" if it only contains holy digits, and "unholy" otherwise. Because `-` is unholy, no negative integers can be holy. Holy integers may be further classified based on how many holes they have. For example, the following digits have a holiness of 1: ``` 469 ``` And these digits have a holiness of 2: ``` 80 ``` We say that the overall holiness of an integer is the sum of the holiness of its digits. Therefore, `80` would have a holiness of 4, and `99` would have a holiness of 2. ## The Challenge Given two integers `n > 0` and `h > 0`, output the `n`th holy integer whose holiness is at least `h`. You may assume that the inputs and outputs will be no greater than the maximum representable integer in your language or `2^64 - 1`, whichever is less. Here is a list of the first 25 holy integers with holiness `h >= 1`, for reference: ``` 0, 4, 6, 8, 9, 40, 44, 46, 48, 49, 60, 64, 66, 68, 69, 80, 84, 86, 88, 89, 90, 94, 96, 98, 99 ``` The first 25 holy integers with holiness `h >= 2` are: ``` 0, 8, 40, 44, 46, 48, 49, 60, 64, 66, 68, 69, 80, 84, 86, 88, 89, 90, 94, 96, 98, 99, 400, 404, 406 ``` [Answer] ## Ruby, ~~109~~ ~~105~~ ~~95~~ 82 bytes ``` ->n,h{(?0..?9*99).select{|x|x.count('469')+2*x.count('80')>=h&&/[12357]/!~x}[n-1]} ``` This is the terrible "calculate from 0 to 99999999999..." approach that happens to be 13 bytes shorter than its lazy counterpart. However, this version is unlikely to finish before the heat death of the universe. Worth 13 bytes, anyway ¯\\_(ツ)\_/¯ You can test it for smaller values by changing `?9*99` to, say, `'99999'`. Here's the old version (95 bytes, with lazy evaluation, which runs near-instantly rather than near-never): ``` ->n,h{(?0..?9*99).lazy.select{|x|x.count('469')+2*x.count('80')>=h&&/[12357]/!~x}.first(n)[-1]} ``` ``` ->n,h{ (?0..?9*99) # range '0' (string) to '9' repeated 99 times, way more than 2**64 .lazy # make the range lazy, so we can call `select' on it .select{|x| # choose only elements such that... x.count('469')+2*x.count('80') # naive holiness calculation >=h # is at least h &&/[12357]/!~x # naive "is holy" calculation } .first(n) # take the first n elements that satisfy the condition [-1] # choose the last one from this array } ``` [Answer] # Python 3, 103 ``` lambda n,h,l='4698080':[y for y in range(2**64-1)if(sum(l.count(x)-(x not in l)for x in str(y))>=h)][n] ``` Here's a solution that uses a more memory efficient approach, but otherwise uses the same algorithm if you want to test it. ``` l='4689080' def f(n,h): c=i=0 while i<n: if sum(l.count(x)-(x not in l)for x in str(c))>=h:u=c;i+=1 c+=1 return u ``` Test cases: ``` assert f(3, 1) == 6 assert f(4, 2) == 44 ``` [Answer] ## Pyth, 32 bytes ``` e.fg*g.{`46890J`Z++lJ/J`8/J`0QE0 ``` Explanation ``` - autoassign Q = eval(input()) .f E0 - first eval(input()) terms of func V starting Z=0 g.{`46890J`Z - Are all the digits in Z in "46890"? `Z - str(Z) J - autoassign J = ^ g - is_subset(V,^) .{`46890 - set("46890") * - ^*V (Only return non-zero if only contains holy numbers) ++lJ/J`8/J`0 - Get the holiness of the number lJ - len(J) + - ^+V /J`8 - J.count("8") + - ^+V /J`0 - J.count("0") g Q - ^>=Q (Is the holiness great enough) e - ^[-1] ``` [Try it here](http://pyth.herokuapp.com/?code=e.fg*g.%7B%6046890J%60Z%2B%2BlJ%2FJ%608%2FJ%600QE0&input=1%0A3&debug=1) Takes input in the form `h \n n` [Answer] ## PowerShell, ~~163~~ ~~150~~ ~~141~~ ~~101~~ ~~98~~ 96 bytes ``` param($n,$h)for(--$i;$n){if(++$i-notmatch"[12357]"-and($i-replace"8|0",11).Length-ge$h){$n--}}$i ``` Takes input, then loops until `$n` is zero. We initially setting `$i=-1` by using a pre-processing trick, which works because `$i`, having not previously been declared, is `$null`. Then we `--` it, which causes PowerShell to evaluate it as `$i = $null - 1`, which is `$i=-1`. Each loop we increment `$i` and then execute a lengthy `if` statement. The first part of the conditional verifies that `$i` doesn't have any of `12357` in it by using the [`-notmatch` operator](https://technet.microsoft.com/en-us/library/hh847759(v=wps.620).aspx), to filter out the unholy numbers. The second part of the conditional checks the quantity of holes in `$i`. It uses the `-replace` operator to replace each `8` or `0` with `11`, and then compares whether the length is >= `$h`. We don't need to worry about stripping out the unholy numbers, since that's in the first part of the conditional, and the single-holed numbers are the same length as `1` anyway, so we don't need to replace them, either. If that is still truthy, we decrement `$n` (as that means we've found another number that satisfies input requirements). Thus when the `for` condition is recalculated to check if `$n` is zero, that means we've found the *nth* one, so we exit the `for` loop, output `$i` and terminate. Edit -- saved 13 bytes by using an array instead of string for `$l` and changing how `$n` is decremented/checked Edit 2 -- saved an additional 9 bytes by checking for `$n` in the `for` conditional and moving the output outside the loop Edit 3 -- saved a whopping 40 more bytes by radically changing how we calculate the holes Edit 4 -- saved an additional 3 bytes by moving the `++` to be a pre-increment on the first part of the conditional Edit 5 -- saved another 2 bytes thanks to [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler) [Answer] # R, ~~109~~ 107 bytes ``` f=function(n,h){m=-1;while(n){m=m+1;if(!grepl("[12357]",m))if(nchar(gsub("([08])","\\1\\1",m))>=h)n=n-1};m} ``` With new lines and indentations: ``` f=function(n,h){ m=-1 while(n){ m=m+1 if(!grepl("[12357]",m)) if(nchar(gsub("([08])","\\1\\1",m))>=h) n=n-1 } m } ``` Usage: ``` > f(4,3) [1] 68 > f(4,2) [1] 44 > f(6,2) [1] 48 > f(10,2) [1] 66 ``` [Answer] ## CJam, ~~36~~ 34 bytes *Thanks to aditsu for saving 2 bytes.* ``` Wq~:X;{{)_Ab39643Zbf=_:*g*1bX<}g}* ``` [Test it here.](http://cjam.aditsu.net/#code=Wq~%3AX%3B%7B%7B)_s9886400sfe%3D_%3A*gf*%3A%2BX%3C%7Dg%7D*&input=25%202) [Answer] ## JavaScript (ES6), 110 bytes ``` f=(n,h,r=[],i=0)=>r.length<n?f(n,h,/[12357]/.test(i)|[...''+i].reduce((t,c)=>t+1+!(c%8),0)<h?r:[...r,i],i+1):r ``` Tail recursive solution that accumulates holy numbers in an array. Out of interest, not requiring the number to be wholly(!) holy makes the holiness count more awkward, but it still saves 10% overall: ``` f=(n,h,r=[],i=0)=>r.length<n?f(n,h,[...''+i].reduce((t,c)=>+"2000101021"[c]+t,0)<h?r:[...r,i],i+1):r ``` [Answer] # Bash + GNU utilities, 67 * 20 bytes saved thanks to @TobySpeight! ``` seq 0 NaN|sed -r "h;/[12357]/d;s/8|0/&&/g;/^.{$1}/!d;x"|sed $2!d\;q ``` * `seq` simply generates integers starting from `0` upwards * `sed -r`: + `h` copy the input line to the hold space + `/12357/d` delete unholy numbers + `s/8|0/&&/g` replace doubly holy digits with twice themselves. Thus singly holy digits are counted once and doubly holy digits are counted twice. + `/^.{$1}/!d` If not matching at least `$1` holes, delete and continue to the next line + `x` bring original number back to the pattern space + implicit print * `sed` + `$2!d` on any lines before line `$2`, delete and continue to the next line + `q` must be at line `$2` - quit (and implicit print) [Ideone.](https://ideone.com/zYgdbk) [Answer] # [MATL](https://esolangs.org/wiki/MATL), 39 ~~40~~ bytes ``` x~q`QtV4688900V!=stA*s2G<?T}N1G=?F1$}tT ``` Inputs are `n` and `h` in that order. [**Try it online!**](http://matl.tryitonline.net/#code=eH5xYFF0VjQ2ODg5MDBWIT1zdEEqczJHPD9UfU4xRz0_RjEkfXRU&input=MjUKMg) We need to keep track of two numbers: current candidate number (to check its holiness) and amount of numbers found that are holy enough. The first is the top od the stack, and the latter is kept as the number of elements in the stack. When the program finishes, only the top needs to displayed. ``` x~q % implicitly take two inputs. Delete one and transform the other into -1 ` % do...while loop Q % add 1 to current candidate number tV % duplicate and convert to string 4688900V! % column char array of '4', '6' etc. Note '8' and '0' are repeated = % compare all combinations. Gives 2D array s % sum of each column: holiness of each digit of candidate number tA* % are all digits holy? Multiply by that s % sum of holiness of all digits, provided they are all holy 2G< % is that less than second input (h)? ? % if so: current candidate not valid. We'll try the next T % push true to be used as loop condition: next iteration } % else: current candidate valid N1G= % does stack size equal first input (n)? ? % if so: we're done F1$ % push false to exit loop. Spec 1 input, to display only top } % else: make a copy of this number tT % duplicate number. Push true to continue with next iteration % implicit end if % implicit end if % implicit end do...while. If top of stack is truthy: next iteration % implicit display ``` [Answer] # JavaScript ES6, 191 bytes Sure, this isn't the most efficient way. But you know me, I love generators <3 ``` H=(x,o=x+"")=>(F=/^[46890]+$/).test(o)&&[...o].map(y=>d+=(F.test(y)+/8|0/.test(y)),d=0)&&d;(n,h)=>(a=(function*(h){q=0;while(1){if(H(q)>=h)yield q;q++}})(h),eval("a.next().value;".repeat(n))) ``` Slightly ungolfed: ``` H = (x, o = x + "") => (F = /^[46890]+$/).test(o) && [...o].map(y => d += (F.test(y) + /8|0/.test(y)), d = 0) && d; Q = (n, h) => (a = (function*(h) { q = 0; while (1) { if (H(q) >= h) yield q; q++ } })(h), eval("a.next().value;".repeat(n))) ``` [Answer] **C# 6, 168 bytes** ``` (n,h)=>{for(int i=0;i<=int.MaxValue;i++){string d=$"{i}";if(d.Any(y=>"12357".Contains(y)))continue;n-=d.Sum(y=>y=='0'||y=='8'?2:1)>=h?1:0;if(n==0)return i;}return -1;} ``` This is a Lambda Expression of type Func< int, int, int>. This code is otimized for min size (not performatic). Below, the beautified code in method declaration (with more performance): ``` int GetHolyNumber(int n, int h) { for (int i = 0; i <= int.MaxValue; i++) { string d = $"{i}"; char[] cs = "12357".ToArray(); if (d.Any(y => cs.Contains(y))) continue; n -= d.Sum(y => y == '0' || y == '8' ? 2 : 1) >= h ? 1 : 0; if (n == 0) return i; } return -1; } ``` [Answer] # JavaScript (ES6), 87 ``` (n,h)=>eval("for(i=0;[...i+''].map(d=>r-=~!(d%8),r=0),/[12357]/.test(i)|r<h||--n;)++i") ``` **Less golfed** ``` f=(n,h)=>{ for (i=0; // this is the loop condition /[12357]/.test(i) // go on if not holy ||([...i+''].map(d=>r-=~!(d%8),r=0),r<h) // go on if not holy enough ||--n; // ok, found one! go on if we need to find more ) ++i; // loop body - using eval this is the returned value return i; // not using eval, an explicit return is needed } ``` **Test** ``` f=(n,h)=>eval("for(i=0;[...i+''].map(d=>r-=~!(d%8),r=0),/[12357]/.test(i)|r<h||--n;)++i") function test() { var a,b [a,b]=I.value.match(/\d+/g) R.textContent = f(a,b) } test() ``` ``` N, H: <input id=I value="25 2" oninput="test()"> >> <span id=R></span> ``` [Answer] ## Lua, ~~155~~ ~~141~~ 140 Bytes Takes both inputs by command-line argument(first argument is n, then h) **Edit: Thanks to @DavisDude, who helped me shaving 14 bytes off and reminded me I didn't have to print all the holy numbers up to n, but only the nth.** ``` a={}x=0while(#a<arg[1])do b,c=(x..""):gsub("[08]","")e,d=b:gsub("[469]","")a[#a+1],x=c*2+d>=arg[2]and #e<1 and x or nil,x+1 end print(a[#a]) ``` ### Ungolfed and explanations ``` x,a=0,{} -- initialise a counter, and the array which -- contains the holy numbers found while(#a<arg[1]) -- iterate while we found less holy numbers than n do b,c=(x..""):gsub("[08]","") -- replace [08] by "", b=the new string -- c=the number of subsitution e,d=b:gsub("[469]","") -- same thing for [469] a[#a+1]=c*2+d>=arg[2] -- insert the number into a if:nb[08]*2+nb[469]>h and #e<1 -- and e is empty (no unholy numbers) and x or nil x=x+1 -- increment x end print(a[#a]) -- print the last element of a ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 22 bytes ``` “J,1’D=þD§S×ẠƊ 0Ç<Cɗ#Ṫ ``` [Try it online!](https://tio.run/##ATIAzf9qZWxsef//4oCcSiwx4oCZRD3DvkTCp1PDl@G6oMaKCjDDhzxDyZcj4bmq////Mv8yNQ "Jelly – Try It Online") ## How it works ``` 0Ç<Cɗ#Ṫ - Main link. Takes h on the left and n on the right ɗ - Group the previous 3 links into a dyad f(k, h): Ç - Call the helper link on k < - Less than h? C - Complement; 0 -> 1, 1 -> 0 0 # - Count up k = 0, 1, 2, ... until n k's return true under f(k, h) Ṫ - Take the last k “J,1’D=þD§S×ẠƊ - Helper link. Takes an integer k on the left D - Digits of k “J,1’ - Compressed integer 4698800 D - Converted to digits þ - Outer product with: = - Equality § - Sum of each row Ɗ - Group the previous 3 links into a monad g(s) over the sums: S - Sum Ạ - All are non-zero? × - Product This calculates the holiness of k, which is 0 if k isn't holy ``` [Answer] # Oracle SQL 11.2, 229 bytes ``` WITH v(c,p,i,j,n)AS(SELECT 0,-1,0,0,0 FROM DUAL UNION ALL SELECT c+1,c,REGEXP_COUNT(c||'','[4,6,9]'),REGEXP_COUNT(c,'[8,0]'),n+DECODE(LENGTH(p),i+j,DECODE(SIGN(i+j*2-:h),-1,0,1),0)FROM v WHERE p<c AND n<:n)SELECT MAX(p)-1 FROM v; ``` Un-golfed ``` :h -> required min holy value :n -> nth number curv -> current number precv -> previous number prech1 -> number of holy 1 letters in previous number prech2 -> number of holy 2 letters in previous number n -> how many numbers with at least the required holy value WITH v(curv,precv,prech1,prech2,n)AS ( SELECT 0 curv, -1 precv, 0 prech1, 0 prech2, 0 n FROM DUAL -- Start with 0 UNION ALL SELECT curv+1, -- Next number curv, -- Current Number REGEXP_COUNT(curv||'','[4,6,9]'), -- number of holy 1 letters REGEXP_COUNT(curv,'[8,0]'), -- number of holy 2 letters n+DECODE(LENGTH(precv),prech1+prech2,DECODE(SIGN(prech1+prech2*2-:h),-1,0,1),0) -- Is the previous number holy enough ? FROM v WHERE precv<curv -- Needed to trick oracle cycle detection AND n<:n -- Until clause ) SELECT MAX(precv)-1 FROM v ``` [Answer] ## Python 2, 96 bytes ``` f=lambda n,h,k=0,s="0046889":-0**n or-~f(n-(sum(map(s.count,`k`))>=h<set(str(k))<=set(s)),h,k+1) ``` The holyness condition on `k` is checked by * `sum(map(s.count,`k`))>=h`, which counts the number of holes by summing the counts for each character in `s="0046889"`, where `0` and `8` appear twice. * `set(str(k))<=set(s))`, which checks that the numbers are all holy. `str` is used rather than backticks to avoid the suffix `L` for longs. These are chained into a single equality using the Python 2 fact that numbers are smaller than sets. The function is defined recursively to count up numbers `k`, decreasing the counter `n` each time a holy number of hit unless it hits `0`. It could then return the `k` that triggered this, but it's shorter to keep the count recursively by adding `1` each time, though an off-by-one requires a base count of `-1` to fix. [Answer] # Haskell, 94 bytes `c` is the holiness of a digit, `v` the holiness of a number, `n!h` does the rest. ``` c=([2,0,0,0,1,0,1,0,2,1]!!) v n|n>9=c(mod n 10)+v(div n 10)|1<2=c n n!h=[i|i<-[0..],v i<=h]!!n ``` Note: I think this is the only answer without the characters `4,6,8`. [Answer] # Lua, 169 bytes ``` function a(n,h)H=0N=0I=-1while N<n do I=I+'1'H=0 if not I:find('[12357]') then _,b=I:gsub('[469]',1)_,c=I:gsub('[08]',1)H=b+2*c end N=H>=h and N+1 or N end print(I) end ``` Ungolfed: ``` function a(n,h) -- nth term, holiness H=0N=0I=-1 -- Really ugly, but hey, it works. Set up 3 vars while N<n do -- While nth term is lower than desired term I=''..I+1 -- Convert number to string (can't coerce since it will become a float) if not I:find('[12357]') then -- If the number doesn't have those numbers _,b=I:gsub('[469]',1) -- _ is the new string, b is the number of changes _,c=I:gsub('[08]',1) -- Same as above. Use 1 to replace to save chars H=b+2*c -- Increase holiness appropriately end N=H>=h and N+1 or N -- If current holiness >= desired holiness, increment N end print(I) -- Once the loop ends, print the current term end ``` [Answer] **Swift** ``` func f(n: Int, h: Int) { var m = 0 let a = [1,2,3,5,7] for j in 0..<Int.max { var c = 0 for i in (j.description.characters.map{(String($0) as NSString).integerValue}) { c += (a.contains(i)) ? 0 : (i == 8 || i == 0) ? 2 :1 } if c >= h { m += 1; if m >= n {print(j); break}} } } ``` [Answer] # [Perl 5](https://www.perl.org/) `-ap`, 58 bytes ``` $_=0;$n=<>;$_++while/[12357]/||y/64980//+y/80//<"@F"||--$n ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tbAWiXP1sbOWiVeW7s8IzMnVT/a0MjY1DxWv6amUt/MxNLCQF9fu1IfRNkoObgp1dTo6qrk/f9vxGXyL7@gJDM/r/i/bmJBDgA "Perl 5 – Try It Online") Input is on two lines with `h` on the first and `n` on the second. ]